Delete non-iOS files
This commit is contained in:
63
.gitmodules
vendored
63
.gitmodules
vendored
@@ -1,78 +1,15 @@
|
||||
[submodule "mapbox-gl-js"]
|
||||
path = mapbox-gl-js
|
||||
url = https://github.com/mapbox/mapbox-gl-js.git
|
||||
[submodule "platform/ios/vendor/mapbox-events-ios"]
|
||||
path = platform/ios/vendor/mapbox-events-ios
|
||||
url = https://github.com/mapbox/mapbox-events-ios.git
|
||||
[submodule "vendor/nunicode"]
|
||||
path = vendor/nunicode
|
||||
url = https://bitbucket.org/alekseyt/nunicode.git
|
||||
[submodule "vendor/earcut.hpp"]
|
||||
path = vendor/earcut.hpp
|
||||
url = https://github.com/mapbox/earcut.hpp.git
|
||||
[submodule "vendor/geojson-vt-cpp"]
|
||||
path = vendor/geojson-vt-cpp
|
||||
url = https://github.com/mapbox/geojson-vt-cpp.git
|
||||
[submodule "vendor/polylabel"]
|
||||
path = vendor/polylabel
|
||||
url = https://github.com/mapbox/polylabel.git
|
||||
[submodule "vendor/protozero"]
|
||||
path = vendor/protozero
|
||||
url = https://github.com/mapbox/protozero.git
|
||||
[submodule "vendor/shelf-pack-cpp"]
|
||||
path = vendor/shelf-pack-cpp
|
||||
url = https://github.com/mapbox/shelf-pack-cpp.git
|
||||
[submodule "vendor/vector-tile"]
|
||||
path = vendor/vector-tile
|
||||
url = https://github.com/mapbox/vector-tile.git
|
||||
[submodule "vendor/wagyu"]
|
||||
path = vendor/wagyu
|
||||
url = https://github.com/mapbox/wagyu.git
|
||||
[submodule "vendor/expected-lite"]
|
||||
path = vendor/expected
|
||||
url = https://github.com/martinmoene/expected-lite.git
|
||||
[submodule "vendor/unique_resource"]
|
||||
path = vendor/unique_resource
|
||||
url = https://github.com/okdshin/unique_resource.git
|
||||
[submodule "vendor/icu"]
|
||||
path = vendor/icu
|
||||
url = https://github.com/unicode-org/icu.git
|
||||
[submodule "vendor/boost"]
|
||||
path = vendor/boost
|
||||
url = https://github.com/mapbox/mapbox-gl-native-boost.git
|
||||
[submodule "vendor/benchmark"]
|
||||
path = vendor/benchmark
|
||||
url = https://github.com/google/benchmark.git
|
||||
[submodule "vendor/cheap-ruler-cpp"]
|
||||
path = vendor/cheap-ruler-cpp
|
||||
url = https://github.com/mapbox/cheap-ruler-cpp.git
|
||||
[submodule "vendor/glfw"]
|
||||
path = vendor/glfw
|
||||
url = https://github.com/glfw/glfw.git
|
||||
[submodule "vendor/eternal"]
|
||||
path = vendor/eternal
|
||||
url = https://github.com/mapbox/eternal.git
|
||||
[submodule "platform/android/vendor/mapbox-gestures-android"]
|
||||
path = platform/android/vendor/mapbox-gestures-android
|
||||
url = https://github.com/mapbox/mapbox-gestures-android.git
|
||||
[submodule "platform/android/vendor/mapbox-java"]
|
||||
path = platform/android/vendor/mapbox-java
|
||||
url = https://github.com/mapbox/mapbox-java.git
|
||||
[submodule "platform/android/vendor/mapbox-events-android"]
|
||||
path = platform/android/vendor/mapbox-events-android
|
||||
url = https://github.com/mapbox/mapbox-events-android.git
|
||||
[submodule "platform/darwin/docs/theme"]
|
||||
path = platform/darwin/docs/theme
|
||||
url = https://github.com/mapbox/jazzy-theme.git
|
||||
[submodule "vendor/mvt-fixtures"]
|
||||
path = vendor/mvt-fixtures
|
||||
url = https://github.com/mapbox/mvt-fixtures.git
|
||||
[submodule "vendor/mapbox-gl-styles"]
|
||||
path = vendor/mapbox-gl-styles
|
||||
url = https://github.com/mapbox/mapbox-gl-styles.git
|
||||
[submodule "vendor/mapbox-base"]
|
||||
path = vendor/mapbox-base
|
||||
url = https://github.com/mapbox/mapbox-base.git
|
||||
[submodule "vendor/googletest"]
|
||||
path = vendor/googletest
|
||||
url = https://github.com/google/googletest.git
|
||||
|
||||
17
.topissuesrc
17
.topissuesrc
@@ -1,17 +0,0 @@
|
||||
{
|
||||
"labels": {
|
||||
"release blocker": 25,
|
||||
"beta blocker": 20,
|
||||
"crash": 5,
|
||||
"build": 5,
|
||||
"bug": 2
|
||||
},
|
||||
"reactions": {
|
||||
"+1": 1,
|
||||
"-1": -1,
|
||||
"laugh": 1,
|
||||
"hooray": 1,
|
||||
"confused": 1,
|
||||
"heart": 1
|
||||
}
|
||||
}
|
||||
@@ -1,128 +0,0 @@
|
||||
# Version of .ycm_extra_conf.py sample file adapted
|
||||
# for the Mapbox GL Native project.
|
||||
#
|
||||
# This file is NOT licensed under the GPLv3, which is the license for the rest
|
||||
# of YouCompleteMe.
|
||||
#
|
||||
# Here's the license text for this file:
|
||||
#
|
||||
# This is free and unencumbered software released into the public domain.
|
||||
#
|
||||
# Anyone is free to copy, modify, publish, use, compile, sell, or
|
||||
# distribute this software, either in source code form or as a compiled
|
||||
# binary, for any purpose, commercial or non-commercial, and by any
|
||||
# means.
|
||||
#
|
||||
# In jurisdictions that recognize copyright laws, the author or authors
|
||||
# of this software dedicate any and all copyright interest in the
|
||||
# software to the public domain. We make this dedication for the benefit
|
||||
# of the public at large and to the detriment of our heirs and
|
||||
# successors. We intend this dedication to be an overt act of
|
||||
# relinquishment in perpetuity of all present and future rights to this
|
||||
# software under copyright law.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
# IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
||||
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
# OTHER DEALINGS IN THE SOFTWARE.
|
||||
#
|
||||
# For more information, please refer to <http://unlicense.org/>
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import string
|
||||
import ycm_core
|
||||
|
||||
compilation_database_folders = [
|
||||
'build/linux-x86_64/Debug',
|
||||
'build/qt-linux-x86_64/Debug',
|
||||
'build/qt4-linux-x86_64/Debug',
|
||||
'build/macos/compdb/Debug',
|
||||
]
|
||||
|
||||
subprocess.call(['make compdb'], shell=True)
|
||||
|
||||
for folder in compilation_database_folders:
|
||||
if os.path.exists( folder ):
|
||||
database = ycm_core.CompilationDatabase( folder )
|
||||
|
||||
SOURCE_EXTENSIONS = [ '.cpp', '.cxx', '.cc', '.c', '.m', '.mm' ]
|
||||
|
||||
|
||||
def DirectoryOfThisScript():
|
||||
return os.path.dirname( os.path.abspath( __file__ ) )
|
||||
|
||||
|
||||
def MakeRelativePathsInFlagsAbsolute( flags, working_directory ):
|
||||
if not working_directory:
|
||||
return list( flags )
|
||||
new_flags = []
|
||||
make_next_absolute = False
|
||||
path_flags = [ '-isystem', '-I', '-iquote', '--sysroot=' ]
|
||||
for flag in flags:
|
||||
new_flag = flag
|
||||
|
||||
if make_next_absolute:
|
||||
make_next_absolute = False
|
||||
if not flag.startswith( '/' ):
|
||||
new_flag = os.path.join( working_directory, flag )
|
||||
|
||||
for path_flag in path_flags:
|
||||
if flag == path_flag:
|
||||
make_next_absolute = True
|
||||
break
|
||||
|
||||
if flag.startswith( path_flag ):
|
||||
path = flag[ len( path_flag ): ]
|
||||
new_flag = path_flag + os.path.join( working_directory, path )
|
||||
break
|
||||
|
||||
if new_flag:
|
||||
new_flags.append( new_flag )
|
||||
return new_flags
|
||||
|
||||
|
||||
def IsHeaderFile( filename ):
|
||||
extension = os.path.splitext( filename )[ 1 ]
|
||||
return extension in [ '.h', '.hxx', '.hpp', '.hh' ]
|
||||
|
||||
|
||||
def GetCompilationInfoForFile( filename ):
|
||||
# The compilation_commands.json file generated by CMake does not have entries
|
||||
# for header files. So we do our best by asking the db for flags for a
|
||||
# corresponding source file, if any. If one exists, the flags for that file
|
||||
# should be good enough.
|
||||
if IsHeaderFile( filename ):
|
||||
basename = os.path.splitext( filename )[ 0 ]
|
||||
for extension in SOURCE_EXTENSIONS:
|
||||
replacement_file = basename + extension
|
||||
if os.path.exists( replacement_file ):
|
||||
compilation_info = database.GetCompilationInfoForFile(
|
||||
replacement_file )
|
||||
if compilation_info.compiler_flags_:
|
||||
return compilation_info
|
||||
return None
|
||||
return database.GetCompilationInfoForFile( filename )
|
||||
|
||||
|
||||
def FlagsForFile( filename, **kwargs ):
|
||||
if not database:
|
||||
return None
|
||||
|
||||
# Bear in mind that compilation_info.compiler_flags_ does NOT return a
|
||||
# python list, but a "list-like" StringVec object
|
||||
compilation_info = GetCompilationInfoForFile( filename )
|
||||
if not compilation_info:
|
||||
return None
|
||||
|
||||
final_flags = MakeRelativePathsInFlagsAbsolute(
|
||||
compilation_info.compiler_flags_,
|
||||
compilation_info.compiler_working_dir_ )
|
||||
|
||||
return {
|
||||
'flags': final_flags,
|
||||
'do_cache': True
|
||||
}
|
||||
121
ARCHITECTURE.md
121
ARCHITECTURE.md
@@ -1,121 +0,0 @@
|
||||
This document aims to outline at a high level the various parts that make up mapbox-gl-native and how they work together.
|
||||
|
||||
# Repository structure
|
||||
|
||||
mapbox-gl-native uses a monolithic that houses both core C++ code and code that wraps the C++ core with SDKs for Android, iOS, macOS, Node.js, and Qt. A "monorepo" allows us to:
|
||||
|
||||
* Make changes to the core API and SDKs simultaneously, ensuring no platform falls behind.
|
||||
* Ensure that core changes do not inadvertently break SDK tests.
|
||||
* Centralize discussions about features and defects that affect multiple platforms.
|
||||
|
||||
In the repository, core C++ code is contained in the `include` and `src` directories. The former includes headers that are considered to make up the "public" core C++ API, while the latter includes `.cpp` implementation files and headers that are private to the implementation. Within both directories, files are nested under an `mbgl` directory, which has various subdirectories based on areas of functionality. Both public and private headers therefore can (and should) always be included with the form `#include <mbgl/___/___.hpp>`.
|
||||
|
||||
Code and build scripts belonging to platform SDKs are contained in the `platform` directory, which has subdirectories for each platform. The `platform/darwin` and `platform/default` directories contain code shared by multiple platform SDKs.
|
||||
|
||||
# Build system
|
||||
|
||||
The mapbox-gl-native build system uses a variety of tools.
|
||||
|
||||
## Make
|
||||
|
||||
GNU Make and a master `Makefile` serves as the coordinating tool for all other build system tools. Most of your interaction with the build system will be via `make` commands. We aim to have a consistent pattern for make targets across platforms: for a given platform, e.g. `ios`, `make ios` builds a reasonable set of end products (though perhaps not all permutations of build options, which can be prohibitively expensive), and `make ios-test` runs a complete test suite for the platform.
|
||||
|
||||
## Git submodules
|
||||
|
||||
Git submodules are used to pull in several dependencies: mason (see below) and several iOS dependencies (though we have plans to phase these out). Initializing these submodules is handled automatically by the necessary `make` targets.
|
||||
|
||||
## npm
|
||||
|
||||
npm is a package manager for Node.js. mapbox-gl-native uses it to pull in several development dependencies that happen to be packaged as node modules -- mainly for testing needs.
|
||||
|
||||
## Mason
|
||||
|
||||
[Mason](https://github.com/mapbox/mason) is Mapbox's own cross platform C/C++ package manager. mapbox-gl-native uses mason packages as a source of precompiled binaries for third-party dependencies such as Boost, RapidJSON, and SQLite, and Mapbox's own C++ modules such as [earcut.hpp](https://github.com/mapbox/earcut.hpp) and [geojson-vt-cpp](https://github.com/mapbox/geojson-vt-cpp). It is also used to obtain a toolchain for Android platform cross-compiliation.
|
||||
|
||||
We track mason dependencies for a given platform in the file `platform/<platform>/scripts/configure.sh`. The `configure` script at the root handles sourcing this file during the build, running the appropriate mason commands, and writing configuration settings for the subsequent build to a `config.gypi` in the build output directory.
|
||||
|
||||
## gyp
|
||||
|
||||
[gyp](https://gyp.gsrc.io/) is a build system originally created for Chromium and since adopted by Node.js. In mapbox-gl-native it's used to build the core C++ static library, the Node.js platform module, and the shared JNI module for Android.
|
||||
|
||||
## Platform-specific subsystems
|
||||
|
||||
Outside of the core C++ static library, platform SDKs typically rely on platform-native build tooling to complete the job.
|
||||
|
||||
* For iOS and macOS this means Xcode and the xcodebuild command line tool.
|
||||
* For Android, Gradle and Android Studio.
|
||||
* For Qt, `qmake`.
|
||||
|
||||
See the relevant platform-specific `README.md` / `INSTALL.md` for details.
|
||||
|
||||
# Major functional components
|
||||
|
||||
## Map
|
||||
## Style
|
||||
|
||||
The "Style" component of mapbox-gl-native contains an implementation of the [Mapbox Style Specification](https://www.mapbox.com/mapbox-gl-style-spec/), defining what data to draw, the order to draw it in, and how to style the data when drawing it.
|
||||
|
||||
In addition to supporting styles loaded from a URL, mapbox-gl-native includes a runtime styling API, which allows users to dynamically modify the current style: add and remove layers, modify layer properties, and so on. As appropriate for a C++ API, the runtime styling API API is _strongly typed_: there are subclasses for each layer type, with correctly-typed accessors for each style property. This results in a large API surface area. Fortunately, this is automated, by generating the API – and the regular portion of the implementation – from the style specification.
|
||||
|
||||
The layers API makes a distinction between public API and internal implementation using [the `Impl` idiom](https://github.com/mapbox/mapbox-gl-native/issues/3254) seen elsewhere in the codebase. Here, it takes the form of parallel class hierarchies:
|
||||
|
||||
* `Layer`, `Source`, and their subclasses form the public API. This is the API consumed by SDK bindings.
|
||||
* `Layer::Impl`, `Source::Impl`, and their subclasses form the internal API. This API is used only by other parts of the core C++ implementation.
|
||||
|
||||
For each subclass of `Layer` or source, there's a corresponding `Impl` subclass. For example, `CircleLayer` and `CircleLayer::Impl`. The base `Layer` class holds a reference to the base `Layer::Impl`, and `CircleLayer` and other subclasses have an `impl()` accessor method that casts this reference to the appropriate subtype.
|
||||
|
||||
## Immutability
|
||||
|
||||
The `Layer::Impl` and `Source::Impl` reference held by `Layer` and `Source` base classes is _immutable_: it's a shared reference to a `const` (read only) pointer. Immutability permits the `Impl` objects to be shared safely between threads when needed -- for example, between the main thread and worker thread that performs computation in the background, or between the main thread and a dedicated renderer thread. See the "Threading" section below for further details on the threading model.
|
||||
|
||||
Immutability is an alternative to several other strategies for safe intra-thread communication. One alternative strategy is to insert locks whenever data is shared between threads and at least one thread may be modifying the data. This strategy is prone to problems such as race conditions (if you forget to use a lock), deadlocks (if locks are acquired in conflicting orders), and poor performance due to lock contention. Another strategy is to copy data whenever it's needed by another thread. For complex structures such as a Mapbox Style, copying can be an expensive operation. With immutability, the approach is to share data without copying, but ensure that any data so shared cannot be modified by any thread, and that the data is not destroyed until the last thread using it relinquishes its reference.
|
||||
|
||||
Immutability is implemented by the `Immutable<T>` template, which acts as a non-nullable shared reference to a `const T`. It has behavior similar to `std::shared_ptr<const T>`, but indicates its intent as an immutable reference that is safe to share between threads.
|
||||
|
||||
Immutability is core to the implementation, and yet one of the defining features of Mapbox GL is the ability to manipulate and mutate the style freely at runtime. How can this be possible if everything is immutable? The answer turns on the distinction mentioned in the previous section between public classes such as `Layer` and private implementations such as `Layer::Impl`. In Mapbox GL, the latter is immutable, but the former is not:
|
||||
|
||||
* **Mutable objects**: `Layer`, `Source`, `Image`, `Light`
|
||||
* **Immutable objects**: `Layer::Impl`, `Source::Impl`, `Image::Impl`, `Light::Impl`
|
||||
|
||||
An instance of a `Layer` subclass such as `CircleLayer` has a reference to an `Immutable<Layer::Impl>`, but is itself mutable -- it has mutating methods such as `setCircleRadius`. Such methods follow a common pattern:
|
||||
|
||||
* Create a new instance of the Impl, copied from the existing Impl. This new instance is temporarily mutable.
|
||||
* Modify this new instance as needed; e.g. set the radius to a new value.
|
||||
* "Freeze" the new instance by making it immutable, and then assign that immutable reference to be the new Impl for the `Layer`.
|
||||
|
||||
Two things to note about this process:
|
||||
|
||||
* No existing Impls are modified -- only the newly created copy.
|
||||
* Only one existing reference to an Impl is modified -- the one held by the `Layer` instance being mutated. Any references to the previous Impl held by other threads remain unchanged. They go on using the previous value for radius until notified by some other means that there has been a change.
|
||||
|
||||
So how do things that are holding references to the previous Impl get notified? The answer is **style diffing**. This is the process by which we determine, from one frame to the next, what parts of the style have changed and therefore what needs to be recalculated in response to those changes in order to draw an updated frame. In parallel to style objects such as `Style`, `Layer`, `Source` and so on, Mapbox GL maintains render objects such as `RenderStyle`, `RenderLayer`, `RenderSource` and so on. These render objects:
|
||||
|
||||
* are mutable
|
||||
* may live on either the main thread or an independent rendering thread, depending on the SDK
|
||||
* contain any and all values calculated from the style objects plus state such as the current zoom level and location -- for example, the set of loaded tiles and the buckets calculated from them
|
||||
|
||||
From one frame to the next, these render objects are updated based on the current state of the style objects. In order to permit the render objects to live on a different thread, this state is communicated as immutable Impl references -- in effect, a snapshot of the style state at the time the frame was requested. And it really is a just snapshot -- we don't communicate things like "the radius of this circle layer was changed", "this layer was removed", etc. Instead, that information is reconstructed by `RenderStyle` by comparing the new snapshot to the old snapshot. Immutability allows us to perform this comparison very efficiently:
|
||||
|
||||
* If the "before" and "after" of two immutable references refer to the same object, we know that it hasn't changed. If they're different, we know it has changed in some way.
|
||||
* We can calculate changes in collections of immutable references (a list of layers or sources) using an efficient [diff algorithm](http://www.xmailserver.org/diff2.pdf). We can further improve this efficiency by making the collections themselves immutable, so that we can avoid running the diff algorithm altogether in the common case where the "before" and "after" collections refer to the same immutable object.
|
||||
|
||||
One final benefit of this approach of diffing immutable objects: we get "smart" updates between two completely independent styles essentially for free. For example, `RenderStyle` doesn't care if the "before" snapshot is from the Mapbox Light style and the "after" snapshot is from the Mapbox Dark style. It will just calculate the difference between the two snapshots, update render data where necessary, and render the next frame. Since those two styles use the same source data and layer IDs, the result will be a fully automatic, seamless transition between light and dark.
|
||||
|
||||
## FileSource
|
||||
## Layout
|
||||
## Rendering
|
||||
## Annotations
|
||||
|
||||
# Threading
|
||||
|
||||
At runtime, mapbox-gl-native uses the following threads:
|
||||
|
||||
* The "main thread" (or other thread on which a `Map` object is created) handles direct `Map` API requests, owns the active `Style` and its associated objects, and renders the map. Since this thread is usually dispatching events triggered by user input, it's important that these duties not require significant computation or perform blocking I/O that would cause UI jank or hangs.
|
||||
* Many of the tasks that require significant computation are associated with layout and styling of map features: parsing vector tiles, computing text layout, and generating data buffers to be consumed by OpenGL. This work happens on "worker threads" that are spawned by the main thread, four per `Style` object. The `Style` and its associated objects handle dispatching tasks to the workers, typically on a tile-by-tile basis.
|
||||
* A "FileSource" thread handles network requests for styles, tiles, and other resources, and I/O on the SQLite database used for offline maps and caching. Requests originate from the main thread, are dispatched by a FileSource internally to its thread, and results are returned to the main thread via an asynchronous callback function. (This is implemented with platform-specific hooks into the native message pump for the requesting thread.)
|
||||
|
||||
To minimize data races and invalid memory access, we aim for zero shared memory state between any two threads. Cross-thread communication occurs via one thread requesting the "invocation" of a task on another thread. The parameters for this task should be passed as value objects, so that they are copied, or as ownership-transferring values such as `std::unique_ptr`. (We're [not entirely there yet](https://github.com/mapbox/mapbox-gl-native/issues/667), but that's the goal.) The result (if any) is likewise passed as a value or ownership-transferring parameter to the callback function.
|
||||
|
||||
Invoking a task on another thread itself creates an ownership obligation: the responsibility for the work happening on the other thread. This ownership is represented by the invocation method returning `std::unique_ptr<AsyncTask>`. Destroying this object indicates that the result of the task is no longer required: the callback is guaranteed not to be called, and the work on the other thread may be aborted (if doing so is convenient).
|
||||
|
||||
All this is implemented by [Thread](https://github.com/mapbox/mapbox-gl-native/blob/master/src/mbgl/util/thread.hpp) and [RunLoop](https://github.com/mapbox/mapbox-gl-native/blob/master/include/mbgl/util/run_loop.hpp).
|
||||
90
appveyor.yml
90
appveyor.yml
@@ -1,90 +0,0 @@
|
||||
platform: x64
|
||||
|
||||
image:
|
||||
- Visual Studio 2015
|
||||
- Visual Studio 2017
|
||||
|
||||
environment:
|
||||
PYTHON: C:\python37
|
||||
|
||||
matrix:
|
||||
- configuration: Release
|
||||
- configuration: Debug
|
||||
|
||||
test: off
|
||||
|
||||
clone_depth: 1
|
||||
|
||||
for:
|
||||
-
|
||||
matrix:
|
||||
only:
|
||||
- image: Visual Studio 2015
|
||||
|
||||
environment:
|
||||
LLVM_VERSION: 5.0.1
|
||||
LLVM_HASH: 981543611D719624ACB29A2CFFD6A479CFF36E8AB5EE8A57D8ECA4F9C4C6956F
|
||||
VCVARSALL: 'C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat'
|
||||
QT_PREFIX: 'C:\Qt\latest\msvc2015_64\lib\cmake'
|
||||
|
||||
-
|
||||
matrix:
|
||||
only:
|
||||
- image: Visual Studio 2017
|
||||
|
||||
environment:
|
||||
LLVM_VERSION: 7.0.0
|
||||
LLVM_HASH: 74b197a3959b0408adf0824be01db8dddfa2f9a967f4085af3fad900ed5fdbf6
|
||||
VCVARSALL: 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvarsall.bat'
|
||||
QT_PREFIX: 'C:\Qt\latest\msvc2017_64\lib\cmake'
|
||||
|
||||
cache:
|
||||
- '%APPVEYOR_BUILD_FOLDER%\.git\modules'
|
||||
- '%APPVEYOR_BUILD_FOLDER%\LLVM-%LLVM_VERSION%-win64.exe'
|
||||
- '%APPVEYOR_BUILD_FOLDER%\cmake-3.10.1-win64-x64.zip'
|
||||
- C:\clcache
|
||||
|
||||
install:
|
||||
- set PATH=%PYTHON%\Scripts;%PYTHON%;%PATH%
|
||||
- pip install clcache
|
||||
- git config --system core.longpaths true
|
||||
- git submodule sync
|
||||
- git submodule update --init
|
||||
- git submodule foreach git submodule update --init
|
||||
- ps: |
|
||||
if (!(Test-Path "LLVM-$env:LLVM_VERSION-win64.exe")) {
|
||||
appveyor DownloadFile "https://releases.llvm.org/$env:LLVM_VERSION/LLVM-$env:LLVM_VERSION-win64.exe"
|
||||
}
|
||||
scripts\check-sha256.ps1 LLVM-$env:LLVM_VERSION-win64.exe "$env:LLVM_HASH"
|
||||
Start-Process -FilePath "LLVM-$env:LLVM_VERSION-win64.exe" -ArgumentList '/S',"/D=C:\LLVM-$env:LLVM_VERSION" -Wait
|
||||
- ps: |
|
||||
if (!(Test-Path cmake-3.10.1-win64-x64.zip)) {
|
||||
appveyor DownloadFile https://cmake.org/files/v3.10/cmake-3.10.1-win64-x64.zip
|
||||
}
|
||||
scripts\check-sha256.ps1 cmake-3.10.1-win64-x64.zip 8251F70C85B58F3CA1F24E4A3B0637E2D609B5E4A341D00B70E02E89244D5029
|
||||
Start-Process -FilePath '7z' -ArgumentList 'x','cmake-3.10.1-win64-x64.zip','-oC:\' -Wait
|
||||
|
||||
before_build:
|
||||
- set PATH=C:\LLVM-%LLVM_VERSION%\bin;%PATH%
|
||||
- set PATH=C:\cmake-3.10.1-win64-x64\bin;%PATH%
|
||||
- set CLCACHE_DIR=c:\clcache
|
||||
- set CLCACHE_CL=clang-cl
|
||||
- clcache -z
|
||||
- set CC=clcache
|
||||
- set CXX=clcache
|
||||
- set CTEST_OUTPUT_ON_FAILURE=1
|
||||
- mkdir %APPVEYOR_BUILD_FOLDER%\build
|
||||
- cd %APPVEYOR_BUILD_FOLDER%\build
|
||||
|
||||
build_script:
|
||||
- call "%VCVARSALL%" amd64
|
||||
- cmake -E remove ../next/vendor
|
||||
- cmake -E copy_directory ../vendor ../next/vendor
|
||||
- cmake -G "Ninja"
|
||||
-DCMAKE_BUILD_TYPE=%CONFIGURATION%
|
||||
-DCMAKE_MAKE_PROGRAM="%APPVEYOR_BUILD_FOLDER%\platform\qt\ninja.exe"
|
||||
-DCMAKE_PREFIX_PATH=%QT_PREFIX%
|
||||
-DMBGL_WITH_QT=ON
|
||||
../next
|
||||
- cmake --build . --target qmapboxgl -- -j %NUMBER_OF_PROCESSORS%
|
||||
- clcache -s
|
||||
@@ -1,67 +0,0 @@
|
||||
#include <benchmark/benchmark.h>
|
||||
|
||||
#include <mbgl/map/map.hpp>
|
||||
#include <mbgl/map/map_options.hpp>
|
||||
#include <mbgl/gfx/headless_frontend.hpp>
|
||||
#include <mbgl/renderer/renderer.hpp>
|
||||
#include <mbgl/style/style.hpp>
|
||||
#include <mbgl/style/image.hpp>
|
||||
#include <mbgl/storage/network_status.hpp>
|
||||
#include <mbgl/util/image.hpp>
|
||||
#include <mbgl/util/io.hpp>
|
||||
#include <mbgl/util/run_loop.hpp>
|
||||
|
||||
using namespace mbgl;
|
||||
|
||||
namespace {
|
||||
|
||||
class QueryBenchmark {
|
||||
public:
|
||||
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<style::Image>("test-icon",
|
||||
decodeImage(util::read_file("benchmark/fixtures/api/default_marker.png")), 1.0));
|
||||
|
||||
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(".").withAccessToken("foobar") };
|
||||
ScreenBox box{{ 0, 0 }, { 1000, 1000 }};
|
||||
};
|
||||
|
||||
} // end namespace
|
||||
|
||||
static void API_queryRenderedFeaturesAll(::benchmark::State& state) {
|
||||
QueryBenchmark bench;
|
||||
|
||||
while (state.KeepRunning()) {
|
||||
bench.frontend.getRenderer()->queryRenderedFeatures(bench.box, {});
|
||||
}
|
||||
}
|
||||
|
||||
static void API_queryRenderedFeaturesLayerFromLowDensity(::benchmark::State& state) {
|
||||
QueryBenchmark bench;
|
||||
|
||||
while (state.KeepRunning()) {
|
||||
bench.frontend.getRenderer()->queryRenderedFeatures(bench.box, {{{ "testlayer" }}, {}});
|
||||
}
|
||||
}
|
||||
|
||||
static void API_queryRenderedFeaturesLayerFromHighDensity(::benchmark::State& state) {
|
||||
QueryBenchmark bench;
|
||||
|
||||
while (state.KeepRunning()) {
|
||||
bench.frontend.getRenderer()->queryRenderedFeatures(bench.box, {{{"road-street" }}, {}});
|
||||
}
|
||||
}
|
||||
|
||||
BENCHMARK(API_queryRenderedFeaturesAll);
|
||||
BENCHMARK(API_queryRenderedFeaturesLayerFromLowDensity);
|
||||
BENCHMARK(API_queryRenderedFeaturesLayerFromHighDensity);
|
||||
@@ -1,136 +0,0 @@
|
||||
#include <benchmark/benchmark.h>
|
||||
|
||||
#include <mbgl/gfx/headless_frontend.hpp>
|
||||
#include <mbgl/map/map.hpp>
|
||||
#include <mbgl/map/map_observer.hpp>
|
||||
#include <mbgl/map/map_options.hpp>
|
||||
#include <mbgl/renderer/renderer.hpp>
|
||||
#include <mbgl/storage/network_status.hpp>
|
||||
#include <mbgl/storage/resource_options.hpp>
|
||||
#include <mbgl/style/image.hpp>
|
||||
#include <mbgl/style/layers/symbol_layer.hpp>
|
||||
#include <mbgl/style/sources/geojson_source.hpp>
|
||||
#include <mbgl/style/style.hpp>
|
||||
#include <mbgl/util/image.hpp>
|
||||
#include <mbgl/util/io.hpp>
|
||||
#include <mbgl/util/run_loop.hpp>
|
||||
|
||||
#include <sstream>
|
||||
|
||||
using namespace mbgl;
|
||||
|
||||
namespace {
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
util::RunLoop loop;
|
||||
};
|
||||
|
||||
static void prepare(Map& map, optional<std::string> json = {}) {
|
||||
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
|
||||
|
||||
auto image = decodeImage(util::read_file("benchmark/fixtures/api/default_marker.png"));
|
||||
map.getStyle().addImage(std::make_unique<style::Image>("test-icon", std::move(image), 1.0));
|
||||
}
|
||||
|
||||
} // end namespace
|
||||
|
||||
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).withAccessToken("foobar") };
|
||||
prepare(map);
|
||||
|
||||
while (state.KeepRunning()) {
|
||||
frontend.render(map);
|
||||
}
|
||||
}
|
||||
|
||||
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).withAccessToken("foobar") };
|
||||
prepare(map, util::read_file("benchmark/fixtures/api/style_formatted_labels.json"));
|
||||
|
||||
while (state.KeepRunning()) {
|
||||
frontend.render(map);
|
||||
}
|
||||
}
|
||||
|
||||
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).withAccessToken("foobar") };
|
||||
|
||||
while (state.KeepRunning()) {
|
||||
prepare(map, { "{}" });
|
||||
frontend.render(map);
|
||||
prepare(map);
|
||||
frontend.render(map);
|
||||
}
|
||||
}
|
||||
|
||||
static void API_renderStill_recreate_map(::benchmark::State& state) {
|
||||
RenderBenchmark bench;
|
||||
|
||||
while (state.KeepRunning()) {
|
||||
HeadlessFrontend frontend { size, pixelRatio };
|
||||
Map map { frontend, MapObserver::nullObserver(),
|
||||
MapOptions().withMapMode(MapMode::Static).withSize(size).withPixelRatio(pixelRatio),
|
||||
ResourceOptions().withCachePath(cachePath).withAccessToken("foobar") };
|
||||
prepare(map);
|
||||
frontend.render(map);
|
||||
}
|
||||
}
|
||||
|
||||
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).withAccessToken("foobar")};
|
||||
prepare(map);
|
||||
auto& style = map.getStyle();
|
||||
const int kSourcesCount = 50;
|
||||
const int kLayersCount = 50;
|
||||
for (int i = 0; i < kSourcesCount; ++i) {
|
||||
std::ostringstream sourceOss;
|
||||
sourceOss << "GeoJSONSource" << i;
|
||||
std::string sourceId{sourceOss.str()};
|
||||
auto source = std::make_unique<GeoJSONSource>(sourceId);
|
||||
style.addSource(std::move(source));
|
||||
for (int j = 0; j < kLayersCount; ++j) {
|
||||
std::ostringstream layerOss;
|
||||
layerOss << sourceId << '#' << j;
|
||||
auto layer = std::make_unique<SymbolLayer>(layerOss.str(), sourceId);
|
||||
style.addLayer(std::move(layer));
|
||||
}
|
||||
}
|
||||
|
||||
while (state.KeepRunning()) {
|
||||
frontend.render(map);
|
||||
}
|
||||
}
|
||||
|
||||
BENCHMARK(API_renderStill_reuse_map);
|
||||
BENCHMARK(API_renderStill_reuse_map_formatted_labels);
|
||||
BENCHMARK(API_renderStill_reuse_map_switch_styles);
|
||||
BENCHMARK(API_renderStill_recreate_map);
|
||||
BENCHMARK(API_renderStill_multiple_sources);
|
||||
@@ -1,23 +0,0 @@
|
||||
{
|
||||
"//": "This file is generated. Do not edit. Regenerate it with scripts/generate-file-lists.js",
|
||||
"sources": [
|
||||
"benchmark/api/query.benchmark.cpp",
|
||||
"benchmark/api/render.benchmark.cpp",
|
||||
"benchmark/function/camera_function.benchmark.cpp",
|
||||
"benchmark/function/composite_function.benchmark.cpp",
|
||||
"benchmark/function/source_function.benchmark.cpp",
|
||||
"benchmark/parse/filter.benchmark.cpp",
|
||||
"benchmark/parse/tile_mask.benchmark.cpp",
|
||||
"benchmark/parse/vector_tile.benchmark.cpp",
|
||||
"benchmark/src/mbgl/benchmark/benchmark.cpp",
|
||||
"benchmark/storage/offline_database.benchmark.cpp",
|
||||
"benchmark/util/dtoa.benchmark.cpp",
|
||||
"benchmark/util/tilecover.benchmark.cpp"
|
||||
],
|
||||
"public_headers": {
|
||||
"mbgl/benchmark.hpp": "benchmark/include/mbgl/benchmark.hpp"
|
||||
},
|
||||
"private_headers": {
|
||||
"mbgl/benchmark/stub_geometry_tile_feature.hpp": "benchmark/src/mbgl/benchmark/stub_geometry_tile_feature.hpp"
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
|
Before Width: | Height: | Size: 1010 B |
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,61 +0,0 @@
|
||||
#include <benchmark/benchmark.h>
|
||||
|
||||
#include <mbgl/style/conversion/json.hpp>
|
||||
#include <mbgl/style/conversion/function.hpp>
|
||||
#include <mbgl/style/conversion/property_value.hpp>
|
||||
#include <mbgl/style/conversion_impl.hpp>
|
||||
|
||||
using namespace mbgl;
|
||||
using namespace mbgl::style;
|
||||
|
||||
static std::string createFunctionJSON(size_t stopCount) {
|
||||
std::string stops = "[";
|
||||
for (size_t i = 0; i < stopCount; i++) {
|
||||
std::string value = std::to_string(24.0f / stopCount * i);
|
||||
if (stops.size() > 1) stops += ",";
|
||||
stops += "[" + value + ", " + value + "]";
|
||||
}
|
||||
stops += "]";
|
||||
return R"({"type": "exponential", "base": 2, "stops": )" + stops + "}";
|
||||
}
|
||||
|
||||
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();
|
||||
optional<PropertyValue<float>> result = conversion::convertJSON<PropertyValue<float>>(doc, error, false, false);
|
||||
if (!result) {
|
||||
state.SkipWithError(error.message.c_str());
|
||||
}
|
||||
}
|
||||
state.SetLabel(std::to_string(stopCount).c_str());
|
||||
}
|
||||
|
||||
static void Evaluate_CameraFunction(benchmark::State& state) {
|
||||
size_t stopCount = state.range(0);
|
||||
auto doc = createFunctionJSON(stopCount);
|
||||
conversion::Error error;
|
||||
optional<PropertyValue<float>> function = conversion::convertJSON<PropertyValue<float>>(doc, error, false, false);
|
||||
if (!function) {
|
||||
state.SkipWithError(error.message.c_str());
|
||||
}
|
||||
|
||||
while(state.KeepRunning()) {
|
||||
float z = 24.0f * static_cast<float>(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);
|
||||
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
#include <benchmark/benchmark.h>
|
||||
|
||||
#include <mbgl/benchmark/stub_geometry_tile_feature.hpp>
|
||||
|
||||
#include <mbgl/style/conversion/json.hpp>
|
||||
#include <mbgl/style/conversion/function.hpp>
|
||||
#include <mbgl/style/conversion/property_value.hpp>
|
||||
#include <mbgl/style/conversion_impl.hpp>
|
||||
|
||||
using namespace mbgl;
|
||||
using namespace mbgl::style;
|
||||
|
||||
static std::string createFunctionJSON(size_t stopCount) {
|
||||
std::string stops = "[";
|
||||
for (size_t outerStop = 0; outerStop < stopCount; outerStop++) {
|
||||
for (size_t innerStop = 0; innerStop < stopCount; innerStop++) {
|
||||
std::string zoom = std::to_string(24.0f / stopCount * outerStop);
|
||||
std::string value = std::to_string(100.0f / stopCount * innerStop);
|
||||
|
||||
if (stops.size() > 1) stops += ",";
|
||||
stops += R"([{"zoom":)" + zoom + R"(,"value":)" + value + "}, " + value + "]";
|
||||
}
|
||||
}
|
||||
stops += "]";
|
||||
return R"({"type": "exponential", "base": 2, "stops": )" + stops + R"(, "property": "x"})";
|
||||
}
|
||||
|
||||
static void Parse_CompositeFunction(benchmark::State& state) {
|
||||
size_t stopCount = state.range(0);
|
||||
|
||||
while (state.KeepRunning()) {
|
||||
conversion::Error error;
|
||||
state.PauseTiming();
|
||||
auto doc = createFunctionJSON(stopCount);
|
||||
state.ResumeTiming();
|
||||
optional<PropertyValue<float>> result = conversion::convertJSON<PropertyValue<float>>(doc, error, true, false);
|
||||
if (!result) {
|
||||
state.SkipWithError(error.message.c_str());
|
||||
}
|
||||
}
|
||||
state.SetLabel(std::to_string(stopCount).c_str());
|
||||
}
|
||||
|
||||
static void Evaluate_CompositeFunction(benchmark::State& state) {
|
||||
size_t stopCount = state.range(0);
|
||||
auto doc = createFunctionJSON(stopCount);
|
||||
conversion::Error error;
|
||||
optional<PropertyValue<float>> function = conversion::convertJSON<PropertyValue<float>>(doc, error, true, false);
|
||||
if (!function) {
|
||||
state.SkipWithError(error.message.c_str());
|
||||
}
|
||||
|
||||
while(state.KeepRunning()) {
|
||||
float z = 24.0f * static_cast<float>(rand() % 100) / 100;
|
||||
function->asExpression().evaluate(z, StubGeometryTileFeature(PropertyMap { { "x", static_cast<int64_t>(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);
|
||||
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
#include <benchmark/benchmark.h>
|
||||
|
||||
#include <mbgl/benchmark/stub_geometry_tile_feature.hpp>
|
||||
|
||||
#include <mbgl/style/conversion/json.hpp>
|
||||
#include <mbgl/style/conversion/property_value.hpp>
|
||||
#include <mbgl/style/conversion_impl.hpp>
|
||||
|
||||
using namespace mbgl;
|
||||
using namespace mbgl::style;
|
||||
|
||||
static std::string createFunctionJSON(size_t stopCount) {
|
||||
std::string stops = "[";
|
||||
for (size_t i = 0; i < stopCount; i++) {
|
||||
std::string value = std::to_string(100.0f / stopCount * i);
|
||||
if (stops.size() > 1) stops += ",";
|
||||
stops += "[" + value + ", " + value + "]";
|
||||
}
|
||||
stops += "]";
|
||||
return R"({"type": "exponential", "base": 2, "stops": )" + stops + R"(, "property": "x"})";
|
||||
}
|
||||
|
||||
static void Parse_SourceFunction(benchmark::State& state) {
|
||||
size_t stopCount = state.range(0);
|
||||
|
||||
while (state.KeepRunning()) {
|
||||
conversion::Error error;
|
||||
state.PauseTiming();
|
||||
auto doc = createFunctionJSON(stopCount);
|
||||
state.ResumeTiming();
|
||||
optional<PropertyValue<float>> result = conversion::convertJSON<PropertyValue<float>>(doc, error, true, false);
|
||||
if (!result) {
|
||||
state.SkipWithError(error.message.c_str());
|
||||
}
|
||||
}
|
||||
state.SetLabel(std::to_string(stopCount).c_str());
|
||||
}
|
||||
|
||||
static void Evaluate_SourceFunction(benchmark::State& state) {
|
||||
size_t stopCount = state.range(0);
|
||||
auto doc = createFunctionJSON(stopCount);
|
||||
conversion::Error error;
|
||||
optional<PropertyValue<float>> function = conversion::convertJSON<PropertyValue<float>>(doc, error, true, false);
|
||||
if (!function) {
|
||||
state.SkipWithError(error.message.c_str());
|
||||
}
|
||||
|
||||
while(state.KeepRunning()) {
|
||||
function->asExpression().evaluate(StubGeometryTileFeature(PropertyMap { { "x", static_cast<int64_t>(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);
|
||||
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <mbgl/util/util.hpp>
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
MBGL_EXPORT int runBenchmark(int argc, char* argv[]);
|
||||
|
||||
} // namespace mbgl
|
||||
@@ -1,34 +0,0 @@
|
||||
#include <benchmark/benchmark.h>
|
||||
|
||||
#include <mbgl/style/filter.hpp>
|
||||
#include <mbgl/style/conversion/json.hpp>
|
||||
#include <mbgl/style/conversion/filter.hpp>
|
||||
#include <mbgl/style/conversion_impl.hpp>
|
||||
#include <mbgl/tile/geometry_tile_data.hpp>
|
||||
#include <mbgl/benchmark/stub_geometry_tile_feature.hpp>
|
||||
|
||||
using namespace mbgl;
|
||||
|
||||
style::Filter parse(const char* expression) {
|
||||
style::conversion::Error error;
|
||||
return *style::conversion::convertJSON<style::Filter>(expression, error);
|
||||
}
|
||||
|
||||
static void Parse_Filter(benchmark::State& state) {
|
||||
while (state.KeepRunning()) {
|
||||
parse(R"FILTER(["==", "foo", "bar"])FILTER");
|
||||
}
|
||||
}
|
||||
|
||||
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 style::expression::EvaluationContext context(&feature);
|
||||
|
||||
while (state.KeepRunning()) {
|
||||
filter(context);
|
||||
}
|
||||
}
|
||||
|
||||
BENCHMARK(Parse_Filter);
|
||||
BENCHMARK(Parse_EvaluateFilter);
|
||||
@@ -1,36 +0,0 @@
|
||||
#include <benchmark/benchmark.h>
|
||||
|
||||
#include <mbgl/algorithm/update_tile_masks.hpp>
|
||||
|
||||
using namespace mbgl;
|
||||
|
||||
class FakeTile {
|
||||
public:
|
||||
FakeTile(TileMask mask_)
|
||||
: mask(std::move(mask_)) {
|
||||
}
|
||||
void setMask(TileMask mask_) {
|
||||
mask = std::move(mask_);
|
||||
}
|
||||
|
||||
const bool usedByRenderedLayers = true;
|
||||
TileMask mask;
|
||||
};
|
||||
|
||||
static void TileMaskGeneration(benchmark::State& state) {
|
||||
std::map<UnwrappedTileID, FakeTile> 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{} },
|
||||
};
|
||||
|
||||
while (state.KeepRunning()) {
|
||||
algorithm::updateTileMasks(renderables);
|
||||
}
|
||||
}
|
||||
|
||||
BENCHMARK(TileMaskGeneration);
|
||||
@@ -1,28 +0,0 @@
|
||||
#include <benchmark/benchmark.h>
|
||||
|
||||
#include <mbgl/tile/vector_tile_data.hpp>
|
||||
#include <mbgl/util/io.hpp>
|
||||
|
||||
using namespace mbgl;
|
||||
|
||||
static void Parse_VectorTile(benchmark::State& state) {
|
||||
auto data = std::make_shared<std::string>(util::read_file("test/fixtures/api/assets/streets/10-163-395.vector.pbf"));
|
||||
|
||||
while (state.KeepRunning()) {
|
||||
std::size_t length = 0;
|
||||
VectorTileData tile(data);
|
||||
for (const auto& name : tile.layerNames()) {
|
||||
if (auto layer = tile.getLayer(name)) {
|
||||
const std::size_t count = layer->featureCount();
|
||||
for (std::size_t i = 0; i < count; i++) {
|
||||
if (auto feature = layer->getFeature(i)) {
|
||||
length += feature->getGeometries().size();
|
||||
length += feature->getProperties().size();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
BENCHMARK(Parse_VectorTile);
|
||||
@@ -1,13 +0,0 @@
|
||||
#include <mbgl/benchmark.hpp>
|
||||
|
||||
#include <benchmark/benchmark.h>
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
int runBenchmark(int argc, char* argv[]) {
|
||||
::benchmark::Initialize(&argc, argv);
|
||||
::benchmark::RunSpecifiedBenchmarks();
|
||||
return 0;
|
||||
}
|
||||
|
||||
} // namespace mbgl
|
||||
@@ -1,41 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <mbgl/tile/geometry_tile_data.hpp>
|
||||
#include <mbgl/util/feature.hpp>
|
||||
|
||||
using namespace mbgl;
|
||||
|
||||
class StubGeometryTileFeature : public GeometryTileFeature {
|
||||
public:
|
||||
StubGeometryTileFeature(PropertyMap properties_)
|
||||
: properties(std::move(properties_)) {
|
||||
}
|
||||
|
||||
StubGeometryTileFeature(FeatureIdentifier id_, FeatureType type_, GeometryCollection geometry_, PropertyMap properties_)
|
||||
: properties(std::move(properties_)),
|
||||
id(std::move(id_)),
|
||||
type(type_),
|
||||
geometry(std::move(geometry_)) {
|
||||
}
|
||||
|
||||
PropertyMap properties;
|
||||
FeatureIdentifier id;
|
||||
FeatureType type = FeatureType::Point;
|
||||
GeometryCollection geometry;
|
||||
|
||||
FeatureType getType() const override {
|
||||
return type;
|
||||
}
|
||||
|
||||
FeatureIdentifier getID() const override {
|
||||
return id;
|
||||
}
|
||||
|
||||
optional<Value> getValue(const std::string& key) const override {
|
||||
return properties.count(key) ? properties.at(key) : optional<Value>();
|
||||
}
|
||||
|
||||
const GeometryCollection& getGeometries() const override {
|
||||
return geometry;
|
||||
}
|
||||
};
|
||||
@@ -1,196 +0,0 @@
|
||||
#include <benchmark/benchmark.h>
|
||||
|
||||
#include <mbgl/storage/offline_database.hpp>
|
||||
#include <mbgl/storage/resource.hpp>
|
||||
#include <mbgl/storage/response.hpp>
|
||||
#include <mbgl/storage/sqlite3.hpp>
|
||||
#include <mbgl/util/string.hpp>
|
||||
#include <mbgl/util/logging.hpp>
|
||||
|
||||
#include <random>
|
||||
|
||||
class OfflineDatabase : public benchmark::Fixture {
|
||||
public:
|
||||
void SetUp(const ::benchmark::State&) override {
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
db.setOfflineMapboxTileCountLimit(100000);
|
||||
|
||||
response.data = std::make_shared<std::string>(50 * 1024, 0);
|
||||
response.mustRevalidate = false;
|
||||
response.expires = mbgl::util::now() + 1h;
|
||||
|
||||
resetAmbientTiles();
|
||||
resetRegion();
|
||||
}
|
||||
|
||||
void resetAmbientTiles() {
|
||||
using namespace mbgl;
|
||||
|
||||
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);
|
||||
db.put(ambient, response);
|
||||
}
|
||||
}
|
||||
|
||||
void resetRegion() {
|
||||
using namespace mbgl;
|
||||
|
||||
auto regions = db.listRegions().value();
|
||||
if (!regions.empty()) {
|
||||
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 }};
|
||||
|
||||
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);
|
||||
db.putRegionResource(regionID, offline, response);
|
||||
}
|
||||
}
|
||||
|
||||
mbgl::Response response;
|
||||
mbgl::OfflineDatabase db{":memory:"};
|
||||
|
||||
const unsigned tileCount = 100;
|
||||
int64_t regionID = 0;
|
||||
};
|
||||
|
||||
BENCHMARK_F(OfflineDatabase, InvalidateRegion)(benchmark::State& state) {
|
||||
while (state.KeepRunning()) {
|
||||
db.invalidateRegion(regionID);
|
||||
}
|
||||
}
|
||||
|
||||
BENCHMARK_F(OfflineDatabase, DeleteRegion)(benchmark::State& state) {
|
||||
while (state.KeepRunning()) {
|
||||
resetRegion();
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
db.putRegionResource(regionID, offline, response);
|
||||
}
|
||||
}
|
||||
BENCHMARK_F(OfflineDatabase, InvalidateAmbientCache)(benchmark::State& state) {
|
||||
while (state.KeepRunning()) {
|
||||
db.invalidateAmbientCache();
|
||||
}
|
||||
}
|
||||
|
||||
BENCHMARK_F(OfflineDatabase, ClearAmbientCache)(benchmark::State& state) {
|
||||
while (state.KeepRunning()) {
|
||||
resetAmbientTiles();
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
db.put(ambient, response);
|
||||
}
|
||||
}
|
||||
|
||||
BENCHMARK_F(OfflineDatabase, InsertBigTileCache)(benchmark::State& state) {
|
||||
using namespace mbgl;
|
||||
|
||||
Response big;
|
||||
big.data = std::make_shared<std::string>(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);
|
||||
db.put(ambient, big);
|
||||
}
|
||||
}
|
||||
|
||||
BENCHMARK_F(OfflineDatabase, GetTile)(benchmark::State& state) {
|
||||
using namespace mbgl;
|
||||
|
||||
std::random_device rd;
|
||||
std::mt19937 gen(rd());
|
||||
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));
|
||||
assert(res != nullopt);
|
||||
}
|
||||
}
|
||||
|
||||
BENCHMARK_F(OfflineDatabase, AddTilesToFullDatabase)(benchmark::State& state) {
|
||||
using namespace mbgl;
|
||||
|
||||
Log::setObserver(std::make_unique<Log::NullObserver>());
|
||||
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);
|
||||
db.put(ambient, response);
|
||||
}
|
||||
|
||||
Log::removeObserver();
|
||||
}
|
||||
|
||||
BENCHMARK_F(OfflineDatabase, AddTilesToDisabledDatabase)(benchmark::State& state) {
|
||||
using namespace mbgl;
|
||||
|
||||
auto regions = db.listRegions().value();
|
||||
if (!regions.empty()) {
|
||||
db.deleteRegion(std::move(regions[0]));
|
||||
}
|
||||
|
||||
// Disables the ambient cache.
|
||||
db.setMaximumAmbientCacheSize(0);
|
||||
|
||||
while (state.KeepRunning()) {
|
||||
const Resource ambient = Resource::tile("mapbox://AddTilesToFullDatabase" +
|
||||
util::toString(state.iterations()), 1, 0, 0, 0, Tileset::Scheme::XYZ);
|
||||
db.put(ambient, response);
|
||||
}
|
||||
}
|
||||
|
||||
BENCHMARK_F(OfflineDatabase, GetTileFromDisabledDatabase)(benchmark::State& state) {
|
||||
using namespace mbgl;
|
||||
|
||||
auto regions = db.listRegions().value();
|
||||
if (!regions.empty()) {
|
||||
db.deleteRegion(std::move(regions[0]));
|
||||
}
|
||||
|
||||
// Disables the ambient cache.
|
||||
db.setMaximumAmbientCacheSize(0);
|
||||
|
||||
while (state.KeepRunning()) {
|
||||
auto res = db.get(Resource::tile("mapbox://tile_ambient", 1, 0, 0, 0, Tileset::Scheme::XYZ));
|
||||
assert(res == nullopt);
|
||||
}
|
||||
}
|
||||
|
||||
BENCHMARK_F(OfflineDatabase, ResizeDatabase)(benchmark::State& state) {
|
||||
uint64_t size = 25 * 1024 * 1024;
|
||||
|
||||
while (state.KeepRunning()) {
|
||||
db.setMaximumAmbientCacheSize(size);
|
||||
|
||||
size -= response.data->size();
|
||||
|
||||
if (size < response.data->size()) {
|
||||
size = 25 * 1024 * 1024;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
#include <benchmark/benchmark.h>
|
||||
|
||||
#include <mbgl/util/dtoa.hpp>
|
||||
|
||||
#include <cfloat>
|
||||
#include <cmath>
|
||||
|
||||
using namespace mbgl;
|
||||
|
||||
static void Util_dtoa(::benchmark::State& state) {
|
||||
while (state.KeepRunning()) {
|
||||
util::dtoa(0.);
|
||||
util::dtoa(M_E);
|
||||
util::dtoa(M_LOG2E);
|
||||
util::dtoa(M_LOG10E);
|
||||
util::dtoa(M_LN2);
|
||||
util::dtoa(M_LN10);
|
||||
util::dtoa(M_PI);
|
||||
util::dtoa(M_PI_2);
|
||||
util::dtoa(M_PI_4);
|
||||
util::dtoa(M_1_PI);
|
||||
util::dtoa(M_2_PI);
|
||||
util::dtoa(M_2_SQRTPI);
|
||||
util::dtoa(M_SQRT2);
|
||||
util::dtoa(M_SQRT1_2);
|
||||
}
|
||||
}
|
||||
|
||||
static void Util_standardDtoa(::benchmark::State& state) {
|
||||
while (state.KeepRunning()) {
|
||||
std::to_string(0.);
|
||||
std::to_string(M_E);
|
||||
std::to_string(M_LOG2E);
|
||||
std::to_string(M_LOG10E);
|
||||
std::to_string(M_LN2);
|
||||
std::to_string(M_LN10);
|
||||
std::to_string(M_PI);
|
||||
std::to_string(M_PI_2);
|
||||
std::to_string(M_PI_4);
|
||||
std::to_string(M_1_PI);
|
||||
std::to_string(M_2_PI);
|
||||
std::to_string(M_2_SQRTPI);
|
||||
std::to_string(M_SQRT2);
|
||||
std::to_string(M_SQRT1_2);
|
||||
}
|
||||
}
|
||||
|
||||
static void Util_dtoaLimits(::benchmark::State& state) {
|
||||
while (state.KeepRunning()) {
|
||||
util::dtoa(DBL_MIN);
|
||||
util::dtoa(DBL_MAX);
|
||||
}
|
||||
}
|
||||
|
||||
static void Util_standardDtoaLimits(::benchmark::State& state) {
|
||||
while (state.KeepRunning()) {
|
||||
std::to_string(DBL_MIN);
|
||||
std::to_string(DBL_MAX);
|
||||
}
|
||||
}
|
||||
|
||||
BENCHMARK(Util_dtoa);
|
||||
BENCHMARK(Util_standardDtoa);
|
||||
|
||||
BENCHMARK(Util_dtoaLimits);
|
||||
BENCHMARK(Util_standardDtoaLimits);
|
||||
@@ -1,93 +0,0 @@
|
||||
#include <benchmark/benchmark.h>
|
||||
#include <mbgl/util/geo.hpp>
|
||||
#include <mbgl/util/geometry.hpp>
|
||||
#include <mbgl/util/tile_coordinate.hpp>
|
||||
#include <mbgl/util/tile_cover.hpp>
|
||||
#include <mbgl/map/transform.hpp>
|
||||
|
||||
using namespace mbgl;
|
||||
|
||||
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;
|
||||
while (state.KeepRunning()) {
|
||||
auto count = util::tileCount(sanFrancisco, 10);
|
||||
length += count;
|
||||
}
|
||||
}
|
||||
|
||||
static void TileCoverPitchedViewport(benchmark::State& state) {
|
||||
Transform transform;
|
||||
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));
|
||||
|
||||
std::size_t length = 0;
|
||||
while (state.KeepRunning()) {
|
||||
auto tiles = util::tileCover(transform.getState(), 8);
|
||||
length += tiles.size();
|
||||
}
|
||||
}
|
||||
|
||||
static void TileCoverBounds(benchmark::State& state) {
|
||||
std::size_t length = 0;
|
||||
while (state.KeepRunning()) {
|
||||
auto tiles = util::tileCover(sanFrancisco, 8);
|
||||
length += tiles.size();
|
||||
}
|
||||
}
|
||||
|
||||
static const auto geomPolygon = Polygon<double>{
|
||||
{
|
||||
{-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;
|
||||
|
||||
while (state.KeepRunning()) {
|
||||
auto tiles = util::tileCover(geomPolygon, 8);
|
||||
length += tiles.size();
|
||||
}
|
||||
}
|
||||
|
||||
static void TileCountPolygon(benchmark::State& state) {
|
||||
std::size_t length = 0;
|
||||
|
||||
while (state.KeepRunning()) {
|
||||
auto tiles = util::tileCount(geomPolygon, 16);
|
||||
length += tiles;
|
||||
}
|
||||
}
|
||||
|
||||
BENCHMARK(TileCountBounds);
|
||||
BENCHMARK(TileCountPolygon);
|
||||
BENCHMARK(TileCoverPitchedViewport);
|
||||
BENCHMARK(TileCoverBounds);
|
||||
BENCHMARK(TileCoverPolygon);
|
||||
|
||||
272
bin/offline.cpp
272
bin/offline.cpp
@@ -1,272 +0,0 @@
|
||||
#include <mbgl/util/default_styles.hpp>
|
||||
#include <mbgl/util/run_loop.hpp>
|
||||
#include <mbgl/util/string.hpp>
|
||||
#include <mbgl/util/geojson.hpp>
|
||||
|
||||
#include <mbgl/storage/default_file_source.hpp>
|
||||
|
||||
#include <args.hxx>
|
||||
|
||||
#include <cstdlib>
|
||||
#include <iostream>
|
||||
#include <csignal>
|
||||
#include <atomic>
|
||||
#include <sstream>
|
||||
#include <fstream>
|
||||
|
||||
using namespace std::literals::chrono_literals;
|
||||
|
||||
std::string readFile(const std::string& fileName) {
|
||||
std::ifstream stream(fileName.c_str());
|
||||
if (!stream.good()) {
|
||||
throw std::runtime_error("Cannot read file: " + fileName);
|
||||
}
|
||||
|
||||
std::stringstream buffer;
|
||||
buffer << stream.rdbuf();
|
||||
stream.close();
|
||||
|
||||
return buffer.str();
|
||||
}
|
||||
|
||||
mapbox::geometry::geometry<double> 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 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";
|
||||
}
|
||||
|
||||
// The above switch is exhaustive, but placate GCC nonetheless:
|
||||
assert(false);
|
||||
return os;
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
args::ArgumentParser argumentParser("Mapbox GL offline tool");
|
||||
args::HelpFlag helpFlag(argumentParser, "help", "Display this help menu", {'h', "help"});
|
||||
|
||||
args::ValueFlag<std::string> tokenValue(argumentParser, "key", "Mapbox access token", {'t', "token"});
|
||||
args::ValueFlag<std::string> styleValue(argumentParser, "URL", "Map stylesheet", {'s', "style"});
|
||||
args::ValueFlag<std::string> outputValue(argumentParser, "file", "Output database file name", {'o', "output"});
|
||||
args::ValueFlag<std::string> apiBaseValue(argumentParser, "URL", "API Base URL", {'a', "apiBaseURL"});
|
||||
|
||||
args::Group mergeGroup(argumentParser, "Merge databases:", args::Group::Validators::AllOrNone);
|
||||
args::ValueFlag<std::string> mergePathValue(mergeGroup, "merge", "Database to merge from", {'m', "merge"});
|
||||
args::ValueFlag<std::string> inputValue(mergeGroup, "input", "Database to merge into. Use with --merge option.", {'i', "input"});
|
||||
|
||||
// LatLngBounds
|
||||
args::Group latLngBoundsGroup(argumentParser, "LatLng bounds:", args::Group::Validators::AllOrNone);
|
||||
args::ValueFlag<double> northValue(latLngBoundsGroup, "degrees", "North latitude", {"north"});
|
||||
args::ValueFlag<double> westValue(latLngBoundsGroup, "degrees", "West longitude", {"west"});
|
||||
args::ValueFlag<double> southValue(latLngBoundsGroup, "degrees", "South latitude", {"south"});
|
||||
args::ValueFlag<double> eastValue(latLngBoundsGroup, "degrees", "East longitude", {"east"});
|
||||
|
||||
// Geometry
|
||||
args::Group geoJSONGroup(argumentParser, "GeoJson geometry:", args::Group::Validators::AllOrNone);
|
||||
args::ValueFlag<std::string> geometryValue(geoJSONGroup, "file", "GeoJSON Feature file containing the region geometry (can't be a FeatureCollection)", {"geojson"});
|
||||
|
||||
args::ValueFlag<double> minZoomValue(argumentParser, "number", "Min zoom level", {"minZoom"});
|
||||
args::ValueFlag<double> maxZoomValue(argumentParser, "number", "Max zoom level", {"maxZoom"});
|
||||
args::ValueFlag<double> pixelRatioValue(argumentParser, "number", "Pixel ratio", {"pixelRatio"});
|
||||
args::ValueFlag<bool> includeIdeographsValue(argumentParser, "boolean", "Include CJK glyphs", {"includeIdeographs"});
|
||||
|
||||
try {
|
||||
argumentParser.ParseCLI(argc, argv);
|
||||
} catch (const args::Help&) {
|
||||
std::cout << argumentParser;
|
||||
exit(0);
|
||||
} catch (const args::ParseError& e) {
|
||||
std::cerr << e.what() << std::endl;
|
||||
std::cerr << argumentParser;
|
||||
exit(1);
|
||||
} catch (const args::ValidationError& e) {
|
||||
std::cerr << e.what() << std::endl;
|
||||
std::cerr << argumentParser;
|
||||
exit(2);
|
||||
}
|
||||
|
||||
std::string style = styleValue ? args::get(styleValue) : mbgl::util::default_styles::streets.url;
|
||||
|
||||
mbgl::optional<std::string> mergePath = {};
|
||||
if (mergePathValue) mergePath = args::get(mergePathValue);
|
||||
mbgl::optional<std::string> inputDb = {};
|
||||
if (inputValue) inputDb = args::get(inputValue);
|
||||
|
||||
const double minZoom = minZoomValue ? args::get(minZoomValue) : 0.0;
|
||||
const double maxZoom = maxZoomValue ? args::get(maxZoomValue) : 15.0;
|
||||
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, pixelRatio, includeIdeographs) };
|
||||
} catch(const std::runtime_error& e) {
|
||||
std::cerr << "Could not parse geojson file " << geometryValue.Get() << ": " << e.what() << std::endl;
|
||||
exit(1);
|
||||
}
|
||||
} else {
|
||||
// Bay area
|
||||
const double north = northValue ? args::get(northValue) : 37.2;
|
||||
const double west = westValue ? args::get(westValue) : -122.8;
|
||||
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, pixelRatio, includeIdeographs) };
|
||||
}
|
||||
}();
|
||||
|
||||
const char* tokenEnv = getenv("MAPBOX_ACCESS_TOKEN");
|
||||
const std::string token = tokenValue ? args::get(tokenValue) : (tokenEnv ? tokenEnv : std::string());
|
||||
|
||||
const std::string apiBaseURL = apiBaseValue ? args::get(apiBaseValue) : mbgl::util::API_BASE_URL;
|
||||
|
||||
|
||||
util::RunLoop loop;
|
||||
DefaultFileSource fileSource(output, ".");
|
||||
std::unique_ptr<OfflineRegion> region;
|
||||
|
||||
fileSource.setAccessToken(token);
|
||||
fileSource.setAPIBaseURL(apiBaseURL);
|
||||
|
||||
if (inputDb && mergePath) {
|
||||
DefaultFileSource inputSource(*inputDb, ".");
|
||||
inputSource.setAccessToken(token);
|
||||
inputSource.setAPIBaseURL(apiBaseURL);
|
||||
|
||||
int retCode = 0;
|
||||
std::cout << "Start Merge" << std::endl;
|
||||
inputSource.mergeOfflineRegions(*mergePath, [&] (mbgl::expected<std::vector<OfflineRegion>, 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.run();
|
||||
return retCode;
|
||||
}
|
||||
|
||||
OfflineRegionMetadata metadata;
|
||||
|
||||
class Observer : public OfflineRegionObserver {
|
||||
public:
|
||||
Observer(OfflineRegion& region_, DefaultFileSource& fileSource_, util::RunLoop& loop_, mbgl::optional<std::string> mergePath_)
|
||||
: region(region_),
|
||||
fileSource(fileSource_),
|
||||
loop(loop_),
|
||||
mergePath(std::move(mergePath_)),
|
||||
start(util::now()) {
|
||||
}
|
||||
|
||||
void statusChanged(OfflineRegionStatus status) override {
|
||||
if (status.downloadState == OfflineRegionDownloadState::Inactive) {
|
||||
std::cout << "stopped" << std::endl;
|
||||
loop.stop();
|
||||
return;
|
||||
}
|
||||
|
||||
std::string bytesPerSecond = "-";
|
||||
|
||||
auto elapsedSeconds = (util::now() - start) / 1s;
|
||||
if (elapsedSeconds != 0) {
|
||||
bytesPerSecond = util::toString(status.completedResourceSize / elapsedSeconds);
|
||||
}
|
||||
|
||||
std::cout << status.completedResourceCount << " / " << status.requiredResourceCount
|
||||
<< " resources"
|
||||
<< status.completedTileCount << " / " << status.requiredTileCount
|
||||
<< "tiles"
|
||||
<< (status.requiredResourceCountIsPrecise ? "; " : " (indeterminate); ")
|
||||
<< status.completedResourceSize << " bytes downloaded"
|
||||
<< " (" << bytesPerSecond << " bytes/sec)"
|
||||
<< std::endl;
|
||||
|
||||
if (status.complete()) {
|
||||
std::cout << "Finished Download" << std::endl;
|
||||
loop.stop();
|
||||
}
|
||||
}
|
||||
|
||||
void responseError(Response::Error error) override {
|
||||
std::cerr << error.reason << " downloading resource: " << error.message << std::endl;
|
||||
}
|
||||
|
||||
void mapboxTileCountLimitExceeded(uint64_t limit) override {
|
||||
std::cerr << "Error: reached limit of " << limit << " offline tiles" << std::endl;
|
||||
}
|
||||
|
||||
OfflineRegion& region;
|
||||
DefaultFileSource& fileSource;
|
||||
util::RunLoop& loop;
|
||||
mbgl::optional<std::string> mergePath;
|
||||
Timestamp start;
|
||||
};
|
||||
|
||||
static auto stop = [&] {
|
||||
if (region) {
|
||||
std::cout << "Stopping download... ";
|
||||
fileSource.setOfflineRegionDownloadState(*region, OfflineRegionDownloadState::Inactive);
|
||||
}
|
||||
};
|
||||
|
||||
std::signal(SIGINT, [] (int) { stop(); });
|
||||
|
||||
fileSource.createOfflineRegion(definition, metadata, [&] (mbgl::expected<OfflineRegion, std::exception_ptr> region_) {
|
||||
if (!region_) {
|
||||
std::cerr << "Error creating region: " << util::toString(region_.error()) << std::endl;
|
||||
loop.stop();
|
||||
exit(1);
|
||||
} else {
|
||||
assert(region_);
|
||||
region = std::make_unique<OfflineRegion>(std::move(*region_));
|
||||
fileSource.setOfflineRegionObserver(*region, std::make_unique<Observer>(*region, fileSource, loop, mergePath));
|
||||
fileSource.setOfflineRegionDownloadState(*region, OfflineRegionDownloadState::Active);
|
||||
}
|
||||
});
|
||||
|
||||
loop.run();
|
||||
return 0;
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -e
|
||||
set -o pipefail
|
||||
|
||||
OFFLINE=./build/macos/Release/mbgl-offline
|
||||
|
||||
# Barcelona
|
||||
$OFFLINE --north 41.4664 --west 2.0407 --south 41.2724 --east 2.2680 --output barcelona.db
|
||||
$OFFLINE --north 41.4664 --west 2.0407 --south 41.2724 --east 2.2680 --output barcelona_sat.db --style mapbox://styles/mapbox/satellite-v8
|
||||
|
||||
# Greater London within the M25 at zoom levels 0–15
|
||||
$OFFLINE --north 51.6777 --west -0.5026 --south 51.3237 --east 0.2527 --maxZoom 15 --output london.db
|
||||
$OFFLINE --north 51.6777 --west -0.5026 --south 51.3237 --east 0.2527 --maxZoom 15 --output london_sat.db --style mapbox://styles/mapbox/satellite-v8
|
||||
|
||||
# The contiguous United States at zoom levels 0–9
|
||||
$OFFLINE --north 49.6107 --west -125.5078 --south 24.2870 --east -66.3574 --maxZoom 9 --output us.db
|
||||
$OFFLINE --north 49.6107 --west -125.5078 --south 24.2870 --east -66.3574 --maxZoom 9 --output us_sat.db --style mapbox://styles/mapbox/satellite-v8
|
||||
110
bin/render.cpp
110
bin/render.cpp
@@ -1,110 +0,0 @@
|
||||
#include <mbgl/map/map.hpp>
|
||||
#include <mbgl/map/map_options.hpp>
|
||||
#include <mbgl/util/image.hpp>
|
||||
#include <mbgl/util/run_loop.hpp>
|
||||
#include <mbgl/util/default_styles.hpp>
|
||||
|
||||
#include <mbgl/gfx/backend.hpp>
|
||||
#include <mbgl/gfx/headless_frontend.hpp>
|
||||
#include <mbgl/style/style.hpp>
|
||||
|
||||
#include <args.hxx>
|
||||
|
||||
#include <cstdlib>
|
||||
#include <iostream>
|
||||
#include <fstream>
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
args::ArgumentParser argumentParser("Mapbox GL render tool");
|
||||
args::HelpFlag helpFlag(argumentParser, "help", "Display this help menu", {"help"});
|
||||
|
||||
args::ValueFlag<std::string> backendValue(argumentParser, "Backend", "Rendering backend", {"backend"});
|
||||
args::ValueFlag<std::string> tokenValue(argumentParser, "key", "Mapbox access token", {'t', "token"});
|
||||
args::ValueFlag<std::string> styleValue(argumentParser, "URL", "Map stylesheet", {'s', "style"});
|
||||
args::ValueFlag<std::string> outputValue(argumentParser, "file", "Output file name", {'o', "output"});
|
||||
args::ValueFlag<std::string> cacheValue(argumentParser, "file", "Cache database file name", {'c', "cache"});
|
||||
args::ValueFlag<std::string> assetsValue(argumentParser, "file", "Directory to which asset:// URLs will resolve", {'a', "assets"});
|
||||
|
||||
args::Flag debugFlag(argumentParser, "debug", "Debug mode", {"debug"});
|
||||
|
||||
args::ValueFlag<double> pixelRatioValue(argumentParser, "number", "Image scale factor", {'r', "ratio"});
|
||||
|
||||
args::ValueFlag<double> zoomValue(argumentParser, "number", "Zoom level", {'z', "zoom"});
|
||||
|
||||
args::ValueFlag<double> lonValue(argumentParser, "degrees", "Longitude", {'x', "lon"});
|
||||
args::ValueFlag<double> latValue(argumentParser, "degrees", "Latitude", {'y', "lat"});
|
||||
args::ValueFlag<double> bearingValue(argumentParser, "degrees", "Bearing", {'b', "bearing"});
|
||||
args::ValueFlag<double> pitchValue(argumentParser, "degrees", "Pitch", {'p', "pitch"});
|
||||
args::ValueFlag<uint32_t> widthValue(argumentParser, "pixels", "Image width", {'w', "width"});
|
||||
args::ValueFlag<uint32_t> heightValue(argumentParser, "pixels", "Image height", {'h', "height"});
|
||||
|
||||
try {
|
||||
argumentParser.ParseCLI(argc, argv);
|
||||
} catch (const args::Help&) {
|
||||
std::cout << argumentParser;
|
||||
exit(0);
|
||||
} catch (const args::ParseError& e) {
|
||||
std::cerr << e.what() << std::endl;
|
||||
std::cerr << argumentParser;
|
||||
exit(1);
|
||||
} catch (const args::ValidationError& e) {
|
||||
std::cerr << e.what() << std::endl;
|
||||
std::cerr << argumentParser;
|
||||
exit(2);
|
||||
}
|
||||
|
||||
std::string style = styleValue ? args::get(styleValue) : mbgl::util::default_styles::streets.url;
|
||||
const double lat = latValue ? args::get(latValue) : 0;
|
||||
const double lon = lonValue ? args::get(lonValue) : 0;
|
||||
const double zoom = zoomValue ? args::get(zoomValue) : 0;
|
||||
const double bearing = bearingValue ? args::get(bearingValue) : 0;
|
||||
const double pitch = pitchValue ? args::get(pitchValue) : 0;
|
||||
const double pixelRatio = pixelRatioValue ? args::get(pixelRatioValue) : 1;
|
||||
|
||||
const uint32_t width = widthValue ? args::get(widthValue) : 512;
|
||||
const uint32_t height = heightValue ? args::get(heightValue) : 512;
|
||||
const std::string output = outputValue ? args::get(outputValue) : "out.png";
|
||||
const std::string cache_file = cacheValue ? args::get(cacheValue) : "cache.sqlite";
|
||||
const std::string asset_root = assetsValue ? args::get(assetsValue) : ".";
|
||||
|
||||
// Try to load the token from the environment.
|
||||
const char* tokenEnv = getenv("MAPBOX_ACCESS_TOKEN");
|
||||
const std::string token = tokenValue ? args::get(tokenValue) : (tokenEnv ? tokenEnv : std::string());
|
||||
|
||||
const bool debug = debugFlag ? args::get(debugFlag) : false;
|
||||
|
||||
using namespace mbgl;
|
||||
|
||||
util::RunLoop loop;
|
||||
|
||||
HeadlessFrontend frontend({ width, height }, pixelRatio);
|
||||
Map map(frontend, MapObserver::nullObserver(),
|
||||
MapOptions().withMapMode(MapMode::Static).withSize(frontend.getSize()).withPixelRatio(pixelRatio),
|
||||
ResourceOptions().withCachePath(cache_file).withAssetPath(asset_root).withAccessToken(std::string(token)));
|
||||
|
||||
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));
|
||||
|
||||
if (debug) {
|
||||
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));
|
||||
out.close();
|
||||
} catch(std::exception& e) {
|
||||
std::cout << "Error: " << e.what() << std::endl;
|
||||
exit(1);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
# Run scripts/generate-file-lists.js to change the source files for this target.
|
||||
load_sources_list(MBGL_BENCHMARK_FILES benchmark/benchmark-files.json)
|
||||
add_executable(mbgl-benchmark ${MBGL_BENCHMARK_FILES})
|
||||
|
||||
target_include_directories(mbgl-benchmark
|
||||
PRIVATE src
|
||||
PRIVATE benchmark/include
|
||||
PRIVATE benchmark/src
|
||||
PRIVATE platform/default/include
|
||||
)
|
||||
|
||||
target_link_libraries(mbgl-benchmark
|
||||
PRIVATE mbgl-core
|
||||
PRIVATE mbgl-vendor-benchmark
|
||||
)
|
||||
|
||||
mbgl_platform_benchmark()
|
||||
|
||||
create_source_groups(mbgl-benchmark)
|
||||
|
||||
set_target_properties(mbgl-benchmark PROPERTIES FOLDER "Executables")
|
||||
|
||||
initialize_xcode_cxx_build_settings(mbgl-benchmark)
|
||||
|
||||
xcode_create_scheme(
|
||||
TARGET mbgl-benchmark
|
||||
OPTIONAL_ARGS
|
||||
"--benchmark_filter=Category.*"
|
||||
"--benchmark_repetitions=1"
|
||||
)
|
||||
@@ -1,46 +0,0 @@
|
||||
# scripts/generate-file-lists.js to change the source files for this target.
|
||||
load_sources_list(MBGL_CORE_FILES src/core-files.json)
|
||||
add_library(mbgl-core STATIC ${MBGL_CORE_FILES})
|
||||
|
||||
target_include_directories(mbgl-core
|
||||
PUBLIC include
|
||||
PRIVATE src
|
||||
)
|
||||
|
||||
target_link_libraries(mbgl-core PRIVATE
|
||||
mbgl-vendor-earcut.hpp
|
||||
mbgl-vendor-eternal
|
||||
mbgl-vendor-expected
|
||||
mbgl-vendor-geojson-vt-cpp
|
||||
mbgl-vendor-shelf-pack-cpp
|
||||
mbgl-vendor-unique_resource
|
||||
mbgl-vendor-wagyu
|
||||
)
|
||||
|
||||
# linux uses ICU from mason, other platforms use vendored ICU
|
||||
if(NOT MBGL_PLATFORM STREQUAL "linux")
|
||||
set(ICU_LIBRARY "mbgl-vendor-icu")
|
||||
endif()
|
||||
|
||||
# FIXME: We should not leak these many
|
||||
# libraries in our public interface.
|
||||
target_link_libraries(mbgl-core PUBLIC
|
||||
mbgl-vendor-boost
|
||||
mapbox-base-extras
|
||||
mapbox-base
|
||||
${ICU_LIBRARY}
|
||||
mbgl-vendor-polylabel
|
||||
mbgl-vendor-protozero
|
||||
Mapbox::Base::Extras::rapidjson
|
||||
mbgl-vendor-vector-tile
|
||||
)
|
||||
|
||||
mbgl_platform_core()
|
||||
|
||||
create_source_groups(mbgl-core)
|
||||
|
||||
set_target_properties(mbgl-core PROPERTIES FOLDER "Core")
|
||||
|
||||
xcode_create_scheme(TARGET mbgl-core)
|
||||
|
||||
initialize_xcode_cxx_build_settings(mbgl-core)
|
||||
@@ -1,18 +0,0 @@
|
||||
find_package(Doxygen)
|
||||
if(DOXYGEN_FOUND)
|
||||
set(DOXYGEN_PROJECT_NAME "Mapbox GL Native")
|
||||
set(DOXYGEN_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/docs")
|
||||
set(DOXYGEN_GENERATE_XML TRUE)
|
||||
set(DOXYGEN_QUIET YES)
|
||||
set(DOXYGEN_WARN_LOGFILE ${CMAKE_BINARY_DIR}/doxygen_warn.log)
|
||||
|
||||
doxygen_add_docs(generate_xml_doxygen
|
||||
${CMAKE_SOURCE_DIR}/include
|
||||
)
|
||||
|
||||
add_custom_target(doxygen_coverage
|
||||
COMMAND ${CMAKE_SOURCE_DIR}/scripts/doxy-coverage.py --quiet --noerror --json="${CMAKE_BINARY_DIR}/doxygen-coverage.json" "${CMAKE_BINARY_DIR}/docs/xml"
|
||||
COMMENT "Checking documentation coverage"
|
||||
DEPENDS generate_xml_doxygen
|
||||
)
|
||||
endif()
|
||||
@@ -1,102 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0830"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "${XCSCHEME_BLUEPRINT_ID}"
|
||||
BuildableName = "${XCSCHEME_BUILDABLE_NAME}"
|
||||
BlueprintName = "${XCSCHEME_BLUEPRINT_NAME}"
|
||||
ReferencedContainer = "container:${XCSCHEME_CONTAINER}">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
</Testables>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "${XCSCHEME_BLUEPRINT_ID}"
|
||||
BuildableName = "${XCSCHEME_BUILDABLE_NAME}"
|
||||
BlueprintName = "${XCSCHEME_BLUEPRINT_NAME}"
|
||||
ReferencedContainer = "container:${XCSCHEME_CONTAINER}">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "YES"
|
||||
customWorkingDirectory = "${XCSCHEME_WORKING_DIRECTORY}"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "${XCSCHEME_BLUEPRINT_ID}"
|
||||
BuildableName = "${XCSCHEME_BUILDABLE_NAME}"
|
||||
BlueprintName = "${XCSCHEME_BLUEPRINT_NAME}"
|
||||
ReferencedContainer = "container:${XCSCHEME_CONTAINER}">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
<CommandLineArguments>${XCSCHEME_COMMAND_LINE_ARGS}
|
||||
</CommandLineArguments>
|
||||
<EnvironmentVariables>
|
||||
<EnvironmentVariable
|
||||
key = "MAPBOX_ACCESS_TOKEN"
|
||||
value = "$ENV{MAPBOX_ACCESS_TOKEN}"
|
||||
isEnabled = "YES">
|
||||
</EnvironmentVariable>
|
||||
</EnvironmentVariables>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "YES"
|
||||
customWorkingDirectory = "${XCSCHEME_WORKING_DIRECTORY}"
|
||||
debugDocumentVersioning = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "${XCSCHEME_BLUEPRINT_ID}"
|
||||
BuildableName = "${XCSCHEME_BUILDABLE_NAME}"
|
||||
BlueprintName = "${XCSCHEME_BLUEPRINT_NAME}"
|
||||
ReferencedContainer = "container:${XCSCHEME_CONTAINER}">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -1,29 +0,0 @@
|
||||
add_executable(mbgl-expression-test
|
||||
expression-test/main.cpp
|
||||
expression-test/expression_test_parser.cpp
|
||||
expression-test/expression_test_runner.cpp
|
||||
expression-test/expression_test_logger.cpp
|
||||
expression-test/test_runner_common.cpp
|
||||
expression-test/test_runner_common.hpp
|
||||
)
|
||||
|
||||
if(APPLE)
|
||||
target_link_libraries(mbgl-expression-test PRIVATE mbgl-loop-darwin)
|
||||
else()
|
||||
target_link_libraries(mbgl-expression-test PRIVATE mbgl-loop-uv)
|
||||
endif()
|
||||
|
||||
target_include_directories(mbgl-expression-test
|
||||
PRIVATE src
|
||||
PRIVATE expression-test
|
||||
PRIVATE render-test
|
||||
)
|
||||
|
||||
target_link_libraries(mbgl-expression-test PRIVATE
|
||||
mbgl-core
|
||||
Mapbox::Base::Extras::args
|
||||
Mapbox::Base::Extras::filesystem
|
||||
Mapbox::Base::Extras::rapidjson
|
||||
)
|
||||
|
||||
add_definitions(-DTEST_RUNNER_ROOT_PATH="${CMAKE_SOURCE_DIR}")
|
||||
@@ -1,24 +0,0 @@
|
||||
# Modify platform/default/filesource-files.json to change the source files for this target.
|
||||
load_sources_list(MBGL_FILESOURCE_FILES platform/default/filesource-files.json)
|
||||
add_library(mbgl-filesource STATIC ${MBGL_FILESOURCE_FILES})
|
||||
|
||||
target_include_directories(mbgl-filesource
|
||||
PRIVATE include
|
||||
PRIVATE src
|
||||
PRIVATE platform/default/include
|
||||
)
|
||||
|
||||
target_link_libraries(mbgl-filesource
|
||||
PUBLIC mbgl-core
|
||||
PUBLIC mbgl-vendor-expected
|
||||
)
|
||||
|
||||
mbgl_filesource()
|
||||
|
||||
create_source_groups(mbgl-filesource)
|
||||
|
||||
set_target_properties(mbgl-filesource PROPERTIES FOLDER "Core")
|
||||
|
||||
xcode_create_scheme(TARGET mbgl-filesource)
|
||||
|
||||
initialize_xcode_cxx_build_settings(mbgl-filesource)
|
||||
@@ -1,49 +0,0 @@
|
||||
add_executable(mbgl-glfw
|
||||
platform/glfw/main.cpp
|
||||
)
|
||||
|
||||
target_sources(mbgl-glfw
|
||||
PRIVATE platform/glfw/glfw_view.hpp
|
||||
PRIVATE platform/glfw/glfw_view.cpp
|
||||
PRIVATE platform/glfw/glfw_backend.hpp
|
||||
PRIVATE platform/glfw/glfw_gl_backend.hpp
|
||||
PRIVATE platform/glfw/glfw_gl_backend.cpp
|
||||
PRIVATE platform/glfw/glfw_renderer_frontend.hpp
|
||||
PRIVATE platform/glfw/glfw_renderer_frontend.cpp
|
||||
PRIVATE platform/glfw/settings_json.hpp
|
||||
PRIVATE platform/glfw/settings_json.cpp
|
||||
)
|
||||
|
||||
target_include_directories(mbgl-glfw
|
||||
PRIVATE platform/default/include
|
||||
)
|
||||
|
||||
target_link_libraries(mbgl-glfw
|
||||
PRIVATE mbgl-core
|
||||
PRIVATE glfw
|
||||
PRIVATE mbgl-vendor-cheap-ruler-cpp
|
||||
PRIVATE Mapbox::Base::Extras::args
|
||||
)
|
||||
|
||||
mbgl_platform_glfw()
|
||||
|
||||
create_source_groups(mbgl-glfw)
|
||||
|
||||
set_target_properties(mbgl-glfw PROPERTIES FOLDER "Executables")
|
||||
|
||||
initialize_xcode_cxx_build_settings(mbgl-glfw)
|
||||
|
||||
xcode_create_scheme(
|
||||
TARGET mbgl-glfw
|
||||
OPTIONAL_ARGS
|
||||
"--style=file.json"
|
||||
"--cache=/tmp/mbgl-cache.db"
|
||||
"--lon=0"
|
||||
"--lat=0"
|
||||
"--zoom=1"
|
||||
"--bearing=0"
|
||||
"--pitch=0"
|
||||
"--fullscreen"
|
||||
"--offline"
|
||||
"--benchmark"
|
||||
)
|
||||
@@ -1,80 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0830"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "${XCSCHEME_BLUEPRINT_ID}"
|
||||
BuildableName = "${XCSCHEME_BUILDABLE_NAME}"
|
||||
BlueprintName = "${XCSCHEME_BLUEPRINT_NAME}"
|
||||
ReferencedContainer = "container:${XCSCHEME_CONTAINER}">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
</Testables>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "${XCSCHEME_BLUEPRINT_ID}"
|
||||
BuildableName = "${XCSCHEME_BUILDABLE_NAME}"
|
||||
BlueprintName = "${XCSCHEME_BLUEPRINT_NAME}"
|
||||
ReferencedContainer = "container:${XCSCHEME_CONTAINER}">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "${XCSCHEME_BLUEPRINT_ID}"
|
||||
BuildableName = "${XCSCHEME_BUILDABLE_NAME}"
|
||||
BlueprintName = "${XCSCHEME_BLUEPRINT_NAME}"
|
||||
ReferencedContainer = "container:${XCSCHEME_CONTAINER}">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -1,20 +0,0 @@
|
||||
# Modify platform/darwin/loop-files.json to change the source files for this target.
|
||||
load_sources_list(MBGL_LOOP_DARWIN_FILES platform/darwin/loop-files.json)
|
||||
add_library(mbgl-loop-darwin STATIC ${MBGL_LOOP_DARWIN_FILES})
|
||||
|
||||
target_include_directories(mbgl-loop-darwin
|
||||
PRIVATE include
|
||||
PRIVATE src
|
||||
)
|
||||
|
||||
target_link_libraries(mbgl-loop-darwin PUBLIC
|
||||
mapbox-base
|
||||
)
|
||||
|
||||
create_source_groups(mbgl-loop-darwin)
|
||||
|
||||
set_target_properties(mbgl-loop-darwin PROPERTIES FOLDER "Core")
|
||||
|
||||
initialize_xcode_cxx_build_settings(mbgl-loop-darwin)
|
||||
|
||||
xcode_create_scheme(TARGET mbgl-loop-darwin)
|
||||
@@ -1,14 +0,0 @@
|
||||
add_library(mbgl-loop-uv INTERFACE)
|
||||
|
||||
target_sources(mbgl-loop-uv INTERFACE
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platform/default/src/mbgl/util/async_task.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platform/default/src/mbgl/util/run_loop.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platform/default/src/mbgl/util/timer.cpp
|
||||
)
|
||||
|
||||
target_include_directories(mbgl-loop-uv INTERFACE
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/include
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src
|
||||
)
|
||||
|
||||
create_source_groups(mbgl-loop-uv)
|
||||
@@ -1,25 +0,0 @@
|
||||
# All dependencies in a single separate file so its checksum can be used in a CI cache key name
|
||||
|
||||
if(MBGL_PLATFORM STREQUAL "android")
|
||||
# noop
|
||||
elseif(MBGL_PLATFORM STREQUAL "ios")
|
||||
# noop
|
||||
elseif(MBGL_PLATFORM STREQUAL "linux")
|
||||
mason_use(libuv VERSION 1.9.1)
|
||||
mason_use(libpng VERSION 1.6.25)
|
||||
mason_use(libjpeg-turbo VERSION 1.5.0)
|
||||
mason_use(icu VERSION 63.1-min-static-data)
|
||||
|
||||
if(WITH_EGL)
|
||||
mason_use(swiftshader VERSION 2018-05-31)
|
||||
endif()
|
||||
elseif(MBGL_PLATFORM STREQUAL "macos")
|
||||
if(WITH_EGL)
|
||||
mason_use(swiftshader VERSION 2018-05-31)
|
||||
endif()
|
||||
elseif(MBGL_PLATFORM STREQUAL "qt")
|
||||
if(NOT WITH_QT_DECODERS)
|
||||
mason_use(libjpeg-turbo VERSION 1.5.0)
|
||||
mason_use(libpng VERSION 1.6.25)
|
||||
endif()
|
||||
endif()
|
||||
@@ -1,227 +0,0 @@
|
||||
# Mason CMake
|
||||
|
||||
include(CMakeParseArguments)
|
||||
|
||||
function(mason_detect_platform)
|
||||
# Determine platform
|
||||
if(NOT MASON_PLATFORM)
|
||||
# we call uname -s manually here since
|
||||
# CMAKE_HOST_SYSTEM_NAME will not be defined before the project() call
|
||||
execute_process(
|
||||
COMMAND uname -s
|
||||
OUTPUT_VARIABLE UNAME
|
||||
OUTPUT_STRIP_TRAILING_WHITESPACE)
|
||||
|
||||
if (UNAME STREQUAL "Darwin")
|
||||
set(MASON_PLATFORM "osx" PARENT_SCOPE)
|
||||
else()
|
||||
set(MASON_PLATFORM "linux" PARENT_SCOPE)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
# Determine platform version string
|
||||
if(NOT MASON_PLATFORM_VERSION)
|
||||
# Android Studio only passes ANDROID_ABI, but we need to adjust that to the Mason
|
||||
if(MASON_PLATFORM STREQUAL "android" AND NOT MASON_PLATFORM_VERSION)
|
||||
if (ANDROID_ABI STREQUAL "armeabi-v7a")
|
||||
set(MASON_PLATFORM_VERSION "arm-v7-14" PARENT_SCOPE)
|
||||
elseif (ANDROID_ABI STREQUAL "arm64-v8a")
|
||||
set(MASON_PLATFORM_VERSION "arm-v8-21" PARENT_SCOPE)
|
||||
elseif (ANDROID_ABI STREQUAL "x86")
|
||||
set(MASON_PLATFORM_VERSION "x86-14" PARENT_SCOPE)
|
||||
elseif (ANDROID_ABI STREQUAL "x86_64")
|
||||
set(MASON_PLATFORM_VERSION "x86-64-21" PARENT_SCOPE)
|
||||
else()
|
||||
message(FATAL_ERROR "Unknown ANDROID_ABI '${ANDROID_ABI}'.")
|
||||
endif()
|
||||
elseif(MASON_PLATFORM STREQUAL "ios")
|
||||
set(MASON_PLATFORM_VERSION "8.0" PARENT_SCOPE)
|
||||
else()
|
||||
execute_process(
|
||||
COMMAND uname -m
|
||||
OUTPUT_VARIABLE MASON_PLATFORM_VERSION
|
||||
OUTPUT_STRIP_TRAILING_WHITESPACE)
|
||||
set(MASON_PLATFORM_VERSION "${MASON_PLATFORM_VERSION}" PARENT_SCOPE)
|
||||
endif()
|
||||
endif()
|
||||
endfunction()
|
||||
|
||||
function(mason_use _PACKAGE)
|
||||
if(NOT _PACKAGE)
|
||||
message(FATAL_ERROR "[Mason] No package name given")
|
||||
endif()
|
||||
|
||||
cmake_parse_arguments("" "HEADER_ONLY" "VERSION" "" ${ARGN})
|
||||
|
||||
if(_UNPARSED_ARGUMENTS)
|
||||
message(FATAL_ERROR "[Mason] mason_use() called with unrecognized arguments: ${_UNPARSED_ARGUMENTS}")
|
||||
endif()
|
||||
|
||||
if(NOT _VERSION)
|
||||
message(FATAL_ERROR "[Mason] Specifying a version is required")
|
||||
endif()
|
||||
|
||||
if(MASON_PACKAGE_${_PACKAGE}_INVOCATION STREQUAL "${MASON_INVOCATION}")
|
||||
# Check that the previous invocation of mason_use didn't select another version of this package
|
||||
if(NOT MASON_PACKAGE_${_PACKAGE}_VERSION STREQUAL ${_VERSION})
|
||||
message(FATAL_ERROR "[Mason] Already using ${_PACKAGE} ${MASON_PACKAGE_${_PACKAGE}_VERSION}. Cannot select version ${_VERSION}.")
|
||||
endif()
|
||||
else()
|
||||
if(_HEADER_ONLY)
|
||||
set(_PLATFORM_ID "headers")
|
||||
else()
|
||||
set(_PLATFORM_ID "${MASON_PLATFORM}-${MASON_PLATFORM_VERSION}")
|
||||
endif()
|
||||
|
||||
set(_SLUG "${_PLATFORM_ID}/${_PACKAGE}/${_VERSION}")
|
||||
set(_INSTALL_PATH "${MASON_PACKAGE_DIR}/${_SLUG}")
|
||||
file(RELATIVE_PATH _INSTALL_PATH_RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${_INSTALL_PATH}")
|
||||
|
||||
if(NOT EXISTS "${_INSTALL_PATH}")
|
||||
set(_CACHE_PATH "${MASON_PACKAGE_DIR}/.binaries/${_SLUG}.tar.gz")
|
||||
if (NOT EXISTS "${_CACHE_PATH}")
|
||||
# Download the package
|
||||
set(_URL "${MASON_REPOSITORY}/${_SLUG}.tar.gz")
|
||||
message("[Mason] Downloading package ${_URL}...")
|
||||
|
||||
set(_STATUS)
|
||||
get_filename_component(_CACHE_DIR "${_CACHE_PATH}" DIRECTORY)
|
||||
file(MAKE_DIRECTORY "${_CACHE_DIR}")
|
||||
file(DOWNLOAD "${_URL}" "${_CACHE_PATH}.tmp" STATUS _STATUS TLS_VERIFY ON)
|
||||
|
||||
list(GET _STATUS 0 _STATUS_CODE)
|
||||
list(GET _STATUS 1 _STATUS_STRING)
|
||||
if(NOT _STATUS_CODE EQUAL 0)
|
||||
message(FATAL_ERROR "[Mason] Failed to download ${_URL}: ${_STATUS_STRING}")
|
||||
else()
|
||||
# We downloaded to a temporary file to prevent half-finished downloads
|
||||
file(RENAME "${_CACHE_PATH}.tmp" "${_CACHE_PATH}")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
# Unpack the package
|
||||
message("[Mason] Unpacking package to ${_INSTALL_PATH_RELATIVE}...")
|
||||
file(MAKE_DIRECTORY "${_INSTALL_PATH}")
|
||||
execute_process(
|
||||
COMMAND ${CMAKE_COMMAND} -E tar xzf "${_CACHE_PATH}"
|
||||
WORKING_DIRECTORY "${_INSTALL_PATH}")
|
||||
endif()
|
||||
|
||||
# Error out if there is no config file.
|
||||
if(NOT EXISTS "${_INSTALL_PATH}/mason.ini")
|
||||
message(FATAL_ERROR "[Mason] Could not find mason.ini for package ${_PACKAGE} ${_VERSION}")
|
||||
endif()
|
||||
|
||||
set(MASON_PACKAGE_${_PACKAGE}_PREFIX "${_INSTALL_PATH}" CACHE STRING "${_PACKAGE} ${_INSTALL_PATH}" FORCE)
|
||||
mark_as_advanced(MASON_PACKAGE_${_PACKAGE}_PREFIX)
|
||||
|
||||
# Load the configuration from the ini file
|
||||
file(STRINGS "${_INSTALL_PATH}/mason.ini" _CONFIG_FILE)
|
||||
foreach(_LINE IN LISTS _CONFIG_FILE)
|
||||
string(REGEX MATCH "^([a-z_]+) *= *" _KEY "${_LINE}")
|
||||
if (_KEY)
|
||||
string(LENGTH "${_KEY}" _KEY_LENGTH)
|
||||
string(SUBSTRING "${_LINE}" ${_KEY_LENGTH} -1 _VALUE)
|
||||
string(REGEX REPLACE ";.*$" "" _VALUE "${_VALUE}") # Trim trailing commas
|
||||
string(REPLACE "{prefix}" "${_INSTALL_PATH}" _VALUE "${_VALUE}")
|
||||
string(STRIP "${_VALUE}" _VALUE)
|
||||
string(REPLACE "=" "" _KEY "${_KEY}")
|
||||
string(STRIP "${_KEY}" _KEY)
|
||||
string(TOUPPER "${_KEY}" _KEY)
|
||||
if(_KEY STREQUAL "INCLUDE_DIRS" OR _KEY STREQUAL "STATIC_LIBS" )
|
||||
separate_arguments(_VALUE)
|
||||
endif()
|
||||
set(MASON_PACKAGE_${_PACKAGE}_${_KEY} "${_VALUE}" CACHE STRING "${_PACKAGE} ${_KEY}" FORCE)
|
||||
mark_as_advanced(MASON_PACKAGE_${_PACKAGE}_${_KEY})
|
||||
endif()
|
||||
endforeach()
|
||||
|
||||
# Compare version in the package to catch errors early on
|
||||
if(NOT _VERSION STREQUAL MASON_PACKAGE_${_PACKAGE}_VERSION)
|
||||
message(FATAL_ERROR "[Mason] Package at ${_INSTALL_PATH_RELATIVE} has version '${MASON_PACKAGE_${_PACKAGE}_VERSION}', but required '${_VERSION}'")
|
||||
endif()
|
||||
|
||||
if(NOT _PACKAGE STREQUAL MASON_PACKAGE_${_PACKAGE}_NAME)
|
||||
message(FATAL_ERROR "[Mason] Package at ${_INSTALL_PATH_RELATIVE} has name '${MASON_PACKAGE_${_PACKAGE}_NAME}', but required '${_NAME}'")
|
||||
endif()
|
||||
|
||||
if(NOT _HEADER_ONLY)
|
||||
if(NOT MASON_PLATFORM STREQUAL MASON_PACKAGE_${_PACKAGE}_PLATFORM)
|
||||
message(FATAL_ERROR "[Mason] Package at ${_INSTALL_PATH_RELATIVE} has platform '${MASON_PACKAGE_${_PACKAGE}_PLATFORM}', but required '${MASON_PLATFORM}'")
|
||||
endif()
|
||||
|
||||
if(NOT MASON_PLATFORM_VERSION STREQUAL MASON_PACKAGE_${_PACKAGE}_PLATFORM_VERSION)
|
||||
message(FATAL_ERROR "[Mason] Package at ${_INSTALL_PATH_RELATIVE} has platform version '${MASON_PACKAGE_${_PACKAGE}_PLATFORM_VERSION}', but required '${MASON_PLATFORM_VERSION}'")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
# Concatenate the static libs and libraries
|
||||
set(_LIBRARIES)
|
||||
list(APPEND _LIBRARIES ${MASON_PACKAGE_${_PACKAGE}_STATIC_LIBS} ${MASON_PACKAGE_${_PACKAGE}_LDFLAGS})
|
||||
set(MASON_PACKAGE_${_PACKAGE}_LIBRARIES "${_LIBRARIES}" CACHE STRING "${_PACKAGE} _LIBRARIES" FORCE)
|
||||
mark_as_advanced(MASON_PACKAGE_${_PACKAGE}_LIBRARIES)
|
||||
|
||||
if(NOT _HEADER_ONLY)
|
||||
string(REGEX MATCHALL "(^| +)-L *([^ ]+)" MASON_PACKAGE_${_PACKAGE}_LIBRARY_DIRS "${MASON_PACKAGE_${_PACKAGE}_LDFLAGS}")
|
||||
string(REGEX REPLACE "(^| +)-L *" "\\1" MASON_PACKAGE_${_PACKAGE}_LIBRARY_DIRS "${MASON_PACKAGE_${_PACKAGE}_LIBRARY_DIRS}")
|
||||
set(MASON_PACKAGE_${_PACKAGE}_LIBRARY_DIRS "${MASON_PACKAGE_${_PACKAGE}_LIBRARY_DIRS}" CACHE STRING "${_PACKAGE} ${MASON_PACKAGE_${_PACKAGE}_LIBRARY_DIRS}" FORCE)
|
||||
mark_as_advanced(MASON_PACKAGE_${_PACKAGE}_LIBRARY_DIRS)
|
||||
endif()
|
||||
|
||||
# Store invocation ID to prevent different versions of the same package in one invocation
|
||||
set(MASON_PACKAGE_${_PACKAGE}_INVOCATION "${MASON_INVOCATION}" CACHE INTERNAL "${_PACKAGE} invocation ID" FORCE)
|
||||
endif()
|
||||
endfunction()
|
||||
|
||||
macro(target_add_mason_package _TARGET _VISIBILITY _PACKAGE)
|
||||
if (NOT MASON_PACKAGE_${_PACKAGE}_INVOCATION)
|
||||
message(FATAL_ERROR "[Mason] Package ${_PACKAGE} has not been initialized yet")
|
||||
endif()
|
||||
|
||||
target_include_directories(${_TARGET} ${_VISIBILITY} "${MASON_PACKAGE_${_PACKAGE}_INCLUDE_DIRS}")
|
||||
target_compile_definitions(${_TARGET} ${_VISIBILITY} "${MASON_PACKAGE_${_PACKAGE}_DEFINITIONS}")
|
||||
target_compile_options(${_TARGET} ${_VISIBILITY} "${MASON_PACKAGE_${_PACKAGE}_OPTIONS}")
|
||||
target_link_libraries(${_TARGET} ${_VISIBILITY} "${MASON_PACKAGE_${_PACKAGE}_LIBRARIES}")
|
||||
endmacro()
|
||||
|
||||
# Setup
|
||||
|
||||
string(RANDOM LENGTH 16 MASON_INVOCATION)
|
||||
|
||||
# Read environment variables if CMake is run in command mode
|
||||
if (CMAKE_ARGC)
|
||||
set(MASON_PLATFORM "$ENV{MASON_PLATFORM}")
|
||||
set(MASON_PLATFORM_VERSION "$ENV{MASON_PLATFORM_VERSION}")
|
||||
set(MASON_PACKAGE_DIR "$ENV{MASON_PACKAGE_DIR}")
|
||||
set(MASON_REPOSITORY "$ENV{MASON_REPOSITORY}")
|
||||
endif()
|
||||
|
||||
# Directory where Mason packages are located; typically ends with mason_packages
|
||||
if (NOT MASON_PACKAGE_DIR)
|
||||
set(MASON_PACKAGE_DIR "${CMAKE_SOURCE_DIR}/mason_packages")
|
||||
endif()
|
||||
|
||||
# URL prefix of where packages are located.
|
||||
if (NOT MASON_REPOSITORY)
|
||||
set(MASON_REPOSITORY "https://mason-binaries.s3.amazonaws.com")
|
||||
endif()
|
||||
|
||||
mason_detect_platform()
|
||||
|
||||
# Execute commands if CMake is run in command mode\
|
||||
if (CMAKE_ARGC AND "${CMAKE_SCRIPT_MODE_FILE}" STREQUAL "${CMAKE_CURRENT_LIST_DIR}/mason.cmake")
|
||||
# Collect remaining arguments for passing to mason_use
|
||||
set(_MASON_ARGS)
|
||||
foreach(I RANGE 4 ${CMAKE_ARGC})
|
||||
list(APPEND _MASON_ARGS "${CMAKE_ARGV${I}}")
|
||||
endforeach()
|
||||
|
||||
# Install the package
|
||||
mason_use(${_MASON_ARGS})
|
||||
|
||||
# Optionally print variables
|
||||
if(DEFINED MASON_PACKAGE_${CMAKE_ARGV4}_${CMAKE_ARGV3})
|
||||
# CMake can't write to stdout with message()
|
||||
execute_process(COMMAND ${CMAKE_COMMAND} -E echo "${MASON_PACKAGE_${CMAKE_ARGV4}_${CMAKE_ARGV3}}")
|
||||
endif()
|
||||
endif()
|
||||
232
cmake/mbgl.cmake
232
cmake/mbgl.cmake
@@ -1,232 +0,0 @@
|
||||
if (NOT MBGL_PLATFORM)
|
||||
if (CMAKE_HOST_SYSTEM_NAME STREQUAL "Darwin")
|
||||
set(MBGL_PLATFORM "macos")
|
||||
else()
|
||||
set(MBGL_PLATFORM "linux")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
if(WITH_NODEJS)
|
||||
find_program(NodeJS_EXECUTABLE NAMES nodejs node)
|
||||
if (NOT NodeJS_EXECUTABLE)
|
||||
message(FATAL_ERROR "Could not find Node.js")
|
||||
endif()
|
||||
|
||||
find_program(npm_EXECUTABLE NAMES npm)
|
||||
if (NOT npm_EXECUTABLE)
|
||||
message(FATAL_ERROR "Could not find npm")
|
||||
endif()
|
||||
|
||||
execute_process(
|
||||
COMMAND "${NodeJS_EXECUTABLE}" -e "process.stdout.write(process.versions.node)"
|
||||
RESULT_VARIABLE _STATUS_CODE
|
||||
OUTPUT_VARIABLE NodeJS_VERSION
|
||||
ERROR_VARIABLE _STATUS_MESSAGE
|
||||
)
|
||||
if(NOT _STATUS_CODE EQUAL 0)
|
||||
message(FATAL_ERROR "Could not detect Node.js version: ${_STATUS_MESSAGE}")
|
||||
endif()
|
||||
|
||||
execute_process(
|
||||
COMMAND "${NodeJS_EXECUTABLE}" -e "process.stdout.write(process.versions.modules)"
|
||||
RESULT_VARIABLE _STATUS_CODE
|
||||
OUTPUT_VARIABLE NodeJS_ABI
|
||||
ERROR_VARIABLE _STATUS_MESSAGE
|
||||
)
|
||||
if(NOT _STATUS_CODE EQUAL 0)
|
||||
message(FATAL_ERROR "Could not detect Node.js ABI version: ${_STATUS_MESSAGE}")
|
||||
endif()
|
||||
|
||||
function(_npm_install DIRECTORY NAME ADDITIONAL_DEPS)
|
||||
SET(NPM_INSTALL_FAILED FALSE)
|
||||
if("${DIRECTORY}/package.json" IS_NEWER_THAN "${DIRECTORY}/node_modules/.${NAME}.stamp")
|
||||
message(STATUS "Running 'npm install' for ${NAME}...")
|
||||
execute_process(
|
||||
COMMAND "${NodeJS_EXECUTABLE}" "${npm_EXECUTABLE}" install --verbose --ignore-scripts
|
||||
WORKING_DIRECTORY "${DIRECTORY}"
|
||||
RESULT_VARIABLE NPM_INSTALL_FAILED
|
||||
OUTPUT_VARIABLE NPM_OUTPUT
|
||||
ERROR_VARIABLE NPM_OUTPUT)
|
||||
message(STATUS "Finished 'npm install' for ${NAME}...")
|
||||
if(NOT NPM_INSTALL_FAILED)
|
||||
execute_process(COMMAND ${CMAKE_COMMAND} -E touch "${DIRECTORY}/node_modules/.${NAME}.stamp")
|
||||
else()
|
||||
message(FATAL_ERROR "NPM install failed:\n${NPM_OUTPUT}")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
add_custom_command(
|
||||
OUTPUT "${DIRECTORY}/node_modules/.${NAME}.stamp"
|
||||
COMMAND "${NodeJS_EXECUTABLE}" "${npm_EXECUTABLE}" install --ignore-scripts
|
||||
COMMAND ${CMAKE_COMMAND} -E touch "${DIRECTORY}/node_modules/.${NAME}.stamp"
|
||||
WORKING_DIRECTORY "${DIRECTORY}"
|
||||
DEPENDS ${ADDITIONAL_DEPS} "${DIRECTORY}/package.json"
|
||||
COMMENT "Running 'npm install' for ${NAME}...")
|
||||
endfunction()
|
||||
|
||||
# Run submodule update
|
||||
set(MBGL_SUBMODULES mapbox-gl-js)
|
||||
if(MBGL_PLATFORM STREQUAL "ios")
|
||||
list(APPEND MBGL_SUBMODULES platform/ios/vendor/mapbox-events-ios)
|
||||
endif()
|
||||
if(MBGL_PLATFORM STREQUAL "ios" OR MBGL_PLATFORM STREQUAL "macos")
|
||||
list(APPEND MBGL_SUBMODULES platform/darwin/docs/theme)
|
||||
endif()
|
||||
|
||||
message(STATUS "Updating submodules...")
|
||||
execute_process(
|
||||
COMMAND git submodule update --init ${MBGL_SUBMODULES}
|
||||
WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")
|
||||
|
||||
if(NOT EXISTS "${CMAKE_SOURCE_DIR}/mapbox-gl-js/node_modules")
|
||||
# Symlink mapbox-gl-js/node_modules so that the modules that are
|
||||
# about to be installed get cached between CI runs.
|
||||
execute_process(
|
||||
COMMAND ln -sF ../node_modules .
|
||||
WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}/mapbox-gl-js")
|
||||
endif()
|
||||
|
||||
# Add target for running submodule update during builds
|
||||
add_custom_target(
|
||||
update-submodules ALL
|
||||
COMMAND git submodule update --init ${MBGL_SUBMODULES}
|
||||
WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}"
|
||||
COMMENT "Updating submodules..."
|
||||
)
|
||||
set_target_properties(update-submodules PROPERTIES FOLDER "Misc")
|
||||
|
||||
# Run npm install for both directories, and add custom commands, and a target that depends on them.
|
||||
_npm_install("${CMAKE_SOURCE_DIR}" mapbox-gl-native update-submodules)
|
||||
_npm_install("${CMAKE_SOURCE_DIR}/mapbox-gl-js/test/integration" mapbox-gl-js "${CMAKE_SOURCE_DIR}/node_modules/.mapbox-gl-native.stamp")
|
||||
add_custom_target(
|
||||
npm-install ALL
|
||||
DEPENDS "${CMAKE_SOURCE_DIR}/node_modules/.mapbox-gl-js.stamp"
|
||||
)
|
||||
set_target_properties(npm-install PROPERTIES FOLDER "Misc")
|
||||
endif()
|
||||
|
||||
# Generate source groups so the files are properly sorted in IDEs like Xcode.
|
||||
function(create_source_groups target)
|
||||
get_target_property(type ${target} TYPE)
|
||||
if(type AND type STREQUAL "INTERFACE_LIBRARY")
|
||||
get_target_property(sources ${target} INTERFACE_SOURCES)
|
||||
else()
|
||||
get_target_property(sources ${target} SOURCES)
|
||||
endif()
|
||||
foreach(file ${sources})
|
||||
get_filename_component(file "${file}" ABSOLUTE)
|
||||
string(REGEX REPLACE "^${CMAKE_SOURCE_DIR}/" "" group "${file}")
|
||||
get_filename_component(group "${group}" DIRECTORY)
|
||||
string(REPLACE "/" "\\" group "${group}")
|
||||
source_group("${group}" FILES "${file}")
|
||||
endforeach()
|
||||
endfunction()
|
||||
|
||||
function(load_sources_list VAR FILELIST)
|
||||
set(_FILES)
|
||||
file(READ "${FILELIST}" _LINES)
|
||||
# Note: this isn't really parsing JSON, but it's good enough for our purposes.
|
||||
set(_REGEX "(^|\n) *(\"([^\"]+)\" *: *)?\"([^\"]+)\",?(\n|$)")
|
||||
string(REGEX MATCHALL "${_REGEX}" _MATCHES "${_LINES}")
|
||||
foreach(_MATCH IN LISTS _MATCHES)
|
||||
string(REGEX MATCH "${_REGEX}" _FILE "${_MATCH}")
|
||||
if (_FILE AND NOT CMAKE_MATCH_3 STREQUAL "//")
|
||||
list(APPEND _FILES "${CMAKE_SOURCE_DIR}/${CMAKE_MATCH_4}")
|
||||
endif()
|
||||
endforeach()
|
||||
set(${VAR} "${_FILES}" PARENT_SCOPE)
|
||||
set_property(DIRECTORY "${CMAKE_SOURCE_DIR}" APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${FILELIST}")
|
||||
endfunction()
|
||||
|
||||
function(target_sources_from_file TARGET TYPE FILELIST)
|
||||
load_sources_list(_FILELIST "${FILELIST}")
|
||||
target_sources(${TARGET} ${TYPE} "${_FILELIST}")
|
||||
endfunction()
|
||||
|
||||
# Creates a library target for a vendored dependency
|
||||
function(add_vendor_target NAME TYPE)
|
||||
set(INCLUDE_TYPE "INTERFACE")
|
||||
set(SOURCE_TYPE "INTERFACE")
|
||||
if (TYPE STREQUAL "STATIC" OR TYPE STREQUAL "SHARED")
|
||||
add_library(${NAME} ${TYPE} "${CMAKE_CURRENT_SOURCE_DIR}/cmake/empty.cpp")
|
||||
set(INCLUDE_TYPE "PUBLIC")
|
||||
set(SOURCE_TYPE "PRIVATE")
|
||||
set_target_properties(${NAME} PROPERTIES SOURCES "")
|
||||
else()
|
||||
add_library(${NAME} ${TYPE})
|
||||
endif()
|
||||
set_target_properties(${NAME} PROPERTIES INTERFACE_SOURCES "")
|
||||
file(STRINGS "${CMAKE_CURRENT_SOURCE_DIR}/vendor/${NAME}/files.txt" FILES)
|
||||
foreach(FILE IN LISTS FILES)
|
||||
target_sources(${NAME} ${SOURCE_TYPE} "${CMAKE_CURRENT_SOURCE_DIR}/vendor/${NAME}/${FILE}")
|
||||
endforeach()
|
||||
target_include_directories(${NAME} SYSTEM ${INCLUDE_TYPE} "${CMAKE_CURRENT_SOURCE_DIR}/vendor/${NAME}/include")
|
||||
create_source_groups(${NAME})
|
||||
endfunction()
|
||||
|
||||
# This little macro lets you set any XCode specific property
|
||||
macro(set_xcode_property TARGET XCODE_PROPERTY XCODE_VALUE)
|
||||
set_property(TARGET ${TARGET} PROPERTY XCODE_ATTRIBUTE_${XCODE_PROPERTY} ${XCODE_VALUE})
|
||||
endmacro (set_xcode_property)
|
||||
|
||||
function(set_xcconfig_target_properties target)
|
||||
# Create a list of linked libraries for use in the xcconfig generation script.
|
||||
get_property(result TARGET ${target} PROPERTY INTERFACE_LINK_LIBRARIES)
|
||||
string(GENEX_STRIP "${result}" result)
|
||||
# Remove target names from the list of linker flags, since Xcode can't deal with them.
|
||||
set(link_flags)
|
||||
foreach(item IN LISTS result)
|
||||
if (NOT TARGET ${item})
|
||||
list(APPEND link_flags ${item})
|
||||
endif()
|
||||
endforeach()
|
||||
string(REGEX REPLACE "(^|;)-framework " "\\1-framework;" link_flags "${link_flags}")
|
||||
string(REPLACE ";" "\" \"" link_flags "${link_flags}")
|
||||
set_xcode_property(${target} XCCONFIG_LINK_LIBRARIES "${link_flags}")
|
||||
endfunction()
|
||||
|
||||
# Set Xcode project build settings to be consistent with the CXX flags we're
|
||||
# using. (Otherwise, Xcode's defaults may override some of these.)
|
||||
function(initialize_xcode_cxx_build_settings target)
|
||||
# -Wall
|
||||
set_xcode_property(${target} GCC_WARN_SIGN_COMPARE YES)
|
||||
set_xcode_property(${target} GCC_WARN_UNINITIALIZED_AUTOS YES)
|
||||
set_xcode_property(${target} GCC_WARN_UNKNOWN_PRAGMAS YES)
|
||||
set_xcode_property(${target} GCC_WARN_UNUSED_FUNCTION YES)
|
||||
set_xcode_property(${target} GCC_WARN_UNUSED_LABEL YES)
|
||||
set_xcode_property(${target} GCC_WARN_UNUSED_PARAMETER YES)
|
||||
set_xcode_property(${target} GCC_WARN_UNUSED_VARIABLE YES)
|
||||
|
||||
# -Wextra
|
||||
set_xcode_property(${target} CLANG_WARN_EMPTY_BODY YES)
|
||||
set_xcode_property(${target} GCC_WARN_ABOUT_MISSING_FIELD_INITIALIZERS YES)
|
||||
|
||||
# -Wshadow
|
||||
set_xcode_property(${target} GCC_WARN_SHADOW YES)
|
||||
|
||||
# -Wnon-virtual-dtor
|
||||
set_xcode_property(${target} GCC_WARN_NON_VIRTUAL_DESTRUCTOR YES)
|
||||
|
||||
# -Wnon-literal-conversion
|
||||
set_xcode_property(${target} CLANG_WARN_NON_LITERAL_NULL_CONVERSION YES)
|
||||
|
||||
# -Wrange-loop-analysis
|
||||
set_xcode_property(${target} CLANG_WARN_RANGE_LOOP_ANALYSIS YES)
|
||||
|
||||
# -flto
|
||||
set_xcode_property(${target} LLVM_LTO $<$<OR:$<CONFIG:Release>,$<CONFIG:RelWithDebInfo>>:YES>)
|
||||
|
||||
# Make all build configurations debuggable — except Release.
|
||||
set_xcode_property(${target} GCC_GENERATE_DEBUGGING_SYMBOLS $<$<NOT:$<CONFIG:Release>>:YES>)
|
||||
|
||||
# -Wunguarded-availability
|
||||
set_xcode_property(${target} CLANG_WARN_UNGUARDED_AVAILABILITY YES_AGGRESSIVE)
|
||||
|
||||
if (DEFINED ENV{CI})
|
||||
set_xcode_property(${target} COMPILER_INDEX_STORE_ENABLE NO)
|
||||
endif()
|
||||
endfunction()
|
||||
|
||||
# CMake 3.1 does not have this yet.
|
||||
set(CMAKE_CXX14_STANDARD_COMPILE_OPTION "-std=c++14")
|
||||
set(CMAKE_CXX14_EXTENSION_COMPILE_OPTION "-std=gnu++14")
|
||||
142
cmake/node.cmake
142
cmake/node.cmake
@@ -1,142 +0,0 @@
|
||||
# Load Node.js
|
||||
set(NODE_MODULE_CACHE_DIR "${CMAKE_SOURCE_DIR}/build/headers")
|
||||
include(node_modules/@mapbox/cmake-node-module/module.cmake)
|
||||
|
||||
add_library(mbgl-loop-node INTERFACE)
|
||||
|
||||
target_sources(mbgl-loop-node INTERFACE
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platform/default/src/mbgl/util/async_task.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platform/default/src/mbgl/util/run_loop.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platform/default/src/mbgl/util/timer.cpp
|
||||
)
|
||||
|
||||
target_include_directories(mbgl-loop-node INTERFACE
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/include
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src
|
||||
)
|
||||
|
||||
create_source_groups(mbgl-loop-node)
|
||||
|
||||
|
||||
add_node_module(mbgl-node
|
||||
INSTALL_PATH "lib/{node_abi}/mbgl.node"
|
||||
NAN_VERSION "2.14.0"
|
||||
|
||||
# Don't build for Node 4.x, 5.x, 7.x, 9.x, 11.x and 12.x
|
||||
# See https://nodejs.org/en/download/releases/ for mapping of Node version to ABI number.
|
||||
# Changes to this property should happen in tandem with updates to the version targets
|
||||
# in platform/node/scripts/publish.sh and the "node" engines property in package.json.
|
||||
EXCLUDE_NODE_ABIS 46 47 51 59 67 72
|
||||
)
|
||||
|
||||
target_sources(mbgl-node INTERFACE
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platform/node/src/node_mapbox_gl_native.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platform/node/src/node_mapbox_gl_native.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platform/node/src/node_logging.hpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platform/node/src/node_logging.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platform/node/src/node_conversion.hpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platform/node/src/node_map.hpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platform/node/src/node_map.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platform/node/src/node_request.hpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platform/node/src/node_request.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platform/node/src/node_feature.hpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platform/node/src/node_feature.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platform/node/src/node_expression.hpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platform/node/src/node_expression.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platform/node/src/util/async_queue.hpp
|
||||
)
|
||||
|
||||
target_include_directories(mbgl-node INTERFACE
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platform/default/include
|
||||
)
|
||||
|
||||
target_link_libraries(mbgl-node INTERFACE
|
||||
mbgl-core
|
||||
mbgl-loop-node
|
||||
)
|
||||
|
||||
set_target_properties(mbgl-node.all PROPERTIES FOLDER "Node.js")
|
||||
|
||||
add_custom_target(mbgl-node.active DEPENDS mbgl-node.abi-${NodeJS_ABI})
|
||||
set_target_properties(mbgl-node.active PROPERTIES FOLDER "Node.js")
|
||||
|
||||
mbgl_platform_node()
|
||||
|
||||
create_source_groups(mbgl-node)
|
||||
|
||||
foreach(ABI IN LISTS mbgl-node::abis)
|
||||
initialize_xcode_cxx_build_settings(mbgl-node.abi-${ABI})
|
||||
set_target_properties(mbgl-node.abi-${ABI} PROPERTIES FOLDER "Node.js")
|
||||
xcode_create_scheme(
|
||||
TARGET mbgl-node.abi-${ABI}
|
||||
NAME "mbgl-node (ABI ${ABI})"
|
||||
)
|
||||
endforeach()
|
||||
|
||||
xcode_create_scheme(
|
||||
TARGET mbgl-node.active
|
||||
TYPE library
|
||||
NAME "mbgl-node (Active ABI)"
|
||||
)
|
||||
|
||||
xcode_create_scheme(
|
||||
TARGET mbgl-node.all
|
||||
TYPE library
|
||||
NAME "mbgl-node (All ABIs)"
|
||||
)
|
||||
|
||||
xcode_create_scheme(
|
||||
TARGET mbgl-node.active
|
||||
TYPE node
|
||||
NAME "node tests (Active ABI)"
|
||||
ARGS
|
||||
"node_modules/.bin/tape platform/node/test/js/**/*.test.js"
|
||||
)
|
||||
|
||||
xcode_create_scheme(
|
||||
TARGET mbgl-node.active
|
||||
TYPE node
|
||||
NAME "node render tests (Active ABI)"
|
||||
ARGS
|
||||
"-r esm"
|
||||
"platform/node/test/render.test.js"
|
||||
OPTIONAL_ARGS
|
||||
"group"
|
||||
"test"
|
||||
)
|
||||
|
||||
xcode_create_scheme(
|
||||
TARGET mbgl-node.active
|
||||
TYPE node
|
||||
NAME "node query tests (Active ABI)"
|
||||
ARGS
|
||||
"-r esm"
|
||||
"platform/node/test/query.test.js"
|
||||
OPTIONAL_ARGS
|
||||
"group"
|
||||
"test"
|
||||
)
|
||||
|
||||
xcode_create_scheme(
|
||||
TARGET mbgl-node.active
|
||||
TYPE node
|
||||
NAME "node expression tests (Active ABI)"
|
||||
ARGS
|
||||
"-r esm"
|
||||
"platform/node/test/expression.test.js"
|
||||
OPTIONAL_ARGS
|
||||
"group"
|
||||
"test"
|
||||
)
|
||||
|
||||
xcode_create_scheme(
|
||||
TARGET mbgl-node.active
|
||||
TYPE node
|
||||
NAME "node-benchmark (Active ABI)"
|
||||
ARGS
|
||||
"-r esm"
|
||||
"platform/node/test/benchmark.js"
|
||||
OPTIONAL_ARGS
|
||||
"group"
|
||||
"test"
|
||||
)
|
||||
@@ -1,102 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0810"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "${XCSCHEME_BLUEPRINT_ID}"
|
||||
BuildableName = "${XCSCHEME_BUILDABLE_NAME}"
|
||||
BlueprintName = "${XCSCHEME_BLUEPRINT_NAME}"
|
||||
ReferencedContainer = "container:${XCSCHEME_CONTAINER}">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
</Testables>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "YES"
|
||||
customWorkingDirectory = "${XCSCHEME_WORKING_DIRECTORY}"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<PathRunnable
|
||||
runnableDebuggingMode = "0"
|
||||
FilePath = "${XCSCHEME_NODE_EXECUTABLE}">
|
||||
</PathRunnable>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "${XCSCHEME_BLUEPRINT_ID}"
|
||||
BuildableName = "${XCSCHEME_BUILDABLE_NAME}"
|
||||
BlueprintName = "${XCSCHEME_BLUEPRINT_NAME}"
|
||||
ReferencedContainer = "container:${XCSCHEME_CONTAINER}">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<CommandLineArguments>${XCSCHEME_COMMAND_LINE_ARGS}
|
||||
</CommandLineArguments>
|
||||
<EnvironmentVariables>
|
||||
<EnvironmentVariable
|
||||
key = "PATH"
|
||||
value = "${XCSCHEME_NODE_PATH}:$PATH"
|
||||
isEnabled = "YES">
|
||||
</EnvironmentVariable>
|
||||
</EnvironmentVariables>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "YES"
|
||||
customWorkingDirectory = "${XCSCHEME_WORKING_DIRECTORY}"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES"
|
||||
debugDocumentVersioning = "YES">
|
||||
<PathRunnable
|
||||
runnableDebuggingMode = "0"
|
||||
FilePath = "${XCSCHEME_NODE_EXECUTABLE}">
|
||||
</PathRunnable>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "${XCSCHEME_BLUEPRINT_ID}"
|
||||
BuildableName = "${XCSCHEME_BUILDABLE_NAME}"
|
||||
BlueprintName = "${XCSCHEME_BLUEPRINT_NAME}"
|
||||
ReferencedContainer = "container:${XCSCHEME_CONTAINER}">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -1,35 +0,0 @@
|
||||
add_executable(mbgl-offline
|
||||
bin/offline.cpp
|
||||
)
|
||||
|
||||
target_include_directories(mbgl-offline
|
||||
PRIVATE platform/default/include
|
||||
)
|
||||
|
||||
target_link_libraries(mbgl-offline
|
||||
PRIVATE mbgl-core
|
||||
PRIVATE Mapbox::Base::Extras::args
|
||||
)
|
||||
|
||||
mbgl_platform_offline()
|
||||
|
||||
create_source_groups(mbgl-offline)
|
||||
|
||||
initialize_xcode_cxx_build_settings(mbgl-offline)
|
||||
|
||||
set_target_properties(mbgl-offline PROPERTIES FOLDER "Executables")
|
||||
|
||||
xcode_create_scheme(
|
||||
TARGET mbgl-offline
|
||||
OPTIONAL_ARGS
|
||||
"--style=file.json"
|
||||
"--north=37.2"
|
||||
"--west=-122.8"
|
||||
"--south=38.1"
|
||||
"--east=-121.7"
|
||||
"--minZoom=0.0"
|
||||
"--maxZoom=15.0"
|
||||
"--pixelRatio=1.0"
|
||||
"--token="
|
||||
"--output=offline.db"
|
||||
)
|
||||
@@ -1,60 +0,0 @@
|
||||
add_executable(
|
||||
mbgl-render-test
|
||||
expression-test/test_runner_common.cpp
|
||||
expression-test/test_runner_common.hpp
|
||||
platform/default/src/mbgl/render-test/main.cpp
|
||||
render-test/allocation_index.cpp
|
||||
render-test/allocation_index.hpp
|
||||
render-test/filesystem.hpp
|
||||
render-test/filesystem.hpp
|
||||
render-test/include/mbgl/render_test.hpp
|
||||
render-test/metadata.hpp
|
||||
render-test/parser.cpp
|
||||
render-test/parser.hpp
|
||||
render-test/render_test.cpp
|
||||
render-test/runner.cpp
|
||||
render-test/runner.hpp
|
||||
)
|
||||
|
||||
if(APPLE)
|
||||
target_link_libraries(
|
||||
mbgl-render-test
|
||||
PRIVATE mbgl-loop-darwin
|
||||
)
|
||||
else()
|
||||
target_link_libraries(
|
||||
mbgl-render-test
|
||||
PRIVATE mbgl-loop-uv
|
||||
)
|
||||
endif()
|
||||
|
||||
target_include_directories(
|
||||
mbgl-render-test
|
||||
PRIVATE src
|
||||
PRIVATE platform/default/include
|
||||
PRIVATE render-test
|
||||
)
|
||||
|
||||
target_include_directories(
|
||||
mbgl-render-test
|
||||
PUBLIC render-test/include
|
||||
PUBLIC include
|
||||
)
|
||||
|
||||
target_link_libraries(
|
||||
mbgl-render-test
|
||||
PRIVATE
|
||||
mbgl-core
|
||||
mbgl-filesource
|
||||
Mapbox::Base::Extras::args
|
||||
mbgl-vendor-expected
|
||||
Mapbox::Base::Extras::filesystem
|
||||
Mapbox::Base::pixelmatch-cpp
|
||||
Mapbox::Base::Extras::rapidjson
|
||||
)
|
||||
|
||||
create_source_groups(mbgl-render-test)
|
||||
|
||||
set_target_properties(mbgl-render-test PROPERTIES FOLDER "Executables")
|
||||
|
||||
add_definitions(-DTEST_RUNNER_ROOT_PATH="${CMAKE_SOURCE_DIR}")
|
||||
@@ -1,39 +0,0 @@
|
||||
add_executable(mbgl-render
|
||||
bin/render.cpp
|
||||
)
|
||||
|
||||
target_include_directories(mbgl-render
|
||||
PRIVATE platform/default/include
|
||||
)
|
||||
|
||||
target_link_libraries(mbgl-render
|
||||
PRIVATE mbgl-core
|
||||
PRIVATE Mapbox::Base::Extras::args
|
||||
)
|
||||
|
||||
mbgl_platform_render()
|
||||
|
||||
create_source_groups(mbgl-render)
|
||||
|
||||
initialize_xcode_cxx_build_settings(mbgl-render)
|
||||
|
||||
set_target_properties(mbgl-render PROPERTIES FOLDER "Executables")
|
||||
|
||||
xcode_create_scheme(
|
||||
TARGET mbgl-render
|
||||
OPTIONAL_ARGS
|
||||
"--style=file.json"
|
||||
"--lon=0"
|
||||
"--lat=0"
|
||||
"--zoom=0"
|
||||
"--bearing=0"
|
||||
"--pitch=0"
|
||||
"--width=512"
|
||||
"--height=512"
|
||||
"--ratio=1"
|
||||
"--token="
|
||||
"--debug"
|
||||
"--output=out.png"
|
||||
"--cache=cache.sqlite"
|
||||
"--assets=."
|
||||
)
|
||||
@@ -1,47 +0,0 @@
|
||||
add_vendor_target(sqlite STATIC)
|
||||
|
||||
target_compile_definitions(sqlite
|
||||
PRIVATE "-DVERSION=\"3.24.0\""
|
||||
PRIVATE "-DSTDC_HEADERS=int"
|
||||
PRIVATE "-DHAVE_SYS_TYPES_H=1"
|
||||
PRIVATE "-DHAVE_SYS_STAT_H=1"
|
||||
PRIVATE "-DHAVE_STDLIB_H=1"
|
||||
PRIVATE "-DHAVE_STRING_H=1"
|
||||
PRIVATE "-DHAVE_MEMORY_H=1"
|
||||
PRIVATE "-DHAVE_STRINGS_H=1"
|
||||
PRIVATE "-DHAVE_INTTYPES_H=1"
|
||||
PRIVATE "-DHAVE_STDINT_H=1"
|
||||
PRIVATE "-DHAVE_UNISTD_H=1"
|
||||
PRIVATE "-DHAVE_DLFCN_H=1"
|
||||
PRIVATE "-DHAVE_FDATASYNC=1"
|
||||
PRIVATE "-DHAVE_USLEEP=1"
|
||||
PRIVATE "-DHAVE_LOCALTIME_R=1"
|
||||
PRIVATE "-DHAVE_GMTIME_R=1"
|
||||
PRIVATE "-DHAVE_DECL_STRERROR_R=1"
|
||||
PRIVATE "-DHAVE_STRERROR_R=1"
|
||||
PRIVATE "-DHAVE_ZLIB_H=1"
|
||||
PRIVATE "-D_REENTRANT=1"
|
||||
PRIVATE "-DSQLITE_THREADSAFE=1"
|
||||
PRIVATE "-DSQLITE_HAVE_ZLIB"
|
||||
|
||||
# These are disabled on purpose, since we're not using these features.
|
||||
# PRIVATE "-DSQLITE_ENABLE_FTS5"
|
||||
# PRIVATE "-DSQLITE_ENABLE_JSON1"
|
||||
# PRIVATE "-DSQLITE_ENABLE_FTS3"
|
||||
# PRIVATE "-DSQLITE_ENABLE_RTREE"
|
||||
)
|
||||
|
||||
target_compile_options(sqlite
|
||||
PRIVATE "-Wno-int-conversion"
|
||||
PRIVATE "-Wno-implicit-fallthrough"
|
||||
)
|
||||
|
||||
if(CMAKE_COMPILER_IS_GNUCXX)
|
||||
if(CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 8.0)
|
||||
target_compile_options(sqlite PRIVATE "-Wno-cast-function-type")
|
||||
else()
|
||||
target_compile_options(sqlite PRIVATE "-Wno-bad-function-cast")
|
||||
endif()
|
||||
elseif(CMAKE_CXX_COMPILER_ID MATCHES ".*Clang")
|
||||
target_compile_options(sqlite PRIVATE "-Wno-cast-function-type")
|
||||
endif()
|
||||
@@ -1,51 +0,0 @@
|
||||
# scripts/generate-file-lists.js to change the source files for this target.
|
||||
load_sources_list(MBGL_TEST_FILES test/test-files.json)
|
||||
if (MBGL_TEST_TARGET_TYPE STREQUAL "library")
|
||||
add_library(mbgl-test SHARED ${MBGL_TEST_FILES})
|
||||
else()
|
||||
add_executable(mbgl-test ${MBGL_TEST_FILES})
|
||||
endif()
|
||||
|
||||
# GCC 8+ trips over GTest's way of defining Test functions
|
||||
target_compile_options(mbgl-test PRIVATE -Wno-shadow)
|
||||
|
||||
if(NOT WITH_NODEJS)
|
||||
target_compile_definitions(mbgl-test PRIVATE "-DTEST_HAS_SERVER=0")
|
||||
endif()
|
||||
|
||||
set_source_files_properties(test/src/mbgl/test/util.cpp PROPERTIES COMPILE_FLAGS -DNODE_EXECUTABLE="${NodeJS_EXECUTABLE}")
|
||||
|
||||
target_include_directories(mbgl-test
|
||||
PRIVATE src
|
||||
PRIVATE test/include
|
||||
PRIVATE test/src
|
||||
PRIVATE platform/default/include
|
||||
)
|
||||
|
||||
target_link_libraries(mbgl-test PRIVATE
|
||||
mbgl-vendor-googletest
|
||||
Mapbox::Base::Extras::args
|
||||
mbgl-core
|
||||
mbgl-vendor-shelf-pack-cpp
|
||||
mbgl-vendor-unique_resource
|
||||
Mapbox::Base::pixelmatch-cpp
|
||||
)
|
||||
|
||||
mbgl_platform_test()
|
||||
|
||||
create_source_groups(mbgl-test)
|
||||
|
||||
initialize_xcode_cxx_build_settings(mbgl-test)
|
||||
|
||||
set_target_properties(mbgl-test PROPERTIES FOLDER "Executables")
|
||||
|
||||
xcode_create_scheme(
|
||||
TARGET mbgl-test
|
||||
OPTIONAL_ARGS
|
||||
"--gtest_filter=Category.*"
|
||||
"--gtest_repeat=0"
|
||||
"--gtest_shuffle=0"
|
||||
"--gtest_break_on_failure=0"
|
||||
"--gtest_throw_on_failure=0"
|
||||
"--gtest_catch_exceptions=0"
|
||||
)
|
||||
@@ -1,29 +0,0 @@
|
||||
execute_process(
|
||||
COMMAND git submodule update --init .
|
||||
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/vendor
|
||||
)
|
||||
|
||||
include(${CMAKE_SOURCE_DIR}/vendor/benchmark.cmake)
|
||||
include(${CMAKE_SOURCE_DIR}/vendor/boost.cmake)
|
||||
include(${CMAKE_SOURCE_DIR}/vendor/cheap-ruler-cpp.cmake)
|
||||
include(${CMAKE_SOURCE_DIR}/vendor/earcut.hpp.cmake)
|
||||
include(${CMAKE_SOURCE_DIR}/vendor/eternal.cmake)
|
||||
include(${CMAKE_SOURCE_DIR}/vendor/expected.cmake)
|
||||
include(${CMAKE_SOURCE_DIR}/vendor/geojson-vt-cpp.cmake)
|
||||
include(${CMAKE_SOURCE_DIR}/vendor/googletest.cmake)
|
||||
include(${CMAKE_SOURCE_DIR}/vendor/icu.cmake)
|
||||
include(${CMAKE_SOURCE_DIR}/vendor/nunicode.cmake)
|
||||
include(${CMAKE_SOURCE_DIR}/vendor/polylabel.cmake)
|
||||
include(${CMAKE_SOURCE_DIR}/vendor/protozero.cmake)
|
||||
include(${CMAKE_SOURCE_DIR}/vendor/shelf-pack-cpp.cmake)
|
||||
include(${CMAKE_SOURCE_DIR}/vendor/unique_resource.cmake)
|
||||
include(${CMAKE_SOURCE_DIR}/vendor/vector-tile.cmake)
|
||||
include(${CMAKE_SOURCE_DIR}/vendor/wagyu.cmake)
|
||||
|
||||
if(NOT TARGET mapbox-base)
|
||||
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/vendor/mapbox-base ${CMAKE_BINARY_DIR}/.build-mapbox-gl-native-mapbox-base EXCLUDE_FROM_ALL)
|
||||
endif()
|
||||
|
||||
if(MBGL_PLATFORM STREQUAL "linux" OR MBGL_PLATFORM STREQUAL "macos")
|
||||
include(${CMAKE_SOURCE_DIR}/vendor/glfw.cmake)
|
||||
endif()
|
||||
@@ -1,75 +0,0 @@
|
||||
function(get_target_filename OUTPUT TARGET)
|
||||
get_target_property(_TYPE "${TARGET}" TYPE)
|
||||
get_target_property(_PREFIX "${TARGET}" PREFIX)
|
||||
if(NOT _PREFIX AND NOT _PREFIX STREQUAL "")
|
||||
set(_PREFIX "${CMAKE_${_TYPE}_PREFIX}")
|
||||
endif()
|
||||
get_target_property(_BASENAME "${TARGET}" OUTPUT_NAME)
|
||||
if(NOT _BASENAME)
|
||||
get_target_property(_BASENAME "${TARGET}" NAME)
|
||||
endif()
|
||||
get_target_property(_SUFFIX "${TARGET}" SUFFIX)
|
||||
if(NOT _SUFFIX AND NOT _SUFFIX STREQUAL "")
|
||||
set(_SUFFIX "${CMAKE_${_TYPE}_SUFFIX}")
|
||||
endif()
|
||||
set(${OUTPUT} "${_PREFIX}${_BASENAME}${_SUFFIX}" PARENT_SCOPE)
|
||||
endfunction()
|
||||
|
||||
function(xcode_create_scheme)
|
||||
if (NOT CMAKE_GENERATOR STREQUAL "Xcode")
|
||||
return()
|
||||
endif()
|
||||
|
||||
cmake_parse_arguments(XCSCHEME "" "TARGET;TYPE;NAME" "ARGS;OPTIONAL_ARGS" ${ARGN})
|
||||
|
||||
if(XCSCHEME_UNPARSED_ARGUMENTS)
|
||||
message(FATAL_ERROR "xcode_create_scheme() called with unrecognized arguments: ${XCSCHEME_UNPARSED_ARGUMENTS}")
|
||||
endif()
|
||||
|
||||
if(NOT XCSCHEME_TARGET)
|
||||
message(FATAL_ERROR "xcode_create_scheme() called without required argument TARGET")
|
||||
endif()
|
||||
|
||||
if(NOT XCSCHEME_TYPE)
|
||||
get_target_property(_TYPE "${XCSCHEME_TARGET}" TYPE)
|
||||
if (_TYPE MATCHES "^.*_LIBRARY$")
|
||||
set(XCSCHEME_TYPE "library")
|
||||
elseif(_TYPE STREQUAL "EXECUTABLE")
|
||||
set(XCSCHEME_TYPE "executable")
|
||||
else()
|
||||
message(FATAL_ERROR "xcode_create_scheme() could not determine type of ${XCSCHEME_TARGET}")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
if(NOT XCSCHEME_NAME)
|
||||
set(XCSCHEME_NAME "${XCSCHEME_TARGET}")
|
||||
endif()
|
||||
|
||||
set(XCODEPROJ_PATH "${PROJECT_BINARY_DIR}/${PROJECT_NAME}.xcodeproj")
|
||||
set(XCSCHEME_OUTPUT_FILE "${XCODEPROJ_PATH}/xcshareddata/xcschemes/${XCSCHEME_NAME}.xcscheme")
|
||||
|
||||
# Prevent overwriting of the scheme file on every CMake rerun.
|
||||
if (EXISTS "${XCSCHEME_OUTPUT_FILE}")
|
||||
return()
|
||||
endif()
|
||||
|
||||
file(RELATIVE_PATH XCSCHEME_CONTAINER "${CMAKE_SOURCE_DIR}" "${XCODEPROJ_PATH}")
|
||||
string(RANDOM LENGTH 24 ALPHABET "0123456789ABCDEF" XCSCHEME_BLUEPRINT_ID)
|
||||
get_target_filename(XCSCHEME_BUILDABLE_NAME "${XCSCHEME_TARGET}")
|
||||
set(XCSCHEME_BLUEPRINT_NAME "${XCSCHEME_TARGET}")
|
||||
set(XCSCHEME_WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")
|
||||
set(XCSCHEME_NODE_EXECUTABLE "${NodeJS_EXECUTABLE}")
|
||||
get_filename_component(XCSCHEME_NODE_PATH "${NodeJS_EXECUTABLE}" DIRECTORY)
|
||||
|
||||
set(XCSCHEME_COMMAND_LINE_ARGS "")
|
||||
foreach(_ARG IN LISTS XCSCHEME_ARGS)
|
||||
set(XCSCHEME_COMMAND_LINE_ARGS "${XCSCHEME_COMMAND_LINE_ARGS}\n <CommandLineArgument\n argument = \"${_ARG}\"\n isEnabled = \"YES\">\n </CommandLineArgument>")
|
||||
endforeach()
|
||||
foreach(_ARG IN LISTS XCSCHEME_OPTIONAL_ARGS)
|
||||
set(XCSCHEME_COMMAND_LINE_ARGS "${XCSCHEME_COMMAND_LINE_ARGS}\n <CommandLineArgument\n argument = \"${_ARG}\"\n isEnabled = \"NO\">\n </CommandLineArgument>")
|
||||
endforeach()
|
||||
|
||||
configure_file(
|
||||
"${CMAKE_SOURCE_DIR}/cmake/${XCSCHEME_TYPE}.xcscheme"
|
||||
"${XCSCHEME_OUTPUT_FILE}")
|
||||
endfunction()
|
||||
@@ -1,177 +0,0 @@
|
||||
#include "expression_test_logger.hpp"
|
||||
#include "expression_test_runner.hpp"
|
||||
#include "filesystem.hpp"
|
||||
|
||||
#include <mbgl/util/io.hpp>
|
||||
#include <mbgl/util/string.hpp>
|
||||
|
||||
#include <sstream>
|
||||
|
||||
using namespace mbgl;
|
||||
using namespace std::literals;
|
||||
|
||||
namespace {
|
||||
|
||||
const char* resultsStyle = R"HTML(
|
||||
<style>
|
||||
body { font: 18px/1.2 -apple-system, BlinkMacSystemFont, "Helvetica Neue", Helvetica, Arial, sans-serif; padding: 10px; }
|
||||
h1 { font-size: 32px; margin-bottom: 0; }
|
||||
button { vertical-align: middle; }
|
||||
h2 { font-size: 24px; font-weight: normal; margin: 10px 0 10px; line-height: 1; }
|
||||
.test { border-bottom: 1px dotted #bbb; padding-bottom: 5px; }
|
||||
.tests { border-top: 1px dotted #bbb; margin-top: 10px; }
|
||||
.test p, .test pre { margin: 0 0 10px; }
|
||||
.test pre { font-size: 14px; }
|
||||
.label { color: white; font-size: 18px; padding: 2px 6px 3px; border-radius: 3px; margin-right: 3px; vertical-align: bottom; display: inline-block; }
|
||||
.hide { display: none; }
|
||||
.test.failed > h2 > span { background: red; }
|
||||
.test.passed > h2 > span { background: green; }
|
||||
.test.ignored > h2 > span { background: grey; }
|
||||
.test.errored > h2 > span { background: #ff006f; }
|
||||
.test.ignored.passed > h2 > span { background: #E8A408; }
|
||||
</style>
|
||||
)HTML";
|
||||
|
||||
const char* resultsHeaderButtons = R"HTML(
|
||||
<button id='toggle-sequence'>Toggle test sequence</button>
|
||||
<button id='toggle-passed'>Toggle passed tests</button>
|
||||
<button id='toggle-ignored'>Toggle ignored tests</button>
|
||||
</h1>
|
||||
)HTML";
|
||||
|
||||
const char* resultsScript = R"HTML(
|
||||
<script>
|
||||
document.getElementById('toggle-passed').addEventListener('click', function (e) {
|
||||
for (const row of document.querySelectorAll('.test.passed')) {
|
||||
row.classList.toggle('hide');
|
||||
}
|
||||
});
|
||||
document.getElementById('toggle-ignored').addEventListener('click', function (e) {
|
||||
for (const row of document.querySelectorAll('.test.ignored')) {
|
||||
row.classList.toggle('hide');
|
||||
}
|
||||
});
|
||||
document.getElementById('toggle-sequence').addEventListener('click', function (e) {
|
||||
document.getElementById('test-sequence').classList.toggle('hide');
|
||||
});
|
||||
</script>
|
||||
)HTML";
|
||||
|
||||
std::string createResultItem(const TestRunOutput& result, const std::string& status, bool shouldHide) {
|
||||
std::ostringstream html;
|
||||
html << "<div class=\"test " << status << (shouldHide ? " hide" : "") << "\">\n";
|
||||
html << R"(<h2><span class="label">)" << status << "</span> " << result.id << "</h2>\n";
|
||||
|
||||
html << "<p><pre>"s << result.expression << "</pre></p>\n"s;
|
||||
if (result.passed) {
|
||||
html << "<strong>Serialized:</strong><p><pre>"s << result.serialized << "</pre></p>\n"s;
|
||||
} else {
|
||||
html << "<p><strong>Difference:</strong><pre>" << result.text << "</pre></p>\n";
|
||||
}
|
||||
html << "</div>\n";
|
||||
|
||||
return html.str();
|
||||
}
|
||||
|
||||
std::string createResultPage(const TestStats& stats, bool shuffle, uint32_t seed) {
|
||||
const std::size_t unsuccessfulCount = stats.errored.size() + stats.failed.size();
|
||||
const bool unsuccessful = unsuccessfulCount > 0;
|
||||
std::ostringstream resultsPage;
|
||||
|
||||
// Style
|
||||
resultsPage << resultsStyle;
|
||||
|
||||
// Header with buttons
|
||||
if (unsuccessful) {
|
||||
resultsPage << R"HTML(<h1 style="color: red;">)HTML";
|
||||
resultsPage << util::toString(unsuccessfulCount) << " tests failed.";
|
||||
} else {
|
||||
resultsPage << R"HTML(<h1 style="color: green;">)HTML";
|
||||
resultsPage << "All tests passed!";
|
||||
}
|
||||
|
||||
resultsPage << resultsHeaderButtons;
|
||||
|
||||
// Test sequence
|
||||
{
|
||||
resultsPage << "<div id='test-sequence' class='hide'>\n";
|
||||
|
||||
// Failed tests
|
||||
if (unsuccessful) {
|
||||
resultsPage << "<p><strong>Failed tests:</strong>";
|
||||
for (const auto& failed : stats.failed) {
|
||||
resultsPage << failed.id << " ";
|
||||
}
|
||||
resultsPage << "<p><strong>Errored tests:</strong>";
|
||||
for (const auto& errored : stats.errored) {
|
||||
resultsPage << errored.id << " ";
|
||||
}
|
||||
resultsPage << "</p>\n";
|
||||
}
|
||||
|
||||
// Test sequence
|
||||
resultsPage << "<p><strong>Test sequence: </strong>";
|
||||
for (const auto& id : stats.ids) {
|
||||
resultsPage << id << " ";
|
||||
}
|
||||
resultsPage << "</p>\n";
|
||||
|
||||
// Shuffle
|
||||
if (shuffle) {
|
||||
resultsPage << "<p><strong>Shuffle seed</strong>: " << util::toString(seed) << "</p>\n";
|
||||
}
|
||||
|
||||
resultsPage << "</div>\n";
|
||||
}
|
||||
|
||||
// Script
|
||||
resultsPage << resultsScript;
|
||||
|
||||
// Tests
|
||||
resultsPage << "<div class=\"tests\">\n";
|
||||
const auto appendResult = [&] (const auto& results, const std::string& status, bool hide = false) {
|
||||
for (const auto& result : results) {
|
||||
resultsPage << createResultItem(result, status, hide);
|
||||
}
|
||||
};
|
||||
|
||||
appendResult(stats.passed, "passed"s, unsuccessful);
|
||||
appendResult(stats.failed, "failed"s);
|
||||
appendResult(stats.errored, "errored"s);
|
||||
appendResult(stats.ignorePassed, "ignored passed"s, unsuccessful);
|
||||
appendResult(stats.ignoreFailed, "ignored"s, true);
|
||||
resultsPage << "</div>\n";
|
||||
|
||||
return resultsPage.str();
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void printStats(const TestStats& stats) {
|
||||
const std::size_t count = stats.testCount();
|
||||
if (std::size_t passedTests = stats.passed.size()) {
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
void writeHTMLResults(const TestStats& stats, const std::string& rootPath, bool shuffle, uint32_t seed) {
|
||||
filesystem::path path = filesystem::path(rootPath) / "index.html"s;
|
||||
try {
|
||||
util::write_file(path.string(), createResultPage(stats, shuffle, seed));
|
||||
printf("Results at: %s\n", path.string().c_str());
|
||||
} catch (std::exception&) {
|
||||
printf(ANSI_COLOR_RED "* ERROR can't write result page %s" ANSI_COLOR_RESET "\n", path.string().c_str());
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
|
||||
#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"
|
||||
|
||||
class TestStats;
|
||||
|
||||
void printStats(const TestStats&);
|
||||
void writeHTMLResults(const TestStats&, const std::string&, bool, uint32_t);
|
||||
@@ -1,511 +0,0 @@
|
||||
#include "expression_test_parser.hpp"
|
||||
|
||||
#include <mbgl/util/io.hpp>
|
||||
#include <mbgl/util/logging.hpp>
|
||||
#include <mbgl/util/variant.hpp>
|
||||
#include <mbgl/style/conversion/function.hpp>
|
||||
#include <mbgl/style/rapidjson_conversion.hpp>
|
||||
#include <mbgl/style/expression/parsing_context.hpp>
|
||||
|
||||
#include <mapbox/geojson/rapidjson.hpp>
|
||||
#include <rapidjson/writer.h>
|
||||
#include <rapidjson/prettywriter.h>
|
||||
#include <rapidjson/stringbuffer.h>
|
||||
|
||||
#include <args.hxx>
|
||||
|
||||
using namespace mbgl;
|
||||
using namespace mbgl::style;
|
||||
using namespace mbgl::style::conversion;
|
||||
using namespace std::literals;
|
||||
|
||||
namespace {
|
||||
|
||||
void writeJSON(rapidjson::PrettyWriter<rapidjson::StringBuffer>& 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(d) : writer.Double(d); },
|
||||
[&] (const std::string& s) { writer.String(s); },
|
||||
[&] (const std::vector<Value>& arr) {
|
||||
writer.StartArray();
|
||||
for(const auto& item : arr) {
|
||||
writeJSON(writer, item);
|
||||
}
|
||||
writer.EndArray();
|
||||
},
|
||||
[&] (const std::unordered_map<std::string, Value>& obj) {
|
||||
writer.StartObject();
|
||||
for(const auto& entry : obj) {
|
||||
writer.Key(entry.first.c_str());
|
||||
writeJSON(writer, entry.second);
|
||||
}
|
||||
writer.EndObject();
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
using ErrorMessage = std::string;
|
||||
using JSONReply = variant<JSDocument, ErrorMessage>;
|
||||
JSONReply readJson(const filesystem::path& jsonPath) {
|
||||
auto maybeJSON = util::readFile(jsonPath);
|
||||
if (!maybeJSON) {
|
||||
return { "Unable to open file "s + jsonPath.string() };
|
||||
}
|
||||
|
||||
JSDocument document;
|
||||
document.Parse<rapidjson::kParseFullPrecisionFlag>(*maybeJSON);
|
||||
if (document.HasParseError()) {
|
||||
return { formatJSONParseError(document) };
|
||||
}
|
||||
|
||||
return { std::move(document) };
|
||||
}
|
||||
|
||||
std::string toString(const JSValue& value) {
|
||||
assert(value.IsString());
|
||||
return { value.GetString(), value.GetStringLength() };
|
||||
}
|
||||
|
||||
optional<Value> toValue(const JSValue& jsvalue) {
|
||||
if (jsvalue.IsNull()) {
|
||||
return Value{};
|
||||
}
|
||||
|
||||
if (jsvalue.IsArray()) {
|
||||
std::vector<Value> values;
|
||||
values.reserve(jsvalue.GetArray().Size());
|
||||
for (const auto& v : jsvalue.GetArray()) {
|
||||
if (auto value = toValue(v)) {
|
||||
values.emplace_back(std::move(*value));
|
||||
}
|
||||
}
|
||||
return {std::move(values)};
|
||||
}
|
||||
|
||||
if (jsvalue.IsObject()) {
|
||||
std::unordered_map<std::string, Value> value_map;
|
||||
for (const auto& pair : jsvalue.GetObject()) {
|
||||
if (auto value = toValue(pair.value)) {
|
||||
value_map.emplace(toString(pair.name), std::move(*value));
|
||||
}
|
||||
}
|
||||
return {std::move(value_map)};
|
||||
}
|
||||
|
||||
if (!jsvalue.IsArray() && !jsvalue.IsObject()) {
|
||||
return toValue(Convertible(&jsvalue));
|
||||
}
|
||||
|
||||
return nullopt;
|
||||
}
|
||||
|
||||
style::expression::type::Type stringToType(const std::string& type) {
|
||||
using namespace style::expression;
|
||||
if (type == "string"s || type == "number-format"s ||
|
||||
type == "image"s) { // TODO: replace once we implement image expressions
|
||||
return type::String;
|
||||
} else if (type == "number"s) {
|
||||
return type::Number;
|
||||
} else if (type == "boolean"s) {
|
||||
return type::Boolean;
|
||||
} else if (type == "object"s) {
|
||||
return type::Object;
|
||||
} else if (type == "color"s) {
|
||||
return type::Color;
|
||||
} else if (type == "value"s) {
|
||||
return type::Value;
|
||||
} else if (type == "formatted"s) {
|
||||
return type::Formatted;
|
||||
}
|
||||
|
||||
// Should not reach.
|
||||
assert(false);
|
||||
return type::Null;
|
||||
}
|
||||
|
||||
optional<style::expression::type::Type> toExpressionType(const PropertySpec& spec) {
|
||||
using namespace style::expression;
|
||||
if (spec.type == "array") {
|
||||
type::Type itemType = spec.value.empty() ? type::Value : stringToType(spec.value);
|
||||
if (spec.length) {
|
||||
return {type::Array(itemType, spec.length)};
|
||||
}
|
||||
return {type::Array(itemType)};
|
||||
}
|
||||
|
||||
if (spec.type == "enum") {
|
||||
return {type::String};
|
||||
}
|
||||
|
||||
return spec.type.empty() ? nullopt : optional<type::Type>{stringToType(spec.type)};
|
||||
}
|
||||
|
||||
void parseCompiled(const JSValue& compiledValue, TestData& data) {
|
||||
const auto& compiled = compiledValue.GetObject();
|
||||
assert(compiled.HasMember("result"));
|
||||
assert(compiled["result"].IsString());
|
||||
const std::string& result = toString(compiled["result"]);
|
||||
data.expected.compiled.success = result == "success";
|
||||
|
||||
if (compiled.HasMember("isFeatureConstant")) {
|
||||
assert(compiled["isFeatureConstant"].IsBool());
|
||||
data.expected.compiled.isFeatureConstant = compiled["isFeatureConstant"].GetBool();
|
||||
}
|
||||
|
||||
if (compiled.HasMember("isZoomConstant")) {
|
||||
assert(compiled["isZoomConstant"].IsBool());
|
||||
data.expected.compiled.isZoomConstant = compiled["isZoomConstant"].GetBool();
|
||||
}
|
||||
|
||||
if (compiled.HasMember("type")) {
|
||||
assert(compiled["type"].IsString());
|
||||
data.expected.compiled.serializedType = toString(compiled["type"]);
|
||||
}
|
||||
|
||||
if (compiled.HasMember("errors")) {
|
||||
assert(compiled["errors"].IsArray());
|
||||
for (const auto& errorVal : compiled["errors"].GetArray()) {
|
||||
assert(errorVal.IsObject());
|
||||
const auto& errorObject = errorVal.GetObject();
|
||||
assert(errorObject.HasMember("key"));
|
||||
assert(errorObject.HasMember("error"));
|
||||
|
||||
std::unordered_map<std::string, Value> errorMap;
|
||||
errorMap.emplace("key"s, Value{toString(errorObject["key"])});
|
||||
errorMap.emplace("error"s, Value{toString(errorObject["error"])});
|
||||
data.expected.compiled.errors.emplace_back(Value{std::move(errorMap)});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void parseExpected(const JSValue& expectedValue, TestData& data) {
|
||||
assert(expectedValue.IsObject());
|
||||
const auto& expected = expectedValue.GetObject();
|
||||
assert(expected.HasMember("compiled"));
|
||||
parseCompiled(expected["compiled"], data);
|
||||
|
||||
// set outputs
|
||||
if (expected.HasMember("outputs")) {
|
||||
data.expected.outputs = toValue(expected["outputs"]);
|
||||
}
|
||||
|
||||
// set serialized
|
||||
if (expected.HasMember("serialized")) {
|
||||
data.expected.serialized = toValue(expected["serialized"]);
|
||||
}
|
||||
}
|
||||
|
||||
void parsePropertySpec(const JSValue& value, TestData& data) {
|
||||
const auto& propertySpec = value.GetObject();
|
||||
PropertySpec spec;
|
||||
|
||||
if (propertySpec.HasMember("type")) {
|
||||
assert(propertySpec["type"].IsString());
|
||||
spec.type = toString(propertySpec["type"]);
|
||||
}
|
||||
|
||||
if (propertySpec.HasMember("value")) {
|
||||
assert(propertySpec["value"].IsString());
|
||||
spec.value = toString(propertySpec["value"]);
|
||||
}
|
||||
|
||||
if (propertySpec.HasMember("length")) {
|
||||
assert(propertySpec["length"].IsNumber());
|
||||
spec.length = propertySpec["length"].GetDouble();
|
||||
}
|
||||
|
||||
if (propertySpec.HasMember("property-type")) {
|
||||
assert(propertySpec["property-type"].IsString());
|
||||
spec.isDataDriven = true;
|
||||
}
|
||||
|
||||
if (propertySpec.HasMember("expression")) {
|
||||
assert(propertySpec["expression"].IsObject());
|
||||
spec.expression = toValue(propertySpec["expression"]);
|
||||
}
|
||||
|
||||
data.spec = std::move(spec);
|
||||
}
|
||||
|
||||
bool parseInputs(const JSValue& inputsValue, TestData& data) {
|
||||
assert(inputsValue.IsArray());
|
||||
for (const auto& input : inputsValue.GetArray()) {
|
||||
assert(input.IsArray());
|
||||
assert(input.Size() == 2);
|
||||
assert(input[0].IsObject());
|
||||
assert(input[1].IsObject());
|
||||
|
||||
// Parse evaluation context, zoom.
|
||||
optional<float> zoom;
|
||||
const auto& evaluationContext = input[0].GetObject();
|
||||
if (evaluationContext.HasMember("zoom")) {
|
||||
assert(evaluationContext["zoom"].IsNumber());
|
||||
zoom = evaluationContext["zoom"].GetDouble();
|
||||
}
|
||||
|
||||
// Parse heatmap density
|
||||
optional<double> heatmapDensity;
|
||||
if (evaluationContext.HasMember("heatmapDensity")) {
|
||||
assert(evaluationContext["heatmapDensity"].IsNumber());
|
||||
heatmapDensity = evaluationContext["heatmapDensity"].GetDouble();
|
||||
}
|
||||
|
||||
// Parse feature properties
|
||||
Feature feature(mapbox::geometry::point<double>(0.0, 0.0));
|
||||
const auto& featureObject = input[1].GetObject();
|
||||
if (featureObject.HasMember("properties")) {
|
||||
assert(featureObject["properties"].IsObject());
|
||||
feature.properties = mapbox::geojson::convert<PropertyMap>(featureObject["properties"]);
|
||||
}
|
||||
|
||||
if (featureObject.HasMember("geometry")) {
|
||||
assert(featureObject["geometry"].IsObject());
|
||||
feature.geometry = mapbox::geojson::convert<mapbox::geometry::geometry<double>>(featureObject["geometry"]);
|
||||
}
|
||||
|
||||
if (featureObject.HasMember("id")) {
|
||||
assert(featureObject["id"].IsNumber() || featureObject["id"].IsString());
|
||||
feature.id = mapbox::geojson::convert<mapbox::feature::identifier>(featureObject["id"]);
|
||||
}
|
||||
|
||||
data.inputs.emplace_back(std::move(zoom), std::move(heatmapDensity), std::move(feature));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::tuple<filesystem::path, std::vector<filesystem::path>, 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::Flag shuffleFlag(argumentParser, "shuffle", "Toggle shuffling the tests order",
|
||||
{ 's', "shuffle" });
|
||||
args::ValueFlag<uint32_t> seedValue(argumentParser, "seed", "Shuffle seed (default: random)",
|
||||
{ "seed" });
|
||||
args::PositionalList<std::string> testNameValues(argumentParser, "URL", "Test name(s)");
|
||||
|
||||
try {
|
||||
argumentParser.ParseCLI(argc, argv);
|
||||
} catch (const args::Help&) {
|
||||
std::ostringstream stream;
|
||||
stream << argumentParser;
|
||||
Log::Info(Event::General, stream.str());
|
||||
exit(0);
|
||||
} catch (const args::ParseError& e) {
|
||||
std::ostringstream stream;
|
||||
stream << argumentParser;
|
||||
Log::Info(Event::General, stream.str());
|
||||
Log::Error(Event::General, e.what());
|
||||
exit(1);
|
||||
} catch (const args::ValidationError& e) {
|
||||
std::ostringstream stream;
|
||||
stream << argumentParser;
|
||||
Log::Info(Event::General, stream.str());
|
||||
Log::Error(Event::General, e.what());
|
||||
exit(2);
|
||||
}
|
||||
|
||||
filesystem::path rootPath {std::string(TEST_RUNNER_ROOT_PATH).append("/mapbox-gl-js/test/integration/expression-tests")};
|
||||
if (!filesystem::exists(rootPath)) {
|
||||
Log::Error(Event::General, "Test path '%s' does not exist.", rootPath.string().c_str());
|
||||
exit(3);
|
||||
}
|
||||
|
||||
std::vector<filesystem::path> paths;
|
||||
for (const auto& testName : args::get(testNameValues)) {
|
||||
paths.emplace_back(rootPath.string() + "/" + testName);
|
||||
}
|
||||
|
||||
if (paths.empty()) {
|
||||
paths.emplace_back(rootPath);
|
||||
}
|
||||
|
||||
// Recursively traverse through the test paths and collect test directories containing "test.json".
|
||||
std::vector<filesystem::path> testPaths;
|
||||
testPaths.reserve(paths.size());
|
||||
for (const auto& path : paths) {
|
||||
if (!filesystem::exists(path)) {
|
||||
Log::Warning(Event::General, "Provided test folder '%s' does not exist.", path.string().c_str());
|
||||
continue;
|
||||
}
|
||||
|
||||
for (auto& testPath : filesystem::recursive_directory_iterator(path)) {
|
||||
if (testPath.path().filename() == "test.json") {
|
||||
testPaths.emplace_back(testPath.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Arguments{ std::move(rootPath),
|
||||
std::move(testPaths),
|
||||
shuffleFlag ? args::get(shuffleFlag) : false,
|
||||
seedValue ? args::get(seedValue) : 1u };
|
||||
}
|
||||
|
||||
Ignores parseExpressionIgnores() {
|
||||
Ignores ignores;
|
||||
const auto mainIgnoresPath = filesystem::path(TEST_RUNNER_ROOT_PATH).append("platform/node/test/ignores.json");
|
||||
auto maybeIgnores = readJson(mainIgnoresPath);
|
||||
if (!maybeIgnores.is<JSDocument>()) { // NOLINT
|
||||
return {};
|
||||
}
|
||||
|
||||
for (const auto& property : maybeIgnores.get<JSDocument>().GetObject()) {
|
||||
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) };
|
||||
ignores.emplace_back(std::move(id), std::move(reason));
|
||||
}
|
||||
|
||||
return ignores;
|
||||
}
|
||||
|
||||
optional<TestData> parseTestData(const filesystem::path& path) {
|
||||
TestData data;
|
||||
auto maybeJson = readJson(path.string());
|
||||
if (!maybeJson.is<JSDocument>()) { // NOLINT
|
||||
Log::Error(Event::General, "Cannot parse test '%s'.", path.string().c_str());
|
||||
return nullopt;
|
||||
}
|
||||
|
||||
data.document = std::move(maybeJson.get<JSDocument>());
|
||||
|
||||
// Check that mandatory test data members are present.
|
||||
if (!data.document.HasMember("expression") || !data.document.HasMember("expected")) {
|
||||
Log::Error(Event::General, "Test fixture '%s' does not contain required data.", path.string().c_str());
|
||||
return nullopt;
|
||||
}
|
||||
|
||||
// Parse propertySpec
|
||||
if (data.document.HasMember("propertySpec")) {
|
||||
assert(data.document["propertySpec"].IsObject());
|
||||
parsePropertySpec(data.document["propertySpec"], data);
|
||||
}
|
||||
|
||||
// Parse expected
|
||||
parseExpected(data.document["expected"], data);
|
||||
|
||||
// Parse inputs
|
||||
if (data.document.HasMember("inputs") && !parseInputs(data.document["inputs"], data)) {
|
||||
Log::Error(Event::General,"Can't convert inputs value for '%s'", path.string().c_str());
|
||||
return nullopt;
|
||||
}
|
||||
|
||||
return {std::move(data)};
|
||||
}
|
||||
|
||||
std::string toJSON(const Value& value, unsigned indent, bool singleLine) {
|
||||
rapidjson::StringBuffer buffer;
|
||||
rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer);
|
||||
if (singleLine) {
|
||||
writer.SetFormatOptions(rapidjson::kFormatSingleLineArray);
|
||||
}
|
||||
writer.SetIndent(' ', indent);
|
||||
writeJSON(writer, value);
|
||||
return buffer.GetString();
|
||||
}
|
||||
|
||||
JSDocument toDocument(const Value& value) {
|
||||
JSDocument document;
|
||||
document.Parse<rapidjson::kParseFullPrecisionFlag>(toJSON(value));
|
||||
return document;
|
||||
}
|
||||
|
||||
Value toValue(const Compiled& compiled) {
|
||||
std::unordered_map<std::string, Value> compiledObject;
|
||||
compiledObject.emplace("result", compiled.success ? "success"s : "error"s);
|
||||
if (compiled.success) {
|
||||
compiledObject.emplace("isFeatureConstant", compiled.isFeatureConstant);
|
||||
compiledObject.emplace("isZoomConstant", compiled.isZoomConstant);
|
||||
compiledObject.emplace("type", compiled.serializedType);
|
||||
} else {
|
||||
compiledObject.emplace("errors", compiled.errors);
|
||||
}
|
||||
return {std::move(compiledObject)};
|
||||
}
|
||||
|
||||
// Serializes native expression types to JS format.
|
||||
// Color and Formatted are exceptions.
|
||||
// TODO: harmonize serialized format to remove this conversion.
|
||||
optional<Value> toValue(const expression::Value& exprValue) {
|
||||
return exprValue.match(
|
||||
[](const Color& c) -> optional<Value> {
|
||||
std::vector<Value> color { double(c.r), double(c.g), double(c.b), double(c.a) };
|
||||
return {Value{std::move(color)}};
|
||||
},
|
||||
[](const expression::Formatted& formatted) -> optional<Value> { return {formatted.toObject()}; },
|
||||
[](const std::vector<expression::Value>& values) -> optional<Value> {
|
||||
std::vector<Value> mbglValues;
|
||||
for (const auto& value : values) {
|
||||
if (auto converted = expression::fromExpressionValue<Value>(value)) {
|
||||
mbglValues.emplace_back(std::move(*converted));
|
||||
}
|
||||
}
|
||||
return {Value{std::move(mbglValues)}};
|
||||
},
|
||||
[](const std::unordered_map<std::string, expression::Value>& valueMap) -> optional<Value> {
|
||||
std::unordered_map<std::string, Value> mbglValueMap;
|
||||
for (const auto& pair : valueMap) {
|
||||
if (auto converted = expression::fromExpressionValue<Value>(pair.second)) {
|
||||
mbglValueMap.emplace(pair.first, std::move(*converted));
|
||||
}
|
||||
}
|
||||
return {Value{std::move(mbglValueMap)}};
|
||||
},
|
||||
[](const auto& v) { return expression::fromExpressionValue<Value>(v); });
|
||||
}
|
||||
|
||||
std::unique_ptr<style::expression::Expression> parseExpression(const JSValue& value,
|
||||
optional<PropertySpec>& spec,
|
||||
TestResult& result) {
|
||||
optional<style::expression::type::Type> expected = spec ? toExpressionType(*spec) : nullopt;
|
||||
expression::ParsingContext ctx = expected ? expression::ParsingContext(*expected) :
|
||||
expression::ParsingContext();
|
||||
Convertible convertible(&value);
|
||||
expression::ParseResult parsed;
|
||||
if (value.IsObject() && !value.IsArray() && expected){
|
||||
Error error;
|
||||
parsed = convertFunctionToExpression(*expected, convertible, error, false /*convert tokens*/);
|
||||
if (!parsed) {
|
||||
// TODO: should the error message be checked for function conversion?
|
||||
}
|
||||
} else {
|
||||
parsed = ctx.parseLayerPropertyExpression(convertible);
|
||||
if (!parsed) {
|
||||
for (const auto& parsingError : ctx.getErrors()) {
|
||||
std::unordered_map<std::string, Value> errorMap;
|
||||
errorMap.emplace("key"s, Value{parsingError.key});
|
||||
errorMap.emplace("error"s, Value{parsingError.message});
|
||||
result.compiled.errors.emplace_back(Value{std::move(errorMap)});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
result.expression = toValue(value);
|
||||
result.compiled.success = bool(parsed);
|
||||
if (parsed) {
|
||||
result.compiled.isFeatureConstant = expression::isFeatureConstant(**parsed);
|
||||
result.compiled.isZoomConstant = expression::isZoomConstant(**parsed);
|
||||
result.compiled.serializedType = style::expression::type::toString((*parsed)->getType());
|
||||
result.serialized = (*parsed)->serialize();
|
||||
return std::move(*parsed);
|
||||
}
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
std::unique_ptr<style::expression::Expression> parseExpression(const optional<Value>& value,
|
||||
optional<PropertySpec>& spec,
|
||||
TestResult& result) {
|
||||
assert(value);
|
||||
auto document = toDocument(*value);
|
||||
assert(!document.HasParseError());
|
||||
return parseExpression(document, spec, result);
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "filesystem.hpp"
|
||||
|
||||
#include <mbgl/style/expression/expression.hpp>
|
||||
#include <mbgl/util/feature.hpp>
|
||||
#include <mbgl/util/optional.hpp>
|
||||
#include <mbgl/util/rapidjson.hpp>
|
||||
|
||||
#include <vector>
|
||||
#include <string>
|
||||
|
||||
using namespace mbgl;
|
||||
|
||||
struct Input {
|
||||
Input(optional<float> zoom_, optional<double> heatmapDensity_, Feature feature_)
|
||||
: zoom(std::move(zoom_)),
|
||||
heatmapDensity(std::move(heatmapDensity_)),
|
||||
feature(std::move(feature_)) {}
|
||||
optional<float> zoom;
|
||||
optional<double> heatmapDensity;
|
||||
Feature feature;
|
||||
};
|
||||
|
||||
struct Compiled {
|
||||
bool operator==(const Compiled& other) const {
|
||||
bool typeEqual = success == other.success &&
|
||||
isFeatureConstant == other.isFeatureConstant &&
|
||||
isZoomConstant == other.isZoomConstant &&
|
||||
serializedType == other.serializedType &&
|
||||
errors == other.errors;
|
||||
return typeEqual;
|
||||
}
|
||||
|
||||
bool success = false;
|
||||
bool isFeatureConstant = false;
|
||||
bool isZoomConstant = false;
|
||||
std::string serializedType;
|
||||
std::vector<Value> errors;
|
||||
};
|
||||
|
||||
struct TestResult {
|
||||
Compiled compiled;
|
||||
optional<Value> expression;
|
||||
optional<Value> outputs;
|
||||
optional<Value> serialized;
|
||||
};
|
||||
|
||||
struct PropertySpec {
|
||||
std::string type;
|
||||
std::string value;
|
||||
std::size_t length = 0;
|
||||
bool isDataDriven = false;
|
||||
optional<Value> expression;
|
||||
};
|
||||
|
||||
class TestData {
|
||||
public:
|
||||
std::vector<Input> inputs;
|
||||
TestResult expected;
|
||||
TestResult result;
|
||||
TestResult recompiled;
|
||||
optional<PropertySpec> spec;
|
||||
JSDocument document;
|
||||
};
|
||||
|
||||
struct Ignore {
|
||||
Ignore(std::string id_, std::string reason_)
|
||||
: id(std::move(id_)),
|
||||
reason(std::move(reason_)) {}
|
||||
|
||||
std::string id;
|
||||
std::string reason;
|
||||
};
|
||||
|
||||
using Arguments = std::tuple<filesystem::path, std::vector<filesystem::path>, bool, uint32_t>;
|
||||
Arguments parseArguments(int argc, char** argv);
|
||||
|
||||
using Ignores = std::vector<Ignore>;
|
||||
Ignores parseExpressionIgnores();
|
||||
optional<TestData> parseTestData(const filesystem::path&);
|
||||
|
||||
std::string toJSON(const Value& value, unsigned indent = 0, bool singleLine = false);
|
||||
JSDocument toDocument(const Value&);
|
||||
Value toValue(const Compiled&);
|
||||
optional<Value> toValue(const style::expression::Value&);
|
||||
|
||||
std::unique_ptr<style::expression::Expression> parseExpression(const JSValue&,
|
||||
optional<PropertySpec>&,
|
||||
TestResult&);
|
||||
std::unique_ptr<style::expression::Expression> parseExpression(const optional<Value>&,
|
||||
optional<PropertySpec>&,
|
||||
TestResult&);
|
||||
|
||||
@@ -1,197 +0,0 @@
|
||||
#include "expression_test_runner.hpp"
|
||||
#include "expression_test_logger.hpp"
|
||||
#include "expression_test_parser.hpp"
|
||||
#include "filesystem.hpp"
|
||||
#include "test_runner_common.hpp"
|
||||
|
||||
#include <mbgl/util/io.hpp>
|
||||
|
||||
#include <rapidjson/writer.h>
|
||||
#include <rapidjson/prettywriter.h>
|
||||
#include <rapidjson/stringbuffer.h>
|
||||
|
||||
#include <sstream>
|
||||
#include <regex>
|
||||
|
||||
using namespace std::literals;
|
||||
|
||||
namespace {
|
||||
|
||||
std::string simpleDiff(const Value& result, const Value& expected) {
|
||||
std::vector<std::string> resultTokens {tokenize(toJSON(result, 2, true))};
|
||||
std::vector<std::string> 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<std::string>& 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) {
|
||||
flush(expectedTokens, i, diff, "-"s);
|
||||
break;
|
||||
}
|
||||
|
||||
if (expectedTokens.size() <= i) {
|
||||
flush(resultTokens, i, diff, "+"s);
|
||||
break;
|
||||
}
|
||||
|
||||
if (resultTokens[i] != expectedTokens[i]) {
|
||||
diff << "-"s << expectedTokens[i] << std::endl;
|
||||
diff << "+"s << resultTokens[i] << std::endl;
|
||||
} else {
|
||||
diff << resultTokens[i] << std::endl;
|
||||
}
|
||||
}
|
||||
return diff.str();
|
||||
}
|
||||
|
||||
void rewriteRoundtrippedType(const std::string& expected, std::string& actual) {
|
||||
if (!expected.rfind("array", 0) && !actual.rfind("array", 0)) {
|
||||
actual = expected;
|
||||
}
|
||||
}
|
||||
|
||||
void updateTest(TestData& data) {
|
||||
assert(data.document["expected"].IsObject());
|
||||
auto& expected = data.document["expected"];
|
||||
auto compiled = toDocument(toValue(data.result.compiled));
|
||||
assert(!compiled.HasParseError());
|
||||
expected["compiled"].Swap(compiled);
|
||||
|
||||
if (data.result.outputs) {
|
||||
auto outputs = toDocument(stripPrecision(data.result.outputs.value_or(Value{})));
|
||||
assert(!outputs.HasParseError());
|
||||
expected["outputs"].Swap(outputs);
|
||||
} else {
|
||||
expected.RemoveMember("outputs");
|
||||
}
|
||||
|
||||
if (data.result.serialized) {
|
||||
auto serialized = toDocument(*data.result.serialized);
|
||||
assert(!serialized.HasParseError());
|
||||
expected["serialized"].Swap(serialized);
|
||||
} else {
|
||||
expected.RemoveMember("serialized");
|
||||
}
|
||||
}
|
||||
|
||||
void writeTestData(const JSDocument& document, const std::string& rootPath, const std::string& id) {
|
||||
rapidjson::StringBuffer buffer;
|
||||
rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer);
|
||||
writer.SetFormatOptions(rapidjson::kFormatSingleLineArray);
|
||||
writer.SetIndent(' ', 2);
|
||||
document.Accept(writer);
|
||||
buffer.Put('\n');
|
||||
filesystem::path path = filesystem::path(rootPath) / id / "test.json"s;
|
||||
try {
|
||||
util::write_file(path.string(), {buffer.GetString(), buffer.GetSize()});
|
||||
} catch (std::exception&) {
|
||||
printf(ANSI_COLOR_RED "* ERROR can't update '%s' test" ANSI_COLOR_RESET "\n", id.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TestRunOutput runExpressionTest(TestData& data, const std::string& rootPath, const std::string& id) {
|
||||
TestRunOutput output(id);
|
||||
const auto evaluateExpression = [&data](std::unique_ptr<style::expression::Expression>& expression,
|
||||
TestResult& result) {
|
||||
assert(expression);
|
||||
std::vector<Value> outputs;
|
||||
if (!data.inputs.empty()) {
|
||||
for (const auto& input : data.inputs) {
|
||||
auto evaluationResult = expression->evaluate(input.zoom, input.feature, input.heatmapDensity);
|
||||
if (!evaluationResult) {
|
||||
std::unordered_map<std::string, Value> error{{"error", Value{evaluationResult.error().message}}};
|
||||
outputs.emplace_back(Value{std::move(error)});
|
||||
} else {
|
||||
auto value = toValue(*evaluationResult);
|
||||
assert(value);
|
||||
outputs.emplace_back(Value{*value});
|
||||
}
|
||||
}
|
||||
}
|
||||
result.outputs = {Value{std::move(outputs)}};
|
||||
};
|
||||
|
||||
// Parse expression
|
||||
auto parsedExpression = parseExpression(data.document["expression"], data.spec, data.result);
|
||||
output.expression = toJSON(data.result.expression.value_or(Value{}), 2, true);
|
||||
|
||||
// Evaluate expression
|
||||
if (parsedExpression) {
|
||||
evaluateExpression(parsedExpression, data.result);
|
||||
output.serialized = toJSON(data.result.serialized.value_or(Value{}), 2, true);
|
||||
|
||||
// round trip
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
if (getenv("UPDATE")) {
|
||||
output.passed = true;
|
||||
updateTest(data);
|
||||
writeTestData(data.document, rootPath, id);
|
||||
return output;
|
||||
}
|
||||
|
||||
bool compileOk = data.result.compiled == data.expected.compiled;
|
||||
bool evalOk = compileOk && deepEqual(data.result.outputs, data.expected.outputs);
|
||||
|
||||
bool recompileOk = true;
|
||||
bool roundTripOk = true;
|
||||
bool serializationOk = true;
|
||||
|
||||
if (data.expected.compiled.success) {
|
||||
serializationOk = compileOk && deepEqual(data.result.serialized, data.expected.serialized);
|
||||
recompileOk = compileOk && data.recompiled.compiled == data.expected.compiled;
|
||||
roundTripOk = recompileOk && deepEqual(data.recompiled.outputs, data.expected.outputs);
|
||||
}
|
||||
|
||||
output.passed = compileOk && evalOk && recompileOk && roundTripOk && serializationOk;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
if (compileOk && !serializationOk) {
|
||||
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;
|
||||
}
|
||||
|
||||
if (compileOk && !evalOk) {
|
||||
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;
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <vector>
|
||||
#include <string>
|
||||
|
||||
class TestData;
|
||||
|
||||
struct TestRunOutput {
|
||||
TestRunOutput(std::string id_) : id(std::move(id_)) {}
|
||||
std::string id;
|
||||
bool passed = false;
|
||||
std::string text;
|
||||
std::string expression;
|
||||
std::string serialized;
|
||||
};
|
||||
|
||||
class TestStats {
|
||||
public:
|
||||
std::size_t testCount() const {
|
||||
return passed.size() + failed.size() + errored.size() +
|
||||
ignorePassed.size() + ignoreFailed.size();
|
||||
}
|
||||
|
||||
std::vector<TestRunOutput> passed;
|
||||
std::vector<TestRunOutput> failed;
|
||||
std::vector<TestRunOutput> errored;
|
||||
std::vector<TestRunOutput> ignorePassed;
|
||||
std::vector<TestRunOutput> ignoreFailed;
|
||||
std::vector<std::string> ids;
|
||||
};
|
||||
|
||||
TestRunOutput runExpressionTest(TestData&, const std::string& rootPath, const std::string& id);
|
||||
@@ -1,9 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <ghc/filesystem.hpp>
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
namespace filesystem = ghc::filesystem;
|
||||
|
||||
} // namespace mbgl
|
||||
@@ -1,75 +0,0 @@
|
||||
#include "expression_test_parser.hpp"
|
||||
#include "expression_test_runner.hpp"
|
||||
#include "expression_test_logger.hpp"
|
||||
|
||||
#include <random>
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
// Parse args
|
||||
std::vector<mbgl::filesystem::path> testPaths;
|
||||
mbgl::filesystem::path rootPath;
|
||||
bool shuffle;
|
||||
uint32_t seed;
|
||||
std::tie(rootPath, testPaths, shuffle, seed) = parseArguments(argc, argv);
|
||||
|
||||
// Parse ignores
|
||||
const auto ignores = parseExpressionIgnores();
|
||||
|
||||
if (shuffle) {
|
||||
printf(ANSI_COLOR_YELLOW "Shuffle seed: %d" ANSI_COLOR_RESET "\n", seed);
|
||||
std::seed_seq sequence { seed };
|
||||
std::mt19937 shuffler(sequence);
|
||||
std::shuffle(testPaths.begin(), testPaths.end(), shuffler);
|
||||
}
|
||||
|
||||
// Run tests, collect stats and output of each run.
|
||||
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());
|
||||
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; });
|
||||
if (it != ignores.end()) {
|
||||
shouldIgnore = true;
|
||||
ignoreReason = (*it).reason;
|
||||
}
|
||||
|
||||
optional<TestRunOutput> testRun;
|
||||
if (auto testData = parseTestData(path)) {
|
||||
testRun = runExpressionTest(*testData, rootPath.string(), id);
|
||||
}
|
||||
|
||||
if (!testRun) {
|
||||
stats.errored.emplace_back(id);
|
||||
printf(ANSI_COLOR_RED "* ERROR can't parse '%s' test" ANSI_COLOR_RESET "\n", id.c_str());
|
||||
continue;
|
||||
}
|
||||
|
||||
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());
|
||||
} 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());
|
||||
}
|
||||
} else {
|
||||
if (testRun->passed) {
|
||||
stats.passed.emplace_back(std::move(*testRun));
|
||||
printf(ANSI_COLOR_GREEN "* PASSED %s" ANSI_COLOR_RESET "\n", id.c_str());
|
||||
} else {
|
||||
printf(ANSI_COLOR_RED "* FAILED %s\n%s" ANSI_COLOR_RESET, id.c_str(), testRun->text.c_str());
|
||||
stats.failed.emplace_back(std::move(*testRun));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
printStats(stats);
|
||||
writeHTMLResults(stats, rootPath.string(), shuffle, seed);
|
||||
|
||||
return stats.errored.size() + stats.failed.size() == 0 ? 0 : 1;
|
||||
}
|
||||
@@ -1,131 +0,0 @@
|
||||
#include "test_runner_common.hpp"
|
||||
|
||||
#include <cmath>
|
||||
#include <regex>
|
||||
|
||||
using namespace mbgl;
|
||||
|
||||
// Strip precision for numbers, so that we can compare evaluated results with fixtures.
|
||||
// Copied from JS expression harness.
|
||||
Value stripPrecision(const Value& value) {
|
||||
const double decimalSigFigs = 6;
|
||||
if (auto num = numericValue<double>(value)) {
|
||||
if (*num == 0) {
|
||||
return *num;
|
||||
}
|
||||
|
||||
const double multiplier = std::pow(10, std::max(0.0, decimalSigFigs - std::ceil(std::log10(std::fabs(*num)))));
|
||||
|
||||
// We strip precision twice in a row here to avoid cases where
|
||||
// stripping an already stripped number will modify its value
|
||||
// due to bad floating point precision luck
|
||||
// eg `Math.floor(8.16598 * 100000) / 100000` -> 8.16597
|
||||
const double firstStrip = std::floor(*num * multiplier) / multiplier;
|
||||
return std::floor(firstStrip * multiplier) / multiplier;
|
||||
}
|
||||
|
||||
if (value.is<std::vector<Value>>()) {
|
||||
std::vector<Value> stripped;
|
||||
const auto& vec = value.get<std::vector<Value>>();
|
||||
stripped.reserve(vec.size());
|
||||
for (const auto& val : vec) {
|
||||
stripped.emplace_back(stripPrecision(val));
|
||||
}
|
||||
return stripped;
|
||||
} else if (value.is<std::unordered_map<std::string, Value>>()) {
|
||||
std::unordered_map<std::string, Value> stripped;
|
||||
const auto& map = value.get<std::unordered_map<std::string, Value>>();
|
||||
for (const auto& pair : map) {
|
||||
stripped.emplace(pair.first, stripPrecision(pair.second));
|
||||
}
|
||||
return stripped;
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
std::vector<std::string> tokenize(std::string str) {
|
||||
std::vector<std::string> tokens;
|
||||
std::regex re("\n");
|
||||
std::copy(std::regex_token_iterator<std::string::iterator>(str.begin(), str.end(), re, -1),
|
||||
std::regex_token_iterator<std::string::iterator>(),
|
||||
std::back_inserter(tokens));
|
||||
return tokens;
|
||||
}
|
||||
|
||||
bool deepEqual(const Value& a, const Value& b) {
|
||||
const auto& anum = numericValue<double>(a);
|
||||
const auto& bnum = numericValue<double>(b);
|
||||
if (anum && bnum) {
|
||||
return stripPrecision(*anum) == stripPrecision(*bnum);
|
||||
}
|
||||
|
||||
if (a.which() != b.which()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (a.getArray() && b.getArray()) {
|
||||
const auto& avec = *a.getArray();
|
||||
const auto& bvec = *b.getArray();
|
||||
if (avec.size() != bvec.size()) {
|
||||
return false;
|
||||
}
|
||||
for (std::size_t i = 0; i < avec.size(); ++i) {
|
||||
if (!deepEqual(avec[i], bvec[i])) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (a.getObject() && b.getObject()) {
|
||||
const auto& amap = *a.getObject();
|
||||
const auto& bmap = *b.getObject();
|
||||
if (amap.size() != bmap.size()) {
|
||||
return false;
|
||||
}
|
||||
for (const auto& pair : amap) {
|
||||
auto it = bmap.find(pair.first);
|
||||
if (it == bmap.end()) {
|
||||
return false;
|
||||
}
|
||||
if (!deepEqual(pair.second, it->second)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (a == b) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (a.getString() && b.getString()) {
|
||||
const auto& strA = *a.getString();
|
||||
const auto& strB = *b.getString();
|
||||
if (strA == strB) {
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
double numA = std::stod(strA);
|
||||
double numB = std::stod(strB);
|
||||
return stripPrecision(numA) == stripPrecision(numB);
|
||||
} catch (...) {
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool deepEqual(const optional<Value>& a, const optional<Value>& b) {
|
||||
if ((a && !b) || (!a && b)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (a && b) {
|
||||
return deepEqual(*a, *b);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <mbgl/util/feature.hpp>
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
using namespace mbgl;
|
||||
|
||||
Value stripPrecision(const Value& value);
|
||||
std::vector<std::string> tokenize(std::string str);
|
||||
bool deepEqual(const Value& a, const Value& b);
|
||||
bool deepEqual(const optional<Value>& a, const optional<Value>& b);
|
||||
@@ -1,74 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <mbgl/actor/aspiring_actor.hpp>
|
||||
#include <mbgl/actor/established_actor.hpp>
|
||||
#include <mbgl/actor/mailbox.hpp>
|
||||
#include <mbgl/actor/message.hpp>
|
||||
#include <mbgl/actor/actor_ref.hpp>
|
||||
#include <mbgl/util/noncopyable.hpp>
|
||||
|
||||
#include <memory>
|
||||
#include <future>
|
||||
#include <type_traits>
|
||||
#include <cassert>
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
/*
|
||||
An `Actor<O>` is an owning reference to an asynchronous object of type `O`: an "actor".
|
||||
Communication with an actor happens via message passing: you send a message to the object
|
||||
(using `invoke`), passing a pointer to the member function to call and arguments which
|
||||
are then forwarded to the actor.
|
||||
|
||||
The actor receives messages sent to it asynchronously, in a manner defined its `Scheduler`.
|
||||
To store incoming messages before their receipt, each actor has a `Mailbox`, which acts as
|
||||
a FIFO queue. Messages sent from actor S to actor R are guaranteed to be processed in the
|
||||
order sent. However, relative order of messages sent by two *different* actors S1 and S2
|
||||
to R is *not* guaranteed (and can't be: S1 and S2 may be acting asynchronously with respect
|
||||
to each other).
|
||||
|
||||
An `Actor<O>` can be converted to an `ActorRef<O>`, a non-owning value object representing
|
||||
a (weak) reference to the actor. Messages can be sent via the `Ref` as well.
|
||||
|
||||
It's safe -- and encouraged -- to pass `Ref`s between actors via messages. This is how two-way
|
||||
communication and other forms of collaboration between multiple actors is accomplished.
|
||||
|
||||
It's safe for a `Ref` to outlive its `Actor` -- the reference is "weak", and does not extend
|
||||
the lifetime of the owning Actor, and sending a message to a `Ref` whose `Actor` has died is
|
||||
a no-op. (In the future, a dead-letters queue or log may be implemented.)
|
||||
|
||||
Construction and destruction of an Actor is synchronous: the corresponding `O`
|
||||
object is constructed synchronously by the `Actor` constructor, and destructed synchronously
|
||||
by the `~Actor` destructor, after ensuring that the `O` is not currently receiving an
|
||||
asynchronous message. The constructor of `O` is passed an `ActorRef<O>` referring to itself
|
||||
(which it can use to self-send messages), followed by the forwarded arguments passed to
|
||||
`Actor<O>`. Asynchronous object construction can be accomplished by directly using the
|
||||
lower-level types, `AspiringActor<O>` and `EstablishedActor<O>`.
|
||||
|
||||
Please don't send messages that contain shared pointers or references. That subverts the
|
||||
purpose of the actor model: prohibiting direct concurrent access to shared state.
|
||||
*/
|
||||
template <class Object>
|
||||
class Actor {
|
||||
public:
|
||||
template <class... Args>
|
||||
Actor(Scheduler& scheduler, Args&&... args)
|
||||
: target(scheduler, parent, std::forward<Args>(args)...) {}
|
||||
|
||||
template <class... Args>
|
||||
Actor(std::shared_ptr<Scheduler> scheduler, Args&&... args)
|
||||
: retainer(std::move(scheduler)), target(*retainer, parent, std::forward<Args>(args)...) {}
|
||||
|
||||
Actor(const Actor&) = delete;
|
||||
|
||||
ActorRef<std::decay_t<Object>> self() {
|
||||
return parent.self();
|
||||
}
|
||||
|
||||
private:
|
||||
std::shared_ptr<Scheduler> retainer;
|
||||
AspiringActor<Object> parent;
|
||||
EstablishedActor<Object> target;
|
||||
};
|
||||
|
||||
} // namespace mbgl
|
||||
@@ -1,64 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <mbgl/actor/mailbox.hpp>
|
||||
#include <mbgl/actor/message.hpp>
|
||||
|
||||
#include <memory>
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
/*
|
||||
An `ActorRef<O>` is a *non*-owning, weak reference to an actor of type `O`. You can send it
|
||||
messages just like an `Actor<O>`. It's a value object: safe to copy and pass between actors
|
||||
via messages.
|
||||
|
||||
An `ActorRef<O>` does not extend the lifetime of the corresponding `Actor<O>`. That's determined
|
||||
entirely by whichever object owns the `Actor<O>` -- the actor's "supervisor".
|
||||
|
||||
It's safe for a `Ref` to outlive its `Actor` -- the reference is "weak", and does not extend
|
||||
the lifetime of the owning Actor, and sending a message to a `Ref` whose `Actor` has died is
|
||||
a no-op. (In the future, a dead-letters queue or log may be implemented.)
|
||||
*/
|
||||
|
||||
template <class Object>
|
||||
class ActorRef {
|
||||
public:
|
||||
ActorRef(Object& object_, std::weak_ptr<Mailbox> weakMailbox_)
|
||||
: object(&object_),
|
||||
weakMailbox(std::move(weakMailbox_)) {
|
||||
}
|
||||
|
||||
template <typename Fn, class... Args>
|
||||
void invoke(Fn fn, Args&&... args) const {
|
||||
if (auto mailbox = weakMailbox.lock()) {
|
||||
mailbox->push(actor::makeMessage(*object, fn, std::forward<Args>(args)...));
|
||||
}
|
||||
}
|
||||
|
||||
template <typename Fn, class... Args>
|
||||
auto ask(Fn fn, Args&&... args) const {
|
||||
// Result type is deduced from the function's return type
|
||||
using ResultType = typename std::result_of<decltype(fn)(Object, Args...)>::type;
|
||||
|
||||
std::promise<ResultType> promise;
|
||||
auto future = promise.get_future();
|
||||
|
||||
if (auto mailbox = weakMailbox.lock()) {
|
||||
mailbox->push(
|
||||
actor::makeMessage(
|
||||
std::move(promise), *object, fn, std::forward<Args>(args)...
|
||||
)
|
||||
);
|
||||
} else {
|
||||
promise.set_exception(std::make_exception_ptr(std::runtime_error("Actor has gone away")));
|
||||
}
|
||||
|
||||
return future;
|
||||
}
|
||||
|
||||
private:
|
||||
Object* object;
|
||||
std::weak_ptr<Mailbox> weakMailbox;
|
||||
};
|
||||
|
||||
} // namespace mbgl
|
||||
@@ -1,60 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <mbgl/actor/mailbox.hpp>
|
||||
#include <mbgl/actor/message.hpp>
|
||||
#include <mbgl/actor/actor_ref.hpp>
|
||||
|
||||
#include <memory>
|
||||
#include <future>
|
||||
#include <type_traits>
|
||||
#include <cassert>
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
template <class Object>
|
||||
class EstablishedActor;
|
||||
|
||||
template <class Object>
|
||||
class Actor;
|
||||
|
||||
/*
|
||||
An `AspiringActor<O>` is one half of the pair of types that comprise an actor (see `Actor<O>`),
|
||||
the other half being `EstablishedActor<O>`. 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<O>` can
|
||||
accept messages for the target object, or provide `ActorRef<O>`s that do so, before the object
|
||||
has actually been constructed by the corresponding `EstablishedActor<O>`. (Such messages are
|
||||
queued in the mailbox until after the object is constructed.)
|
||||
|
||||
This allows for an `AspiringActor<O>` to be created and safely used by a thread other than the
|
||||
one on which the target object will (eventually) live.
|
||||
*/
|
||||
template <class Object>
|
||||
class AspiringActor {
|
||||
public:
|
||||
AspiringActor() : mailbox(std::make_shared<Mailbox>()) {
|
||||
// mailbox starts closed because the `Object` hasn't yet been constructed
|
||||
assert(!mailbox->isOpen());
|
||||
}
|
||||
|
||||
AspiringActor(const AspiringActor&) = delete;
|
||||
|
||||
ActorRef<std::decay_t<Object>> self() {
|
||||
return ActorRef<std::decay_t<Object>>(object(), mailbox);
|
||||
}
|
||||
|
||||
private:
|
||||
std::shared_ptr<Mailbox> mailbox;
|
||||
std::aligned_storage_t<sizeof(Object)> objectStorage;
|
||||
|
||||
Object& object() {
|
||||
return *reinterpret_cast<Object *>(&objectStorage);
|
||||
}
|
||||
|
||||
friend class EstablishedActor<Object>;
|
||||
friend class Actor<Object>;
|
||||
};
|
||||
|
||||
} // namespace mbgl
|
||||
@@ -1,80 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <mbgl/actor/aspiring_actor.hpp>
|
||||
#include <mbgl/actor/mailbox.hpp>
|
||||
#include <mbgl/actor/message.hpp>
|
||||
#include <mbgl/actor/actor_ref.hpp>
|
||||
|
||||
#include <memory>
|
||||
#include <future>
|
||||
#include <type_traits>
|
||||
#include <cassert>
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
/*
|
||||
An `EstablishedActor<O>` is one half of the pair of types that comprise an actor (see `Actor<O>`),
|
||||
the other half being `AspiringActor<O>`. 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<O>`: 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
|
||||
therefore live entirely on the thread intended to own `O`.
|
||||
*/
|
||||
|
||||
template <class Object>
|
||||
class EstablishedActor {
|
||||
public:
|
||||
// Construct the Object from a parameter pack `args` (i.e. `Object(args...)`)
|
||||
template <typename U = Object, class... Args, typename std::enable_if<
|
||||
std::is_constructible<U, Args...>::value ||
|
||||
std::is_constructible<U, ActorRef<U>, Args...>::value
|
||||
>::type * = nullptr>
|
||||
EstablishedActor(Scheduler& scheduler, AspiringActor<Object>& parent_, Args&& ... args)
|
||||
: parent(parent_) {
|
||||
emplaceObject(std::forward<Args>(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 <class ArgsTuple, std::size_t ArgCount = std::tuple_size<std::decay_t<ArgsTuple>>::value>
|
||||
EstablishedActor(Scheduler& scheduler, AspiringActor<Object>& parent_, ArgsTuple&& args)
|
||||
: parent(parent_) {
|
||||
emplaceObject(std::forward<ArgsTuple>(args), std::make_index_sequence<ArgCount>{});
|
||||
parent.mailbox->open(scheduler);
|
||||
}
|
||||
|
||||
EstablishedActor(const EstablishedActor&) = delete;
|
||||
|
||||
~EstablishedActor() {
|
||||
parent.mailbox->close();
|
||||
parent.object().~Object();
|
||||
}
|
||||
|
||||
private:
|
||||
// Enabled for Objects with a constructor taking ActorRef<Object> as the first parameter
|
||||
template <typename U = Object, class... Args, typename std::enable_if<std::is_constructible<U, ActorRef<U>, Args...>::value>::type * = nullptr>
|
||||
void emplaceObject(Args&&... args_) {
|
||||
new (&parent.objectStorage) Object(parent.self(), std::forward<Args>(args_)...);
|
||||
}
|
||||
|
||||
// Enabled for plain Objects
|
||||
template <typename U = Object, class... Args, typename std::enable_if<std::is_constructible<U, Args...>::value>::type * = nullptr>
|
||||
void emplaceObject(Args&&... args_) {
|
||||
new (&parent.objectStorage) Object(std::forward<Args>(args_)...);
|
||||
}
|
||||
|
||||
// Used to expand a tuple holding the constructor arguments
|
||||
template <class ArgsTuple, std::size_t... I>
|
||||
void emplaceObject(ArgsTuple&& args, std::index_sequence<I...>) {
|
||||
emplaceObject(std::move(std::get<I>(std::forward<ArgsTuple>(args)))...);
|
||||
(void) args; // mark args as used: if it's empty tuple, it's not actually used above.
|
||||
}
|
||||
|
||||
AspiringActor<Object>& parent;
|
||||
};
|
||||
|
||||
} // namespace mbgl
|
||||
@@ -1,52 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <mbgl/util/optional.hpp>
|
||||
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <queue>
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
class Scheduler;
|
||||
class Message;
|
||||
|
||||
class Mailbox : public std::enable_shared_from_this<Mailbox> {
|
||||
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
|
||||
// sent to it. The mailbox must be a "holding" mailbox, as created by the
|
||||
// default constructor Mailbox().
|
||||
void open(Scheduler& scheduler_);
|
||||
void close();
|
||||
|
||||
bool isOpen() const;
|
||||
|
||||
void push(std::unique_ptr<Message>);
|
||||
void receive();
|
||||
|
||||
static void maybeReceive(std::weak_ptr<Mailbox>);
|
||||
static std::function<void()> makeClosure(std::weak_ptr<Mailbox>);
|
||||
|
||||
private:
|
||||
optional<Scheduler*> scheduler;
|
||||
|
||||
std::recursive_mutex receivingMutex;
|
||||
std::mutex pushingMutex;
|
||||
|
||||
bool closed { false };
|
||||
|
||||
std::mutex queueMutex;
|
||||
std::queue<std::unique_ptr<Message>> queue;
|
||||
};
|
||||
|
||||
} // namespace mbgl
|
||||
@@ -1,108 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <mbgl/util/optional.hpp>
|
||||
|
||||
#include <future>
|
||||
#include <utility>
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
// A movable type-erasing function wrapper. This allows to store arbitrary invokable
|
||||
// things (like std::function<>, or the result of a movable-only std::bind()) in the queue.
|
||||
// Source: http://stackoverflow.com/a/29642072/331379
|
||||
class Message {
|
||||
public:
|
||||
virtual ~Message() = default;
|
||||
virtual void operator()() = 0;
|
||||
};
|
||||
|
||||
template <class Object, class MemberFn, class ArgsTuple>
|
||||
class MessageImpl : public Message {
|
||||
public:
|
||||
MessageImpl(Object& object_, MemberFn memberFn_, ArgsTuple argsTuple_)
|
||||
: object(object_),
|
||||
memberFn(memberFn_),
|
||||
argsTuple(std::move(argsTuple_)) {
|
||||
}
|
||||
|
||||
void operator()() override {
|
||||
invoke(std::make_index_sequence<std::tuple_size<ArgsTuple>::value>());
|
||||
}
|
||||
|
||||
template <std::size_t... I>
|
||||
void invoke(std::index_sequence<I...>) {
|
||||
(object.*memberFn)(std::move(std::get<I>(argsTuple))...);
|
||||
}
|
||||
|
||||
Object& object;
|
||||
MemberFn memberFn;
|
||||
ArgsTuple argsTuple;
|
||||
};
|
||||
|
||||
template <class ResultType, class Object, class MemberFn, class ArgsTuple>
|
||||
class AskMessageImpl : public Message {
|
||||
public:
|
||||
AskMessageImpl(std::promise<ResultType> promise_, Object& object_, MemberFn memberFn_, ArgsTuple argsTuple_)
|
||||
: object(object_),
|
||||
memberFn(memberFn_),
|
||||
argsTuple(std::move(argsTuple_)),
|
||||
promise(std::move(promise_)) {
|
||||
}
|
||||
|
||||
void operator()() override {
|
||||
promise.set_value(ask(std::make_index_sequence<std::tuple_size<ArgsTuple>::value>()));
|
||||
}
|
||||
|
||||
template <std::size_t... I>
|
||||
ResultType ask(std::index_sequence<I...>) {
|
||||
return (object.*memberFn)(std::move(std::get<I>(argsTuple))...);
|
||||
}
|
||||
|
||||
Object& object;
|
||||
MemberFn memberFn;
|
||||
ArgsTuple argsTuple;
|
||||
std::promise<ResultType> promise;
|
||||
};
|
||||
|
||||
template <class Object, class MemberFn, class ArgsTuple>
|
||||
class AskMessageImpl<void, Object, MemberFn, ArgsTuple> : public Message {
|
||||
public:
|
||||
AskMessageImpl(std::promise<void> promise_, Object& object_, MemberFn memberFn_, ArgsTuple argsTuple_)
|
||||
: object(object_),
|
||||
memberFn(memberFn_),
|
||||
argsTuple(std::move(argsTuple_)),
|
||||
promise(std::move(promise_)) {
|
||||
}
|
||||
|
||||
void operator()() override {
|
||||
ask(std::make_index_sequence<std::tuple_size<ArgsTuple>::value>());
|
||||
promise.set_value();
|
||||
}
|
||||
|
||||
template <std::size_t... I>
|
||||
void ask(std::index_sequence<I...>) {
|
||||
(object.*memberFn)(std::move(std::get<I>(argsTuple))...);
|
||||
}
|
||||
|
||||
Object& object;
|
||||
MemberFn memberFn;
|
||||
ArgsTuple argsTuple;
|
||||
std::promise<void> promise;
|
||||
};
|
||||
|
||||
namespace actor {
|
||||
|
||||
template <class Object, class MemberFn, class... Args>
|
||||
std::unique_ptr<Message> makeMessage(Object& object, MemberFn memberFn, Args&&... args) {
|
||||
auto tuple = std::make_tuple(std::forward<Args>(args)...);
|
||||
return std::make_unique<MessageImpl<Object, MemberFn, decltype(tuple)>>(object, memberFn, std::move(tuple));
|
||||
}
|
||||
|
||||
template <class ResultType, class Object, class MemberFn, class... Args>
|
||||
std::unique_ptr<Message> makeMessage(std::promise<ResultType>&& promise, Object& object, MemberFn memberFn, Args&&... args) {
|
||||
auto tuple = std::make_tuple(std::forward<Args>(args)...);
|
||||
return std::make_unique<AskMessageImpl<ResultType, Object, MemberFn, decltype(tuple)>>(std::move(promise), object, memberFn, std::move(tuple));
|
||||
}
|
||||
|
||||
} // namespace actor
|
||||
} // namespace mbgl
|
||||
@@ -1,63 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <mapbox/weak.hpp>
|
||||
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
class Mailbox;
|
||||
|
||||
/*
|
||||
A `Scheduler` is responsible for coordinating the processing of messages by
|
||||
one or more actors via their mailboxes. It's an abstract interface. Currently,
|
||||
the following concrete implementations exist:
|
||||
|
||||
* `ThreadPool` can coordinate an unlimited number of actors over any number of
|
||||
threads via a pool, preserving the following behaviors:
|
||||
|
||||
- Messages from each individual mailbox are processed in order
|
||||
- Only a single message from a mailbox is processed at a time; there is no
|
||||
concurrency within a mailbox
|
||||
|
||||
Subject to these constraints, processing can happen on whatever thread in the
|
||||
pool is available.
|
||||
|
||||
* `Scheduler::GetCurrent()` is typically used to create a mailbox and `ActorRef`
|
||||
for an object that lives on the main thread and is not itself wrapped an
|
||||
`Actor`. The underlying implementation of this Scheduler should usually be
|
||||
a `RunLoop`
|
||||
auto mailbox = std::make_shared<Mailbox>(*Scheduler::Get());
|
||||
Actor<Worker> worker(threadPool, ActorRef<Foo>(*this, mailbox));
|
||||
*/
|
||||
class Scheduler {
|
||||
public:
|
||||
virtual ~Scheduler() = default;
|
||||
|
||||
// Enqueues a function for execution.
|
||||
virtual void schedule(std::function<void()>) = 0;
|
||||
// Makes a weak pointer to this Scheduler.
|
||||
virtual mapbox::base::WeakPtr<Scheduler> makeWeakPtr() = 0;
|
||||
|
||||
// Returns a closure wrapping the given one.
|
||||
//
|
||||
// When the returned closure is invoked for the first time, it schedules
|
||||
// the given closure to this scheduler, the consequent calls of the
|
||||
// returned closure are ignored.
|
||||
//
|
||||
// If this scheduler is already deleted by the time the returnded closure is
|
||||
// first invoked, the call is ignored.
|
||||
std::function<void()> bindOnce(std::function<void()>);
|
||||
|
||||
// Set/Get the current Scheduler for this thread
|
||||
static Scheduler* GetCurrent();
|
||||
static void SetCurrent(Scheduler*);
|
||||
|
||||
// Get the scheduler for asynchronous tasks. This method
|
||||
// will lazily initialize a shared worker pool when ran
|
||||
// from the first time.
|
||||
static std::shared_ptr<Scheduler> GetBackground();
|
||||
};
|
||||
|
||||
} // namespace mbgl
|
||||
@@ -1,70 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <mbgl/util/geometry.hpp>
|
||||
#include <mbgl/util/variant.hpp>
|
||||
#include <mbgl/util/color.hpp>
|
||||
#include <mbgl/style/property_value.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
using AnnotationID = uint64_t;
|
||||
using AnnotationIDs = std::vector<AnnotationID>;
|
||||
|
||||
class SymbolAnnotation {
|
||||
public:
|
||||
SymbolAnnotation(Point<double> geometry_, std::string icon_ = {}) : geometry(geometry_), icon(std::move(icon_)) {}
|
||||
|
||||
Point<double> geometry;
|
||||
std::string icon;
|
||||
};
|
||||
|
||||
using ShapeAnnotationGeometry = variant<
|
||||
LineString<double>,
|
||||
Polygon<double>,
|
||||
MultiLineString<double>,
|
||||
MultiPolygon<double>>;
|
||||
|
||||
class LineAnnotation {
|
||||
public:
|
||||
LineAnnotation(ShapeAnnotationGeometry geometry_,
|
||||
style::PropertyValue<float> opacity_ = 1.0f,
|
||||
style::PropertyValue<float> width_ = 1.0f,
|
||||
style::PropertyValue<Color> color_ = Color::black())
|
||||
: geometry(std::move(geometry_)),
|
||||
opacity(std::move(opacity_)),
|
||||
width(std::move(width_)),
|
||||
color(std::move(color_)) {}
|
||||
|
||||
ShapeAnnotationGeometry geometry;
|
||||
style::PropertyValue<float> opacity;
|
||||
style::PropertyValue<float> width;
|
||||
style::PropertyValue<Color> color;
|
||||
};
|
||||
|
||||
class FillAnnotation {
|
||||
public:
|
||||
FillAnnotation(ShapeAnnotationGeometry geometry_,
|
||||
style::PropertyValue<float> opacity_ = 1.0f,
|
||||
style::PropertyValue<Color> color_ = Color::black(),
|
||||
style::PropertyValue<Color> outlineColor_ = {})
|
||||
: geometry(std::move(geometry_)),
|
||||
opacity(std::move(opacity_)),
|
||||
color(std::move(color_)),
|
||||
outlineColor(std::move(outlineColor_)) {}
|
||||
|
||||
ShapeAnnotationGeometry geometry;
|
||||
style::PropertyValue<float> opacity;
|
||||
style::PropertyValue<Color> color;
|
||||
style::PropertyValue<Color> outlineColor;
|
||||
};
|
||||
|
||||
using Annotation = variant<
|
||||
SymbolAnnotation,
|
||||
LineAnnotation,
|
||||
FillAnnotation>;
|
||||
|
||||
} // namespace mbgl
|
||||
@@ -1,44 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <memory>
|
||||
|
||||
namespace mbgl {
|
||||
namespace gfx {
|
||||
|
||||
class Backend {
|
||||
public:
|
||||
enum class Type : uint8_t {
|
||||
OpenGL,
|
||||
};
|
||||
|
||||
static constexpr Type DefaultType = Type::OpenGL;
|
||||
|
||||
static void SetType(const Type value) {
|
||||
if (Value(value) != value) {
|
||||
abort(); // SetType must be called prior to any GetType calls.
|
||||
}
|
||||
}
|
||||
|
||||
static Type GetType() {
|
||||
return Value(DefaultType);
|
||||
}
|
||||
|
||||
template <typename T, typename... Args>
|
||||
static std::unique_ptr<T> Create(Args... args) {
|
||||
return Create<Type::OpenGL, T, Args...>(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
private:
|
||||
template <Type, typename T, typename... Args>
|
||||
static std::unique_ptr<T> Create(Args...);
|
||||
|
||||
static Type Value(Type value) {
|
||||
static const Type type = value;
|
||||
return type;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace gfx
|
||||
} // namespace mbgl
|
||||
@@ -1,37 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
namespace mbgl {
|
||||
namespace gfx {
|
||||
|
||||
class RendererBackend;
|
||||
|
||||
class BackendScope {
|
||||
public:
|
||||
// There are two types of scopes: Creating an "Implicit" scope tells Mapbox GL that the
|
||||
// supporting windowing system has already activated the GL Backend and that no further actions
|
||||
// are required. Creating an "Explicit" scope actually enables the GL Backend, and disables it
|
||||
// when the BackendScope is destroyed.
|
||||
enum class ScopeType : bool {
|
||||
Implicit,
|
||||
Explicit,
|
||||
};
|
||||
|
||||
BackendScope(RendererBackend&, ScopeType = ScopeType::Explicit);
|
||||
~BackendScope();
|
||||
|
||||
// Returns true when there is currently a BackendScope active in this thread.
|
||||
static bool exists();
|
||||
|
||||
private:
|
||||
void activate();
|
||||
void deactivate();
|
||||
|
||||
BackendScope* priorScope;
|
||||
BackendScope* nextScope;
|
||||
RendererBackend& backend;
|
||||
const ScopeType scopeType;
|
||||
bool activated = false;
|
||||
};
|
||||
|
||||
} // namespace gfx
|
||||
} // namespace mbgl
|
||||
@@ -1,47 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <mbgl/util/size.hpp>
|
||||
|
||||
#include <memory>
|
||||
#include <cassert>
|
||||
|
||||
namespace mbgl {
|
||||
namespace gfx {
|
||||
|
||||
class RenderableResource {
|
||||
protected:
|
||||
explicit RenderableResource() = default;
|
||||
|
||||
public:
|
||||
virtual ~RenderableResource() = default;
|
||||
RenderableResource(const RenderableResource&) = delete;
|
||||
RenderableResource& operator=(const RenderableResource&) = delete;
|
||||
};
|
||||
|
||||
class Renderable {
|
||||
protected:
|
||||
Renderable(const Size size_, std::unique_ptr<RenderableResource> resource_)
|
||||
: size(size_), resource(std::move(resource_)) {
|
||||
}
|
||||
virtual ~Renderable() = default;
|
||||
|
||||
public:
|
||||
Size getSize() const {
|
||||
return size;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
T& getResource() const {
|
||||
assert(resource);
|
||||
return static_cast<T&>(*resource);
|
||||
}
|
||||
|
||||
virtual void wait() {}
|
||||
|
||||
protected:
|
||||
Size size;
|
||||
std::unique_ptr<RenderableResource> resource;
|
||||
};
|
||||
|
||||
} // namespace gfx
|
||||
} // namespace mbgl
|
||||
@@ -1,72 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <mbgl/util/util.hpp>
|
||||
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
|
||||
namespace mbgl {
|
||||
namespace gfx {
|
||||
|
||||
class Context;
|
||||
class Renderable;
|
||||
class BackendScope;
|
||||
|
||||
// We can make some optimizations if we know that the drawing context is not shared with other code.
|
||||
enum class ContextMode : bool {
|
||||
Unique,
|
||||
Shared,
|
||||
};
|
||||
|
||||
class RendererBackend {
|
||||
protected:
|
||||
explicit RendererBackend(ContextMode);
|
||||
|
||||
public:
|
||||
virtual ~RendererBackend();
|
||||
RendererBackend(const RendererBackend&) = delete;
|
||||
RendererBackend& operator=(const RendererBackend&) = delete;
|
||||
|
||||
// Returns the device's context.
|
||||
Context& getContext();
|
||||
|
||||
template <typename T>
|
||||
T& getContext() {
|
||||
return static_cast<T&>(getContext());
|
||||
}
|
||||
|
||||
bool contextIsShared() const {
|
||||
return contextMode == ContextMode::Shared;
|
||||
}
|
||||
|
||||
// Returns a reference to the default surface that should be rendered on.
|
||||
virtual Renderable& getDefaultRenderable() = 0;
|
||||
|
||||
protected:
|
||||
virtual std::unique_ptr<Context> createContext() = 0;
|
||||
|
||||
// Called when the backend's GL context needs to be made active or inactive. These are called,
|
||||
// as a matched pair, exclusively through BackendScope, in two situations:
|
||||
//
|
||||
// 1. When releasing GL resources during Renderer destruction
|
||||
// (Including calling CustomLayerHost::deinitialize during RenderCustomLayer destruction)
|
||||
// 2. When renderering through Renderer::render()
|
||||
// (Including calling CustomLayerHost::initialize for newly added custom layers and
|
||||
// CustomLayerHost::deinitialize on layer removal)
|
||||
virtual void activate() = 0;
|
||||
virtual void deactivate() = 0;
|
||||
|
||||
protected:
|
||||
std::unique_ptr<Context> context;
|
||||
const ContextMode contextMode;
|
||||
std::once_flag initialized;
|
||||
|
||||
friend class BackendScope;
|
||||
};
|
||||
|
||||
MBGL_CONSTEXPR bool operator==(const RendererBackend& a, const RendererBackend& b) {
|
||||
return &a == &b;
|
||||
}
|
||||
|
||||
} // namespace gfx
|
||||
} // namespace mbgl
|
||||
@@ -1,24 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <mbgl/gfx/renderable.hpp>
|
||||
|
||||
#include <cstdlib>
|
||||
|
||||
namespace mbgl {
|
||||
namespace gl {
|
||||
|
||||
class RenderableResource : public gfx::RenderableResource {
|
||||
protected:
|
||||
explicit RenderableResource() = default;
|
||||
|
||||
public:
|
||||
virtual void bind() = 0;
|
||||
|
||||
virtual void swap() {
|
||||
// Renderable resources that require a swap function to be called explicitly
|
||||
// can override this method.
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace gl
|
||||
} // namespace mbgl
|
||||
@@ -1,56 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <mbgl/gfx/renderer_backend.hpp>
|
||||
#include <mbgl/util/image.hpp>
|
||||
#include <mbgl/util/size.hpp>
|
||||
#include <mbgl/util/util.hpp>
|
||||
|
||||
namespace mbgl {
|
||||
namespace gl {
|
||||
|
||||
class Context;
|
||||
using ProcAddress = void (*)();
|
||||
using FramebufferID = uint32_t;
|
||||
|
||||
class RendererBackend : public gfx::RendererBackend {
|
||||
public:
|
||||
RendererBackend(gfx::ContextMode);
|
||||
~RendererBackend() override;
|
||||
|
||||
// Called prior to rendering to update the internally assumed OpenGL state.
|
||||
virtual void updateAssumedState() = 0;
|
||||
|
||||
protected:
|
||||
std::unique_ptr<gfx::Context> createContext() override;
|
||||
|
||||
// Called with the name of an OpenGL extension that should be loaded. RendererBackend implementations
|
||||
// must call the API-specific version that obtains the function pointer for this function,
|
||||
// or a null pointer if unsupported/unavailable.
|
||||
virtual ProcAddress getExtensionFunctionPointer(const char*) = 0;
|
||||
|
||||
// Reads the color pixel data from the currently bound framebuffer.
|
||||
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<FramebufferID>::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.
|
||||
void assumeFramebufferBinding(FramebufferID fbo);
|
||||
void assumeViewport(int32_t x, int32_t y, const Size&);
|
||||
void assumeScissorTest(bool);
|
||||
|
||||
// Returns true when assumed framebuffer binding hasn't changed from the implicit binding.
|
||||
bool implicitFramebufferBound();
|
||||
|
||||
public:
|
||||
// Triggers an OpenGL state update if the internal assumed state doesn't match the
|
||||
// supplied values.
|
||||
void setFramebufferBinding(FramebufferID fbo);
|
||||
void setViewport(int32_t x, int32_t y, const Size&);
|
||||
void setScissorTest(bool);
|
||||
};
|
||||
|
||||
} // namespace gl
|
||||
} // namespace mbgl
|
||||
@@ -1,24 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <mbgl/util/optional.hpp>
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
namespace mbgl {
|
||||
namespace platform {
|
||||
|
||||
class Collator {
|
||||
public:
|
||||
explicit Collator(bool caseSensitive, bool diacriticSensitive, optional<std::string> locale = nullopt);
|
||||
int compare(const std::string& lhs, const std::string& rhs) const;
|
||||
std::string resolvedLocale() const;
|
||||
bool operator==(const Collator& other) const;
|
||||
|
||||
private:
|
||||
class Impl;
|
||||
std::shared_ptr<Impl> impl;
|
||||
};
|
||||
|
||||
} // namespace platform
|
||||
} // namespace mbgl
|
||||
@@ -1,15 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace mbgl {
|
||||
namespace platform {
|
||||
|
||||
std::string formatNumber(double number,
|
||||
const std::string& localeId,
|
||||
const std::string& currency,
|
||||
uint8_t minFractionDigits,
|
||||
uint8_t maxFractionDigits);
|
||||
|
||||
} // namespace platform
|
||||
} // namespace mbgl
|
||||
@@ -1,14 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <mbgl/layermanager/layer_factory.hpp>
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
class BackgroundLayerFactory : public LayerFactory {
|
||||
protected:
|
||||
const style::LayerTypeInfo* getTypeInfo() const noexcept final;
|
||||
std::unique_ptr<style::Layer> createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept final;
|
||||
std::unique_ptr<RenderLayer> createRenderLayer(Immutable<style::Layer::Impl>) noexcept final;
|
||||
};
|
||||
|
||||
} // namespace mbgl
|
||||
@@ -1,15 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <mbgl/layermanager/layer_factory.hpp>
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
class CircleLayerFactory : public LayerFactory {
|
||||
protected:
|
||||
const style::LayerTypeInfo* getTypeInfo() const noexcept final;
|
||||
std::unique_ptr<style::Layer> createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept final;
|
||||
std::unique_ptr<Bucket> createBucket(const BucketParameters&, const std::vector<Immutable<style::LayerProperties>>&) noexcept final;
|
||||
std::unique_ptr<RenderLayer> createRenderLayer(Immutable<style::Layer::Impl>) noexcept final;
|
||||
};
|
||||
|
||||
} // namespace mbgl
|
||||
@@ -1,17 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <mbgl/layermanager/layer_factory.hpp>
|
||||
#include <mbgl/style/layer.hpp>
|
||||
|
||||
#include <array>
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
class CustomLayerFactory : public LayerFactory {
|
||||
protected:
|
||||
const style::LayerTypeInfo* getTypeInfo() const noexcept final;
|
||||
std::unique_ptr<style::Layer> createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept final;
|
||||
std::unique_ptr<RenderLayer> createRenderLayer(Immutable<style::Layer::Impl>) noexcept final;
|
||||
};
|
||||
|
||||
} // namespace mbgl
|
||||
@@ -1,15 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <mbgl/layermanager/layer_factory.hpp>
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
class FillExtrusionLayerFactory : public LayerFactory {
|
||||
protected:
|
||||
const style::LayerTypeInfo* getTypeInfo() const noexcept final;
|
||||
std::unique_ptr<style::Layer> createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept final;
|
||||
std::unique_ptr<Layout> createLayout(const LayoutParameters&, std::unique_ptr<GeometryTileLayer>, const std::vector<Immutable<style::LayerProperties>>&) noexcept final;
|
||||
std::unique_ptr<RenderLayer> createRenderLayer(Immutable<style::Layer::Impl>) noexcept final;
|
||||
};
|
||||
|
||||
} // namespace mbgl
|
||||
@@ -1,15 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <mbgl/layermanager/layer_factory.hpp>
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
class FillLayerFactory : public LayerFactory {
|
||||
protected:
|
||||
const style::LayerTypeInfo* getTypeInfo() const noexcept final;
|
||||
std::unique_ptr<style::Layer> createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept final;
|
||||
std::unique_ptr<Layout> createLayout(const LayoutParameters&, std::unique_ptr<GeometryTileLayer>, const std::vector<Immutable<style::LayerProperties>>&) noexcept final;
|
||||
std::unique_ptr<RenderLayer> createRenderLayer(Immutable<style::Layer::Impl>) noexcept final;
|
||||
};
|
||||
|
||||
} // namespace mbgl
|
||||
@@ -1,15 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <mbgl/layermanager/layer_factory.hpp>
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
class HeatmapLayerFactory : public LayerFactory {
|
||||
protected:
|
||||
const style::LayerTypeInfo* getTypeInfo() const noexcept final;
|
||||
std::unique_ptr<style::Layer> createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept final;
|
||||
std::unique_ptr<Bucket> createBucket(const BucketParameters&, const std::vector<Immutable<style::LayerProperties>>&) noexcept final;
|
||||
std::unique_ptr<RenderLayer> createRenderLayer(Immutable<style::Layer::Impl>) noexcept final;
|
||||
};
|
||||
|
||||
} // namespace mbgl
|
||||
@@ -1,14 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <mbgl/layermanager/layer_factory.hpp>
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
class HillshadeLayerFactory : public LayerFactory {
|
||||
protected:
|
||||
const style::LayerTypeInfo* getTypeInfo() const noexcept final;
|
||||
std::unique_ptr<style::Layer> createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept final;
|
||||
std::unique_ptr<RenderLayer> createRenderLayer(Immutable<style::Layer::Impl>) noexcept final;
|
||||
};
|
||||
|
||||
} // namespace mbgl
|
||||
@@ -1,43 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <mbgl/style/layer.hpp>
|
||||
|
||||
#include <vector>
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
namespace style {
|
||||
class LayerProperties;
|
||||
} // namespace style
|
||||
class Bucket;
|
||||
class BucketParameters;
|
||||
class GeometryTileLayer;
|
||||
class Layout;
|
||||
class LayoutParameters;
|
||||
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 {
|
||||
public:
|
||||
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<style::Layer> createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept = 0;
|
||||
/// Returns a new RenderLayer instance.
|
||||
virtual std::unique_ptr<RenderLayer> createRenderLayer(Immutable<style::Layer::Impl>) noexcept = 0;
|
||||
/// Returns a new Bucket instance on success call; returns `nullptr` otherwise.
|
||||
virtual std::unique_ptr<Bucket> createBucket(const BucketParameters&, const std::vector<Immutable<style::LayerProperties>>&) noexcept;
|
||||
/// Returns a new Layout instance on success call; returns `nullptr` otherwise.
|
||||
virtual std::unique_ptr<Layout> createLayout(const LayoutParameters&, std::unique_ptr<GeometryTileLayer>, const std::vector<Immutable<style::LayerProperties>>&) noexcept;
|
||||
|
||||
protected:
|
||||
optional<std::string> getSource(const style::conversion::Convertible& value) const noexcept;
|
||||
bool initSourceLayerAndFilter(style::Layer*, const style::conversion::Convertible& value) const noexcept;
|
||||
};
|
||||
|
||||
} // namespace mbgl
|
||||
@@ -1,70 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <mbgl/style/layer.hpp>
|
||||
|
||||
#include <vector>
|
||||
|
||||
namespace mbgl {
|
||||
namespace style {
|
||||
class LayerProperties;
|
||||
} // namespace style
|
||||
class GeometryTileLayer;
|
||||
class LayerFactory;
|
||||
class RenderLayer;
|
||||
class Bucket;
|
||||
class BucketParameters;
|
||||
class Layout;
|
||||
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.
|
||||
*/
|
||||
class LayerManager {
|
||||
public:
|
||||
/**
|
||||
* @brief A singleton getter.
|
||||
*
|
||||
* @return LayerManager*
|
||||
*/
|
||||
static LayerManager* get() noexcept;
|
||||
|
||||
/// Returns a new Layer instance on success call; returns `nullptr` otherwise.
|
||||
std::unique_ptr<style::Layer> 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<RenderLayer> createRenderLayer(Immutable<style::Layer::Impl>) noexcept;
|
||||
/// Returns a new Bucket instance on success call; returns `nullptr` otherwise.
|
||||
std::unique_ptr<Bucket> createBucket(const BucketParameters&, const std::vector<Immutable<style::LayerProperties>>&) noexcept;
|
||||
/// Returns a new Layout instance on success call; returns `nullptr` otherwise.
|
||||
std::unique_ptr<Layout> createLayout(const LayoutParameters&, std::unique_ptr<GeometryTileLayer>,
|
||||
const std::vector<Immutable<style::LayerProperties>>&) 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
|
||||
* implementation).
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
static const bool annotationsEnabled;
|
||||
|
||||
protected:
|
||||
virtual ~LayerManager() = default;
|
||||
virtual LayerFactory* getFactory(const std::string& type) noexcept = 0;
|
||||
virtual LayerFactory* getFactory(const style::LayerTypeInfo*) noexcept = 0;
|
||||
};
|
||||
|
||||
} // namespace mbgl
|
||||
@@ -1,17 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <mbgl/layermanager/layer_factory.hpp>
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
class LineLayerFactory : public LayerFactory {
|
||||
protected:
|
||||
const style::LayerTypeInfo* getTypeInfo() const noexcept final;
|
||||
std::unique_ptr<style::Layer> createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept final;
|
||||
std::unique_ptr<Layout> createLayout(const LayoutParameters& parameters,
|
||||
std::unique_ptr<GeometryTileLayer> tileLayer,
|
||||
const std::vector<Immutable<style::LayerProperties>>& group) noexcept final;
|
||||
std::unique_ptr<RenderLayer> createRenderLayer(Immutable<style::Layer::Impl>) noexcept final;
|
||||
};
|
||||
|
||||
} // namespace mbgl
|
||||
@@ -1,14 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <mbgl/layermanager/layer_factory.hpp>
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
class RasterLayerFactory : public LayerFactory {
|
||||
protected:
|
||||
const style::LayerTypeInfo* getTypeInfo() const noexcept final;
|
||||
std::unique_ptr<style::Layer> createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept final;
|
||||
std::unique_ptr<RenderLayer> createRenderLayer(Immutable<style::Layer::Impl>) noexcept final;
|
||||
};
|
||||
|
||||
} // namespace mbgl
|
||||
@@ -1,17 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <mbgl/layermanager/layer_factory.hpp>
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
class SymbolLayerFactory : public LayerFactory {
|
||||
protected:
|
||||
const style::LayerTypeInfo* getTypeInfo() const noexcept final;
|
||||
std::unique_ptr<style::Layer> createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept final;
|
||||
std::unique_ptr<Layout> createLayout(const LayoutParameters& parameters,
|
||||
std::unique_ptr<GeometryTileLayer> tileLayer,
|
||||
const std::vector<Immutable<style::LayerProperties>>& group) noexcept final;
|
||||
std::unique_ptr<RenderLayer> createRenderLayer(Immutable<style::Layer::Impl>) noexcept final;
|
||||
};
|
||||
|
||||
} // namespace mbgl
|
||||
@@ -1,30 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <mbgl/util/geo.hpp>
|
||||
#include <mbgl/util/optional.hpp>
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
/**
|
||||
* @brief Holds options to limit what parts of a map are visible. All fields are
|
||||
* optional.
|
||||
*/
|
||||
struct BoundOptions {
|
||||
/// Sets the latitude and longitude bounds to which the camera center are constrained
|
||||
BoundOptions& withLatLngBounds(LatLngBounds b) { bounds = b; return *this; }
|
||||
/// Sets the minimum zoom level
|
||||
BoundOptions& withMinZoom(double z) { minZoom = z; return *this; }
|
||||
/// Sets the maximum zoom level
|
||||
BoundOptions& withMaxZoom(double z) { maxZoom = z; return *this; }
|
||||
|
||||
/// Constrain the center of the camera to be within these bounds.
|
||||
optional<LatLngBounds> bounds;
|
||||
|
||||
/// Maximum zoom level allowed.
|
||||
optional<double> maxZoom;
|
||||
|
||||
/// Minimum zoom level allowed.
|
||||
optional<double> minZoom;
|
||||
};
|
||||
|
||||
} // namespace mbgl
|
||||
@@ -1,99 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <mbgl/util/geo.hpp>
|
||||
#include <mbgl/util/chrono.hpp>
|
||||
#include <mbgl/util/unitbezier.hpp>
|
||||
#include <mbgl/util/optional.hpp>
|
||||
|
||||
#include <functional>
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
/** Various options for describing the viewpoint of a map. All fields are
|
||||
optional.
|
||||
Anchor and center points are mutually exclusive, with preference for the
|
||||
center point when both are set.
|
||||
*/
|
||||
struct CameraOptions {
|
||||
CameraOptions& withCenter(const optional<LatLng>& o) { center = o; return *this; }
|
||||
CameraOptions& withPadding(const optional<EdgeInsets>& p) { padding = p; return *this; }
|
||||
CameraOptions& withAnchor(const optional<ScreenCoordinate>& o) { anchor = o; return *this; }
|
||||
CameraOptions& withZoom(const optional<double>& o) { zoom = o; return *this; }
|
||||
CameraOptions& withBearing(const optional<double>& o) { bearing = o; return *this; }
|
||||
CameraOptions& withPitch(const optional<double>& o) { pitch = o; return *this; }
|
||||
|
||||
/** Coordinate at the center of the map. */
|
||||
optional<LatLng> center;
|
||||
|
||||
/** Padding around the interior of the view that affects the frame of
|
||||
reference for `center`. */
|
||||
optional<EdgeInsets> padding;
|
||||
|
||||
/** Point of reference for `zoom` and `angle`, assuming an origin at the
|
||||
top-left corner of the view. */
|
||||
optional<ScreenCoordinate> anchor;
|
||||
|
||||
/** Zero-based zoom level. Constrained to the minimum and maximum zoom
|
||||
levels. */
|
||||
optional<double> zoom;
|
||||
|
||||
/** Bearing, measured in degrees from true north. Wrapped to [0, 360). */
|
||||
optional<double> bearing;
|
||||
|
||||
/** Pitch toward the horizon measured in degrees , with 0 deg resulting in a
|
||||
two-dimensional map. */
|
||||
optional<double> pitch;
|
||||
};
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
constexpr bool operator!=(const CameraOptions& a, const CameraOptions& b) {
|
||||
return !(a == b);
|
||||
}
|
||||
|
||||
/** Various options for describing a transition between viewpoints with
|
||||
animation. All fields are optional; the default values depend on how this
|
||||
struct is used. */
|
||||
struct AnimationOptions {
|
||||
/** Time to animate to the viewpoint defined herein. */
|
||||
optional<Duration> duration;
|
||||
|
||||
/** Average velocity of a flyTo() transition, measured in screenfuls per
|
||||
second, assuming a linear timing curve.
|
||||
|
||||
A <i>screenful</i> is the visible span in pixels. It does not correspond
|
||||
to a fixed physical distance but rather varies by zoom level. */
|
||||
optional<double> velocity;
|
||||
|
||||
/** Zero-based zoom level at the peak of the flyTo() transition’s flight
|
||||
path. */
|
||||
optional<double> minZoom;
|
||||
|
||||
/** The easing timing curve of the transition. */
|
||||
optional<mbgl::util::UnitBezier> easing;
|
||||
|
||||
/** A function that is called on each frame of the transition, just before a
|
||||
screen update, except on the last frame. The first parameter indicates
|
||||
the elapsed time as a percentage of the duration. */
|
||||
std::function<void(double)> transitionFrameFn;
|
||||
|
||||
/** A function that is called once on the last frame of the transition, just
|
||||
before the corresponding screen update. */
|
||||
std::function<void()> transitionFinishFn;
|
||||
|
||||
/** Creates an animation with no options specified. */
|
||||
AnimationOptions() {}
|
||||
|
||||
/** Creates an animation with the specified duration. */
|
||||
AnimationOptions(Duration d)
|
||||
: duration(d) {}
|
||||
};
|
||||
|
||||
} // namespace mbgl
|
||||
@@ -1,26 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
enum MapChange : uint8_t {
|
||||
MapChangeRegionWillChange = 0,
|
||||
MapChangeRegionWillChangeAnimated = 1,
|
||||
MapChangeRegionIsChanging = 2,
|
||||
MapChangeRegionDidChange = 3,
|
||||
MapChangeRegionDidChangeAnimated = 4,
|
||||
MapChangeWillStartLoadingMap = 5,
|
||||
MapChangeDidFinishLoadingMap = 6,
|
||||
MapChangeDidFailLoadingMap = 7,
|
||||
MapChangeWillStartRenderingFrame = 8,
|
||||
MapChangeDidFinishRenderingFrame = 9,
|
||||
MapChangeDidFinishRenderingFrameFullyRendered = 10,
|
||||
MapChangeWillStartRenderingMap = 11,
|
||||
MapChangeDidFinishRenderingMap = 12,
|
||||
MapChangeDidFinishRenderingMapFullyRendered = 13,
|
||||
MapChangeDidFinishLoadingStyle = 14,
|
||||
MapChangeSourceDidChange = 15
|
||||
};
|
||||
|
||||
} // namespace mbgl
|
||||
@@ -1,135 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <mbgl/util/optional.hpp>
|
||||
#include <mbgl/util/chrono.hpp>
|
||||
#include <mbgl/map/bound_options.hpp>
|
||||
#include <mbgl/map/map_observer.hpp>
|
||||
#include <mbgl/map/map_options.hpp>
|
||||
#include <mbgl/map/mode.hpp>
|
||||
#include <mbgl/util/noncopyable.hpp>
|
||||
#include <mbgl/util/size.hpp>
|
||||
#include <mbgl/annotation/annotation.hpp>
|
||||
#include <mbgl/map/camera.hpp>
|
||||
#include <mbgl/util/geometry.hpp>
|
||||
#include <mbgl/map/projection_mode.hpp>
|
||||
#include <mbgl/storage/resource_options.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <functional>
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
class RendererFrontend;
|
||||
|
||||
namespace style {
|
||||
class Image;
|
||||
class Style;
|
||||
} // namespace style
|
||||
|
||||
class Map : private util::noncopyable {
|
||||
public:
|
||||
explicit Map(RendererFrontend&,
|
||||
MapObserver&,
|
||||
const MapOptions&,
|
||||
const ResourceOptions&);
|
||||
~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<void (std::exception_ptr)>;
|
||||
void renderStill(StillImageCallback);
|
||||
void renderStill(const CameraOptions&, MapDebugOptions, StillImageCallback);
|
||||
|
||||
// Triggers a repaint.
|
||||
void triggerRepaint();
|
||||
|
||||
style::Style& getStyle();
|
||||
const style::Style& getStyle() const;
|
||||
|
||||
void setStyle(std::unique_ptr<style::Style>);
|
||||
|
||||
// Transition
|
||||
void cancelTransitions();
|
||||
void setGestureInProgress(bool);
|
||||
bool isGestureInProgress() const;
|
||||
bool isRotating() const;
|
||||
bool isScaling() const;
|
||||
bool isPanning() const;
|
||||
|
||||
// Camera
|
||||
CameraOptions getCameraOptions(optional<EdgeInsets> = {}) const;
|
||||
void jumpTo(const CameraOptions&);
|
||||
void easeTo(const CameraOptions&, const AnimationOptions&);
|
||||
void flyTo(const CameraOptions&, const AnimationOptions&);
|
||||
void moveBy(const ScreenCoordinate&, const AnimationOptions& = {});
|
||||
void scaleBy(double scale, optional<ScreenCoordinate> 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&, optional<double> bearing = {}, optional<double> pitch = {}) const;
|
||||
CameraOptions cameraForLatLngs(const std::vector<LatLng>&, const EdgeInsets&, optional<double> bearing = {}, optional<double> pitch = {}) const;
|
||||
CameraOptions cameraForGeometry(const Geometry<double>&, const EdgeInsets&, optional<double> bearing = {}, optional<double> pitch = {}) const;
|
||||
LatLngBounds latLngBoundsForCamera(const CameraOptions&) const;
|
||||
|
||||
/// @name Bounds
|
||||
/// @{
|
||||
|
||||
void setBounds(const BoundOptions& options);
|
||||
|
||||
/// Returns the current map bound options. All optional fields in BoundOptions are set.
|
||||
BoundOptions getBounds() const;
|
||||
|
||||
/// @}
|
||||
|
||||
// Map Options
|
||||
void setNorthOrientation(NorthOrientation);
|
||||
void setConstrainMode(ConstrainMode);
|
||||
void setViewportMode(ViewportMode);
|
||||
void setSize(Size);
|
||||
MapOptions getMapOptions() const;
|
||||
|
||||
//Projection Mode
|
||||
void setProjectionMode(const ProjectionMode&);
|
||||
ProjectionMode getProjectionMode() const;
|
||||
|
||||
// Projection
|
||||
ScreenCoordinate pixelForLatLng(const LatLng&) const;
|
||||
LatLng latLngForPixel(const ScreenCoordinate&) const;
|
||||
|
||||
// Annotations
|
||||
void addAnnotationImage(std::unique_ptr<style::Image>);
|
||||
void removeAnnotationImage(const std::string&);
|
||||
double getTopOffsetPixelsForAnnotationImage(const std::string&);
|
||||
|
||||
AnnotationID addAnnotation(const Annotation&);
|
||||
void updateAnnotation(AnnotationID, const Annotation&);
|
||||
void removeAnnotation(AnnotationID);
|
||||
|
||||
// Tile prefetching
|
||||
//
|
||||
// When loading a map, if `PrefetchZoomDelta` is set to any number greater than 0, the map will
|
||||
// first request a tile for `zoom - delta` in a attempt to display a full map at lower
|
||||
// resolution as quick as possible. It will get clamped at the tile source minimum zoom. The
|
||||
// default `delta` is 4.
|
||||
void setPrefetchZoomDelta(uint8_t delta);
|
||||
uint8_t getPrefetchZoomDelta() const;
|
||||
|
||||
// Debug
|
||||
void setDebug(MapDebugOptions);
|
||||
void cycleDebugOptions();
|
||||
MapDebugOptions getDebug() const;
|
||||
|
||||
bool isFullyLoaded() const;
|
||||
void dumpDebugLogs() const;
|
||||
|
||||
protected:
|
||||
class Impl;
|
||||
const std::unique_ptr<Impl> impl;
|
||||
|
||||
// For testing only.
|
||||
Map(std::unique_ptr<Impl>);
|
||||
};
|
||||
|
||||
} // namespace mbgl
|
||||
@@ -1,62 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <mbgl/style/source.hpp>
|
||||
#include <mbgl/style/image.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
enum class MapLoadError {
|
||||
StyleParseError,
|
||||
StyleLoadError,
|
||||
NotFoundError,
|
||||
UnknownError,
|
||||
};
|
||||
|
||||
class MapObserver {
|
||||
public:
|
||||
virtual ~MapObserver() = default;
|
||||
|
||||
static MapObserver& nullObserver() {
|
||||
static MapObserver mapObserver;
|
||||
return mapObserver;
|
||||
}
|
||||
|
||||
enum class CameraChangeMode : uint32_t {
|
||||
Immediate,
|
||||
Animated
|
||||
};
|
||||
|
||||
enum class RenderMode : uint32_t {
|
||||
Partial,
|
||||
Full
|
||||
};
|
||||
|
||||
struct RenderFrameStatus {
|
||||
RenderMode mode;
|
||||
bool needsRepaint; // In continous mode, shows that there are ongoig transitions.
|
||||
bool placementChanged;
|
||||
};
|
||||
|
||||
virtual void onCameraWillChange(CameraChangeMode) {}
|
||||
virtual void onCameraIsChanging() {}
|
||||
virtual void onCameraDidChange(CameraChangeMode) {}
|
||||
virtual void onWillStartLoadingMap() {}
|
||||
virtual void onDidFinishLoadingMap() {}
|
||||
virtual void onDidFailLoadingMap(MapLoadError, const std::string&) {}
|
||||
virtual void onWillStartRenderingFrame() {}
|
||||
virtual void onDidFinishRenderingFrame(RenderFrameStatus) {}
|
||||
virtual void onWillStartRenderingMap() {}
|
||||
virtual void onDidFinishRenderingMap(RenderMode) {}
|
||||
virtual void onDidFinishLoadingStyle() {}
|
||||
virtual void onSourceChanged(style::Source&) {}
|
||||
virtual void onDidBecomeIdle() {}
|
||||
virtual void onStyleImageMissing(const std::string&) {}
|
||||
// This method should return true if unused image can be removed,
|
||||
// false otherwise. By default, unused image will be removed.
|
||||
virtual bool onCanRemoveUnusedStyleImage(const std::string&) { return true; }
|
||||
};
|
||||
|
||||
} // namespace mbgl
|
||||
@@ -1,142 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <mbgl/map/mode.hpp>
|
||||
#include <mbgl/util/geo.hpp>
|
||||
#include <mbgl/util/size.hpp>
|
||||
|
||||
#include <memory>
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
/**
|
||||
* @brief Holds values for Map options.
|
||||
*/
|
||||
class MapOptions final {
|
||||
public:
|
||||
/**
|
||||
* @brief Constructs a MapOptions object with default values.
|
||||
*/
|
||||
MapOptions();
|
||||
~MapOptions();
|
||||
|
||||
MapOptions(MapOptions&&) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Sets the map rendering mode. By default, it is set to Continuous
|
||||
* so the map will render as data arrives from the network and react
|
||||
* immediately to state changes.
|
||||
*
|
||||
* @param mode Map rendering mode.
|
||||
* @return MapOptions for chaining options together.
|
||||
*/
|
||||
MapOptions& withMapMode(MapMode mode);
|
||||
|
||||
/**
|
||||
* @brief Gets the previously set (or default) map mode.
|
||||
*
|
||||
* @return map mode.
|
||||
*/
|
||||
MapMode mapMode() const;
|
||||
|
||||
/**
|
||||
* @brief Sets the map constrain mode. This can be used to limit the map
|
||||
* to wrap around the globe horizontally. By default, it is set to
|
||||
* HeightOnly.
|
||||
*
|
||||
* @param mode Map constrain mode.
|
||||
* @return MapOptions for chaining options together.
|
||||
*/
|
||||
MapOptions& withConstrainMode(ConstrainMode mode);
|
||||
|
||||
/**
|
||||
* @brief Gets the previously set (or default) constrain mode.
|
||||
*
|
||||
* @return constrain mode.
|
||||
*/
|
||||
ConstrainMode constrainMode() const;
|
||||
|
||||
/**
|
||||
* @brief Sets the viewport mode. This can be used to flip the vertical
|
||||
* orientation of the map as some devices may use inverted orientation.
|
||||
*
|
||||
* @param mode Viewport mode.
|
||||
* @return MapOptions for chaining options together.
|
||||
*/
|
||||
MapOptions& withViewportMode(ViewportMode mode);
|
||||
|
||||
/**
|
||||
* @brief Gets the previously set (or default) viewport mode.
|
||||
*
|
||||
* @return viewport mode.
|
||||
*/
|
||||
ViewportMode viewportMode() const;
|
||||
|
||||
/**
|
||||
* @brief Specify whether to enable cross-source symbol collision detection
|
||||
* or not. By default, it is set to true.
|
||||
*
|
||||
* @param enableCollisions true to enable, false to disable
|
||||
* @return MapOptions for chaining options together.
|
||||
*/
|
||||
MapOptions& withCrossSourceCollisions(bool enableCollisions);
|
||||
|
||||
/**
|
||||
* @brief Gets the previously set (or default) crossSourceCollisions value.
|
||||
*
|
||||
* @return true if ecross-source symbol collision detection enabled,
|
||||
* false otherwise.
|
||||
*/
|
||||
bool crossSourceCollisions() const;
|
||||
|
||||
/**
|
||||
* @brief Sets the orientation of the Map. By default, it is set to
|
||||
* Upwards.
|
||||
*
|
||||
* @param orientation Orientation of the Map.
|
||||
* @return reference to MapOptions for chaining options together.
|
||||
*/
|
||||
MapOptions& withNorthOrientation(NorthOrientation orientation);
|
||||
|
||||
/**
|
||||
* @brief Gets the previously set (or default) orientation.
|
||||
*
|
||||
* @return Map orientation.
|
||||
*/
|
||||
NorthOrientation northOrientation() const;
|
||||
|
||||
/**
|
||||
* @brief Sets the size to resize the map object and renderer backend.
|
||||
*
|
||||
* @param size_ A size given in logical pixels.
|
||||
* @return reference to MapOptions for chaining options together.
|
||||
*/
|
||||
MapOptions& withSize(Size size_);
|
||||
|
||||
/**
|
||||
* @brief Gets the previously set size.
|
||||
*
|
||||
* @return Size.
|
||||
*/
|
||||
Size size() const;
|
||||
|
||||
/**
|
||||
* @brief Sets the custom pixel ratio. By default, it is set to 1.
|
||||
*
|
||||
* @param ratio Pixel ratio value.
|
||||
* @return reference to MapOptions for chaining options together.
|
||||
*/
|
||||
MapOptions& withPixelRatio(float ratio);
|
||||
|
||||
/**
|
||||
* @brief Gets the previously set (or default) pixel ratio value.
|
||||
*
|
||||
* @return pixel ratio value.
|
||||
*/
|
||||
float pixelRatio() const;
|
||||
|
||||
private:
|
||||
class Impl;
|
||||
std::unique_ptr<Impl> impl_;
|
||||
};
|
||||
|
||||
} // namespace mbgl
|
||||
@@ -1,64 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <mbgl/util/util.hpp>
|
||||
#include <mbgl/util/traits.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
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
|
||||
};
|
||||
|
||||
// We can choose to constrain the map both horizontally or vertically, or only
|
||||
// vertically e.g. while panning.
|
||||
enum class ConstrainMode : EnumType {
|
||||
None,
|
||||
HeightOnly,
|
||||
WidthAndHeight,
|
||||
};
|
||||
|
||||
// Satisfies embedding platforms that requires the viewport coordinate systems
|
||||
// to be set according to its standards.
|
||||
enum class ViewportMode : EnumType {
|
||||
Default,
|
||||
FlippedY,
|
||||
};
|
||||
|
||||
enum class MapDebugOptions : EnumType {
|
||||
NoDebug = 0,
|
||||
TileBorders = 1 << 1,
|
||||
ParseStatus = 1 << 2,
|
||||
Timestamps = 1 << 3,
|
||||
Collision = 1 << 4,
|
||||
Overdraw = 1 << 5,
|
||||
StencilClip = 1 << 6,
|
||||
DepthBuffer = 1 << 7,
|
||||
};
|
||||
|
||||
MBGL_CONSTEXPR MapDebugOptions operator|(MapDebugOptions lhs, MapDebugOptions rhs) {
|
||||
return MapDebugOptions(mbgl::underlying_type(lhs) | mbgl::underlying_type(rhs));
|
||||
}
|
||||
|
||||
MBGL_CONSTEXPR MapDebugOptions& operator|=(MapDebugOptions& lhs, MapDebugOptions rhs) {
|
||||
return (lhs = MapDebugOptions(mbgl::underlying_type(lhs) | mbgl::underlying_type(rhs)));
|
||||
}
|
||||
|
||||
MBGL_CONSTEXPR bool operator&(MapDebugOptions lhs, MapDebugOptions rhs) {
|
||||
return mbgl::underlying_type(lhs) & mbgl::underlying_type(rhs);
|
||||
}
|
||||
|
||||
MBGL_CONSTEXPR MapDebugOptions& operator&=(MapDebugOptions& lhs, MapDebugOptions rhs) {
|
||||
return (lhs = MapDebugOptions(mbgl::underlying_type(lhs) & mbgl::underlying_type(rhs)));
|
||||
}
|
||||
|
||||
MBGL_CONSTEXPR MapDebugOptions operator~(MapDebugOptions value) {
|
||||
return MapDebugOptions(~mbgl::underlying_type(value));
|
||||
}
|
||||
|
||||
} // namespace mbgl
|
||||
@@ -1,34 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <mbgl/util/optional.hpp>
|
||||
|
||||
#include <functional>
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
/**
|
||||
* @brief Holds values for Axonometric rendering. All fields are
|
||||
* 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; }
|
||||
|
||||
/**
|
||||
* @brief Set to True to enable axonometric rendering, false otherwise.
|
||||
*/
|
||||
optional<bool> axonometric;
|
||||
|
||||
/**
|
||||
* @brief The X skew value represents how much to skew on the x-axis.
|
||||
*/
|
||||
optional<double> xSkew;
|
||||
|
||||
/**
|
||||
* @brief The Y skew value represents how much to skew on the y-axis.
|
||||
*/
|
||||
optional<double> ySkew;
|
||||
};
|
||||
|
||||
} // namespace mbgl
|
||||
@@ -1,14 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <mbgl/math/minmax.hpp>
|
||||
|
||||
namespace mbgl {
|
||||
namespace util {
|
||||
|
||||
template <typename T>
|
||||
T clamp(T value, T min_, T max_) {
|
||||
return max(min_, min(max_, value));
|
||||
}
|
||||
|
||||
} // namespace util
|
||||
} // namespace mbgl
|
||||
@@ -1,41 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <type_traits>
|
||||
|
||||
#if defined(__ANDROID__)
|
||||
#include <android/api-level.h>
|
||||
#endif
|
||||
|
||||
namespace mbgl {
|
||||
namespace util {
|
||||
|
||||
// Computes the log2(x) rounded up to the next integer.
|
||||
// (== number of bits required to store x)
|
||||
uint32_t ceil_log2(uint64_t x);
|
||||
|
||||
template <typename T>
|
||||
T log2(T x) {
|
||||
// log2() is producing wrong results on ARMv5 binaries
|
||||
// running on ARMv7+ CPUs.
|
||||
#if defined(__ANDROID__)
|
||||
return ::log(x) / M_LN2;
|
||||
#else
|
||||
return ::log2(x);
|
||||
#endif
|
||||
}
|
||||
|
||||
} // namespace util
|
||||
} // namespace mbgl
|
||||
|
||||
// log2 is not available on Android before API 18.
|
||||
#if defined(__ANDROID__) && defined(__GNUC__) && \
|
||||
defined(__ANDROID_API__) && __ANDROID_API__ < 18
|
||||
|
||||
template <typename T>
|
||||
typename std::enable_if_t<std::is_floating_point<T>::value, T> log2(T x) {
|
||||
return ::log(x) / M_LN2;
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,41 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <type_traits>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
namespace mbgl {
|
||||
namespace util {
|
||||
|
||||
template <typename T>
|
||||
typename std::enable_if_t<std::is_integral<T>::value, T> max(T a, T b) {
|
||||
return std::max(a, b);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
typename std::enable_if_t<std::is_floating_point<T>::value, T> max(T a, T b) {
|
||||
return ::fmax(a, b);
|
||||
}
|
||||
|
||||
template <typename T, typename... Ts>
|
||||
typename std::enable_if_t<std::is_arithmetic<T>::value, T> max(T a, T b, Ts... args) {
|
||||
return max(a, max(b, args...));
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
typename std::enable_if_t<std::is_integral<T>::value, T> min(T a, T b) {
|
||||
return std::min(a, b);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
typename std::enable_if_t<std::is_floating_point<T>::value, T> min(T a, T b) {
|
||||
return ::fmin(a, b);
|
||||
}
|
||||
|
||||
template <typename T, typename... Ts>
|
||||
typename std::enable_if_t<std::is_arithmetic<T>::value, T> min(T a, T b, Ts... args) {
|
||||
return min(a, min(b, args...));
|
||||
}
|
||||
|
||||
} // namespace util
|
||||
} // namespace mbgl
|
||||
@@ -1,24 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <cmath>
|
||||
|
||||
namespace mbgl {
|
||||
namespace util {
|
||||
|
||||
// Constrains n to the given range (including min, excluding max) via modular
|
||||
// arithmetic.
|
||||
template <typename T>
|
||||
T wrap(T value, T min, T max) {
|
||||
if (value >= min && value < max) {
|
||||
return value;
|
||||
} else if (value == max) {
|
||||
return min;
|
||||
}
|
||||
|
||||
const T delta = max - min;
|
||||
const T wrapped = min + std::fmod(value - min, delta);
|
||||
return value < min ? wrapped + delta : wrapped;
|
||||
}
|
||||
|
||||
} // namespace util
|
||||
} // namespace mbgl
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user