diff --git a/.clang-format b/.clang-format new file mode 100644 index 000000000..ad4509ef2 --- /dev/null +++ b/.clang-format @@ -0,0 +1,94 @@ +Language: Cpp +AccessModifierOffset: -2 +AlignAfterOpenBracket: Align +AlignArrayOfStructures: None +AlignConsecutiveAssignments: None +AlignConsecutiveDeclarations: None +AlignConsecutiveMacros: Consecutive +AlignEscapedNewlines: Right +AlignOperands: Align +AlignTrailingComments: true +AllowAllArgumentsOnNextLine: false +AllowAllParametersOfDeclarationOnNextLine: false +AllowShortBlocksOnASingleLine: Empty +AllowShortCaseLabelsOnASingleLine: false +AllowShortEnumsOnASingleLine: true +AllowShortFunctionsOnASingleLine: Inline +AllowShortIfStatementsOnASingleLine: Never +AllowShortLambdasOnASingleLine: Inline +# AlwaysBreakAfterReturnType: +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: Yes +BinPackArguments: false +BitFieldColonSpacing: After +BreakBeforeBraces: Custom +BraceWrapping: + AfterCaseLabel: false + AfterClass: true + AfterControlStatement: Always + AfterEnum: false # see AllowShortEnumsOnASingleLine + AfterFunction: true # see AllowShortFunctionsOnASingleLine + AfterNamespace: false + AfterStruct: true + AfterExternBlock: true + BeforeCatch: false + BeforeElse: true + BeforeLambdaBody: false + BeforeWhile: false + SplitEmptyFunction: false + SplitEmptyRecord: false + SplitEmptyNamespace: false +BreakBeforeBinaryOperators: None +BreakBeforeConceptDeclarations: false +BreakBeforeTernaryOperators: true +BreakConstructorInitializers: BeforeComma +BreakInheritanceList: AfterComma +BreakStringLiterals: true +ColumnLimit: 120 +CompactNamespaces: false +ContinuationIndentWidth: 2 +Cpp11BracedListStyle: true +DeriveLineEnding: true +EmptyLineAfterAccessModifier: Leave +EmptyLineBeforeAccessModifier: LogicalBlock +FixNamespaceComments: true +IncludeBlocks: Preserve +IndentCaseBlocks: false +IndentCaseLabels: true +IndentExternBlock: NoIndent +IndentPPDirectives: None +IndentRequires: true +IndentWidth: 4 +IndentWrappedFunctionNames: true +KeepEmptyLinesAtTheStartOfBlocks: false +LambdaBodyIndentation: Signature +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +# PackConstructorInitializers: CurrentLine # only clang-format > 14 +PointerAlignment: Left +#QualifierAlignment: Left # only clang-format > 14 +ReferenceAlignment: Left +ReflowComments: true +SortIncludes: Never +SpaceAfterLogicalNot: false +SpaceAfterTemplateKeyword: false +SpaceBeforeInheritanceColon: true +Standard: c++14 +BinPackParameters: false +BreakBeforeInheritanceComma: false +IncludeCategories: + # Headers in <> without extension. + - Regex: '<([A-Za-z0-9\Q/-_\E])+>' + Priority: 1 + # Headers in <> from specific external libraries. + - Regex: '<(boost)\/' + Priority: 2 + # Headers in <> from specific external libraries. + - Regex: '<(mapnik)\/' + Priority: 3 + # Headers in <> with extension. + - Regex: '<([A-Za-z0-9.\Q/-_\E])+>' + Priority: 4 + # Headers in "" with extension. + - Regex: '"([A-Za-z0-9.\Q/-_\E])+"' + Priority: 5 diff --git a/.github/workflows/build_test.yml b/.github/workflows/build_test.yml new file mode 100644 index 000000000..f4e5685a4 --- /dev/null +++ b/.github/workflows/build_test.yml @@ -0,0 +1,76 @@ +name: Build and Test + +on: + push: + branches-ignore: + - "no-ci-*" + pull_request: + branches: + - "**" + +jobs: + windows: + name: Windows memory mapped + uses: mapnik/mapnik/.github/workflows/windows.yml@master + with: + VCPKG_SHA: 2e34a79a814551424d9b1a981b3b110e0a8fbdfd + NUGET_REGISTRY: https://nuget.pkg.github.com/mapnik/index.json + NUGET_USERNAME: mapnik + USE_MEMORY_MAPPED_FILE: 'ON' + secrets: + NUGET_REGISTRY_PAT: ${{ secrets.VCPKG_CACHE_PAT }} + + windows-mmf-off: + name: Windows file based + uses: mapnik/mapnik/.github/workflows/windows.yml@master + with: + VCPKG_SHA: 2e34a79a814551424d9b1a981b3b110e0a8fbdfd + NUGET_REGISTRY: https://nuget.pkg.github.com/mapnik/index.json + NUGET_USERNAME: mapnik + USE_MEMORY_MAPPED_FILE: 'OFF' + secrets: + NUGET_REGISTRY_PAT: ${{ secrets.VCPKG_CACHE_PAT }} + + ubuntu: + name: Linux memory mapped + uses: mapnik/mapnik/.github/workflows/ubuntu.yml@master + with: + VCPKG_SHA: 2e34a79a814551424d9b1a981b3b110e0a8fbdfd + NUGET_REGISTRY: https://nuget.pkg.github.com/mapnik/index.json + NUGET_USERNAME: mapnik + USE_MEMORY_MAPPED_FILE: 'ON' + secrets: + NUGET_REGISTRY_PAT: ${{ secrets.VCPKG_CACHE_PAT }} + + ubuntu-mmf-off: + name: Linux file based + uses: mapnik/mapnik/.github/workflows/ubuntu.yml@master + with: + VCPKG_SHA: 2e34a79a814551424d9b1a981b3b110e0a8fbdfd + NUGET_REGISTRY: https://nuget.pkg.github.com/mapnik/index.json + NUGET_USERNAME: mapnik + USE_MEMORY_MAPPED_FILE: 'OFF' + secrets: + NUGET_REGISTRY_PAT: ${{ secrets.VCPKG_CACHE_PAT }} + + macos: + name: MacOS memory mapped + uses: mapnik/mapnik/.github/workflows/macos.yml@master + with: + VCPKG_SHA: 2e34a79a814551424d9b1a981b3b110e0a8fbdfd + NUGET_REGISTRY: https://nuget.pkg.github.com/mapnik/index.json + NUGET_USERNAME: mapnik + USE_MEMORY_MAPPED_FILE: 'ON' + secrets: + NUGET_REGISTRY_PAT: ${{ secrets.VCPKG_CACHE_PAT }} + + macos-mmf-off: + name: MacOS file based + uses: mapnik/mapnik/.github/workflows/macos.yml@master + with: + VCPKG_SHA: 2e34a79a814551424d9b1a981b3b110e0a8fbdfd + NUGET_REGISTRY: https://nuget.pkg.github.com/mapnik/index.json + NUGET_USERNAME: mapnik + USE_MEMORY_MAPPED_FILE: 'OFF' + secrets: + NUGET_REGISTRY_PAT: ${{ secrets.VCPKG_CACHE_PAT }} diff --git a/.github/workflows/macos.yml b/.github/workflows/macos.yml new file mode 100644 index 000000000..1f195c3fd --- /dev/null +++ b/.github/workflows/macos.yml @@ -0,0 +1,125 @@ +name: MacOS + +on: + workflow_call: + inputs: + VCPKG_SHA: + required: true + type: string + NUGET_REGISTRY: + required: true + type: string + NUGET_USERNAME: + required: true + type: string + USE_MEMORY_MAPPED_FILE: + required: true + type: string + secrets: + NUGET_REGISTRY_PAT: + required: true + +env: + VCPKG_BINARY_SOURCES: "clear;nuget,GitHub,readwrite" + VCPKG_NUGET_REPOSITORY: https://github.com/mapnik/mapnik/vcpkg-cache.git + UPDATE: 1 + preset: macos-ci + mono: mono + +jobs: + build: + runs-on: macos-latest + steps: + - name: Install required system packages + run: | + brew install automake ninja lcov + + - name: checkout mapnik + uses: actions/checkout@v2 + with: + submodules: "recursive" + + - name: checkout vcpkg + uses: actions/checkout@v2 + with: + repository: "microsoft/vcpkg" + ref: ${{ inputs.VCPKG_SHA }} + path: vcpkg + + - name: "Setup vcpkg" + shell: bash + run: ./vcpkg/bootstrap-vcpkg.sh + + - name: "Setup NuGet Credentials" + shell: "bash" + run: > + ${{ env.mono }} `./vcpkg/vcpkg fetch nuget | tail -n 1` + sources add + -source "${{ inputs.NUGET_REGISTRY }}" + -storepasswordincleartext + -name "GitHub" + -username "${{ inputs.NUGET_USERNAME }}" + -password "${{ secrets.NUGET_REGISTRY_PAT }}" + + - name: "Setup NuGet apikey" + shell: "bash" + run: > + ${{ env.mono }} `./vcpkg/vcpkg fetch nuget | tail -n 1` + setapikey "${{ secrets.NUGET_REGISTRY_PAT }}" -Source "${{ inputs.NUGET_REGISTRY }}" + + - name: Configure CMake + run: cmake -DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake -DUSE_MEMORY_MAPPED_FILE=${{ inputs.USE_MEMORY_MAPPED_FILE }} --preset=${{ env.preset }} + + - name: Build + run: cmake --build --preset ${{ env.preset }} + + - name: Test + run: ctest --preset ${{ env.preset }} + + - name: Test visuals + continue-on-error: true + working-directory: build/${{ env.preset }}/out + env: + PROJ_LIB: ${{ github.workspace }}/build/${{ env.preset }}/vcpkg_installed/x64-osx/share/proj4 + run: ./mapnik-test-visual -j $(sysctl -n hw.logicalcpu) --output-dir ./visual-test-result + + - name: Pack visual test results + working-directory: build/${{ env.preset }}/out + run: tar cfvz visual-test-results.tar.gz ./visual-test-result + + - name: Run Benchmark + working-directory: build/${{ env.preset }}/out + env: + PROJ_LIB: ${{ github.workspace }}/build/${{ env.preset }}/vcpkg_installed/x64-osx/share/proj4 + run: ./run_benchmarks + + - name: Coverage + working-directory: build/${{ env.preset }} + run: | + lcov --directory . --capture --output-file coverage.info + lcov --remove coverage.info '/usr/*' '*/vcpkg_installed/*' '/.cache/*' '*/test/*' --output-file coverage.info + lcov --list coverage.info + + - name: Upload coverage to Codecov + uses: codecov/codecov-action@v2 + with: + files: build/${{ env.preset }}/coverage.info + + - name: Package + if: failure() + run: cmake --build --preset ${{ env.preset }} --target package + + - name: Upload mapnik build artifact + uses: actions/upload-artifact@v2 + if: failure() + with: + name: ${{ env.preset }}-mmio-${{ inputs.USE_MEMORY_MAPPED_FILE }} + path: build/${{ env.preset }}/mapnik-*.tar.gz + retention-days: 2 + + - name: Upload visual test results + uses: actions/upload-artifact@v2 + with: + name: ${{ env.preset }}-visual-tests-mmio-${{ inputs.USE_MEMORY_MAPPED_FILE }} + path: build/${{ env.preset }}/out/visual-test-results.tar.gz + retention-days: 2 diff --git a/.github/workflows/ubuntu.yml b/.github/workflows/ubuntu.yml new file mode 100644 index 000000000..18646915d --- /dev/null +++ b/.github/workflows/ubuntu.yml @@ -0,0 +1,141 @@ +name: Ubuntu + +on: + workflow_call: + inputs: + VCPKG_SHA: + required: true + type: string + NUGET_REGISTRY: + required: true + type: string + NUGET_USERNAME: + required: true + type: string + USE_MEMORY_MAPPED_FILE: + required: true + type: string + secrets: + NUGET_REGISTRY_PAT: + required: true + +env: + VCPKG_BINARY_SOURCES: "clear;nuget,GitHub,readwrite" + VCPKG_NUGET_REPOSITORY: https://github.com/mapnik/mapnik/vcpkg-cache.git + UPDATE: 1 + preset: linux-ci + mono: mono + +jobs: + build: + runs-on: ubuntu-latest + + services: + postgres: + image: postgis/postgis + env: + POSTGRES_PASSWORD: password + POSTGRES_DB: mapnik-tmp-postgis-test-db + ports: + - 5432:5432 + options: >- + --health-cmd pg_isready + --health-interval 10s + --health-timeout 5s + --health-retries 5 + + steps: + - name: Install required system packages + shell: "bash" + run: | + sudo apt-get install -y gperf libxxf86vm-dev ninja-build postgresql-client lcov + + - name: checkout mapnik + uses: actions/checkout@v2 + with: + submodules: "recursive" + + - name: checkout vcpkg + uses: actions/checkout@v2 + with: + repository: "microsoft/vcpkg" + ref: ${{ inputs.VCPKG_SHA }} + path: vcpkg + + - name: "Setup vcpkg" + shell: bash + run: ./vcpkg/bootstrap-vcpkg.sh + + - name: "Setup NuGet Credentials" + shell: "bash" + run: > + ${{ env.mono }} `./vcpkg/vcpkg fetch nuget | tail -n 1` + sources add + -source "${{ inputs.NUGET_REGISTRY }}" + -storepasswordincleartext + -name "GitHub" + -username "${{ inputs.NUGET_USERNAME }}" + -password "${{ secrets.NUGET_REGISTRY_PAT }}" + + - name: "Setup NuGet apikey" + shell: "bash" + run: > + ${{ env.mono }} `./vcpkg/vcpkg fetch nuget | tail -n 1` + setapikey "${{ secrets.NUGET_REGISTRY_PAT }}" -Source "${{ inputs.NUGET_REGISTRY }}" + + - name: Configure CMake + run: cmake -DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake -DUSE_MEMORY_MAPPED_FILE=${{ inputs.USE_MEMORY_MAPPED_FILE }} --preset=${{ env.preset }} + + - name: Build + run: cmake --build --preset ${{ env.preset }} + + - name: Test + run: ctest --preset ${{ env.preset }} + + - name: Test visuals + continue-on-error: true + working-directory: build/${{ env.preset }}/out + env: + PROJ_LIB: ${{ github.workspace }}/build/${{ env.preset }}/vcpkg_installed/x64-linux/share/proj4 + run: ./mapnik-test-visual -j $(nproc) --output-dir ./visual-test-result + + - name: Pack visual test results + working-directory: build/${{ env.preset }}/out + run: tar cfvz visual-test-results.tar.gz ./visual-test-result + + - name: Run Benchmarks + working-directory: build/${{ env.preset }}/out + env: + PROJ_LIB: ${{ github.workspace }}/build/${{ env.preset }}/vcpkg_installed/x64-linux/share/proj4 + run: ./run_benchmarks + + - name: Coverage + working-directory: build/${{ env.preset }} + run: | + lcov --directory . --capture --output-file coverage.info + lcov --remove coverage.info '/usr/*' '*/vcpkg_installed/*' '/.cache/*' '*/test/*' --output-file coverage.info + lcov --list coverage.info + + - name: Upload coverage to Codecov + uses: codecov/codecov-action@v2 + with: + files: build/${{ env.preset }}/coverage.info + + - name: Package + if: failure() + run: cmake --build --preset ${{ env.preset }} --target package + + - name: Upload mapnik build artifact + uses: actions/upload-artifact@v2 + if: failure() + with: + name: ${{ env.preset }}-artifact-mmio-${{ inputs.USE_MEMORY_MAPPED_FILE }} + path: build/${{ env.preset }}/mapnik-*.tar.gz + retention-days: 2 + + - name: Upload visual test results + uses: actions/upload-artifact@v2 + with: + name: ${{ env.preset }}-visual-tests-mmio-${{ inputs.USE_MEMORY_MAPPED_FILE }} + path: build/${{ env.preset }}/out/visual-test-results.tar.gz + retention-days: 2 diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml new file mode 100644 index 000000000..14b43f96b --- /dev/null +++ b/.github/workflows/windows.yml @@ -0,0 +1,114 @@ +name: Windows + +on: + workflow_call: + inputs: + VCPKG_SHA: + required: true + type: string + NUGET_REGISTRY: + required: true + type: string + NUGET_USERNAME: + required: true + type: string + USE_MEMORY_MAPPED_FILE: + required: true + type: string + secrets: + NUGET_REGISTRY_PAT: + required: true + +env: + VCPKG_BINARY_SOURCES: "clear;nuget,GitHub,readwrite" + VCPKG_NUGET_REPOSITORY: https://github.com/mapnik/vcpkg-cache.git + UPDATE: 1 + preset: windows-ci + +jobs: + build: + runs-on: windows-latest + + steps: + - name: Install required system packages + run: | + choco install ninja OpenCppCoverage + echo "C:\Program Files\OpenCppCoverage" >> $env:GITHUB_PATH + + - uses: ilammy/msvc-dev-cmd@v1 + + - name: checkout mapnik + uses: actions/checkout@v2 + with: + submodules: "recursive" + + - name: checkout vcpkg + uses: actions/checkout@v2 + with: + repository: "microsoft/vcpkg" + ref: ${{ inputs.VCPKG_SHA }} + path: vcpkg + + - name: "Setup vcpkg" + run: ./vcpkg/bootstrap-vcpkg.bat + + - name: "Setup NuGet Credentials" + shell: "bash" + run: > + `./vcpkg/vcpkg fetch nuget | tail -n 1` + sources add + -source "${{ inputs.NUGET_REGISTRY }}" + -storepasswordincleartext + -name "GitHub" + -username "${{ inputs.NUGET_USERNAME }}" + -password "${{ secrets.NUGET_REGISTRY_PAT }}" + + - name: "Setup NuGet apikey" + shell: "bash" + run: > + `./vcpkg/vcpkg fetch nuget | tail -n 1` + setapikey "${{ secrets.NUGET_REGISTRY_PAT }}" -Source "${{ inputs.NUGET_REGISTRY }}" + + - name: Configure CMake + run: cmake -DCMAKE_TOOLCHAIN_FILE=${{ github.workspace }}/vcpkg/scripts/buildsystems/vcpkg.cmake -DUSE_MEMORY_MAPPED_FILE=${{ inputs.USE_MEMORY_MAPPED_FILE }} --preset ${{env.preset}} + + - name: Build + run: cmake --build --preset ${{env.preset}} + + - name: Test + run: OpenCppCoverage --modules *libmapnik* --modules mapnik*.exe --modules *.input --sources ${{ github.workspace }} --export_type binary --cover_children -- ctest --preset ${{env.preset}} + + - name: Test visuals + shell: pwsh + continue-on-error: true + working-directory: build/${{ env.preset }}/out + env: + PROJ_LIB: ${{ github.workspace }}/build/${{ env.preset }}/vcpkg_installed/x64-windows/share/proj4 + run: OpenCppCoverage --modules *libmapnik* --modules mapnik*.exe --modules *.input --sources ${{ github.workspace }} --export_type binary --input_coverage=${{ github.workspace }}/ctest.cov --cover_children -- .\mapnik-test-visual.exe -j (Get-CimInstance -ClassName Win32_ComputerSystem).NumberOfLogicalProcessors --output-dir ./visual-test-result + + - name: Pack visual test results + working-directory: build/${{ env.preset }}/out + run: tar cfvz visual-test-results.tar.gz ./visual-test-result + + - name: Upload coverage to Codecov + uses: codecov/codecov-action@v2 + with: + files: build/${{ env.preset }}/out/mapnik-test-visual.cov + + - name: Package + if: failure() + run: cmake --build --preset ${{env.preset}} --target package + + - uses: actions/upload-artifact@v2 + if: failure() + with: + name: ${{ env.preset }}-artifact-mmio-${{ inputs.USE_MEMORY_MAPPED_FILE }} + path: build/*-ci/mapnik-*.tar.gz + retention-days: 2 + + - name: Upload visual test results + uses: actions/upload-artifact@v2 + with: + name: ${{ env.preset }}-visual-tests-mmio-${{ inputs.USE_MEMORY_MAPPED_FILE }} + path: build/${{ env.preset }}/out/visual-test-results.tar.gz + retention-days: 2 diff --git a/CMakePresets.json b/CMakePresets.json index cb8f774de..46720854c 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -173,6 +173,60 @@ "windows-default", "release-build" ] + }, + { + "name": "ci-options", + "hidden": true, + "cacheVariables": { + "BUILD_TESTING": "ON", + "BUILD_DEMO_VIEWER": "OFF" + } + }, + { + "name": "windows-ci", + "description": "used by the ci pipeline", + "inherits": [ + "windows-release", + "ci-options" + ], + "cacheVariables": { + "INSTALL_DEPENDENCIES": "ON", + "ADDITIONAL_LIBARIES_PATHS": "${sourceDir}/build/${presetName}/vcpkg_installed/x64-windows/bin" + }, + "environment": { + "PROJ_LIB": "${sourceDir}/build/${presetName}/vcpkg_installed/x64-windows/share/proj4" + } + }, + { + "name": "linux-ci", + "description": "used by the ci pipeline", + "inherits": [ + "release-with-debug-build", + "use-gcc", + "ci-options" + ], + "cacheVariables": { + "CMAKE_CXX_FLAGS": "--coverage" + }, + "environment": { + "PROJ_LIB": "${sourceDir}/build/${presetName}/vcpkg_installed/x64-linux/share/proj4" + } + }, + { + "name": "macos-ci", + "description": "used by the ci pipeline", + "inherits": [ + "use-ninja", + "release-with-debug-build", + "default-build-dir", + "ci-options" + ], + "cacheVariables": { + "CMAKE_CXX_FLAGS": "-fprofile-arcs -ftest-coverage" + }, + "environment": { + "PROJ_LIB": "${sourceDir}/build/${presetName}/vcpkg_installed/x64-osx/share/proj4" + } } ], "buildPresets": [ @@ -199,6 +253,18 @@ { "name": "linux-gcc-release", "configurePreset": "linux-gcc-release" + }, + { + "name": "windows-ci", + "configurePreset": "windows-ci" + }, + { + "name": "linux-ci", + "configurePreset": "linux-ci" + }, + { + "name": "macos-ci", + "configurePreset": "macos-ci" } ], "testPresets": [ @@ -212,6 +278,27 @@ "noTestsAction": "error", "stopOnFailure": false } + }, + { + "name": "windows-ci", + "configurePreset": "windows-ci", + "inherits": [ + "test-default" + ] + }, + { + "name": "linux-ci", + "configurePreset": "linux-ci", + "inherits": [ + "test-default" + ] + }, + { + "name": "macos-ci", + "configurePreset": "macos-ci", + "inherits": [ + "test-default" + ] } ] } diff --git a/benchmark/include/bench_framework.hpp b/benchmark/include/bench_framework.hpp index c7729dd16..593931103 100644 --- a/benchmark/include/bench_framework.hpp +++ b/benchmark/include/bench_framework.hpp @@ -10,7 +10,7 @@ // stl #include -#include // log10, round +#include // log10, round #include // snprintf #include #include @@ -22,36 +22,28 @@ namespace benchmark { -template +template using milliseconds = std::chrono::duration; -template +template using seconds = std::chrono::duration; class test_case { -protected: + protected: mapnik::parameters params_; std::size_t threads_; std::size_t iterations_; -public: + + public: test_case(mapnik::parameters const& params) - : params_(params), - threads_(mapnik::safe_cast(*params.get("threads", 0))), - iterations_(mapnik::safe_cast(*params.get("iterations", 0))) - {} - std::size_t threads() const - { - return threads_; - } - std::size_t iterations() const - { - return iterations_; - } - mapnik::parameters const& params() const - { - return params_; - } + : params_(params) + , threads_(mapnik::safe_cast(*params.get("threads", 0))) + , iterations_(mapnik::safe_cast(*params.get("iterations", 0))) + {} + std::size_t threads() const { return threads_; } + std::size_t iterations() const { return iterations_; } + mapnik::parameters const& params() const { return params_; } virtual bool validate() const = 0; virtual bool operator()() const = 0; }; @@ -59,21 +51,25 @@ public: // gathers --long-option values in 'params'; // returns the index of the first non-option argument, // or negated index of an ill-formed option argument -inline int parse_args(int argc, char** argv, mapnik::parameters & params) +inline int parse_args(int argc, char** argv, mapnik::parameters& params) { - for (int i = 1; i < argc; ++i) { + for (int i = 1; i < argc; ++i) + { const char* opt = argv[i]; - if (opt[0] != '-') { + if (opt[0] != '-') + { // non-option argument, return its index return i; } - if (opt[1] != '-') { + if (opt[1] != '-') + { // we only accept --long-options, but instead of throwing, // just issue a warning and let the caller decide what to do std::clog << argv[0] << ": invalid option '" << opt << "'\n"; return -i; // negative means ill-formed option #i } - if (opt[2] == '\0') { + if (opt[2] == '\0') + { // option-list terminator '--' return i + 1; } @@ -81,15 +77,18 @@ inline int parse_args(int argc, char** argv, mapnik::parameters & params) // take option name without the leading '--' std::string key(opt + 2); size_t eq = key.find('='); - if (eq != std::string::npos) { + if (eq != std::string::npos) + { // one-argument form '--foo=bar' params[key.substr(0, eq)] = key.substr(eq + 1); } - else if (i + 1 < argc) { + else if (i + 1 < argc) + { // two-argument form '--foo' 'bar' params[key] = std::string(argv[++i]); } - else { + else + { // missing second argument std::clog << argv[0] << ": missing option '" << opt << "' value\n"; return -i; // negative means ill-formed option #i @@ -100,7 +99,8 @@ inline int parse_args(int argc, char** argv, mapnik::parameters & params) inline void handle_common_args(mapnik::parameters const& params) { - if (auto severity = params.get("log")) { + if (auto severity = params.get("log")) + { if (*severity == "debug") mapnik::logger::set_severity(mapnik::logger::debug); else if (*severity == "warn") @@ -110,37 +110,35 @@ inline void handle_common_args(mapnik::parameters const& params) else if (*severity == "none") mapnik::logger::set_severity(mapnik::logger::none); else - std::clog << "ignoring option --log='" << *severity - << "' (allowed values are: debug, warn, error, none)\n"; + std::clog << "ignoring option --log='" << *severity << "' (allowed values are: debug, warn, error, none)\n"; } } -inline int handle_args(int argc, char** argv, mapnik::parameters & params) +inline int handle_args(int argc, char** argv, mapnik::parameters& params) { int res = parse_args(argc, argv, params); handle_common_args(params); return res; } -#define BENCHMARK(test_class,name) \ - int main(int argc, char** argv) \ - { \ - try \ - { \ - mapnik::parameters params; \ - benchmark::handle_args(argc,argv,params); \ - test_class test_runner(params); \ - auto result = run(test_runner,name); \ - testing::run_cleanup(); \ - return result; \ - } \ - catch (std::exception const& ex) \ - { \ - std::clog << ex.what() << "\n"; \ - testing::run_cleanup(); \ - return -1; \ - } \ - } \ +#define BENCHMARK(test_class, name) \ + int main(int argc, char** argv) \ + { \ + try \ + { \ + mapnik::parameters params; \ + benchmark::handle_args(argc, argv, params); \ + test_class test_runner(params); \ + auto result = run(test_runner, name); \ + testing::run_cleanup(); \ + return result; \ + } catch (std::exception const& ex) \ + { \ + std::clog << ex.what() << "\n"; \ + testing::run_cleanup(); \ + return -1; \ + } \ + } struct big_number_fmt { @@ -149,7 +147,9 @@ struct big_number_fmt const char* u; big_number_fmt(int width, double value, int base = 1000) - : w(width), v(value), u("") + : w(width) + , v(value) + , u("") { static const char* suffixes = "\0\0k\0M\0G\0T\0P\0E\0Z\0Y\0\0"; u = suffixes; @@ -165,7 +165,7 @@ struct big_number_fmt } }; -template +template int run(T const& test_runner, std::string const& name) { try @@ -196,8 +196,7 @@ int run(T const& test_runner, std::string const& name) std::mutex mtx_ready; std::unique_lock lock_ready(mtx_ready); - auto stub = [&](T const& test_copy) - { + auto stub = [&](T const& test_copy) { // workers will wait on this mutex until the main thread // constructs all of them and starts measuring time std::unique_lock my_lock(mtx_ready); @@ -207,14 +206,14 @@ int run(T const& test_runner, std::string const& name) std::vector tg; tg.reserve(num_threads); - for (auto i = num_threads; i-- > 0; ) + for (auto i = num_threads; i-- > 0;) { tg.emplace_back(stub, test_runner); } start = std::chrono::high_resolution_clock::now(); lock_ready.unlock(); // wait for all workers to finish - for (auto & t : tg) + for (auto& t : tg) { if (t.joinable()) t.join(); @@ -228,7 +227,8 @@ int run(T const& test_runner, std::string const& name) else { start = std::chrono::high_resolution_clock::now(); - do { + do + { test_runner(); elapsed = std::chrono::high_resolution_clock::now() - start; total_iters += num_iters; @@ -243,21 +243,27 @@ int run(T const& test_runner, std::string const& name) std::clog << std::left << std::setw(43) << name; std::clog << std::resetiosflags(std::ios::adjustfield); - if (num_threads > 0) { - std::clog << ' ' << std::setw(3) << num_threads - << " worker" << (num_threads > 1 ? "s" : " "); + if (num_threads > 0) + { + std::clog << ' ' << std::setw(3) << num_threads << " worker" << (num_threads > 1 ? "s" : " "); } - else { + else + { std::clog << " main thread"; } - std::snprintf(msg, sizeof(msg), - " %*.0f%s iters %6.0f milliseconds %*.0f%s i/t/s\n", - itersf.w, itersf.v, itersf.u, dur_total, - ips.w, ips.v, ips.u); + std::snprintf(msg, + sizeof(msg), + " %*.0f%s iters %6.0f milliseconds %*.0f%s i/t/s\n", + itersf.w, + itersf.v, + itersf.u, + dur_total, + ips.w, + ips.v, + ips.u); std::clog << msg; return 0; - } - catch (std::exception const& ex) + } catch (std::exception const& ex) { std::clog << "test runner did not complete: " << ex.what() << "\n"; return 4; @@ -267,18 +273,15 @@ int run(T const& test_runner, std::string const& name) struct sequencer { sequencer(int argc, char** argv) - : exit_code_(0) + : exit_code_(0) { benchmark::handle_args(argc, argv, params_); } - int done() const - { - return exit_code_; - } + int done() const { return exit_code_; } - template - sequencer & run(std::string const& name, Args && ...args) + template + sequencer& run(std::string const& name, Args&&... args) { // Test instance lifetime is confined to this function Test test_runner(params_, std::forward(args)...); @@ -287,11 +290,11 @@ struct sequencer return *this; // allow chaining calls } -protected: + protected: mapnik::parameters params_; int exit_code_; }; -} +} // namespace benchmark #endif // MAPNIK_BENCH_FRAMEWORK_HPP diff --git a/benchmark/include/compare_images.hpp b/benchmark/include/compare_images.hpp index ff90e01a0..21f34732a 100644 --- a/benchmark/include/compare_images.hpp +++ b/benchmark/include/compare_images.hpp @@ -5,32 +5,31 @@ #include #include - namespace benchmark { - bool compare_images(std::string const& src_fn,std::string const& dest_fn) +bool compare_images(std::string const& src_fn, std::string const& dest_fn) +{ + std::unique_ptr reader1(mapnik::get_image_reader(dest_fn, "png")); + if (!reader1.get()) { - std::unique_ptr reader1(mapnik::get_image_reader(dest_fn,"png")); - if (!reader1.get()) - { - throw mapnik::image_reader_exception("Failed to load: " + dest_fn); - } - - std::unique_ptr reader2(mapnik::get_image_reader(src_fn,"png")); - if (!reader2.get()) - { - throw mapnik::image_reader_exception("Failed to load: " + src_fn); - } - - const mapnik::image_any desc_any = reader1->read(0,0,reader1->width(), reader1->height()); - const mapnik::image_any src_any = reader2->read(0,0,reader2->width(), reader2->height()); - - mapnik::image_rgba8 const& dest = mapnik::util::get(desc_any); - mapnik::image_rgba8 const& src = mapnik::util::get(src_any); - - return compare(dest, src, 0, true) == 0; + throw mapnik::image_reader_exception("Failed to load: " + dest_fn); } + std::unique_ptr reader2(mapnik::get_image_reader(src_fn, "png")); + if (!reader2.get()) + { + throw mapnik::image_reader_exception("Failed to load: " + src_fn); + } + + const mapnik::image_any desc_any = reader1->read(0, 0, reader1->width(), reader1->height()); + const mapnik::image_any src_any = reader2->read(0, 0, reader2->width(), reader2->height()); + + mapnik::image_rgba8 const& dest = mapnik::util::get(desc_any); + mapnik::image_rgba8 const& src = mapnik::util::get(src_any); + + return compare(dest, src, 0, true) == 0; } +} // namespace benchmark + #endif // MAPNIK_COMPARE_IMAGES_HPP diff --git a/benchmark/src/normalize_angle.cpp b/benchmark/src/normalize_angle.cpp index bc137a95f..fcfc7a5c2 100644 --- a/benchmark/src/normalize_angle.cpp +++ b/benchmark/src/normalize_angle.cpp @@ -2,20 +2,23 @@ #include -template +template struct bench_func : benchmark::test_case { - T (* const func_)(T); + T (*const func_)(T); T const value_; bench_func(mapnik::parameters const& params, T (*func)(T), T value) - : test_case(params), func_(func), value_(value) {} + : test_case(params) + , func_(func) + , value_(value) + {} bool validate() const { return true; } - bool operator() () const + bool operator()() const { - for (auto i = this->iterations_; i-- > 0; ) + for (auto i = this->iterations_; i-- > 0;) { func_(value_); } @@ -23,47 +26,46 @@ struct bench_func : benchmark::test_case } }; -#define BENCH_FUNC1(func, value) \ - run>(#func "(" #value ")", func, value) +#define BENCH_FUNC1(func, value) run>(#func "(" #value ")", func, value) int main(int argc, char** argv) { return benchmark::sequencer(argc, argv) - .BENCH_FUNC1(mapnik::util::normalize_angle, +3) - .BENCH_FUNC1(mapnik::util::normalize_angle, +6) - .BENCH_FUNC1(mapnik::util::normalize_angle, +9) - .BENCH_FUNC1(mapnik::util::normalize_angle, +12) - .BENCH_FUNC1(mapnik::util::normalize_angle, +15) - .BENCH_FUNC1(mapnik::util::normalize_angle, +20) - .BENCH_FUNC1(mapnik::util::normalize_angle, +30) - .BENCH_FUNC1(mapnik::util::normalize_angle, +40) - .BENCH_FUNC1(mapnik::util::normalize_angle, +50) - .BENCH_FUNC1(mapnik::util::normalize_angle, +70) - .BENCH_FUNC1(mapnik::util::normalize_angle, +90) - .BENCH_FUNC1(mapnik::util::normalize_angle, +110) - .BENCH_FUNC1(mapnik::util::normalize_angle, +130) - .BENCH_FUNC1(mapnik::util::normalize_angle, +157) - .BENCH_FUNC1(mapnik::util::normalize_angle, +209) - .BENCH_FUNC1(mapnik::util::normalize_angle, +314) - .BENCH_FUNC1(mapnik::util::normalize_angle, +628) - .BENCH_FUNC1(mapnik::util::normalize_angle, +942) - .BENCH_FUNC1(mapnik::util::normalize_angle, -3) - .BENCH_FUNC1(mapnik::util::normalize_angle, -6) - .BENCH_FUNC1(mapnik::util::normalize_angle, -9) - .BENCH_FUNC1(mapnik::util::normalize_angle, -12) - .BENCH_FUNC1(mapnik::util::normalize_angle, -15) - .BENCH_FUNC1(mapnik::util::normalize_angle, -20) - .BENCH_FUNC1(mapnik::util::normalize_angle, -30) - .BENCH_FUNC1(mapnik::util::normalize_angle, -40) - .BENCH_FUNC1(mapnik::util::normalize_angle, -50) - .BENCH_FUNC1(mapnik::util::normalize_angle, -70) - .BENCH_FUNC1(mapnik::util::normalize_angle, -90) - .BENCH_FUNC1(mapnik::util::normalize_angle, -110) - .BENCH_FUNC1(mapnik::util::normalize_angle, -130) - .BENCH_FUNC1(mapnik::util::normalize_angle, -157) - .BENCH_FUNC1(mapnik::util::normalize_angle, -209) - .BENCH_FUNC1(mapnik::util::normalize_angle, -314) - .BENCH_FUNC1(mapnik::util::normalize_angle, -628) - .BENCH_FUNC1(mapnik::util::normalize_angle, -942) - .done(); + .BENCH_FUNC1(mapnik::util::normalize_angle, +3) + .BENCH_FUNC1(mapnik::util::normalize_angle, +6) + .BENCH_FUNC1(mapnik::util::normalize_angle, +9) + .BENCH_FUNC1(mapnik::util::normalize_angle, +12) + .BENCH_FUNC1(mapnik::util::normalize_angle, +15) + .BENCH_FUNC1(mapnik::util::normalize_angle, +20) + .BENCH_FUNC1(mapnik::util::normalize_angle, +30) + .BENCH_FUNC1(mapnik::util::normalize_angle, +40) + .BENCH_FUNC1(mapnik::util::normalize_angle, +50) + .BENCH_FUNC1(mapnik::util::normalize_angle, +70) + .BENCH_FUNC1(mapnik::util::normalize_angle, +90) + .BENCH_FUNC1(mapnik::util::normalize_angle, +110) + .BENCH_FUNC1(mapnik::util::normalize_angle, +130) + .BENCH_FUNC1(mapnik::util::normalize_angle, +157) + .BENCH_FUNC1(mapnik::util::normalize_angle, +209) + .BENCH_FUNC1(mapnik::util::normalize_angle, +314) + .BENCH_FUNC1(mapnik::util::normalize_angle, +628) + .BENCH_FUNC1(mapnik::util::normalize_angle, +942) + .BENCH_FUNC1(mapnik::util::normalize_angle, -3) + .BENCH_FUNC1(mapnik::util::normalize_angle, -6) + .BENCH_FUNC1(mapnik::util::normalize_angle, -9) + .BENCH_FUNC1(mapnik::util::normalize_angle, -12) + .BENCH_FUNC1(mapnik::util::normalize_angle, -15) + .BENCH_FUNC1(mapnik::util::normalize_angle, -20) + .BENCH_FUNC1(mapnik::util::normalize_angle, -30) + .BENCH_FUNC1(mapnik::util::normalize_angle, -40) + .BENCH_FUNC1(mapnik::util::normalize_angle, -50) + .BENCH_FUNC1(mapnik::util::normalize_angle, -70) + .BENCH_FUNC1(mapnik::util::normalize_angle, -90) + .BENCH_FUNC1(mapnik::util::normalize_angle, -110) + .BENCH_FUNC1(mapnik::util::normalize_angle, -130) + .BENCH_FUNC1(mapnik::util::normalize_angle, -157) + .BENCH_FUNC1(mapnik::util::normalize_angle, -209) + .BENCH_FUNC1(mapnik::util::normalize_angle, -314) + .BENCH_FUNC1(mapnik::util::normalize_angle, -628) + .BENCH_FUNC1(mapnik::util::normalize_angle, -942) + .done(); } diff --git a/benchmark/src/test_array_allocation.cpp b/benchmark/src/test_array_allocation.cpp index 186c1620e..592a93d07 100644 --- a/benchmark/src/test_array_allocation.cpp +++ b/benchmark/src/test_array_allocation.cpp @@ -14,15 +14,19 @@ #define FULL_ZERO_CHECK -inline void ensure_zero(uint8_t * data, uint32_t size) { +inline void ensure_zero(uint8_t* data, uint32_t size) +{ #ifdef FULL_ZERO_CHECK - for (std::size_t i=0;i array_; test1(mapnik::parameters const& params) - : test_case(params), - size_(*params.get("size",256*256)), - array_(size_,0) { } - bool validate() const - { - return true; - } + : test_case(params) + , size_(*params.get("size", 256 * 256)) + , array_(size_, 0) + {} + bool validate() const { return true; } bool operator()() const { - for (std::size_t i=0;i array_; test1b(mapnik::parameters const& params) - : test_case(params), - size_(*params.get("size",256*256)), - array_(size_,0) { } - bool validate() const - { - return true; - } + : test_case(params) + , size_(*params.get("size", 256 * 256)) + , array_(size_, 0) + {} + bool validate() const { return true; } bool operator()() const { - for (std::size_t i=0;i array_; test1c(mapnik::parameters const& params) - : test_case(params), - size_(*params.get("size",256*256)), - array_(size_,0) { } - bool validate() const - { - return true; - } + : test_case(params) + , size_(*params.get("size", 256 * 256)) + , array_(size_, 0) + {} + bool validate() const { return true; } bool operator()() const { - for (std::size_t i=0;i(::operator new(sizeof(uint8_t) * size_)); - std::fill(data,data + size_,0); - ensure_zero(data,size_); - ::operator delete(data); - } - return true; + for (std::size_t i = 0; i < iterations_; ++i) + { + uint8_t* data = static_cast(::operator new(sizeof(uint8_t) * size_)); + std::fill(data, data + size_, 0); + ensure_zero(data, size_); + ::operator delete(data); + } + return true; } }; - class test2 : public benchmark::test_case { -public: + public: uint32_t size_; std::vector array_; test2(mapnik::parameters const& params) - : test_case(params), - size_(*params.get("size",256*256)), - array_(size_,0) { } - bool validate() const - { - return true; - } + : test_case(params) + , size_(*params.get("size", 256 * 256)) + , array_(size_, 0) + {} + bool validate() const { return true; } bool operator()() const { - for (std::size_t i=0;i(::operator new(sizeof(uint8_t)*size_)); - memcpy(data, &array_[0], size_); - ensure_zero(data,size_); - ::operator delete(data),data=0; - } - return true; + for (std::size_t i = 0; i < iterations_; ++i) + { + uint8_t* data = static_cast(::operator new(sizeof(uint8_t) * size_)); + memcpy(data, &array_[0], size_); + ensure_zero(data, size_); + ::operator delete(data), data = 0; + } + return true; } }; class test3 : public benchmark::test_case { -public: + public: uint32_t size_; std::vector array_; test3(mapnik::parameters const& params) - : test_case(params), - size_(*params.get("size",256*256)), - array_(size_,0) { } - bool validate() const - { - return true; - } + : test_case(params) + , size_(*params.get("size", 256 * 256)) + , array_(size_, 0) + {} + bool validate() const { return true; } bool operator()() const { - for (std::size_t i=0;i data(size_); - ensure_zero(&data[0],data.size()); - } - return true; + for (std::size_t i = 0; i < iterations_; ++i) + { + std::vector data(size_); + ensure_zero(&data[0], data.size()); + } + return true; } }; - class test3b : public benchmark::test_case { -public: + public: uint32_t size_; std::vector array_; test3b(mapnik::parameters const& params) - : test_case(params), - size_(*params.get("size",256*256)), - array_(size_,0) { } - bool validate() const - { - return true; - } + : test_case(params) + , size_(*params.get("size", 256 * 256)) + , array_(size_, 0) + {} + bool validate() const { return true; } bool operator()() const { - for (std::size_t i=0;i data(0); - data.resize(size_,0); - ensure_zero(&data[0],data.size()); - } - return true; + for (std::size_t i = 0; i < iterations_; ++i) + { + std::vector data(0); + data.resize(size_, 0); + ensure_zero(&data[0], data.size()); + } + return true; } }; - class test3c : public benchmark::test_case { -public: + public: uint32_t size_; std::vector array_; test3c(mapnik::parameters const& params) - : test_case(params), - size_(*params.get("size",256*256)), - array_(size_,0) { } - bool validate() const - { - return true; - } + : test_case(params) + , size_(*params.get("size", 256 * 256)) + , array_(size_, 0) + {} + bool validate() const { return true; } bool operator()() const { - for (std::size_t i=0;i data(0); - data.assign(size_,0); - ensure_zero(&data[0],data.size()); - } - return true; + for (std::size_t i = 0; i < iterations_; ++i) + { + std::vector data(0); + data.assign(size_, 0); + ensure_zero(&data[0], data.size()); + } + return true; } }; class test3d : public benchmark::test_case { -public: + public: uint32_t size_; std::vector array_; test3d(mapnik::parameters const& params) - : test_case(params), - size_(*params.get("size",256*256)), - array_(size_,0) { } - bool validate() const - { - return true; - } + : test_case(params) + , size_(*params.get("size", 256 * 256)) + , array_(size_, 0) + {} + bool validate() const { return true; } bool operator()() const { - for (std::size_t i=0;i data(size_); - for (std::size_t i=0;i data(size_); + for (std::size_t i = 0; i < size_; ++i) + { + if (data[i] != 0) + { + throw std::runtime_error("found non zero value"); + } + } + } + return true; } }; class test4 : public benchmark::test_case { -public: + public: uint32_t size_; std::vector array_; test4(mapnik::parameters const& params) - : test_case(params), - size_(*params.get("size",256*256)), - array_(size_,0) { } - bool validate() const - { - return true; - } + : test_case(params) + , size_(*params.get("size", 256 * 256)) + , array_(size_, 0) + {} + bool validate() const { return true; } bool operator()() const { - for (std::size_t i=0;i array_; test5(mapnik::parameters const& params) - : test_case(params), - size_(*params.get("size",256*256)), - array_(size_,0) { } - bool validate() const - { - return true; - } + : test_case(params) + , size_(*params.get("size", 256 * 256)) + , array_(size_, 0) + {} + bool validate() const { return true; } bool operator()() const { - for (std::size_t i=0;i array_; test5b(mapnik::parameters const& params) - : test_case(params), - size_(*params.get("size",256*256)), - array_(size_,0) { } - bool validate() const - { - return true; - } + : test_case(params) + , size_(*params.get("size", 256 * 256)) + , array_(size_, 0) + {} + bool validate() const { return true; } bool operator()() const { - for (std::size_t i=0;i array_; test6(mapnik::parameters const& params) - : test_case(params), - size_(*params.get("size",256*256)), - array_(size_,0) { } - bool validate() const - { - return true; - } + : test_case(params) + , size_(*params.get("size", 256 * 256)) + , array_(size_, 0) + {} + bool validate() const { return true; } bool operator()() const { - for (std::size_t i=0;i data(static_cast(0),static_cast(size_)); - ensure_zero(&data[0],size_); - } - return true; + for (std::size_t i = 0; i < iterations_; ++i) + { + std::valarray data(static_cast(0), static_cast(size_)); + ensure_zero(&data[0], size_); + } + return true; } }; @@ -335,24 +326,23 @@ public: class test7 : public benchmark::test_case { -public: + public: uint32_t size_; std::vector array_; test7(mapnik::parameters const& params) - : test_case(params), - size_(*params.get("size",256*256)), - array_(size_,0) { } - bool validate() const - { - return true; - } + : test_case(params) + , size_(*params.get("size", 256 * 256)) + , array_(size_, 0) + {} + bool validate() const { return true; } bool operator()() const { - for (std::size_t i=0;i data(size_,0); - ensure_zero(&data[0],size_); - } - return true; + for (std::size_t i = 0; i < iterations_; ++i) + { + boost::container::static_vector data(size_, 0); + ensure_zero(&data[0], size_); + } + return true; } }; #endif @@ -360,20 +350,20 @@ public: int main(int argc, char** argv) { return benchmark::sequencer(argc, argv) - .run("calloc") - .run("malloc/memcpy") - .run("malloc/memset") - .run("operator new/std::fill") - .run("operator new/memcpy") - .run("vector(N)") - .run("vector/resize") - .run("vector/assign") - .run("deque(N)") - .run("std::string range") - .run("std::string &[0]") - .run("valarray") + .run("calloc") + .run("malloc/memcpy") + .run("malloc/memset") + .run("operator new/std::fill") + .run("operator new/memcpy") + .run("vector(N)") + .run("vector/resize") + .run("vector/assign") + .run("deque(N)") + .run("std::string range") + .run("std::string &[0]") + .run("valarray") #if BOOST_VERSION >= 105400 - .run("static_vector") + .run("static_vector") #endif - .done(); + .done(); } diff --git a/benchmark/src/test_expression_parse.cpp b/benchmark/src/test_expression_parse.cpp index f39fb8e84..d35a57ab2 100644 --- a/benchmark/src/test_expression_parse.cpp +++ b/benchmark/src/test_expression_parse.cpp @@ -7,10 +7,12 @@ class test : public benchmark::test_case { std::string expr_; -public: + + public: test(mapnik::parameters const& params) - : test_case(params), - expr_("((([mapnik::geometry_type]=2) and ([oneway]=1)) and ([class]='path'))") {} + : test_case(params) + , expr_("((([mapnik::geometry_type]=2) and ([oneway]=1)) and ([class]='path'))") + {} bool validate() const { mapnik::expression_ptr expr = mapnik::parse_expression(expr_); @@ -18,24 +20,24 @@ public: bool ret = (result == expr_); if (!ret) { - std::clog << result << " != " << expr_ << "\n"; + std::clog << result << " != " << expr_ << "\n"; } return ret; } bool operator()() const { - for (std::size_t i=0;i line_data = params.get("line"); - if (line_data) - { - line_data_ = *line_data; - } - } + : test_case(params) + , line_data_("this is one line\nand this is a second line\nand a third line") + { + boost::optional line_data = params.get("line"); + if (line_data) + { + line_data_ = *line_data; + } + } bool validate() const { @@ -25,14 +23,15 @@ public: std::string csv_line; std::stringstream s; s << line_data_; - std::getline(s,csv_line,newline); + std::getline(s, csv_line, newline); if (csv_line != first) { return true; } else { - std::clog << "Error: the parsed line (" << csv_line << ") should be a subset of the original line (" << line_data_ << ") (ensure you pass a line with a \\n)\n"; + std::clog << "Error: the parsed line (" << csv_line << ") should be a subset of the original line (" + << line_data_ << ") (ensure you pass a line with a \\n)\n"; } return true; } @@ -42,29 +41,28 @@ public: std::string csv_line; std::stringstream s; s << line_data_; - for (unsigned i=0;i line_data = params.get("line"); - if (line_data) - { - line_data_ = *line_data; - } - } + : test_case(params) + , line_data_("this is one line\nand this is a second line\nand a third line") + { + boost::optional line_data = params.get("line"); + if (line_data) + { + line_data_ = *line_data; + } + } bool validate() const { @@ -74,14 +72,15 @@ public: std::string csv_line; std::stringstream s; s << line_data_; - csv_utils::getline_csv(s,csv_line,newline,quote); + csv_utils::getline_csv(s, csv_line, newline, quote); if (csv_line != first) { return true; } else { - std::clog << "Error: the parsed line (" << csv_line << ") should be a subset of the original line (" << line_data_ << ") (ensure you pass a line with a \\n)\n"; + std::clog << "Error: the parsed line (" << csv_line << ") should be a subset of the original line (" + << line_data_ << ") (ensure you pass a line with a \\n)\n"; } return true; } @@ -92,9 +91,9 @@ public: std::string csv_line; std::stringstream s; s << line_data_; - for (unsigned i=0;i images_; -public: + + public: test(mapnik::parameters const& params) - : test_case(params), - images_{ - "./test/data/images/dummy.jpg", - "./test/data/images/dummy.jpeg", - "./test/data/images/dummy.png", - "./test/data/images/dummy.tif", - "./test/data/images/dummy.tiff", - //"./test/data/images/landusepattern.jpeg", // will fail since it is a png - //"./test/data/images/xcode-CgBI.png", // will fail since its an invalid png - "./test/data/svg/octocat.svg", - "./test/data/svg/place-of-worship-24.svg", - "./test/data/svg/point_sm.svg", - "./test/data/svg/point.svg", - "./test/data/svg/airfield-12.svg" - } {} - bool validate() const - { - return true; - } + : test_case(params) + , images_{"./test/data/images/dummy.jpg", + "./test/data/images/dummy.jpeg", + "./test/data/images/dummy.png", + "./test/data/images/dummy.tif", + "./test/data/images/dummy.tiff", + //"./test/data/images/landusepattern.jpeg", // will fail since it is a png + //"./test/data/images/xcode-CgBI.png", // will fail since its an invalid png + "./test/data/svg/octocat.svg", + "./test/data/svg/place-of-worship-24.svg", + "./test/data/svg/point_sm.svg", + "./test/data/svg/point.svg", + "./test/data/svg/airfield-12.svg"} + {} + bool validate() const { return true; } bool operator()() const { unsigned count = 0; - for (std::size_t i=0;i(params); // add whitespace to trigger phony "reprojection" - mapnik::layer lay("layer",m.srs() + " "); + mapnik::layer lay("layer", m.srs() + " "); lay.set_datasource(ds); lay.add_style("style"); m.add_layer(lay); // dummy style to ensure that layer is processed - m.insert_style("style",mapnik::feature_type_style()); + m.insert_style("style", mapnik::feature_type_style()); // dummy bbox, but "valid" because minx and miny are less // with an invalid bbox then layer.visible() returns false // and the initial rendering setup is not run - m.zoom_to_box(mapnik::box2d(-1,-1,0,0)); - for (unsigned i=0;i(-1, -1, 0, 0)); + for (unsigned i = 0; i < iterations_; ++i) { - mapnik::image_rgba8 im(256,256); - mapnik::agg_renderer ren(m,im); + mapnik::image_rgba8 im(256, 256); + mapnik::agg_renderer ren(m, im); ren.apply(); } return true; } }; -BENCHMARK(test,"rendering with reprojection") +BENCHMARK(test, "rendering with reprojection") diff --git a/benchmark/src/test_numeric_cast_vs_static_cast.cpp b/benchmark/src/test_numeric_cast_vs_static_cast.cpp index 9e14bf31e..542006910 100644 --- a/benchmark/src/test_numeric_cast_vs_static_cast.cpp +++ b/benchmark/src/test_numeric_cast_vs_static_cast.cpp @@ -9,23 +9,25 @@ class test_static : public benchmark::test_case { double step_; std::uint8_t start_; -public: + + public: test_static(mapnik::parameters const& params) - : test_case(params), - step_(STEP_NUM), - start_(START_NUM) {} - bool validate() const - { - return true; - } + : test_case(params) + , step_(STEP_NUM) + , start_(START_NUM) + {} + bool validate() const { return true; } bool operator()() const { double value_ = 0.0; std::uint8_t x; - for (std::size_t i=0;i(start_) * value_; - if (c >= 256.0) c = 255.0; - if (c < 0.0) c = 0.0; + if (c >= 256.0) + c = 255.0; + if (c < 0.0) + c = 0.0; x = static_cast(c); value_ += step_; } @@ -33,35 +35,34 @@ public: } }; -using boost::numeric::positive_overflow; using boost::numeric::negative_overflow; +using boost::numeric::positive_overflow; class test_numeric : public benchmark::test_case { double step_; std::uint8_t start_; -public: + + public: test_numeric(mapnik::parameters const& params) - : test_case(params), - step_(STEP_NUM), - start_(START_NUM) {} - bool validate() const - { - return true; - } + : test_case(params) + , step_(STEP_NUM) + , start_(START_NUM) + {} + bool validate() const { return true; } bool operator()() const { double value_ = 0.0; std::uint8_t x; - for (std::size_t i=0;i(start_ * value_); - } - catch(negative_overflow&) + } catch (negative_overflow&) { x = std::numeric_limits::min(); - } - catch(positive_overflow&) + } catch (positive_overflow&) { x = std::numeric_limits::max(); } @@ -73,8 +74,5 @@ public: int main(int argc, char** argv) { - return benchmark::sequencer(argc, argv) - .run("static_cast") - .run("numeric_cast") - .done(); + return benchmark::sequencer(argc, argv).run("static_cast").run("numeric_cast").done(); } diff --git a/benchmark/src/test_offset_converter.cpp b/benchmark/src/test_offset_converter.cpp index c0d25da89..93988ce4c 100644 --- a/benchmark/src/test_offset_converter.cpp +++ b/benchmark/src/test_offset_converter.cpp @@ -14,31 +14,36 @@ struct fake_path cont_type::iterator itr_; fake_path(std::initializer_list l) - : fake_path(l.begin(), l.size()) { - } + : fake_path(l.begin(), l.size()) + {} - fake_path(std::vector const &v) - : fake_path(v.begin(), v.size()) { - } + fake_path(std::vector const& v) + : fake_path(v.begin(), v.size()) + {} - template - fake_path(Itr itr, size_t sz) { + template + fake_path(Itr itr, size_t sz) + { size_t num_coords = sz >> 1; vertices_.reserve(num_coords); - for (size_t i = 0; i < num_coords; ++i) { + for (size_t i = 0; i < num_coords; ++i) + { double x = *itr++; double y = *itr++; unsigned cmd = (i == 0) ? mapnik::SEG_MOVETO : mapnik::SEG_LINETO; vertices_.push_back(std::make_tuple(x, y, cmd)); - if (i == num_coords - 1) cmd = mapnik::SEG_END; + if (i == num_coords - 1) + cmd = mapnik::SEG_END; vertices_.push_back(std::make_tuple(x, y, cmd)); } itr_ = vertices_.begin(); } - unsigned vertex(double *x, double *y) { - if (itr_ == vertices_.end()) { + unsigned vertex(double* x, double* y) + { + if (itr_ == vertices_.end()) + { return mapnik::SEG_END; } *x = std::get<0>(*itr_); @@ -48,33 +53,30 @@ struct fake_path return cmd; } - void rewind(unsigned) { - itr_ = vertices_.begin(); - } + void rewind(unsigned) { itr_ = vertices_.begin(); } }; class test_offset : public benchmark::test_case { -public: + public: test_offset(mapnik::parameters const& params) - : test_case(params) {} - bool validate() const - { - return true; - } + : test_case(params) + {} + bool validate() const { return true; } bool operator()() const { std::vector path; int mysize = 2500; int x1 = 0; - path.reserve(mysize*2); - for( int i = 0; i < mysize; i++ ) + path.reserve(mysize * 2); + for (int i = 0; i < mysize; i++) { - path.push_back( i ); - path.push_back( 0 ); + path.push_back(i); + path.push_back(0); } fake_path fpath(path); - for (std::size_t i=0;i off_path(fpath); off_path.set_offset(10); unsigned cmd; @@ -88,15 +90,14 @@ public: } }; - int main(int argc, char** argv) { mapnik::parameters params; - benchmark::handle_args(argc,argv,params); + benchmark::handle_args(argc, argv, params); int return_value = 0; { test_offset test_runner(params); - return_value = run(test_runner,"offset_test"); + return_value = run(test_runner, "offset_test"); } return return_value; } diff --git a/benchmark/src/test_png_encoding1.cpp b/benchmark/src/test_png_encoding1.cpp index ec98f2884..9c4cc6f64 100644 --- a/benchmark/src/test_png_encoding1.cpp +++ b/benchmark/src/test_png_encoding1.cpp @@ -4,23 +4,23 @@ class test : public benchmark::test_case { mapnik::image_rgba8 im_; -public: + + public: test(mapnik::parameters const& params) - : test_case(params), - im_(256,256) {} - bool validate() const - { - return true; - } + : test_case(params) + , im_(256, 256) + {} + bool validate() const { return true; } bool operator()() const { std::string out; - for (std::size_t i=0;i im_; -public: + + public: test(mapnik::parameters const& params) - : test_case(params) { + : test_case(params) + { std::string filename("./benchmark/data/multicolor.png"); - std::unique_ptr reader(mapnik::get_image_reader(filename,"png")); + std::unique_ptr reader(mapnik::get_image_reader(filename, "png")); if (!reader.get()) { throw mapnik::image_reader_exception("Failed to load: " + filename); } - im_ = std::make_shared(reader->width(),reader->height()); - reader->read(0,0,*im_); + im_ = std::make_shared(reader->width(), reader->height()); + reader->read(0, 0, *im_); } bool validate() const { std::string expected("./benchmark/data/multicolor-hextree-expected.png"); std::string actual("./benchmark/data/multicolor-hextree-actual.png"); - mapnik::save_to_file(*im_,actual, "png8:m=h:z=1"); - return benchmark::compare_images(actual,expected); + mapnik::save_to_file(*im_, actual, "png8:m=h:z=1"); + return benchmark::compare_images(actual, expected); } bool operator()() const { std::string out; - for (std::size_t i=0;i const& geom, mapnik::box2d const& extent, std::string const& name) { - using path_type = mapnik::transform_path_adapter>; + using path_type = + mapnik::transform_path_adapter>; using ren_base = agg::renderer_base; using renderer = agg::renderer_scanline_aa_solid; - mapnik::image_rgba8 im(256,256); + mapnik::image_rgba8 im(256, 256); mapnik::fill(im, mapnik::color("white")); - mapnik::box2d padded_extent(155,134,665,466);//extent; + mapnik::box2d padded_extent(155, 134, 665, 466); // extent; padded_extent.pad(10); - mapnik::view_transform tr(im.width(),im.height(),padded_extent,0,0); - agg::rendering_buffer buf(im.bytes(),im.width(),im.height(), im.row_size()); + mapnik::view_transform tr(im.width(), im.height(), padded_extent, 0, 0); + agg::rendering_buffer buf(im.bytes(), im.width(), im.height(), im.row_size()); agg::pixfmt_rgba32_plain pixf(buf); ren_base renb(pixf); renderer ren(renb); - mapnik::proj_transform prj_trans(mapnik::projection("epsg:4326"),mapnik::projection("epsg:4326")); - ren.color(agg::rgba8(127,127,127,255)); + mapnik::proj_transform prj_trans(mapnik::projection("epsg:4326"), mapnik::projection("epsg:4326")); + ren.color(agg::rgba8(127, 127, 127, 255)); agg::rasterizer_scanline_aa<> ras; for (auto const& poly : geom) { mapnik::geometry::polygon_vertex_adapter va(poly); - path_type path(tr,va,prj_trans); + path_type path(tr, va, prj_trans); ras.add_path(path); } agg::scanline_u8 sl; agg::render_scanlines(ras, sl, ren); - mapnik::save_to_file(im,name); + mapnik::save_to_file(im, name); } class test1 : public benchmark::test_case @@ -70,15 +71,15 @@ class test1 : public benchmark::test_case std::string wkt_in_; mapnik::box2d extent_; std::string expected_; -public: + + public: using conv_clip = agg::conv_clip_polygon>; - test1(mapnik::parameters const& params, - std::string const& wkt_in, - mapnik::box2d const& extent) - : test_case(params), - wkt_in_(wkt_in), - extent_(extent), - expected_("./benchmark/data/polygon_clipping_agg") {} + test1(mapnik::parameters const& params, std::string const& wkt_in, mapnik::box2d const& extent) + : test_case(params) + , wkt_in_(wkt_in) + , extent_(extent) + , expected_("./benchmark/data/polygon_clipping_agg") + {} bool validate() const { mapnik::geometry::geometry geom; @@ -99,14 +100,8 @@ public: mapnik::geometry::polygon const& poly = mapnik::util::get>(geom); mapnik::geometry::polygon_vertex_adapter va(poly); - conv_clip clipped(va); - clipped.clip_box( - extent_.minx(), - extent_.miny(), - extent_.maxx(), - extent_.maxy()); - + clipped.clip_box(extent_.minx(), extent_.miny(), extent_.maxx(), extent_.maxy()); clipped.rewind(0); mapnik::geometry::polygon poly2; @@ -118,7 +113,8 @@ public: { if (cmd == mapnik::SEG_MOVETO) { - x0 = x; y0 = y; + x0 = x; + y0 = y; } if (cmd == mapnik::SEG_CLOSE) @@ -126,7 +122,7 @@ public: ring.emplace_back(x0, y0); break; } - ring.emplace_back(x,y); + ring.emplace_back(x, y); } poly2.push_back(std::move(ring)); // interior rings @@ -135,30 +131,31 @@ public: { if (cmd == mapnik::SEG_MOVETO) { - x0 = x; y0 = y; + x0 = x; + y0 = y; } else if (cmd == mapnik::SEG_CLOSE) { - ring.emplace_back(x0,y0); + ring.emplace_back(x0, y0); poly2.push_back(std::move(ring)); ring.clear(); continue; } - ring.emplace_back(x,y); + ring.emplace_back(x, y); } - std::string expect = expected_+".png"; - std::string actual = expected_+"_actual.png"; + std::string expect = expected_ + ".png"; + std::string actual = expected_ + "_actual.png"; mapnik::geometry::multi_polygon mp; mp.emplace_back(poly2); auto env = mapnik::geometry::envelope(mp); if (!mapnik::util::exists(expect) || (std::getenv("UPDATE") != nullptr)) { std::clog << "generating expected image: " << expect << "\n"; - render(mp,env,expect); + render(mp, env, expect); } - render(mp,env,actual); - return benchmark::compare_images(actual,expect); + render(mp, env, actual); + return benchmark::compare_images(actual, expect); } bool operator()() const { @@ -178,29 +175,28 @@ public: return false; } bool valid = true; - for (unsigned i=0;i const& poly = mapnik::util::get>(geom); mapnik::geometry::polygon_vertex_adapter va(poly); conv_clip clipped(va); - clipped.clip_box( - extent_.minx(), - extent_.miny(), - extent_.maxx(), - extent_.maxy()); + clipped.clip_box(extent_.minx(), extent_.miny(), extent_.maxx(), extent_.maxy()); unsigned cmd; - double x,y; + double x, y; // NOTE: this rewind is critical otherwise // agg_conv_adapter_vpgen will give garbage // values for the first vertex clipped.rewind(0); - while ((cmd = clipped.vertex(&x, &y)) != mapnik::SEG_END) { + while ((cmd = clipped.vertex(&x, &y)) != mapnik::SEG_END) + { count++; } unsigned expected_count = 30; - if (count != expected_count) { - std::clog << "test1: clipping failed: processed " << count << " verticies but expected " << expected_count << "\n"; + if (count != expected_count) + { + std::clog << "test1: clipping failed: processed " << count << " verticies but expected " + << expected_count << "\n"; valid = false; } } @@ -208,20 +204,19 @@ public: } }; - class test3 : public benchmark::test_case { std::string wkt_in_; mapnik::box2d extent_; std::string expected_; -public: - test3(mapnik::parameters const& params, - std::string const& wkt_in, - mapnik::box2d const& extent) - : test_case(params), - wkt_in_(wkt_in), - extent_(extent), - expected_("./benchmark/data/polygon_clipping_boost") {} + + public: + test3(mapnik::parameters const& params, std::string const& wkt_in, mapnik::box2d const& extent) + : test_case(params) + , wkt_in_(wkt_in) + , extent_(extent) + , expected_("./benchmark/data/polygon_clipping_boost") + {} bool validate() const { mapnik::geometry::geometry geom; @@ -234,12 +229,12 @@ public: std::clog << "empty geom!\n"; return false; } - if (!geom.is >()) + if (!geom.is>()) { std::clog << "not a polygon!\n"; return false; } - mapnik::geometry::polygon & poly = mapnik::util::get >(geom); + mapnik::geometry::polygon& poly = mapnik::util::get>(geom); mapnik::geometry::correct(poly); mapnik::geometry::linear_ring bbox; @@ -249,15 +244,15 @@ public: bbox.emplace_back(extent_.maxx(), extent_.miny()); bbox.emplace_back(extent_.minx(), extent_.miny()); - std::deque > result; + std::deque> result; boost::geometry::intersection(bbox, poly, result); - std::string expect = expected_+".png"; - std::string actual = expected_+"_actual.png"; + std::string expect = expected_ + ".png"; + std::string actual = expected_ + "_actual.png"; mapnik::geometry::multi_polygon mp; - for (auto const& _geom: result) + for (auto const& _geom : result) { - //std::clog << boost::geometry::dsv(geom) << "\n"; + // std::clog << boost::geometry::dsv(geom) << "\n"; mp.emplace_back(_geom); } mapnik::geometry::geometry geom2(mp); @@ -265,10 +260,10 @@ public: if (!mapnik::util::exists(expect) || (std::getenv("UPDATE") != nullptr)) { std::clog << "generating expected image: " << expect << "\n"; - render(mp,env,expect); + render(mp, env, expect); } - render(mp,env,actual); - return benchmark::compare_images(actual,expect); + render(mp, env, actual); + return benchmark::compare_images(actual, expect); } bool operator()() const { @@ -282,12 +277,12 @@ public: std::clog << "empty geom!\n"; return false; } - if (!geom.is >()) + if (!geom.is>()) { std::clog << "not a polygon!\n"; return false; } - mapnik::geometry::polygon & poly = mapnik::util::get >(geom); + mapnik::geometry::polygon& poly = mapnik::util::get>(geom); mapnik::geometry::correct(poly); mapnik::geometry::linear_ring bbox; @@ -298,22 +293,25 @@ public: bbox.emplace_back(extent_.minx(), extent_.miny()); bool valid = true; - for (unsigned i=0;i > result; + std::deque> result; boost::geometry::intersection(bbox, poly, result); unsigned count = 0; for (auto const& _geom : result) { mapnik::geometry::polygon_vertex_adapter va(_geom); unsigned cmd; - double x,y; - while ((cmd = va.vertex(&x, &y)) != mapnik::SEG_END) { + double x, y; + while ((cmd = va.vertex(&x, &y)) != mapnik::SEG_END) + { ++count; } unsigned expected_count = 29; - if (count != expected_count) { - std::clog << "test3: clipping failed: processed " << count << " verticies but expected " << expected_count << "\n"; + if (count != expected_count) + { + std::clog << "test3: clipping failed: processed " << count << " verticies but expected " + << expected_count << "\n"; valid = false; } } @@ -500,8 +498,8 @@ public: } unsigned expected_count = 29; if (count != expected_count) { - std::clog << "test3: clipping failed: processed " << count << " verticies but expected " << expected_count << "\n"; - valid = false; + std::clog << "test3: clipping failed: processed " << count << " verticies but expected " << +expected_count << "\n"; valid = false; } } } @@ -513,13 +511,16 @@ public: int main(int argc, char** argv) { mapnik::parameters params; - benchmark::handle_args(argc,argv,params); + benchmark::handle_args(argc, argv, params); // polygon/rect clipping - // IN : POLYGON ((155 203, 233 454, 315 340, 421 446, 463 324, 559 466, 665 253, 528 178, 394 229, 329 138, 212 134, 183 228, 200 264, 155 203),(313 190, 440 256, 470 248, 510 305, 533 237, 613 263, 553 397, 455 262, 405 378, 343 287, 249 334, 229 191, 313 190)) - // RECT : POLYGON ((181 106, 181 470, 631 470, 631 106, 181 106)) - // OUT (expected) - // POLYGON ((181 286.6666666666667, 233 454, 315 340, 421 446, 463 324, 559 466, 631 321.3207547169811, 631 234.38686131386862, 528 178, 394 229, 329 138, 212 134, 183 228, 200 264, 181 238.24444444444444, 181 286.6666666666667),(313 190, 440 256, 470 248, 510 305, 533 237, 613 263, 553 397, 455 262, 405 378, 343 287, 249 334, 229 191, 313 190)) + // IN : POLYGON ((155 203, 233 454, 315 340, 421 446, 463 324, 559 466, 665 253, 528 178, 394 229, 329 138, 212 134, + // 183 228, 200 264, 155 203),(313 190, 440 256, 470 248, 510 305, 533 237, 613 263, 553 397, 455 262, 405 378, 343 + // 287, 249 334, 229 191, 313 190)) RECT : POLYGON ((181 106, 181 470, 631 470, 631 106, 181 106)) OUT (expected) + // POLYGON ((181 286.6666666666667, 233 454, 315 340, 421 446, 463 324, 559 466, 631 321.3207547169811, 631 + // 234.38686131386862, 528 178, 394 229, 329 138, 212 134, 183 228, 200 264, 181 238.24444444444444, 181 + // 286.6666666666667),(313 190, 440 256, 470 248, 510 305, 533 237, 613 263, 553 397, 455 262, 405 378, 343 287, 249 + // 334, 229 191, 313 190)) #if 0 mapnik::box2d clipping_box(181,106,631,470); std::string filename_("./benchmark/data/polygon.wkt"); @@ -544,5 +545,5 @@ int main(int argc, char** argv) } */ #endif - return 0;// return_value; + return 0; // return_value; } diff --git a/benchmark/src/test_polygon_clipping_rendering.cpp b/benchmark/src/test_polygon_clipping_rendering.cpp index 758505d9d..b0daba0c9 100644 --- a/benchmark/src/test_polygon_clipping_rendering.cpp +++ b/benchmark/src/test_polygon_clipping_rendering.cpp @@ -8,53 +8,51 @@ class test : public benchmark::test_case { std::string xml_; mapnik::box2d extent_; -public: - test(mapnik::parameters const& params, - std::string const& xml, - mapnik::box2d const& extent) - : test_case(params), - xml_(xml), - extent_(extent) - {} + + public: + test(mapnik::parameters const& params, std::string const& xml, mapnik::box2d const& extent) + : test_case(params) + , xml_(xml) + , extent_(extent) + {} bool validate() const { - mapnik::Map m(256,256); - mapnik::load_map(m,xml_); + mapnik::Map m(256, 256); + mapnik::load_map(m, xml_); m.zoom_to_box(extent_); - mapnik::image_rgba8 im(m.width(),m.height()); - mapnik::agg_renderer ren(m,im); + mapnik::image_rgba8 im(m.width(), m.height()); + mapnik::agg_renderer ren(m, im); ren.apply(); - //mapnik::save_to_file(im.data(),"test.png"); + // mapnik::save_to_file(im.data(),"test.png"); return true; } bool operator()() const { - mapnik::Map m(256,256); - mapnik::load_map(m,xml_); + mapnik::Map m(256, 256); + mapnik::load_map(m, xml_); m.zoom_to_box(extent_); - for (unsigned i=0;i ren(m,im); + mapnik::image_rgba8 im(m.width(), m.height()); + mapnik::agg_renderer ren(m, im); ren.apply(); } return true; } }; - int main(int argc, char** argv) { mapnik::parameters params; - benchmark::handle_args(argc,argv,params); + benchmark::handle_args(argc, argv, params); mapnik::datasource_cache::instance().register_datasources("./plugins/input/"); - mapnik::box2d z1(-20037508.3428,-8317435.0606,20037508.3428,18399242.7298); + mapnik::box2d z1(-20037508.3428, -8317435.0606, 20037508.3428, 18399242.7298); // bbox for 16/10491/22911.png - mapnik::box2d z16(-13622912.929097254,6026906.8062295765,-13621689.93664469,6028129.79868214); + mapnik::box2d z16(-13622912.929097254, 6026906.8062295765, -13621689.93664469, 6028129.79868214); return benchmark::sequencer(argc, argv) - .run("polygon clip render z1", "benchmark/data/polygon_rendering_clip.xml", z1) - .run("polygon noclip render z1", "benchmark/data/polygon_rendering_no_clip.xml", z1) - .run("polygon clip render z16", "benchmark/data/polygon_rendering_clip.xml", z16) - .run("polygon noclip render z16", "benchmark/data/polygon_rendering_no_clip.xml", z16) - .done(); + .run("polygon clip render z1", "benchmark/data/polygon_rendering_clip.xml", z1) + .run("polygon noclip render z1", "benchmark/data/polygon_rendering_no_clip.xml", z1) + .run("polygon clip render z16", "benchmark/data/polygon_rendering_clip.xml", z16) + .run("polygon noclip render z16", "benchmark/data/polygon_rendering_no_clip.xml", z16) + .done(); } diff --git a/benchmark/src/test_proj_transform1.cpp b/benchmark/src/test_proj_transform1.cpp index be85685d8..96e338ceb 100644 --- a/benchmark/src/test_proj_transform1.cpp +++ b/benchmark/src/test_proj_transform1.cpp @@ -10,45 +10,46 @@ class test : public benchmark::test_case mapnik::box2d from_; mapnik::box2d to_; bool defer_proj_init_; -public: + + public: test(mapnik::parameters const& params, std::string const& src, std::string const& dest, mapnik::box2d const& from, mapnik::box2d const& to, bool defer_proj) - : test_case(params), - src_(src), - dest_(dest), - from_(from), - to_(to), - defer_proj_init_(defer_proj) {} + : test_case(params) + , src_(src) + , dest_(dest) + , from_(from) + , to_(to) + , defer_proj_init_(defer_proj) + {} bool validate() const { - mapnik::projection src(src_,defer_proj_init_); - mapnik::projection dest(dest_,defer_proj_init_); - mapnik::proj_transform tr(src,dest); + mapnik::projection src(src_, defer_proj_init_); + mapnik::projection dest(dest_, defer_proj_init_); + mapnik::proj_transform tr(src, dest); mapnik::box2d bbox = from_; - if (!tr.forward(bbox)) return false; - return ((std::fabs(bbox.minx() - to_.minx()) < .5) && - (std::fabs(bbox.maxx() - to_.maxx()) < .5) && - (std::fabs(bbox.miny() - to_.miny()) < .5) && - (std::fabs(bbox.maxy() - to_.maxy()) < .5) - ); + if (!tr.forward(bbox)) + return false; + return ((std::fabs(bbox.minx() - to_.minx()) < .5) && (std::fabs(bbox.maxx() - to_.maxx()) < .5) && + (std::fabs(bbox.miny() - to_.miny()) < .5) && (std::fabs(bbox.maxy() - to_.maxy()) < .5)); } bool operator()() const { - mapnik::projection src(src_,defer_proj_init_); - mapnik::projection dest(dest_,defer_proj_init_); - mapnik::proj_transform tr(src,dest); - for (std::size_t i=0;i box(j,k,j,k); - if (!tr.forward(box)) throw std::runtime_error("could not transform coords"); + mapnik::box2d box(j, k, j, k); + if (!tr.forward(box)) + throw std::runtime_error("could not transform coords"); } } } @@ -59,16 +60,17 @@ public: // echo -180 -60 | cs2cs -f "%.10f" epsg:4326 +to epsg:3857 int main(int argc, char** argv) { - mapnik::box2d from(-180,-80,180,80); - mapnik::box2d to(-20037508.3427892476,-15538711.0963092316,20037508.3427892476,15538711.0963092316); + mapnik::box2d from(-180, -80, 180, 80); + mapnik::box2d to(-20037508.3427892476, -15538711.0963092316, 20037508.3427892476, 15538711.0963092316); std::string from_str("epsg:4326"); std::string to_str("epsg:3857"); std::string from_str2("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"); - std::string to_str2("+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs +over"); + std::string to_str2("+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m " + "+nadgrids=@null +wktext +no_defs +over"); return benchmark::sequencer(argc, argv) - .run("lonlat->merc epsg (internal)", from_str, to_str, from, to, true) - .run("lonlat->merc literal (libproj)", from_str2, to_str2, from, to, true) - .run("merc->lonlat epsg (internal)", to_str, from_str, to, from, true) - .run("merc->lonlat literal (libproj)", to_str2, from_str2, to, from, true) - .done(); + .run("lonlat->merc epsg (internal)", from_str, to_str, from, to, true) + .run("lonlat->merc literal (libproj)", from_str2, to_str2, from, to, true) + .run("merc->lonlat epsg (internal)", to_str, from_str, to, from, true) + .run("merc->lonlat literal (libproj)", to_str2, from_str2, to, from, true) + .done(); } diff --git a/benchmark/src/test_quad_tree.cpp b/benchmark/src/test_quad_tree.cpp index e3aabac7c..ea92e32a5 100644 --- a/benchmark/src/test_quad_tree.cpp +++ b/benchmark/src/test_quad_tree.cpp @@ -6,43 +6,41 @@ using quad_tree_type = mapnik::quad_tree; class test : public benchmark::test_case { -public: + public: test(mapnik::parameters const& params) - : test_case(params) {} + : test_case(params) + {} - bool validate() const - { - return true; - } + bool validate() const { return true; } bool operator()() const { std::random_device rd; std::default_random_engine engine(rd()); std::uniform_int_distribution uniform_dist(0, 2048); - quad_tree_type tree(mapnik::box2d(0,0,2048,2048)); - //populate + quad_tree_type tree(mapnik::box2d(0, 0, 2048, 2048)); + // populate for (size_t i = 0; i < iterations_; ++i) { int cx = uniform_dist(engine); int cy = uniform_dist(engine); int sx = 0.2 * uniform_dist(engine); int sy = 0.2 * uniform_dist(engine); - mapnik::box2d box(cx - sx,cy - sy, cx + sx, cy + sy); + mapnik::box2d box(cx - sx, cy - sy, cx + sx, cy + sy); tree.insert(i, box); } // bounding box query - std::size_t count=0; + std::size_t count = 0; for (size_t i = 0; i < iterations_; ++i) { int cx = uniform_dist(engine); int cy = uniform_dist(engine); int sx = 0.4 * uniform_dist(engine); int sy = 0.4 * uniform_dist(engine); - mapnik::box2d box(cx - sx,cy - sy, cx + sx, cy + sy); + mapnik::box2d box(cx - sx, cy - sy, cx + sx, cy + sy); auto itr = tree.query_in_box(box); auto end = tree.query_end(); - for ( ;itr != end; ++itr) + for (; itr != end; ++itr) { ++count; } @@ -51,4 +49,4 @@ public: } }; -BENCHMARK(test,"quad_tree creation") +BENCHMARK(test, "quad_tree creation") diff --git a/benchmark/src/test_rendering.cpp b/benchmark/src/test_rendering.cpp index beea28969..0ba1fdff4 100644 --- a/benchmark/src/test_rendering.cpp +++ b/benchmark/src/test_rendering.cpp @@ -15,16 +15,17 @@ class test : public benchmark::test_case mapnik::value_integer height_; double scale_factor_; std::string preview_; -public: + + public: test(mapnik::parameters const& params) - : test_case(params), - xml_(), - extent_(), - width_(*params.get("width",256)), - height_(*params.get("height",256)), - scale_factor_(*params.get("scale_factor",1.0)), - preview_(*params.get("preview","")) - { + : test_case(params) + , xml_() + , extent_() + , width_(*params.get("width", 256)) + , height_(*params.get("height", 256)) + , scale_factor_(*params.get("scale_factor", 1.0)) + , preview_(*params.get("preview", "")) + { boost::optional map = params.get("map"); if (!map) { @@ -43,70 +44,75 @@ public: { throw std::runtime_error("please provide a --extent= arg"); }*/ - - } + } bool validate() const { - mapnik::Map m(width_,height_); - mapnik::load_map(m,xml_,true); - if (extent_.valid()) { + mapnik::Map m(width_, height_); + mapnik::load_map(m, xml_, true); + if (extent_.valid()) + { m.zoom_to_box(extent_); - } else { + } + else + { m.zoom_all(); } - mapnik::image_rgba8 im(m.width(),m.height()); - mapnik::agg_renderer ren(m,im,scale_factor_); + mapnik::image_rgba8 im(m.width(), m.height()); + mapnik::agg_renderer ren(m, im, scale_factor_); ren.apply(); - if (!preview_.empty()) { + if (!preview_.empty()) + { std::clog << "preview available at " << preview_ << "\n"; - mapnik::save_to_file(im,preview_); + mapnik::save_to_file(im, preview_); } return true; } bool operator()() const { - if (!preview_.empty()) { + if (!preview_.empty()) + { return false; } - mapnik::Map m(width_,height_); - mapnik::load_map(m,xml_); - if (extent_.valid()) { + mapnik::Map m(width_, height_); + mapnik::load_map(m, xml_); + if (extent_.valid()) + { m.zoom_to_box(extent_); - } else { + } + else + { m.zoom_all(); } - for (unsigned i=0;i ren(m,im,scale_factor_); + mapnik::image_rgba8 im(m.width(), m.height()); + mapnik::agg_renderer ren(m, im, scale_factor_); ren.apply(); } return true; } }; - int main(int argc, char** argv) { int return_value = 0; try { mapnik::parameters params; - benchmark::handle_args(argc,argv,params); + benchmark::handle_args(argc, argv, params); boost::optional name = params.get("name"); if (!name) { std::clog << "please provide a name for this test\n"; return -1; } - mapnik::freetype_engine::register_fonts("./fonts/",true); + mapnik::freetype_engine::register_fonts("./fonts/", true); mapnik::datasource_cache::instance().register_datasources("./plugins/input/"); { test test_runner(params); - return_value = run(test_runner,*name); + return_value = run(test_runner, *name); } - } - catch (std::exception const& ex) + } catch (std::exception const& ex) { std::clog << ex.what() << "\n"; return -1; diff --git a/benchmark/src/test_rendering_shared_map.cpp b/benchmark/src/test_rendering_shared_map.cpp index 75631f78c..3d16f61fd 100644 --- a/benchmark/src/test_rendering_shared_map.cpp +++ b/benchmark/src/test_rendering_shared_map.cpp @@ -12,14 +12,15 @@ #include #include -template void process_layers(Renderer & ren, - mapnik::request const& m_req, - mapnik::projection const& map_proj, - std::vector const& layers, - double scale_denom) +template +void process_layers(Renderer& ren, + mapnik::request const& m_req, + mapnik::projection const& map_proj, + std::vector const& layers, + double scale_denom) { unsigned layers_size = layers.size(); - for (unsigned i=0; i < layers_size; ++i) + for (unsigned i = 0; i < layers_size; ++i) { mapnik::layer const& lyr = layers[i]; if (lyr.visible(scale_denom)) @@ -50,17 +51,18 @@ class test : public benchmark::test_case double scale_factor_; std::string preview_; mutable mapnik::image_rgba8 im_; -public: + + public: test(mapnik::parameters const& params) - : test_case(params), - xml_(), - extent_(), - width_(*params.get("width",256)), - height_(*params.get("height",256)), - m_(new mapnik::Map(width_,height_)), - scale_factor_(*params.get("scale_factor",2.0)), - preview_(*params.get("preview","")), - im_(m_->width(),m_->height()) + : test_case(params) + , xml_() + , extent_() + , width_(*params.get("width", 256)) + , height_(*params.get("height", 256)) + , m_(new mapnik::Map(width_, height_)) + , scale_factor_(*params.get("scale_factor", 2.0)) + , preview_(*params.get("preview", "")) + , im_(m_->width(), m_->height()) { boost::optional map = params.get("map"); if (!map) @@ -70,7 +72,7 @@ public: xml_ = *map; boost::optional ext = params.get("extent"); - mapnik::load_map(*m_,xml_,true); + mapnik::load_map(*m_, xml_, true); if (ext && !ext->empty()) { if (!extent_.from_string(*ext)) @@ -87,42 +89,44 @@ public: bool validate() const { - mapnik::request m_req(width_,height_,extent_); + mapnik::request m_req(width_, height_, extent_); mapnik::attributes variables; m_req.set_buffer_size(m_->buffer_size()); - mapnik::projection map_proj(m_->srs(),true); - double scale_denom = mapnik::scale_denominator(m_req.scale(),map_proj.is_geographic()); + mapnik::projection map_proj(m_->srs(), true); + double scale_denom = mapnik::scale_denominator(m_req.scale(), map_proj.is_geographic()); scale_denom *= scale_factor_; - mapnik::agg_renderer ren(*m_,m_req,variables,im_,scale_factor_); + mapnik::agg_renderer ren(*m_, m_req, variables, im_, scale_factor_); ren.start_map_processing(*m_); std::vector const& layers = m_->layers(); - process_layers(ren,m_req,map_proj,layers,scale_denom); + process_layers(ren, m_req, map_proj, layers, scale_denom); ren.end_map_processing(*m_); - if (!preview_.empty()) { + if (!preview_.empty()) + { std::clog << "preview available at " << preview_ << "\n"; - mapnik::save_to_file(im_,preview_); + mapnik::save_to_file(im_, preview_); } return true; } bool operator()() const { - if (!preview_.empty()) { + if (!preview_.empty()) + { return false; } - for (unsigned i=0;iwidth(),m_->height()); + mapnik::request m_req(width_, height_, extent_); + mapnik::image_rgba8 im(m_->width(), m_->height()); mapnik::attributes variables; m_req.set_buffer_size(m_->buffer_size()); - mapnik::projection map_proj(m_->srs(),true); - double scale_denom = mapnik::scale_denominator(m_req.scale(),map_proj.is_geographic()); + mapnik::projection map_proj(m_->srs(), true); + double scale_denom = mapnik::scale_denominator(m_req.scale(), map_proj.is_geographic()); scale_denom *= scale_factor_; - mapnik::agg_renderer ren(*m_,m_req,variables,im,scale_factor_); + mapnik::agg_renderer ren(*m_, m_req, variables, im, scale_factor_); ren.start_map_processing(*m_); std::vector const& layers = m_->layers(); - process_layers(ren,m_req,map_proj,layers,scale_denom); + process_layers(ren, m_req, map_proj, layers, scale_denom); ren.end_map_processing(*m_); bool diff = false; mapnik::image_rgba8 const& dest = im; @@ -133,37 +137,37 @@ public: const unsigned int* row_to = dest.get_row(y); for (unsigned int x = 0; x < width_; ++x) { - if (row_from[x] != row_to[x]) diff = true; + if (row_from[x] != row_to[x]) + diff = true; } } - if (diff) throw std::runtime_error("images differ"); + if (diff) + throw std::runtime_error("images differ"); } return true; } }; - int main(int argc, char** argv) { int return_value = 0; try { mapnik::parameters params; - benchmark::handle_args(argc,argv,params); + benchmark::handle_args(argc, argv, params); boost::optional name = params.get("name"); if (!name) { std::clog << "please provide a name for this test\n"; return -1; } - mapnik::freetype_engine::register_fonts("./fonts/",true); + mapnik::freetype_engine::register_fonts("./fonts/", true); mapnik::datasource_cache::instance().register_datasources("./plugins/input/"); { test test_runner(params); - return_value = run(test_runner,*name); + return_value = run(test_runner, *name); } - } - catch (std::exception const& ex) + } catch (std::exception const& ex) { std::clog << ex.what() << "\n"; return -1; diff --git a/benchmark/src/test_to_bool.cpp b/benchmark/src/test_to_bool.cpp index 83759baaa..5a24df984 100644 --- a/benchmark/src/test_to_bool.cpp +++ b/benchmark/src/test_to_bool.cpp @@ -4,27 +4,31 @@ class test : public benchmark::test_case { std::string value_; -public: + + public: test(mapnik::parameters const& params) - : test_case(params), - value_("true") {} + : test_case(params) + , value_("true") + {} bool validate() const { bool result = false; - mapnik::util::string2bool(value_.data(),value_.data()+value_.size(),result); - if (!result) return result; - mapnik::util::string2bool(value_,result); + mapnik::util::string2bool(value_.data(), value_.data() + value_.size(), result); + if (!result) + return result; + mapnik::util::string2bool(value_, result); return (result == true); } bool operator()() const { - for (std::size_t i=0;ibool") +BENCHMARK(test, "string->bool") diff --git a/benchmark/src/test_to_double.cpp b/benchmark/src/test_to_double.cpp index 9fcd2d52f..b99218df4 100644 --- a/benchmark/src/test_to_double.cpp +++ b/benchmark/src/test_to_double.cpp @@ -4,29 +4,36 @@ class test : public benchmark::test_case { std::string value_; -public: + + public: test(mapnik::parameters const& params) - : test_case(params), - value_("1.23456789") {} + : test_case(params) + , value_("1.23456789") + {} bool validate() const { double result = 0; - if (!mapnik::util::string2double(value_.data(),value_.data()+value_.size(),result)) return false; - if (result != 1.23456789) return false; + if (!mapnik::util::string2double(value_.data(), value_.data() + value_.size(), result)) + return false; + if (result != 1.23456789) + return false; result = 0; - if (!mapnik::util::string2double(value_,result)) return false; - if (result != 1.23456789) return false; + if (!mapnik::util::string2double(value_, result)) + return false; + if (result != 1.23456789) + return false; return true; } bool operator()() const { - for (std::size_t i=0;idouble") +BENCHMARK(test, "string->double") diff --git a/benchmark/src/test_to_int.cpp b/benchmark/src/test_to_int.cpp index c8367c63e..d705ce979 100644 --- a/benchmark/src/test_to_int.cpp +++ b/benchmark/src/test_to_int.cpp @@ -4,29 +4,36 @@ class test : public benchmark::test_case { std::string value_; -public: + + public: test(mapnik::parameters const& params) - : test_case(params), - value_("123456789") {} + : test_case(params) + , value_("123456789") + {} bool validate() const { mapnik::value_integer result = 0; - if (!mapnik::util::string2int(value_.data(),value_.data()+value_.size(),result)) return false; - if (result != 123456789) return false; + if (!mapnik::util::string2int(value_.data(), value_.data() + value_.size(), result)) + return false; + if (result != 123456789) + return false; result = 0; - if (!mapnik::util::string2int(value_,result)) return false; - if (result != 123456789) return false; + if (!mapnik::util::string2int(value_, result)) + return false; + if (result != 123456789) + return false; return true; } bool operator()() const { - for (std::size_t i=0;iint") +BENCHMARK(test, "string->int") diff --git a/benchmark/src/test_to_string1.cpp b/benchmark/src/test_to_string1.cpp index 187d231e5..003b36a15 100644 --- a/benchmark/src/test_to_string1.cpp +++ b/benchmark/src/test_to_string1.cpp @@ -4,25 +4,28 @@ class test : public benchmark::test_case { double value_; -public: + + public: test(mapnik::parameters const& params) - : test_case(params), - value_(-0.1234) {} + : test_case(params) + , value_(-0.1234) + {} bool validate() const { std::string s; - mapnik::util::to_string(s,value_); + mapnik::util::to_string(s, value_); return (s == "-0.1234"); } bool operator()() const { std::string out; - for (std::size_t i=0;istring") +BENCHMARK(test, "to_string double->string") diff --git a/benchmark/src/test_to_string2.cpp b/benchmark/src/test_to_string2.cpp index c1797111d..a39233840 100644 --- a/benchmark/src/test_to_string2.cpp +++ b/benchmark/src/test_to_string2.cpp @@ -4,10 +4,12 @@ class test : public benchmark::test_case { double value_; -public: + + public: test(mapnik::parameters const& params) - : test_case(params), - value_(-0.1234) {} + : test_case(params) + , value_(-0.1234) + {} bool validate() const { std::ostringstream s; @@ -17,7 +19,8 @@ public: bool operator()() const { std::string out; - for (std::size_t i=0;istring") +BENCHMARK(test, "ostringstream double->string") diff --git a/benchmark/src/test_utf_encoding.cpp b/benchmark/src/test_utf_encoding.cpp index 87224ecbf..badb0a661 100644 --- a/benchmark/src/test_utf_encoding.cpp +++ b/benchmark/src/test_utf_encoding.cpp @@ -13,27 +13,29 @@ using mapnik::util::from_u8string; class test : public benchmark::test_case { std::string utf8_; -public: + + public: test(mapnik::parameters const& params) - : test_case(params), - utf8_(from_u8string(u8"שלום")) {} + : test_case(params) + , utf8_(from_u8string(u8"שלום")) + {} bool validate() const { std::wstring_convert, char32_t> utf32conv; std::u32string utf32 = utf32conv.from_bytes(utf8_); - if (utf32.size() != 4) return false; - if (utf32[0] != 0x5e9 && - utf32[1] != 0x5dc && - utf32[2] != 0x5d5 && - utf32[3] != 0x5dd) return false; + if (utf32.size() != 4) + return false; + if (utf32[0] != 0x5e9 && utf32[1] != 0x5dc && utf32[2] != 0x5d5 && utf32[3] != 0x5dd) + return false; return true; } bool operator()() const { std::u32string utf32; std::wstring_convert, char32_t> utf32conv; - for (std::size_t i=0;i(utf8_); - if (utf32.size() != 4) return false; - if (utf32[0] != 0x5e9 && - utf32[1] != 0x5dc && - utf32[2] != 0x5d5 && - utf32[3] != 0x5dd) return false; + if (utf32.size() != 4) + return false; + if (utf32[0] != 0x5e9 && utf32[1] != 0x5dc && utf32[2] != 0x5d5 && utf32[3] != 0x5dd) + return false; return true; } bool operator()() const { - std::u32string utf32; - for (std::size_t i=0;i(utf8_); - } + std::u32string utf32; + for (std::size_t i = 0; i < iterations_; ++i) + { + utf32 = boost::locale::conv::utf_to_utf(utf8_); + } return true; } }; @@ -71,28 +75,30 @@ public: class test3 : public benchmark::test_case { std::string utf8_; -public: + + public: test3(mapnik::parameters const& params) - : test_case(params), - utf8_(from_u8string(u8"שלום")) {} + : test_case(params) + , utf8_(from_u8string(u8"שלום")) + {} bool validate() const { mapnik::transcoder tr_("utf-8"); - mapnik::value_unicode_string utf32 = tr_.transcode(utf8_.data(),utf8_.size()); - //std::u32string utf32 = boost::locale::conv::utf_to_utf(utf8_); - if (utf32.length() != 4) return false; - if (utf32[0] != 0x5e9 && - utf32[1] != 0x5dc && - utf32[2] != 0x5d5 && - utf32[3] != 0x5dd) return false; + mapnik::value_unicode_string utf32 = tr_.transcode(utf8_.data(), utf8_.size()); + // std::u32string utf32 = boost::locale::conv::utf_to_utf(utf8_); + if (utf32.length() != 4) + return false; + if (utf32[0] != 0x5e9 && utf32[1] != 0x5dc && utf32[2] != 0x5d5 && utf32[3] != 0x5dd) + return false; return true; } bool operator()() const { mapnik::transcoder tr_("utf-8"); mapnik::value_unicode_string utf32; - for (std::size_t i=0;i is not supported on __linux__\n"; #endif test2 test_runner2(params); - return_value = return_value | run(test_runner2,"utf encode boost::locale"); + return_value = return_value | run(test_runner2, "utf encode boost::locale"); test3 test_runner3(params); - return_value = return_value | run(test_runner3,"utf encode ICU"); + return_value = return_value | run(test_runner3, "utf encode ICU"); return return_value; } diff --git a/benchmark/template.cpp b/benchmark/template.cpp index a91ecb36a..706649d3f 100644 --- a/benchmark/template.cpp +++ b/benchmark/template.cpp @@ -2,16 +2,12 @@ class test : public benchmark::test_case { -public: + public: test(mapnik::parameters const& params) - : test_case(params) {} - bool validate() const - { - return true; - } - void operator()() const - { - } + : test_case(params) + {} + bool validate() const { return true; } + void operator()() const {} }; -BENCHMARK(test,"test name") +BENCHMARK(test, "test name") diff --git a/cmake/clang-format.cmake b/cmake/clang-format.cmake new file mode 100644 index 000000000..7681ffbf2 --- /dev/null +++ b/cmake/clang-format.cmake @@ -0,0 +1,16 @@ +function(format_dir dir) + file(GLOB_RECURSE sources + "${dir}/*.cpp" + "${dir}/*.hpp" + ) + execute_process(COMMAND clang-format -style=file -i ${sources}) +endfunction() + + +format_dir(benchmark) +format_dir(demo) +format_dir(include) +format_dir(plugins) +format_dir(src) +format_dir(test) +format_dir(utils) diff --git a/demo/c++/rundemo.cpp b/demo/c++/rundemo.cpp index 1406ca4a8..dc4f8e823 100644 --- a/demo/c++/rundemo.cpp +++ b/demo/c++/rundemo.cpp @@ -45,19 +45,21 @@ #include - -int main ( int, char** ) +int main(int, char**) { using namespace mapnik; - const std::string srs_lcc="+proj=lcc +ellps=GRS80 +lat_0=49 +lon_0=-95 +lat+1=49 +lat_2=77 +datum=NAD83 +units=m +no_defs"; - const std::string srs_merc="+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs +over"; + const std::string srs_lcc = + "+proj=lcc +ellps=GRS80 +lat_0=49 +lon_0=-95 +lat+1=49 +lat_2=77 +datum=NAD83 +units=m +no_defs"; + const std::string srs_merc = "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 " + "+units=m +nadgrids=@null +wktext +no_defs +over"; - try { + try + { std::cout << " running demo ... \n"; datasource_cache::instance().register_datasources("plugins/input/"); freetype_engine::register_font("fonts/dejavu-fonts-ttf-2.37/ttf/DejaVuSans.ttf"); - Map m(800,600); + Map m(800, 600); m.set_background(parse_color("white")); m.set_srs(srs_merc); // create styles @@ -93,13 +95,13 @@ int main ( int, char** ) rule r; { line_symbolizer line_sym; - put(line_sym,keys::stroke,color(0,0,0)); - put(line_sym,keys::stroke_width,1.0); + put(line_sym, keys::stroke, color(0, 0, 0)); + put(line_sym, keys::stroke_width, 1.0); dash_array dash; - dash.emplace_back(8,4); - dash.emplace_back(2,2); - dash.emplace_back(2,2); - put(line_sym,keys::stroke_dasharray,dash); + dash.emplace_back(8, 4); + dash.emplace_back(2, 2); + dash.emplace_back(2, 2); + put(line_sym, keys::stroke_dasharray, dash); r.append(std::move(line_sym)); } provlines_style.add_rule(std::move(r)); @@ -127,10 +129,10 @@ int main ( int, char** ) r.set_filter(parse_expression("[CLASS] = 3 or [CLASS] = 4")); { line_symbolizer line_sym; - put(line_sym,keys::stroke,color(171,158,137)); - put(line_sym,keys::stroke_width,2.0); - put(line_sym,keys::stroke_linecap,ROUND_CAP); - put(line_sym,keys::stroke_linejoin,ROUND_JOIN); + put(line_sym, keys::stroke, color(171, 158, 137)); + put(line_sym, keys::stroke_width, 2.0); + put(line_sym, keys::stroke_linecap, ROUND_CAP); + put(line_sym, keys::stroke_linejoin, ROUND_JOIN); r.append(std::move(line_sym)); } roads34_style.add_rule(std::move(r)); @@ -144,10 +146,10 @@ int main ( int, char** ) r.set_filter(parse_expression("[CLASS] = 2")); { line_symbolizer line_sym; - put(line_sym,keys::stroke,color(171,158,137)); - put(line_sym,keys::stroke_width,4.0); - put(line_sym,keys::stroke_linecap,ROUND_CAP); - put(line_sym,keys::stroke_linejoin,ROUND_JOIN); + put(line_sym, keys::stroke, color(171, 158, 137)); + put(line_sym, keys::stroke_width, 4.0); + put(line_sym, keys::stroke_linecap, ROUND_CAP); + put(line_sym, keys::stroke_linejoin, ROUND_JOIN); r.append(std::move(line_sym)); } roads2_style_1.add_rule(std::move(r)); @@ -160,10 +162,10 @@ int main ( int, char** ) r.set_filter(parse_expression("[CLASS] = 2")); { line_symbolizer line_sym; - put(line_sym,keys::stroke,color(255,250,115)); - put(line_sym,keys::stroke_width,2.0); - put(line_sym,keys::stroke_linecap,ROUND_CAP); - put(line_sym,keys::stroke_linejoin,ROUND_JOIN); + put(line_sym, keys::stroke, color(255, 250, 115)); + put(line_sym, keys::stroke_width, 2.0); + put(line_sym, keys::stroke_linecap, ROUND_CAP); + put(line_sym, keys::stroke_linejoin, ROUND_JOIN); r.append(std::move(line_sym)); } roads2_style_2.add_rule(std::move(r)); @@ -177,10 +179,10 @@ int main ( int, char** ) r.set_filter(parse_expression("[CLASS] = 1")); { line_symbolizer line_sym; - put(line_sym,keys::stroke,color(188,149,28)); - put(line_sym,keys::stroke_width,7.0); - put(line_sym,keys::stroke_linecap,ROUND_CAP); - put(line_sym,keys::stroke_linejoin,ROUND_JOIN); + put(line_sym, keys::stroke, color(188, 149, 28)); + put(line_sym, keys::stroke_width, 7.0); + put(line_sym, keys::stroke_linecap, ROUND_CAP); + put(line_sym, keys::stroke_linejoin, ROUND_JOIN); r.append(std::move(line_sym)); } roads1_style_1.add_rule(std::move(r)); @@ -193,10 +195,10 @@ int main ( int, char** ) r.set_filter(parse_expression("[CLASS] = 1")); { line_symbolizer line_sym; - put(line_sym,keys::stroke,color(242,191,36)); - put(line_sym,keys::stroke_width,5.0); - put(line_sym,keys::stroke_linecap,ROUND_CAP); - put(line_sym,keys::stroke_linejoin,ROUND_JOIN); + put(line_sym, keys::stroke, color(242, 191, 36)); + put(line_sym, keys::stroke_width, 5.0); + put(line_sym, keys::stroke_linecap, ROUND_CAP); + put(line_sym, keys::stroke_linejoin, ROUND_JOIN); r.append(std::move(line_sym)); } roads1_style_2.add_rule(std::move(r)); @@ -212,10 +214,11 @@ int main ( int, char** ) text_placements_ptr placement_finder = std::make_shared(); placement_finder->defaults.format_defaults.face_name = "DejaVu Sans Book"; placement_finder->defaults.format_defaults.text_size = 10.0; - placement_finder->defaults.format_defaults.fill = color(0,0,0); - placement_finder->defaults.format_defaults.halo_fill = color(255,255,200); + placement_finder->defaults.format_defaults.fill = color(0, 0, 0); + placement_finder->defaults.format_defaults.halo_fill = color(255, 255, 200); placement_finder->defaults.format_defaults.halo_radius = 1.0; - placement_finder->defaults.set_format_tree(std::make_shared(parse_expression("[GEONAME]"))); + placement_finder->defaults.set_format_tree( + std::make_shared(parse_expression("[GEONAME]"))); put(text_sym, keys::text_placements_, placement_finder); r.append(std::move(text_sym)); } @@ -228,9 +231,9 @@ int main ( int, char** ) // Provincial polygons { parameters p; - p["type"]="shape"; - p["file"]="demo/data/boundaries"; - p["encoding"]="utf8"; + p["type"] = "shape"; + p["file"] = "demo/data/boundaries"; + p["encoding"] = "utf8"; layer lyr("Provinces"); lyr.set_datasource(datasource_cache::instance().create(p)); @@ -242,8 +245,8 @@ int main ( int, char** ) // Drainage { parameters p; - p["type"]="shape"; - p["file"]="demo/data/qcdrainage"; + p["type"] = "shape"; + p["file"] = "demo/data/qcdrainage"; layer lyr("Quebec Hydrography"); lyr.set_datasource(datasource_cache::instance().create(p)); lyr.set_srs(srs_lcc); @@ -253,8 +256,8 @@ int main ( int, char** ) { parameters p; - p["type"]="shape"; - p["file"]="demo/data/ontdrainage"; + p["type"] = "shape"; + p["file"] = "demo/data/ontdrainage"; layer lyr("Ontario Hydrography"); lyr.set_datasource(datasource_cache::instance().create(p)); lyr.set_srs(srs_lcc); @@ -265,8 +268,8 @@ int main ( int, char** ) // Provincial boundaries { parameters p; - p["type"]="shape"; - p["file"]="demo/data/boundaries_l"; + p["type"] = "shape"; + p["file"] = "demo/data/boundaries_l"; layer lyr("Provincial borders"); lyr.set_srs(srs_lcc); lyr.set_datasource(datasource_cache::instance().create(p)); @@ -277,8 +280,8 @@ int main ( int, char** ) // Roads { parameters p; - p["type"]="shape"; - p["file"]="demo/data/roads"; + p["type"] = "shape"; + p["file"] = "demo/data/roads"; layer lyr("Roads"); lyr.set_srs(srs_lcc); lyr.set_datasource(datasource_cache::instance().create(p)); @@ -293,8 +296,8 @@ int main ( int, char** ) // popplaces { parameters p; - p["type"]="shape"; - p["file"]="demo/data/popplaces"; + p["type"] = "shape"; + p["file"] = "demo/data/popplaces"; p["encoding"] = "utf8"; layer lyr("Populated Places"); lyr.set_srs(srs_lcc); @@ -303,28 +306,28 @@ int main ( int, char** ) m.add_layer(lyr); } - m.zoom_to_box(box2d(-8024477.28459,5445190.38849,-7381388.20071,5662941.44855)); + m.zoom_to_box(box2d(-8024477.28459, 5445190.38849, -7381388.20071, 5662941.44855)); - image_rgba8 buf(m.width(),m.height()); - agg_renderer ren(m,buf); + image_rgba8 buf(m.width(), m.height()); + agg_renderer ren(m, buf); ren.apply(); std::string msg("These maps have been rendered using AGG in the current directory:\n"); #ifdef HAVE_JPEG - save_to_file(buf,"demo.jpg","jpeg"); + save_to_file(buf, "demo.jpg", "jpeg"); msg += "- demo.jpg\n"; #endif #ifdef HAVE_PNG - save_to_file(buf,"demo.png","png"); - save_to_file(buf,"demo256.png","png8"); + save_to_file(buf, "demo.png", "png"); + save_to_file(buf, "demo256.png", "png8"); msg += "- demo.png\n"; msg += "- demo256.png\n"; #endif #ifdef HAVE_TIFF - save_to_file(buf,"demo.tif","tiff"); + save_to_file(buf, "demo.tif", "tiff"); msg += "- demo.tif\n"; #endif #ifdef HAVE_WEBP - save_to_file(buf,"demo.webp","webp"); + save_to_file(buf, "demo.webp", "webp"); msg += "- demo.webp\n"; #endif msg += "Have a look!\n"; @@ -332,8 +335,8 @@ int main ( int, char** ) #if defined(HAVE_CAIRO) // save to pdf/svg files - save_to_cairo_file(m,"cairo-demo.pdf"); - save_to_cairo_file(m,"cairo-demo.svg"); + save_to_cairo_file(m, "cairo-demo.pdf"); + save_to_cairo_file(m, "cairo-demo.svg"); /* we could also do: @@ -342,38 +345,36 @@ int main ( int, char** ) but instead let's build up a surface for more flexibility */ - cairo_surface_ptr image_surface( - cairo_image_surface_create(CAIRO_FORMAT_ARGB32,m.width(),m.height()), - cairo_surface_closer()); + cairo_surface_ptr image_surface(cairo_image_surface_create(CAIRO_FORMAT_ARGB32, m.width(), m.height()), + cairo_surface_closer()); double scale_factor = 1.0; cairo_ptr image_context(create_context(image_surface)); - mapnik::cairo_renderer png_render(m,image_context,scale_factor); + mapnik::cairo_renderer png_render(m, image_context, scale_factor); png_render.apply(); // we can now write to png with cairo functionality cairo_surface_write_to_png(&*image_surface, "cairo-demo.png"); // but we can also benefit from quantization by converting // to a mapnik image object and then saving that - mapnik::image_rgba8 im_data(cairo_image_surface_get_width(&*image_surface), cairo_image_surface_get_height(&*image_surface)); + mapnik::image_rgba8 im_data(cairo_image_surface_get_width(&*image_surface), + cairo_image_surface_get_height(&*image_surface)); cairo_image_to_rgba8(im_data, image_surface); - save_to_file(im_data, "cairo-demo256.png","png8"); + save_to_file(im_data, "cairo-demo256.png", "png8"); cairo_surface_finish(&*image_surface); std::cout << "Three maps have been rendered using Cairo in the current directory:\n" - "- cairo-demo.png\n" - "- cairo-demo256.png\n" - "- cairo-demo.pdf\n" - "- cairo-demo.svg\n" - "Have a look!\n"; + "- cairo-demo.png\n" + "- cairo-demo256.png\n" + "- cairo-demo.pdf\n" + "- cairo-demo.svg\n" + "Have a look!\n"; #endif // save map definition (data + style) save_map(m, "map.xml"); - } - catch ( std::exception const& ex ) + } catch (std::exception const& ex) { std::cerr << "### std::exception: " << ex.what() << std::endl; return EXIT_FAILURE; - } - catch ( ... ) + } catch (...) { std::cerr << "### Unknown exception." << std::endl; return EXIT_FAILURE; diff --git a/demo/viewer/about_dialog.cpp b/demo/viewer/about_dialog.cpp index ed63e3d7c..075e321cb 100644 --- a/demo/viewer/about_dialog.cpp +++ b/demo/viewer/about_dialog.cpp @@ -17,12 +17,10 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ - #include "about_dialog.hpp" - -about_dialog::about_dialog(QWidget *parent) - : QDialog(parent) +about_dialog::about_dialog(QWidget* parent) + : QDialog(parent) { - ui.setupUi(this); + ui.setupUi(this); } diff --git a/demo/viewer/about_dialog.hpp b/demo/viewer/about_dialog.hpp index 480631ed6..80d201d57 100644 --- a/demo/viewer/about_dialog.hpp +++ b/demo/viewer/about_dialog.hpp @@ -17,8 +17,6 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ - - #if !defined ABOUT_DIALOG_HPP #define ABOUT_DIALOG_HPP @@ -27,12 +25,12 @@ class about_dialog : public QDialog { - Q_OBJECT -public: - about_dialog(QWidget * parent = 0); -private: - Ui::Dialog ui; + Q_OBJECT + public: + about_dialog(QWidget* parent = 0); + + private: + Ui::Dialog ui; }; - -#endif //ABOUT_DIALOG_HPP +#endif // ABOUT_DIALOG_HPP diff --git a/demo/viewer/info_dialog.cpp b/demo/viewer/info_dialog.cpp index 85898d2c6..e2ad82392 100644 --- a/demo/viewer/info_dialog.cpp +++ b/demo/viewer/info_dialog.cpp @@ -17,24 +17,22 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ - #include "info_dialog.hpp" - -info_dialog::info_dialog(QVector > const& info, QWidget *parent) - : QDialog(parent) +info_dialog::info_dialog(QVector> const& info, QWidget* parent) + : QDialog(parent) { - ui.setupUi(this); - ui.tableWidget->setHorizontalHeaderItem(0,new QTableWidgetItem("Name")); - ui.tableWidget->setHorizontalHeaderItem(1,new QTableWidgetItem("Value")); + ui.setupUi(this); + ui.tableWidget->setHorizontalHeaderItem(0, new QTableWidgetItem("Name")); + ui.tableWidget->setHorizontalHeaderItem(1, new QTableWidgetItem("Value")); - ui.tableWidget->setRowCount(info.size()); - ui.tableWidget->setColumnCount(2); - for (int i=0;isetItem(i,0,keyItem); - ui.tableWidget->setItem(i,1,valueItem); - } + ui.tableWidget->setRowCount(info.size()); + ui.tableWidget->setColumnCount(2); + for (int i = 0; i < info.size(); ++i) + { + QTableWidgetItem* keyItem = new QTableWidgetItem(info[i].first); + QTableWidgetItem* valueItem = new QTableWidgetItem(info[i].second); + ui.tableWidget->setItem(i, 0, keyItem); + ui.tableWidget->setItem(i, 1, valueItem); + } } diff --git a/demo/viewer/info_dialog.hpp b/demo/viewer/info_dialog.hpp index 404de4a00..877be514e 100644 --- a/demo/viewer/info_dialog.hpp +++ b/demo/viewer/info_dialog.hpp @@ -17,8 +17,6 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ - - #ifndef INFO_DIALOG_HPP #define INFO_DIALOG_HPP @@ -27,12 +25,12 @@ class info_dialog : public QDialog { - Q_OBJECT + Q_OBJECT public: - info_dialog(QVector > const& info,QWidget * parent = 0); - private: - Ui::InfoDialog ui; + info_dialog(QVector> const& info, QWidget* parent = 0); + + private: + Ui::InfoDialog ui; }; - -#endif //INFO_DIALOG_HPP +#endif // INFO_DIALOG_HPP diff --git a/demo/viewer/layer_info_dialog.cpp b/demo/viewer/layer_info_dialog.cpp index 2b9947d57..c5c5bf4de 100644 --- a/demo/viewer/layer_info_dialog.cpp +++ b/demo/viewer/layer_info_dialog.cpp @@ -17,7 +17,6 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ - #include "layer_info_dialog.hpp" // mapnik @@ -26,14 +25,13 @@ #include #include - -layer_info_dialog::layer_info_dialog(mapnik::layer& lay, QWidget *parent) - : QDialog(parent) +layer_info_dialog::layer_info_dialog(mapnik::layer& lay, QWidget* parent) + : QDialog(parent) { ui.setupUi(this); - ui.tableWidget->setHorizontalHeaderItem(0,new QTableWidgetItem("Name")); - ui.tableWidget->setHorizontalHeaderItem(1,new QTableWidgetItem("Value")); + ui.tableWidget->setHorizontalHeaderItem(0, new QTableWidgetItem("Name")); + ui.tableWidget->setHorizontalHeaderItem(1, new QTableWidgetItem("Value")); // Layer name ui.layerNameEdit->setText(QString(lay.name().c_str())); @@ -50,17 +48,17 @@ layer_info_dialog::layer_info_dialog(mapnik::layer& lay, QWidget *parent) ui.tableWidget->setColumnCount(2); mapnik::parameters::const_iterator pos; - int index=0; - for (pos = ps.begin();pos != ps.end();++pos) + int index = 0; + for (pos = ps.begin(); pos != ps.end(); ++pos) { boost::optional result; - mapnik::util::apply_visitor(mapnik::value_extractor_visitor(result),pos->second); + mapnik::util::apply_visitor(mapnik::value_extractor_visitor(result), pos->second); if (result) { - QTableWidgetItem *keyItem = new QTableWidgetItem(QString(pos->first.c_str())); - QTableWidgetItem *valueItem = new QTableWidgetItem(QString((*result).c_str())); - ui.tableWidget->setItem(index,0,keyItem); - ui.tableWidget->setItem(index,1,valueItem); + QTableWidgetItem* keyItem = new QTableWidgetItem(QString(pos->first.c_str())); + QTableWidgetItem* valueItem = new QTableWidgetItem(QString((*result).c_str())); + ui.tableWidget->setItem(index, 0, keyItem); + ui.tableWidget->setItem(index, 1, valueItem); ++index; } } @@ -69,5 +67,5 @@ layer_info_dialog::layer_info_dialog(mapnik::layer& lay, QWidget *parent) Ui::LayerInfoDialog& layer_info_dialog::getUI() { - return ui; + return ui; } diff --git a/demo/viewer/layer_info_dialog.hpp b/demo/viewer/layer_info_dialog.hpp index d3c46cefa..798fb7b1c 100644 --- a/demo/viewer/layer_info_dialog.hpp +++ b/demo/viewer/layer_info_dialog.hpp @@ -17,28 +17,25 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ - - #ifndef LAYER_INFO_DIALOG_HPP #define LAYER_INFO_DIALOG_HPP #include "ui_layer_info.h" #include -namespace mapnik -{ +namespace mapnik { class layer; } class layer_info_dialog : public QDialog { - Q_OBJECT + Q_OBJECT public: - layer_info_dialog(mapnik::layer& l, QWidget * parent = 0); + layer_info_dialog(mapnik::layer& l, QWidget* parent = 0); Ui::LayerInfoDialog& getUI(); - private: - Ui::LayerInfoDialog ui; + + private: + Ui::LayerInfoDialog ui; }; - -#endif //LAYER_INFO_DIALOG_HPP +#endif // LAYER_INFO_DIALOG_HPP diff --git a/demo/viewer/layerdelegate.cpp b/demo/viewer/layerdelegate.cpp index d441e1e11..e4879ca2e 100644 --- a/demo/viewer/layerdelegate.cpp +++ b/demo/viewer/layerdelegate.cpp @@ -17,38 +17,32 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ - #include #include "layerdelegate.hpp" -LayerDelegate::LayerDelegate(QObject *parent) +LayerDelegate::LayerDelegate(QObject* parent) : QAbstractItemDelegate(parent) -{ -} +{} -void LayerDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, - const QModelIndex &index) const +void LayerDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const { painter->setRenderHint(QPainter::Antialiasing); - painter->setPen(QPen(QColor(255,0,0),1)); + painter->setPen(QPen(QColor(255, 0, 0), 1)); if (option.state & QStyle::State_Selected) painter->setBrush(QBrush(QColor(0, 0, 255, 64))); else painter->setBrush(QBrush(QColor(255, 0, 0, 64))); - - painter->drawRoundedRect(option.rect,4,4); + painter->drawRoundedRect(option.rect, 4, 4); if (option.state & QStyle::State_Selected) painter->setBrush(option.palette.highlightedText()); else painter->setBrush(QBrush(QColor(255, 120, 0, 127))); - } -QSize LayerDelegate::sizeHint(const QStyleOptionViewItem & /* option */, - const QModelIndex & /* index */) const +QSize LayerDelegate::sizeHint(const QStyleOptionViewItem& /* option */, const QModelIndex& /* index */) const { - return QSize(120,24); + return QSize(120, 24); } diff --git a/demo/viewer/layerdelegate.hpp b/demo/viewer/layerdelegate.hpp index 3dc1d28d3..37b031c71 100644 --- a/demo/viewer/layerdelegate.hpp +++ b/demo/viewer/layerdelegate.hpp @@ -33,12 +33,10 @@ class LayerDelegate : public QAbstractItemDelegate { Q_OBJECT -public: - LayerDelegate(QObject *parent = 0); - void paint(QPainter *painter, const QStyleOptionViewItem &option, - const QModelIndex &index) const; - QSize sizeHint(const QStyleOptionViewItem &option, - const QModelIndex &index ) const; + public: + LayerDelegate(QObject* parent = 0); + void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const; + QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const; }; -#endif //LAYER_DELEGATE_HPP +#endif // LAYER_DELEGATE_HPP diff --git a/demo/viewer/layerlistmodel.cpp b/demo/viewer/layerlistmodel.cpp index ec0eaac26..eb14bd681 100644 --- a/demo/viewer/layerlistmodel.cpp +++ b/demo/viewer/layerlistmodel.cpp @@ -17,8 +17,6 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ - - #include "layerlistmodel.hpp" #include #include @@ -26,14 +24,16 @@ using mapnik::Map; -LayerListModel::LayerListModel(std::shared_ptr map, QObject *parent) - : QAbstractListModel(parent), - map_(map) {} +LayerListModel::LayerListModel(std::shared_ptr map, QObject* parent) + : QAbstractListModel(parent) + , map_(map) +{} int LayerListModel::rowCount(QModelIndex const&) const { - if (map_) return map_->layers().size(); - return 0; + if (map_) + return map_->layers().size(); + return 0; } QVariant LayerListModel::data(QModelIndex const& index, int role) const @@ -59,9 +59,9 @@ QVariant LayerListModel::data(QModelIndex const& index, int role) const else if (role == Qt::CheckStateRole) { if (map_->layers().at(index.row()).active()) - return QVariant(Qt::Checked); + return QVariant(Qt::Checked); else - return QVariant(Qt::Unchecked); + return QVariant(Qt::Unchecked); } else if (role == Qt::ForegroundRole) { @@ -76,8 +76,7 @@ QVariant LayerListModel::data(QModelIndex const& index, int role) const } } -QVariant LayerListModel::headerData(int section, Qt::Orientation orientation, - int role) const +QVariant LayerListModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role != Qt::DisplayRole) return QVariant(); @@ -88,37 +87,37 @@ QVariant LayerListModel::headerData(int section, Qt::Orientation orientation, return QString("TODO Row %1").arg(section); } -bool LayerListModel::setData(const QModelIndex &index, - const QVariant &value, int role) +bool LayerListModel::setData(const QModelIndex& index, const QVariant& value, int role) { - if (!map_) return false; + if (!map_) + return false; - if (index.isValid() && role == Qt::CheckStateRole) - { - int status = value.toInt(); - std::vector & layers = const_cast& >(map_->layers()); - layers.at(index.row()).set_active(status); - emit dataChanged(index, index); - return true; - } - return false; + if (index.isValid() && role == Qt::CheckStateRole) + { + int status = value.toInt(); + std::vector& layers = const_cast&>(map_->layers()); + layers.at(index.row()).set_active(status); + emit dataChanged(index, index); + return true; + } + return false; } Qt::ItemFlags LayerListModel::flags(QModelIndex const& index) const { Qt::ItemFlags flags = QAbstractItemModel::flags(index); if (index.isValid()) - flags |= Qt::ItemIsUserCheckable; + flags |= Qt::ItemIsUserCheckable; return flags; } boost::optional LayerListModel::map_layer(int i) { - if (map_) - { - std::vector & layers = const_cast& >(map_->layers()); - if (i < int(layers.size())) - return boost::optional(layers[i]); - } - return boost::optional(); + if (map_) + { + std::vector& layers = const_cast&>(map_->layers()); + if (i < int(layers.size())) + return boost::optional(layers[i]); + } + return boost::optional(); } diff --git a/demo/viewer/layerlistmodel.hpp b/demo/viewer/layerlistmodel.hpp index 9f29f051c..c0872cadd 100644 --- a/demo/viewer/layerlistmodel.hpp +++ b/demo/viewer/layerlistmodel.hpp @@ -17,8 +17,6 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ - - #ifndef LAYER_LIST_MODEL_HPP #define LAYER_LIST_MODEL_HPP @@ -32,20 +30,18 @@ class LayerListModel : public QAbstractListModel { - Q_OBJECT - public: - LayerListModel(std::shared_ptr map, QObject * parent = 0); - int rowCount(const QModelIndex &parent = QModelIndex()) const; - QVariant data(const QModelIndex &index, int role) const; - QVariant headerData(int section, Qt::Orientation orientation, - int role = Qt::DisplayRole) const; - bool setData(const QModelIndex &index, const QVariant &value, - int role = Qt::EditRole); - Qt::ItemFlags flags(QModelIndex const& index) const; - boost::optional map_layer(int i); + Q_OBJECT + public: + LayerListModel(std::shared_ptr map, QObject* parent = 0); + int rowCount(const QModelIndex& parent = QModelIndex()) const; + QVariant data(const QModelIndex& index, int role) const; + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; + bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole); + Qt::ItemFlags flags(QModelIndex const& index) const; + boost::optional map_layer(int i); - private: - std::shared_ptr map_; + private: + std::shared_ptr map_; }; -#endif //LAYER_LIST_MODEL_HPP +#endif // LAYER_LIST_MODEL_HPP diff --git a/demo/viewer/layerwidget.cpp b/demo/viewer/layerwidget.cpp index 5733f1e63..c23cc05fb 100644 --- a/demo/viewer/layerwidget.cpp +++ b/demo/viewer/layerwidget.cpp @@ -17,7 +17,6 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ - #include "layerwidget.hpp" #include #include @@ -33,65 +32,59 @@ #include "layer_info_dialog.hpp" LayerTab::LayerTab(QWidget* parent) - : QListView(parent) {} + : QListView(parent) +{} - -void LayerTab::paintEvent(QPaintEvent *e) +void LayerTab::paintEvent(QPaintEvent* e) { QListView::paintEvent(e); } -void LayerTab::dataChanged(const QModelIndex &topLeft, - const QModelIndex &bottomRight, - const QVector &roles) +void LayerTab::dataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight, const QVector& roles) { emit update_mapwidget(); QListView::dataChanged(topLeft, bottomRight, roles); } -void LayerTab::selectionChanged(const QItemSelection & selected, const QItemSelection &) +void LayerTab::selectionChanged(const QItemSelection& selected, const QItemSelection&) { - QModelIndexList list = selected.indexes(); - if (list.size() != 0) - { - qDebug("SELECTED LAYER -> %d",list[0].row()); - emit layerSelected(list[0].row()); - } + QModelIndexList list = selected.indexes(); + if (list.size() != 0) + { + qDebug("SELECTED LAYER -> %d", list[0].row()); + emit layerSelected(list[0].row()); + } } void LayerTab::layerInfo() { - qDebug("Layer info"); - QModelIndexList indexes = selectedIndexes(); - if (indexes.size() > 0) - { - qDebug("id = %d",indexes[0].row()); - - } + qDebug("Layer info"); + QModelIndexList indexes = selectedIndexes(); + if (indexes.size() > 0) + { + qDebug("id = %d", indexes[0].row()); + } } void LayerTab::layerInfo2(QModelIndex const& index) { - qDebug("LayerInfo id = %d",index.row()); - QVector > params; - QVector style_names; - unsigned i = index.row(); - LayerListModel * model = static_cast(this->model()); - boost::optional layer = model->map_layer(i); + qDebug("LayerInfo id = %d", index.row()); + QVector> params; + QVector style_names; + unsigned i = index.row(); + LayerListModel* model = static_cast(this->model()); + boost::optional layer = model->map_layer(i); - if (layer) - { - layer_info_dialog dlg(*layer,this); - dlg.exec(); - } + if (layer) + { + layer_info_dialog dlg(*layer, this); + dlg.exec(); + } } -StyleTab::StyleTab(QWidget*) +StyleTab::StyleTab(QWidget*) {} + +void StyleTab::contextMenuEvent(QContextMenuEvent* event) { - -} - -void StyleTab::contextMenuEvent(QContextMenuEvent * event ) -{ - qDebug("test"); + qDebug("test"); } diff --git a/demo/viewer/layerwidget.hpp b/demo/viewer/layerwidget.hpp index 6761d79a4..854020443 100644 --- a/demo/viewer/layerwidget.hpp +++ b/demo/viewer/layerwidget.hpp @@ -17,7 +17,6 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ - #ifndef LAYERWIDGET_HPP #define LAYERWIDGET_HPP @@ -28,27 +27,28 @@ class LayerTab : public QListView { Q_OBJECT -public: - LayerTab(QWidget* parent=0); - void paintEvent(QPaintEvent *e); -signals: + public: + LayerTab(QWidget* parent = 0); + void paintEvent(QPaintEvent* e); + signals: void update_mapwidget(); void layerSelected(int) const; -public slots: + public slots: void layerInfo(); void layerInfo2(QModelIndex const&); -protected slots: - void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector &roles); - void selectionChanged(const QItemSelection & selected, const QItemSelection &); + protected slots: + void dataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight, const QVector& roles); + void selectionChanged(const QItemSelection& selected, const QItemSelection&); }; class StyleTab : public QTreeView { Q_OBJECT -public: - StyleTab(QWidget* parent=0); -protected: - void contextMenuEvent(QContextMenuEvent * event ); + public: + StyleTab(QWidget* parent = 0); + + protected: + void contextMenuEvent(QContextMenuEvent* event); }; #endif diff --git a/demo/viewer/main.cpp b/demo/viewer/main.cpp index ef840cca6..09e90fac3 100644 --- a/demo/viewer/main.cpp +++ b/demo/viewer/main.cpp @@ -17,7 +17,6 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ - // qt #include #include @@ -26,27 +25,26 @@ #include #include "mainwindow.hpp" -int main( int argc, char **argv ) +int main(int argc, char** argv) { using mapnik::datasource_cache; using mapnik::freetype_engine; try { -#if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0) +#if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0) QApplication::setAttribute(Qt::AA_EnableHighDpiScaling); -#endif +#endif QCoreApplication::setOrganizationName("Mapnik"); QCoreApplication::setOrganizationDomain("mapnik.org"); QCoreApplication::setApplicationName("Viewer"); - QSettings settings("viewer.ini",QSettings::IniFormat); + QSettings settings("viewer.ini", QSettings::IniFormat); // register input plug-ins - QString plugins_dir = settings.value("mapnik/plugins_dir", - QVariant("/usr/local/lib/mapnik/input/")).toString(); + QString plugins_dir = settings.value("mapnik/plugins_dir", QVariant("/usr/local/lib/mapnik/input/")).toString(); datasource_cache::instance().register_datasources(plugins_dir.toStdString()); // register fonts int count = settings.beginReadArray("mapnik/fonts"); - for (int index=0; index < count; ++index) + for (int index = 0; index < count; ++index) { settings.setArrayIndex(index); QString font_dir = settings.value("dir").toString(); @@ -54,37 +52,40 @@ int main( int argc, char **argv ) } settings.endArray(); - QApplication app( argc, argv ); + QApplication app(argc, argv); MainWindow window; window.show(); - if (argc > 1) window.open(argv[1]); + if (argc > 1) + window.open(argv[1]); if (argc >= 3) { QStringList list = QString(argv[2]).split(","); - if (list.size()==4) + if (list.size() == 4) { bool ok; double x0 = list[0].toDouble(&ok); double y0 = list[1].toDouble(&ok); double x1 = list[2].toDouble(&ok); double y1 = list[3].toDouble(&ok); - if (ok) window.set_default_extent(x0,y0,x1,y1); + if (ok) + window.set_default_extent(x0, y0, x1, y1); } } else { std::shared_ptr map = window.get_map(); - if (map) map->zoom_all(); + if (map) + map->zoom_all(); } if (argc == 4) { bool ok; double scaling_factor = QString(argv[3]).toDouble(&ok); - if (ok) window.set_scaling_factor(scaling_factor); + if (ok) + window.set_scaling_factor(scaling_factor); } return app.exec(); - } - catch (std::exception const& ex) + } catch (std::exception const& ex) { std::cerr << "Could not start viewer: '" << ex.what() << "'\n"; return 1; diff --git a/demo/viewer/mainwindow.cpp b/demo/viewer/mainwindow.cpp index 338180f66..9253a25fa 100644 --- a/demo/viewer/mainwindow.cpp +++ b/demo/viewer/mainwindow.cpp @@ -17,7 +17,6 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ - // stl #include @@ -58,27 +57,27 @@ #include MainWindow::MainWindow() - : filename_(), - default_extent_(-20037508.3428,-20037508.3428,20037508.3428,20037508.3428) + : filename_() + , default_extent_(-20037508.3428, -20037508.3428, 20037508.3428, 20037508.3428) { mapWidget_ = new MapWidget(this); - QSplitter *splitter = new QSplitter(this); - QTabWidget *tabWidget=new QTabWidget; + QSplitter* splitter = new QSplitter(this); + QTabWidget* tabWidget = new QTabWidget; layerTab_ = new LayerTab; layerTab_->setFocusPolicy(Qt::NoFocus); - layerTab_->setIconSize(QSize(16,16)); + layerTab_->setIconSize(QSize(16, 16)); - //LayerDelegate *delegate = new LayerDelegate(this); - //layerTab_->setItemDelegate(delegate); - //layerTab_->setItemDelegate(new QItemDelegate(this)); - //layerTab_->setViewMode(QListView::IconMode); + // LayerDelegate *delegate = new LayerDelegate(this); + // layerTab_->setItemDelegate(delegate); + // layerTab_->setItemDelegate(new QItemDelegate(this)); + // layerTab_->setViewMode(QListView::IconMode); layerTab_->setFlow(QListView::TopToBottom); - tabWidget->addTab(layerTab_,tr("Layers")); + tabWidget->addTab(layerTab_, tr("Layers")); // Styles tab styleTab_ = new StyleTab; - tabWidget->addTab(styleTab_,tr("Styles")); + tabWidget->addTab(styleTab_, tr("Styles")); splitter->addWidget(tabWidget); splitter->addWidget(mapWidget_); QList list; @@ -89,7 +88,7 @@ MainWindow::MainWindow() mapWidget_->setFocusPolicy(Qt::StrongFocus); mapWidget_->setFocus(); - //setCentralWidget(mapWidget_); + // setCentralWidget(mapWidget_); setCentralWidget(splitter); createActions(); createMenus(); @@ -97,29 +96,28 @@ MainWindow::MainWindow() createContextMenu(); setWindowTitle(tr("Mapnik Viewer")); - status=new QStatusBar(this); + status = new QStatusBar(this); status->showMessage(tr("")); setStatusBar(status); - resize(800,600); + resize(800, 600); - //connect mapview to layerlist - connect(mapWidget_, SIGNAL(mapViewChanged()),layerTab_, SLOT(update())); + // connect mapview to layerlist + connect(mapWidget_, SIGNAL(mapViewChanged()), layerTab_, SLOT(update())); // slider - connect(slider_,SIGNAL(valueChanged(int)),mapWidget_,SLOT(zoomToLevel(int))); + connect(slider_, SIGNAL(valueChanged(int)), mapWidget_, SLOT(zoomToLevel(int))); // renderer selector - connect(renderer_selector_,SIGNAL(currentIndexChanged(QString const&)), - mapWidget_, SLOT(updateRenderer(QString const&))); + connect(renderer_selector_, + SIGNAL(currentIndexChanged(QString const&)), + mapWidget_, + SLOT(updateRenderer(QString const&))); // scale factor - connect(scale_factor_,SIGNAL(valueChanged(double)), - mapWidget_, SLOT(updateScaleFactor(double))); + connect(scale_factor_, SIGNAL(valueChanged(double)), mapWidget_, SLOT(updateScaleFactor(double))); // - connect(layerTab_,SIGNAL(update_mapwidget()),mapWidget_,SLOT(updateMap())); - connect(layerTab_,SIGNAL(layerSelected(int)), - mapWidget_,SLOT(layerSelected(int))); + connect(layerTab_, SIGNAL(update_mapwidget()), mapWidget_, SLOT(updateMap())); + connect(layerTab_, SIGNAL(layerSelected(int)), mapWidget_, SLOT(layerSelected(int))); } - MainWindow::~MainWindow() { delete mapWidget_; @@ -141,8 +139,7 @@ void MainWindow::open(QString const& path) { if (path.isNull()) { - filename_ = QFileDialog::getOpenFileName(this,tr("Open Mapnik file"), - currentPath,"*.xml"); + filename_ = QFileDialog::getOpenFileName(this, tr("Open Mapnik file"), currentPath, "*.xml"); } else { @@ -151,18 +148,15 @@ void MainWindow::open(QString const& path) if (!filename_.isEmpty()) { - load_map_file(filename_); setWindowTitle(tr("%1 - Mapnik Viewer").arg(filename_)); } - } void MainWindow::reload() { if (!filename_.isEmpty()) { - mapnik::box2d bbox = mapWidget_->getMap()->get_current_extent(); load_map_file(filename_); mapWidget_->zoomToBox(bbox); @@ -173,39 +167,37 @@ void MainWindow::reload() void MainWindow::save() { QString initialPath = QDir::currentPath() + "/untitled.xml"; - QString filename = QFileDialog::getSaveFileName(this, tr("Save"), + QString filename = QFileDialog::getSaveFileName(this, + tr("Save"), initialPath, - tr("%1 Files (*.xml)") - .arg(QString("Mapnik definition"))); + tr("%1 Files (*.xml)").arg(QString("Mapnik definition"))); if (!filename.isEmpty()) { - std::cout<<"saving "<< filename.toStdString() << std::endl; - mapnik::save_map(*mapWidget_->getMap(),filename.toStdString()); + std::cout << "saving " << filename.toStdString() << std::endl; + mapnik::save_map(*mapWidget_->getMap(), filename.toStdString()); } } void MainWindow::load_map_file(QString const& filename) { - std::cout << "loading "<< filename.toStdString() << std::endl; + std::cout << "loading " << filename.toStdString() << std::endl; unsigned width = mapWidget_->width(); unsigned height = mapWidget_->height(); - std::shared_ptr map(new mapnik::Map(width,height)); + std::shared_ptr map(new mapnik::Map(width, height)); mapWidget_->setMap(map); try { mapnik::auto_cpu_timer t(std::clog, "loading map took: "); - mapnik::load_map(*map,filename.toStdString()); - } - catch (std::exception const& ex) + mapnik::load_map(*map, filename.toStdString()); + } catch (std::exception const& ex) { std::cout << ex.what() << "\n"; - } - catch (...) + } catch (...) { std::cerr << "Exception caught in load_map\n"; } - layerTab_->setModel(new LayerListModel(map,this)); - styleTab_->setModel(new StyleModel(map,this)); + layerTab_->setModel(new LayerListModel(map, this)); + styleTab_->setModel(new StyleModel(map, this)); zoom_all(); } @@ -252,15 +244,15 @@ void MainWindow::about() void MainWindow::export_as() { - QAction *action = qobject_cast(sender()); + QAction* action = qobject_cast(sender()); QByteArray fileFormat = action->data().toByteArray(); QString initialPath = QDir::currentPath() + "/map." + fileFormat; - QString fileName = QFileDialog::getSaveFileName(this, tr("Export As"), - initialPath, - tr("%1 Files (*.%2);;All Files (*)") - .arg(QString(fileFormat.toUpper())) - .arg(QString(fileFormat))); + QString fileName = QFileDialog::getSaveFileName( + this, + tr("Export As"), + initialPath, + tr("%1 Files (*.%2);;All Files (*)").arg(QString(fileFormat.toUpper())).arg(QString(fileFormat))); if (!fileName.isEmpty()) { QPixmap const& pix = mapWidget_->pixmap(); @@ -270,77 +262,76 @@ void MainWindow::export_as() void MainWindow::print() { - - //Q_ASSERT(mapWidget_->pixmap()); - //QPrintDialog dialog(&printer, this); - //if (dialog.exec()) { - // QPainter painter(&printer); - // QRect rect = painter.viewport(); - // QSize size = mapWidget_->pixmap()->size(); - // size.scale(rect.size(), Qt::KeepAspectRatio); - // painter.setViewport(rect.x(), rect.y(), size.width(), size.height()); - // painter.setWindow(mapWidget_->pixmap()->rect()); - // painter.drawPixmap(0, 0, *mapWidget_->pixmap()); - //} + // Q_ASSERT(mapWidget_->pixmap()); + // QPrintDialog dialog(&printer, this); + // if (dialog.exec()) { + // QPainter painter(&printer); + // QRect rect = painter.viewport(); + // QSize size = mapWidget_->pixmap()->size(); + // size.scale(rect.size(), Qt::KeepAspectRatio); + // painter.setViewport(rect.x(), rect.y(), size.width(), size.height()); + // painter.setWindow(mapWidget_->pixmap()->rect()); + // painter.drawPixmap(0, 0, *mapWidget_->pixmap()); + // } } void MainWindow::createActions() { - //exportAct = new QAction(tr("&Export as ..."),this); - //exportAct->setShortcut(tr("Ctrl+E")); - //connect(exportAct, SIGNAL(triggered()), this, SLOT(export_as())); - zoomAllAct = new QAction(QIcon(":/images/home.png"),tr("Zoom All"),this); + // exportAct = new QAction(tr("&Export as ..."),this); + // exportAct->setShortcut(tr("Ctrl+E")); + // connect(exportAct, SIGNAL(triggered()), this, SLOT(export_as())); + zoomAllAct = new QAction(QIcon(":/images/home.png"), tr("Zoom All"), this); connect(zoomAllAct, SIGNAL(triggered()), this, SLOT(zoom_all())); - zoomBoxAct = new QAction(QIcon(":/images/zoombox.png"),tr("Zoom To Box"),this); + zoomBoxAct = new QAction(QIcon(":/images/zoombox.png"), tr("Zoom To Box"), this); zoomBoxAct->setCheckable(true); connect(zoomBoxAct, SIGNAL(triggered()), this, SLOT(zoom_to_box())); - panAct = new QAction(QIcon(":/images/pan.png"),tr("Pan"),this); + panAct = new QAction(QIcon(":/images/pan.png"), tr("Pan"), this); panAct->setCheckable(true); connect(panAct, SIGNAL(triggered()), this, SLOT(pan())); - infoAct = new QAction(QIcon(":/images/info.png"),tr("Info"),this); + infoAct = new QAction(QIcon(":/images/info.png"), tr("Info"), this); infoAct->setCheckable(true); connect(infoAct, SIGNAL(triggered()), this, SLOT(info())); - toolsGroup=new QActionGroup(this); + toolsGroup = new QActionGroup(this); toolsGroup->addAction(zoomBoxAct); toolsGroup->addAction(panAct); toolsGroup->addAction(infoAct); zoomBoxAct->setChecked(true); - openAct=new QAction(tr("Open Map definition"),this); - connect(openAct,SIGNAL(triggered()),this,SLOT(open())); - saveAct=new QAction(tr("Save Map definition"),this); - connect(saveAct,SIGNAL(triggered()),this,SLOT(save())); + openAct = new QAction(tr("Open Map definition"), this); + connect(openAct, SIGNAL(triggered()), this, SLOT(open())); + saveAct = new QAction(tr("Save Map definition"), this); + connect(saveAct, SIGNAL(triggered()), this, SLOT(save())); - panLeftAct = new QAction(QIcon(":/images/left.png"),tr("&Pan Left"),this); + panLeftAct = new QAction(QIcon(":/images/left.png"), tr("&Pan Left"), this); connect(panLeftAct, SIGNAL(triggered()), this, SLOT(pan_left())); - panRightAct = new QAction(QIcon(":/images/right.png"),tr("&Pan Right"),this); + panRightAct = new QAction(QIcon(":/images/right.png"), tr("&Pan Right"), this); connect(panRightAct, SIGNAL(triggered()), this, SLOT(pan_right())); - panUpAct = new QAction(QIcon(":/images/up.png"),tr("&Pan Up"),this); + panUpAct = new QAction(QIcon(":/images/up.png"), tr("&Pan Up"), this); connect(panUpAct, SIGNAL(triggered()), this, SLOT(pan_up())); - panDownAct = new QAction(QIcon(":/images/down.png"),tr("&Pan Down"),this); + panDownAct = new QAction(QIcon(":/images/down.png"), tr("&Pan Down"), this); connect(panDownAct, SIGNAL(triggered()), this, SLOT(pan_down())); - reloadAct = new QAction(QIcon(":/images/reload.png"),tr("Reload"),this); + reloadAct = new QAction(QIcon(":/images/reload.png"), tr("Reload"), this); connect(reloadAct, SIGNAL(triggered()), this, SLOT(reload())); - layerInfo = new QAction(QIcon(":/images/info.png"),tr("&Layer info"),layerTab_); - connect(layerInfo, SIGNAL(triggered()), layerTab_,SLOT(layerInfo())); - connect(layerTab_, SIGNAL(doubleClicked(QModelIndex const&)), layerTab_,SLOT(layerInfo2(QModelIndex const&))); + layerInfo = new QAction(QIcon(":/images/info.png"), tr("&Layer info"), layerTab_); + connect(layerInfo, SIGNAL(triggered()), layerTab_, SLOT(layerInfo())); + connect(layerTab_, SIGNAL(doubleClicked(QModelIndex const&)), layerTab_, SLOT(layerInfo2(QModelIndex const&))); foreach (QByteArray format, QImageWriter::supportedImageFormats()) { QString text = tr("%1...").arg(QString(format).toUpper()); - QAction *action = new QAction(text, this); + QAction* action = new QAction(text, this); action->setData(format); connect(action, SIGNAL(triggered()), this, SLOT(export_as())); exportAsActs.append(action); } - printAct = new QAction(QIcon(":/images/print.png"),tr("&Print ..."),this); + printAct = new QAction(QIcon(":/images/print.png"), tr("&Print ..."), this); printAct->setShortcut(tr("Ctrl+E")); connect(printAct, SIGNAL(triggered()), this, SLOT(print())); @@ -348,17 +339,17 @@ void MainWindow::createActions() exitAct->setShortcut(tr("Ctrl+Q")); connect(exitAct, SIGNAL(triggered()), this, SLOT(close())); - aboutAct = new QAction(QIcon(":/images/about.png"),tr("&About"), this); + aboutAct = new QAction(QIcon(":/images/about.png"), tr("&About"), this); connect(aboutAct, SIGNAL(triggered()), this, SLOT(about())); } void MainWindow::createMenus() { exportMenu = new QMenu(tr("&Export As"), this); - foreach (QAction *action, exportAsActs) + foreach (QAction* action, exportAsActs) exportMenu->addAction(action); - fileMenu = new QMenu(tr("&File"),this); + fileMenu = new QMenu(tr("&File"), this); fileMenu->addAction(openAct); fileMenu->addAction(saveAct); fileMenu->addMenu(exportMenu); @@ -402,8 +393,8 @@ void MainWindow::createToolBars() scale_factor_->setValue(1.0); fileToolBar->addWidget(scale_factor_); - slider_ = new QSlider(Qt::Horizontal,fileToolBar); - slider_->setRange(1,18); + slider_ = new QSlider(Qt::Horizontal, fileToolBar); + slider_->setRange(1, 18); slider_->setTickPosition(QSlider::TicksBelow); slider_->setTickInterval(1); slider_->setTracking(false); @@ -411,9 +402,7 @@ void MainWindow::createToolBars() fileToolBar->addAction(aboutAct); } - - -void MainWindow::set_default_extent(double x0,double y0, double x1, double y1) +void MainWindow::set_default_extent(double x0, double y0, double x1, double y1) { try { @@ -423,12 +412,12 @@ void MainWindow::set_default_extent(double x0,double y0, double x1, double y1) mapnik::projection prj(map_ptr->srs()); prj.forward(x0, y0); prj.forward(x1, y1); - default_extent_=mapnik::box2d(x0, y0, x1, y1); + default_extent_ = mapnik::box2d(x0, y0, x1, y1); mapWidget_->zoomToBox(default_extent_); std::cout << "SET DEFAULT EXT:" << default_extent_ << std::endl; } - } - catch (...) {} + } catch (...) + {} } void MainWindow::set_scaling_factor(double scaling_factor) diff --git a/demo/viewer/mainwindow.hpp b/demo/viewer/mainwindow.hpp index 4926d5ff0..62e17994a 100644 --- a/demo/viewer/mainwindow.hpp +++ b/demo/viewer/mainwindow.hpp @@ -17,7 +17,6 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ - #ifndef MAINWINDOW_HPP #define MAINWINDOW_HPP @@ -30,7 +29,7 @@ #include "mapwidget.hpp" -//using namespace mapnik; +// using namespace mapnik; class LayerTab; class StyleTab; @@ -41,22 +40,24 @@ class QDoubleSpinBox; class MainWindow : public QMainWindow { Q_OBJECT - public: + public: MainWindow(); virtual ~MainWindow(); - void set_default_extent(double x0,double y0,double x1, double y1); + void set_default_extent(double x0, double y0, double x1, double y1); void set_scaling_factor(double scaling_factor); -public : + + public: std::shared_ptr get_map(); -protected: + + protected: void closeEvent(QCloseEvent* event); -public slots: + public slots: void zoom_all(); void zoom_to_box(); void pan(); void info(); void export_as(); - void open(QString const& path = QString()); + void open(QString const& path = QString()); void reload(); void save(); void print(); @@ -65,7 +66,8 @@ public slots: void pan_right(); void pan_up(); void pan_down(); -private: + + private: void createActions(); void createMenus(); void createToolBars(); @@ -74,43 +76,42 @@ private: QString currentPath; QString filename_; - QAbstractItemModel *model; - LayerTab *layerTab_; - StyleTab * styleTab_; - MapWidget * mapWidget_; - //actions - QList exportAsActs; - QActionGroup *toolsGroup; + QAbstractItemModel* model; + LayerTab* layerTab_; + StyleTab* styleTab_; + MapWidget* mapWidget_; + // actions + QList exportAsActs; + QActionGroup* toolsGroup; - QAction *zoomAllAct; - QAction *zoomBoxAct; - QAction *panAct; - QAction *infoAct; - QAction *openAct; - QAction *saveAct; - QAction *printAct; - QAction *exitAct; - QAction *aboutAct; - QAction *panLeftAct; - QAction *panRightAct; - QAction *panUpAct; - QAction *panDownAct; - QAction *reloadAct; - QAction *layerInfo; - //toolbars - QToolBar *fileToolBar; - QToolBar *editToolBar; - //menus - QMenu *exportMenu; - QMenu *fileMenu; - QMenu *helpMenu; - //status bar - QStatusBar *status; - QSlider * slider_; - QComboBox * renderer_selector_; - QDoubleSpinBox * scale_factor_; + QAction* zoomAllAct; + QAction* zoomBoxAct; + QAction* panAct; + QAction* infoAct; + QAction* openAct; + QAction* saveAct; + QAction* printAct; + QAction* exitAct; + QAction* aboutAct; + QAction* panLeftAct; + QAction* panRightAct; + QAction* panUpAct; + QAction* panDownAct; + QAction* reloadAct; + QAction* layerInfo; + // toolbars + QToolBar* fileToolBar; + QToolBar* editToolBar; + // menus + QMenu* exportMenu; + QMenu* fileMenu; + QMenu* helpMenu; + // status bar + QStatusBar* status; + QSlider* slider_; + QComboBox* renderer_selector_; + QDoubleSpinBox* scale_factor_; mapnik::box2d default_extent_; }; - -#endif //MAINWINDOW_HPP +#endif // MAINWINDOW_HPP diff --git a/demo/viewer/mapwidget.cpp b/demo/viewer/mapwidget.cpp index 81579e373..ba3e1c000 100644 --- a/demo/viewer/mapwidget.cpp +++ b/demo/viewer/mapwidget.cpp @@ -17,7 +17,6 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ - #include #include @@ -41,153 +40,139 @@ #include "mapwidget.hpp" #include "info_dialog.hpp" -using mapnik::image_rgba8; -using mapnik::Map; -using mapnik::layer; using mapnik::box2d; using mapnik::coord2d; +using mapnik::feature_kv_iterator; using mapnik::feature_ptr; -using mapnik::view_transform; +using mapnik::image_rgba8; +using mapnik::layer; +using mapnik::Map; using mapnik::projection; using mapnik::scale_denominator; -using mapnik::feature_kv_iterator; +using mapnik::view_transform; -double scales [] = {279541132.014, - 139770566.007, - 69885283.0036, - 34942641.5018, - 17471320.7509, - 8735660.37545, - 4367830.18772, - 2183915.09386, - 1091957.54693, - 545978.773466, - 272989.386733, - 136494.693366, - 68247.3466832, - 34123.6733416, - 17061.8366708, - 8530.9183354, - 4265.4591677, - 2132.72958385, - 1066.36479192, - 533.182395962}; +double scales[] = {279541132.014, 139770566.007, 69885283.0036, 34942641.5018, 17471320.7509, + 8735660.37545, 4367830.18772, 2183915.09386, 1091957.54693, 545978.773466, + 272989.386733, 136494.693366, 68247.3466832, 34123.6733416, 17061.8366708, + 8530.9183354, 4265.4591677, 2132.72958385, 1066.36479192, 533.182395962}; -MapWidget::MapWidget(QWidget *parent) - : QWidget(parent), - map_(), - selected_(1), - extent_(), - cur_tool_(ZoomToBox), - start_x_(0), - start_y_(0), - end_x_(0), - end_y_(0), - drag_(false), - first_(true), - pen_(QColor(0,0,255,96)), - selectedLayer_(-1), - scaling_factor_(1.0), - cur_renderer_(AGG) +MapWidget::MapWidget(QWidget* parent) + : QWidget(parent) + , map_() + , selected_(1) + , extent_() + , cur_tool_(ZoomToBox) + , start_x_(0) + , start_y_(0) + , end_x_(0) + , end_y_(0) + , drag_(false) + , first_(true) + , pen_(QColor(0, 0, 255, 96)) + , selectedLayer_(-1) + , scaling_factor_(1.0) + , cur_renderer_(AGG) { - pen_.setWidth(3); - pen_.setCapStyle(Qt::RoundCap); - pen_.setJoinStyle(Qt::RoundJoin); + pen_.setWidth(3); + pen_.setCapStyle(Qt::RoundCap); + pen_.setJoinStyle(Qt::RoundJoin); } void MapWidget::setTool(eTool tool) { - cur_tool_=tool; + cur_tool_ = tool; } void MapWidget::paintEvent(QPaintEvent*) { - QPainter painter(this); + QPainter painter(this); - if (drag_) - { - if (cur_tool_ == ZoomToBox) - { - unsigned width = end_x_-start_x_; - unsigned height = end_y_-start_y_; - painter.drawPixmap(QPoint(0, 0),pix_); - painter.setPen(pen_); - painter.setBrush(QColor(200,200,255,128)); - painter.drawRect(start_x_,start_y_,width,height); - } - else if (cur_tool_ == Pan) - { - int dx = end_x_-start_x_; - int dy = end_y_-start_y_; - painter.setBrush(QColor(200,200,200,128)); - painter.drawRect(0,0,width(),height()); - painter.drawPixmap(QPoint(dx,dy),pix_); - } - } - else - { - painter.drawPixmap(QPoint(0, 0),pix_); - } - painter.end(); + if (drag_) + { + if (cur_tool_ == ZoomToBox) + { + unsigned width = end_x_ - start_x_; + unsigned height = end_y_ - start_y_; + painter.drawPixmap(QPoint(0, 0), pix_); + painter.setPen(pen_); + painter.setBrush(QColor(200, 200, 255, 128)); + painter.drawRect(start_x_, start_y_, width, height); + } + else if (cur_tool_ == Pan) + { + int dx = end_x_ - start_x_; + int dy = end_y_ - start_y_; + painter.setBrush(QColor(200, 200, 200, 128)); + painter.drawRect(0, 0, width(), height()); + painter.drawPixmap(QPoint(dx, dy), pix_); + } + } + else + { + painter.drawPixmap(QPoint(0, 0), pix_); + } + painter.end(); } -void MapWidget::resizeEvent(QResizeEvent * ev) +void MapWidget::resizeEvent(QResizeEvent* ev) { - if (map_) - { - map_->resize(ev->size().width(),ev->size().height()); - updateMap(); - } + if (map_) + { + map_->resize(ev->size().width(), ev->size().height()); + updateMap(); + } } void MapWidget::mousePressEvent(QMouseEvent* e) { - if (e->button()==Qt::LeftButton) - { - if (cur_tool_ == ZoomToBox || cur_tool_==Pan) - { - start_x_ = e->x(); - start_y_ = e->y(); - drag_=true; - } - else if (cur_tool_==Info) - { - if (map_) - { - QVector > info; - - projection map_proj(map_->srs(), true); // map projection - double scale_denom = scale_denominator(map_->scale(),map_proj.is_geographic()); - view_transform t(map_->width(),map_->height(),map_->get_current_extent()); - - for (unsigned index = 0; index < map_->layer_count();++index) + if (e->button() == Qt::LeftButton) + { + if (cur_tool_ == ZoomToBox || cur_tool_ == Pan) + { + start_x_ = e->x(); + start_y_ = e->y(); + drag_ = true; + } + else if (cur_tool_ == Info) + { + if (map_) { - if (int(index) != selectedLayer_) continue; + QVector> info; - layer & layer = map_->layers()[index]; - if (!layer.visible(scale_denom)) continue; - std::string name = layer.name(); - double x = e->x(); - double y = e->y(); - std::cout << "query at " << x << "," << y << "\n"; - projection layer_proj(layer.srs(), true); - mapnik::proj_transform prj_trans(map_proj,layer_proj); - //std::auto_ptr data(new mapnik::memory_datasource); - mapnik::featureset_ptr fs = map_->query_map_point(index,x,y); + projection map_proj(map_->srs(), true); // map projection + double scale_denom = scale_denominator(map_->scale(), map_proj.is_geographic()); + view_transform t(map_->width(), map_->height(), map_->get_current_extent()); - if (fs) - { - feature_ptr feat = fs->next(); - if (feat) - { - feature_kv_iterator itr(*feat,true); - feature_kv_iterator end(*feat); + for (unsigned index = 0; index < map_->layer_count(); ++index) + { + if (int(index) != selectedLayer_) + continue; - for ( ;itr!=end; ++itr) - { - info.push_back(QPair(QString(std::get<0>(*itr).c_str()), - std::get<1>(*itr).to_string().c_str())); - } + layer& layer = map_->layers()[index]; + if (!layer.visible(scale_denom)) + continue; + std::string name = layer.name(); + double x = e->x(); + double y = e->y(); + std::cout << "query at " << x << "," << y << "\n"; + projection layer_proj(layer.srs(), true); + mapnik::proj_transform prj_trans(map_proj, layer_proj); + // std::auto_ptr data(new mapnik::memory_datasource); + mapnik::featureset_ptr fs = map_->query_map_point(index, x, y); + + if (fs) + { + feature_ptr feat = fs->next(); + if (feat) + { + feature_kv_iterator itr(*feat, true); + feature_kv_iterator end(*feat); + + for (; itr != end; ++itr) + { + info.push_back(QPair(QString(std::get<0>(*itr).c_str()), + std::get<1>(*itr).to_string().c_str())); + } #if 0 // using path_type = mapnik::transform_path_adapter; @@ -219,288 +204,285 @@ void MapWidget::mousePressEvent(QMouseEvent* e) } } #endif - } - } + } + } - if (info.size() > 0) - { - info_dialog info_dlg(info,this); - info_dlg.exec(); - break; - } + if (info.size() > 0) + { + info_dialog info_dlg(info, this); + info_dlg.exec(); + break; + } + } + + // remove annotation layer + map_->layers().erase( + remove_if(map_->layers().begin(), map_->layers().end(), bind(&layer::name, _1) == "*annotations*"), + map_->layers().end()); } - - // remove annotation layer - map_->layers().erase(remove_if(map_->layers().begin(), - map_->layers().end(), - bind(&layer::name,_1) == "*annotations*") - , map_->layers().end()); - } - } - } - else if (e->button()==Qt::RightButton) - { - //updateMap(); - } + } + } + else if (e->button() == Qt::RightButton) + { + // updateMap(); + } } void MapWidget::mouseMoveEvent(QMouseEvent* e) { - if (cur_tool_ == ZoomToBox || cur_tool_==Pan) - { - end_x_ = e->x(); - end_y_ = e->y(); - update(); - } + if (cur_tool_ == ZoomToBox || cur_tool_ == Pan) + { + end_x_ = e->x(); + end_y_ = e->y(); + update(); + } } void MapWidget::mouseReleaseEvent(QMouseEvent* e) { - if (e->button()==Qt::LeftButton) - { - end_x_ = e->x(); - end_y_ = e->y(); - if (cur_tool_ == ZoomToBox) - { - drag_=false; - if (map_) - { - view_transform t(map_->width(),map_->height(),map_->get_current_extent()); - box2d box = t.backward(box2d(start_x_,start_y_,end_x_,end_y_)); - map_->zoom_to_box(box); - updateMap(); - } - } - else if (cur_tool_==Pan) - { - drag_=false; - if (map_) - { - int cx = int(0.5 * map_->width()); - int cy = int(0.5 * map_->height()); - int dx = end_x_ - start_x_; - int dy = end_y_ - start_y_; - map_->pan(cx - dx ,cy - dy); - updateMap(); - } - } - } + if (e->button() == Qt::LeftButton) + { + end_x_ = e->x(); + end_y_ = e->y(); + if (cur_tool_ == ZoomToBox) + { + drag_ = false; + if (map_) + { + view_transform t(map_->width(), map_->height(), map_->get_current_extent()); + box2d box = t.backward(box2d(start_x_, start_y_, end_x_, end_y_)); + map_->zoom_to_box(box); + updateMap(); + } + } + else if (cur_tool_ == Pan) + { + drag_ = false; + if (map_) + { + int cx = int(0.5 * map_->width()); + int cy = int(0.5 * map_->height()); + int dx = end_x_ - start_x_; + int dy = end_y_ - start_y_; + map_->pan(cx - dx, cy - dy); + updateMap(); + } + } + } } void MapWidget::wheelEvent(QWheelEvent* e) { - if (!map_) - { - return; - } -#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) - QPointF corner(map_->width(), map_->height()); - QPointF zoomCoords; - double zoom; - if (e->angleDelta().y() > 0) - { - zoom = 0.5; - QPointF center = corner / 2; - QPointF delta = e->position() - center; - zoomCoords = zoom * delta + center; - } - else - { - zoom = 2.0; - zoomCoords = corner - e->position(); - } + if (!map_) + { + return; + } +#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) + QPointF corner(map_->width(), map_->height()); + QPointF zoomCoords; + double zoom; + if (e->angleDelta().y() > 0) + { + zoom = 0.5; + QPointF center = corner / 2; + QPointF delta = e->position() - center; + zoomCoords = zoom * delta + center; + } + else + { + zoom = 2.0; + zoomCoords = corner - e->position(); + } #else - QPoint corner(map_->width(), map_->height()); - QPoint zoomCoords; - double zoom; - if (e->delta() > 0) - { - zoom = 0.5; - QPoint center = corner / 2; - QPoint delta = e->pos() - center; - zoomCoords = zoom * delta + center; - } - else - { - zoom = 2.0; - zoomCoords = corner - e->pos(); - } + QPoint corner(map_->width(), map_->height()); + QPoint zoomCoords; + double zoom; + if (e->delta() > 0) + { + zoom = 0.5; + QPoint center = corner / 2; + QPoint delta = e->pos() - center; + zoomCoords = zoom * delta + center; + } + else + { + zoom = 2.0; + zoomCoords = corner - e->pos(); + } #endif - map_->pan_and_zoom(zoomCoords.x(), zoomCoords.y(), zoom); - updateMap(); + map_->pan_and_zoom(zoomCoords.x(), zoomCoords.y(), zoom); + updateMap(); } -void MapWidget::keyPressEvent(QKeyEvent *e) +void MapWidget::keyPressEvent(QKeyEvent* e) { - std::cout << "key pressed:"<< e->key()<<"\n"; - switch (e->key()) { - case Qt::Key_Minus: - zoomOut(); - break; - case Qt::Key_Plus: - case 61: - zoomIn(); - break; - case 65: - defaultView(); - break; - case Qt::Key_Up: - panUp(); - break; - case Qt::Key_Down: - panDown(); - break; - case Qt::Key_Left: - panLeft(); - break; - case Qt::Key_Right: - panRight(); - break; - case 49: - zoomToLevel(10); - break; - case 50: - zoomToLevel(11); - break; - case 51: - zoomToLevel(12); - break; - case 52: - zoomToLevel(13); - break; - case 53: - zoomToLevel(14); - break; - case 54: - zoomToLevel(15); - break; - case 55: - zoomToLevel(16); - break; - case 56: - zoomToLevel(17); - break; - case 57: - zoomToLevel(18); - break; - default: - QWidget::keyPressEvent(e); - } - - + std::cout << "key pressed:" << e->key() << "\n"; + switch (e->key()) + { + case Qt::Key_Minus: + zoomOut(); + break; + case Qt::Key_Plus: + case 61: + zoomIn(); + break; + case 65: + defaultView(); + break; + case Qt::Key_Up: + panUp(); + break; + case Qt::Key_Down: + panDown(); + break; + case Qt::Key_Left: + panLeft(); + break; + case Qt::Key_Right: + panRight(); + break; + case 49: + zoomToLevel(10); + break; + case 50: + zoomToLevel(11); + break; + case 51: + zoomToLevel(12); + break; + case 52: + zoomToLevel(13); + break; + case 53: + zoomToLevel(14); + break; + case 54: + zoomToLevel(15); + break; + case 55: + zoomToLevel(16); + break; + case 56: + zoomToLevel(17); + break; + case 57: + zoomToLevel(18); + break; + default: + QWidget::keyPressEvent(e); + } } void MapWidget::zoomToBox(mapnik::box2d const& bbox) { - if (map_) - { - map_->zoom_to_box(bbox); - updateMap(); - } + if (map_) + { + map_->zoom_to_box(bbox); + updateMap(); + } } void MapWidget::defaultView() { - if (map_) - { - map_->resize(width(),height()); - map_->zoom_all(); - updateMap(); - } + if (map_) + { + map_->resize(width(), height()); + map_->zoom_all(); + updateMap(); + } } void MapWidget::zoomIn() { - if (map_) - { - map_->zoom(0.5); - updateMap(); - } + if (map_) + { + map_->zoom(0.5); + updateMap(); + } } void MapWidget::zoomOut() { - if (map_) - { - map_->zoom(2.0); - updateMap(); - } + if (map_) + { + map_->zoom(2.0); + updateMap(); + } } void MapWidget::panUp() { - if (map_) - { - double cx = 0.5*map_->width(); - double cy = 0.5*map_->height(); - map_->pan(int(cx),int(cy - cy*0.25)); - updateMap(); - } + if (map_) + { + double cx = 0.5 * map_->width(); + double cy = 0.5 * map_->height(); + map_->pan(int(cx), int(cy - cy * 0.25)); + updateMap(); + } } void MapWidget::panDown() { - if (map_) - { - double cx = 0.5*map_->width(); - double cy = 0.5*map_->height(); - map_->pan(int(cx),int(cy + cy*0.25)); - updateMap(); - } + if (map_) + { + double cx = 0.5 * map_->width(); + double cy = 0.5 * map_->height(); + map_->pan(int(cx), int(cy + cy * 0.25)); + updateMap(); + } } void MapWidget::panLeft() { - if (map_) - { - double cx = 0.5*map_->width(); - double cy = 0.5*map_->height(); - map_->pan(int(cx - cx * 0.25),int(cy)); - updateMap(); - } + if (map_) + { + double cx = 0.5 * map_->width(); + double cy = 0.5 * map_->height(); + map_->pan(int(cx - cx * 0.25), int(cy)); + updateMap(); + } } void MapWidget::panRight() { - if (map_) - { - double cx = 0.5*map_->width(); - double cy = 0.5*map_->height(); - map_->pan(int(cx + cx * 0.25),int(cy)); - updateMap(); - } + if (map_) + { + double cx = 0.5 * map_->width(); + double cy = 0.5 * map_->height(); + map_->pan(int(cx + cx * 0.25), int(cy)); + updateMap(); + } } - void MapWidget::zoomToLevel(int level) { - if ( map_ && level >= 0 && level < 19 ) - { - double scale_denom = scales[level]; - std::cerr << "scale denominator = " << scale_denom << "\n"; - mapnik::box2d ext = map_->get_current_extent(); - double width = static_cast(map_->width()); - double height= static_cast(map_->height()); - mapnik::coord2d pt = ext.center(); + if (map_ && level >= 0 && level < 19) + { + double scale_denom = scales[level]; + std::cerr << "scale denominator = " << scale_denom << "\n"; + mapnik::box2d ext = map_->get_current_extent(); + double width = static_cast(map_->width()); + double height = static_cast(map_->height()); + mapnik::coord2d pt = ext.center(); - double res = scale_denom * 0.00028; + double res = scale_denom * 0.00028; - mapnik::box2d box(pt.x - 0.5 * width * res, - pt.y - 0.5 * height*res, - pt.x + 0.5 * width * res, - pt.y + 0.5 * height*res); - map_->zoom_to_box(box); - updateMap(); - } + mapnik::box2d box(pt.x - 0.5 * width * res, + pt.y - 0.5 * height * res, + pt.x + 0.5 * width * res, + pt.y + 0.5 * height * res); + map_->zoom_to_box(box); + updateMap(); + } } -void MapWidget::export_to_file(unsigned ,unsigned ,std::string const&,std::string const&) +void MapWidget::export_to_file(unsigned, unsigned, std::string const&, std::string const&) { - //image_rgba8 image(width,height); - //agg_renderer renderer(map,image); - //renderer.apply(); - //image.saveToFile(filename,type); + // image_rgba8 image(width,height); + // agg_renderer renderer(map,image); + // renderer.apply(); + // image.saveToFile(filename,type); std::cout << "Export to file .." << std::endl; } @@ -509,47 +491,44 @@ void MapWidget::set_scaling_factor(double scaling_factor) scaling_factor_ = scaling_factor; } -void render_agg(mapnik::Map const& map, double scaling_factor, QPixmap & pix) +void render_agg(mapnik::Map const& map, double scaling_factor, QPixmap& pix) { - unsigned width=map.width(); - unsigned height=map.height(); + unsigned width = map.width(); + unsigned height = map.height(); - image_rgba8 buf(width,height); - mapnik::agg_renderer ren(map,buf,scaling_factor); + image_rgba8 buf(width, height); + mapnik::agg_renderer ren(map, buf, scaling_factor); try { mapnik::auto_cpu_timer t(std::clog, "rendering took: "); ren.apply(); - QImage image((uchar*)buf.data(),width,height,QImage::Format_ARGB32); + QImage image((uchar*)buf.data(), width, height, QImage::Format_ARGB32); pix = QPixmap::fromImage(image.rgbSwapped()); } - //catch (mapnik::config_error & ex) + // catch (mapnik::config_error & ex) //{ - // std::cerr << ex.what() << std::endl; - //} + // std::cerr << ex.what() << std::endl; + // } catch (std::exception const& ex) { std::cerr << "exception: " << ex.what() << std::endl; - } - catch (...) + } catch (...) { std::cerr << "Unknown exception caught!\n"; } } - -void render_grid(mapnik::Map const& map, double scaling_factor, QPixmap & pix) +void render_grid(mapnik::Map const& map, double scaling_factor, QPixmap& pix) { std::cerr << "Not supported" << std::endl; } - -void render_cairo(mapnik::Map const& map, double scaling_factor, QPixmap & pix) +void render_cairo(mapnik::Map const& map, double scaling_factor, QPixmap& pix) { // FIXME #ifdef HAVE_CAIRO - mapnik::cairo_surface_ptr image_surface(cairo_image_surface_create(CAIRO_FORMAT_ARGB32,map.width(),map.height()), + mapnik::cairo_surface_ptr image_surface(cairo_image_surface_create(CAIRO_FORMAT_ARGB32, map.width(), map.height()), mapnik::cairo_surface_closer()); mapnik::cairo_ptr cairo = mapnik::create_context(image_surface); if (cairo) @@ -560,16 +539,19 @@ void render_cairo(mapnik::Map const& map, double scaling_factor, QPixmap & pix) } mapnik::image_rgba8 data(map.width(), map.height()); mapnik::cairo_image_to_rgba8(data, image_surface); - QImage image((uchar*)data.bytes(),data.width(),data.height(),QImage::Format_ARGB32); + QImage image((uchar*)data.bytes(), data.width(), data.height(), QImage::Format_ARGB32); pix = QPixmap::fromImage(image.rgbSwapped()); #endif } void MapWidget::updateRenderer(QString const& txt) { - if (txt == "AGG") cur_renderer_ = AGG; - else if (txt == "Cairo") cur_renderer_ = Cairo; - else if (txt == "Grid") cur_renderer_ = Grid; + if (txt == "AGG") + cur_renderer_ = AGG; + else if (txt == "Cairo") + cur_renderer_ = Cairo; + else if (txt == "Grid") + cur_renderer_ = Grid; std::cerr << "Update renderer called" << std::endl; updateMap(); } @@ -582,50 +564,49 @@ void MapWidget::updateScaleFactor(double scale_factor) void MapWidget::updateMap() { - if (map_) - { - if (cur_renderer_== AGG) - { - render_agg(*map_, scaling_factor_, pix_); - } - else if (cur_renderer_ == Cairo) - { - render_cairo(*map_, scaling_factor_, pix_); - } - else if (cur_renderer_ == Grid) - { - render_grid(*map_, scaling_factor_, pix_); - } - else - { - std::cerr << "Unknown renderer..." << std::endl; - } + if (map_) + { + if (cur_renderer_ == AGG) + { + render_agg(*map_, scaling_factor_, pix_); + } + else if (cur_renderer_ == Cairo) + { + render_cairo(*map_, scaling_factor_, pix_); + } + else if (cur_renderer_ == Grid) + { + render_grid(*map_, scaling_factor_, pix_); + } + else + { + std::cerr << "Unknown renderer..." << std::endl; + } - try - { - projection prj(map_->srs(), true); // map projection - box2d ext = map_->get_current_extent(); - double x0 = ext.minx(); - double y0 = ext.miny(); - double x1 = ext.maxx(); - double y1 = ext.maxy(); - double z = 0; - std::string dest_srs = {"epsg:4326"}; - mapnik::proj_transform proj_tr(map_->srs(), dest_srs); + try + { + projection prj(map_->srs(), true); // map projection + box2d ext = map_->get_current_extent(); + double x0 = ext.minx(); + double y0 = ext.miny(); + double x1 = ext.maxx(); + double y1 = ext.maxy(); + double z = 0; + std::string dest_srs = {"epsg:4326"}; + mapnik::proj_transform proj_tr(map_->srs(), dest_srs); - proj_tr.forward(x0, y0, z); - proj_tr.forward(x1, y1, z); - std::cout << "MAP SIZE:" << map_->width() << "," << map_->height() << std::endl; - std::cout << "BBOX (WGS84): " << x0 << "," << y0 << "," << x1 << "," << y1 << "\n"; - update(); - // emit signal to interested widgets - emit mapViewChanged(); - } - catch (...) - { - std::cerr << "Unknown exception caught!\n"; - } - } + proj_tr.forward(x0, y0, z); + proj_tr.forward(x1, y1, z); + std::cout << "MAP SIZE:" << map_->width() << "," << map_->height() << std::endl; + std::cout << "BBOX (WGS84): " << x0 << "," << y0 << "," << x1 << "," << y1 << "\n"; + update(); + // emit signal to interested widgets + emit mapViewChanged(); + } catch (...) + { + std::cerr << "Unknown exception caught!\n"; + } + } } std::shared_ptr MapWidget::getMap() @@ -638,7 +619,6 @@ void MapWidget::setMap(std::shared_ptr map) map_ = map; } - void MapWidget::layerSelected(int index) { selectedLayer_ = index; diff --git a/demo/viewer/mapwidget.hpp b/demo/viewer/mapwidget.hpp index db192a8ee..4f6748f71 100644 --- a/demo/viewer/mapwidget.hpp +++ b/demo/viewer/mapwidget.hpp @@ -17,7 +17,6 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ - #ifndef MAP_WIDGET_HPP #define MAP_WIDGET_HPP @@ -30,7 +29,6 @@ #include #include - #ifndef Q_MOC_RUN #include #endif @@ -39,22 +37,16 @@ class MapWidget : public QWidget { Q_OBJECT -public: - enum eTool - { + public: + enum eTool { ZoomToBox = 1, Pan, Info, }; - enum eRenderer - { - AGG, - Cairo, - Grid - }; + enum eRenderer { AGG, Cairo, Grid }; -private: + private: std::shared_ptr map_; int selected_; QPixmap pix_; @@ -70,11 +62,12 @@ private: int selectedLayer_; double scaling_factor_; eRenderer cur_renderer_; -public: - MapWidget(QWidget *parent=0); + + public: + MapWidget(QWidget* parent = 0); void setTool(eTool tool); std::shared_ptr getMap(); - inline QPixmap const& pixmap() const { return pix_;} + inline QPixmap const& pixmap() const { return pix_; } void setMap(std::shared_ptr map); void defaultView(); void zoomToBox(mapnik::box2d const& box); @@ -85,26 +78,24 @@ public: void panUp(); void panDown(); void set_scaling_factor(double); -public slots: + public slots: void zoomToLevel(int level); void updateMap(); void layerSelected(int); void updateRenderer(QString const& txt); void updateScaleFactor(double scale_factor); -signals: + signals: void mapViewChanged(); -protected: + + protected: void paintEvent(QPaintEvent* ev); void resizeEvent(QResizeEvent* ev); void mousePressEvent(QMouseEvent* e); void mouseMoveEvent(QMouseEvent* e); void mouseReleaseEvent(QMouseEvent* e); void wheelEvent(QWheelEvent* e); - void keyPressEvent(QKeyEvent *e); - void export_to_file(unsigned width, - unsigned height, - std::string const& filename, - std::string const& type); + void keyPressEvent(QKeyEvent* e); + void export_to_file(unsigned width, unsigned height, std::string const& filename, std::string const& type); }; #endif // MAP_WIDGET_HPP diff --git a/demo/viewer/styles_model.cpp b/demo/viewer/styles_model.cpp index 5eef82032..101152682 100644 --- a/demo/viewer/styles_model.cpp +++ b/demo/viewer/styles_model.cpp @@ -17,7 +17,6 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ - #include "styles_model.hpp" #include #include @@ -39,70 +38,50 @@ class node : private mapnik::util::noncopyable { struct node_base { - virtual QString name() const=0; - virtual QIcon icon() const=0; + virtual QString name() const = 0; + virtual QIcon icon() const = 0; virtual ~node_base() {} }; - template + template struct wrap : public node_base { - wrap(T const& obj) - : obj_(obj) {} + wrap(T const& obj) + : obj_(obj) + {} - ~wrap() {} + ~wrap() {} - QString name () const - { - return obj_.name(); - } + QString name() const { return obj_.name(); } - QIcon icon() const - { - return obj_.icon(); - } + QIcon icon() const { return obj_.icon(); } - T obj_; + T obj_; }; -public: - template - node ( T const& obj, node * parent=0) - : impl_(new wrap(obj)), - parent_(parent) + public: + template + node(T const& obj, node* parent = 0) + : impl_(new wrap(obj)) + , parent_(parent) {} - QString name() const - { - return impl_->name(); - } + QString name() const { return impl_->name(); } - QIcon icon() const - { - return impl_->icon(); - } + QIcon icon() const { return impl_->icon(); } - unsigned num_children() const - { - return children_.count(); - } + unsigned num_children() const { return children_.count(); } - node * child(unsigned row) const - { - return children_.value(row); - } + node* child(unsigned row) const { return children_.value(row); } - node * parent() const - { - return parent_; - } + node* parent() const { return parent_; } - node * add_child(node * child) + node* add_child(node* child) { children_.push_back(child); return child; } - int row () const + int row() const { if (parent_) return parent_->children_.indexOf(const_cast(this)); @@ -110,94 +89,90 @@ public: return 0; } - ~node() - { - qDeleteAll(children_); - } + ~node() { qDeleteAll(children_); } -private: + private: const std::unique_ptr impl_; QList children_; - node * parent_; + node* parent_; }; - struct symbolizer_info { - QString operator() (mapnik::point_symbolizer const& sym) const + QString operator()(mapnik::point_symbolizer const& sym) const { boost::ignore_unused_variable_warning(sym); return QString("PointSymbolizer"); } - QString operator() (mapnik::line_symbolizer const& sym) const + QString operator()(mapnik::line_symbolizer const& sym) const { boost::ignore_unused_variable_warning(sym); return QString("LineSymbolizer"); } - QString operator() (mapnik::line_pattern_symbolizer const& sym) const + QString operator()(mapnik::line_pattern_symbolizer const& sym) const { boost::ignore_unused_variable_warning(sym); return QString("LinePatternSymbolizer"); } - QString operator() (mapnik::polygon_symbolizer const& sym) const + QString operator()(mapnik::polygon_symbolizer const& sym) const { boost::ignore_unused_variable_warning(sym); return QString("PolygonSymbolizer"); } - QString operator() (mapnik::polygon_pattern_symbolizer const& sym) const + QString operator()(mapnik::polygon_pattern_symbolizer const& sym) const { boost::ignore_unused_variable_warning(sym); return QString("PolygonSymbolizer"); } - QString operator() (mapnik::text_symbolizer const& sym) const + QString operator()(mapnik::text_symbolizer const& sym) const { boost::ignore_unused_variable_warning(sym); return QString("TextSymbolizer"); } - QString operator() (mapnik::shield_symbolizer const& sym) const + QString operator()(mapnik::shield_symbolizer const& sym) const { boost::ignore_unused_variable_warning(sym); return QString("ShieldSymbolizer"); } - QString operator() (mapnik::markers_symbolizer const& sym) const + QString operator()(mapnik::markers_symbolizer const& sym) const { boost::ignore_unused_variable_warning(sym); return QString("MarkersSymbolizer"); } - QString operator() (mapnik::building_symbolizer const& sym) const + QString operator()(mapnik::building_symbolizer const& sym) const { boost::ignore_unused_variable_warning(sym); return QString("BuildingSymbolizer"); } - template - QString operator() (T const& ) const + template + QString operator()(T const&) const { - return QString ("FIXME"); + return QString("FIXME"); } }; struct symbolizer_icon { - QIcon operator() (mapnik::polygon_symbolizer const& sym) const + QIcon operator()(mapnik::polygon_symbolizer const& sym) const { - QPixmap pix(16,16); + QPixmap pix(16, 16); QPainter painter(&pix); mapnik::color const& fill = mapnik::get(sym, mapnik::keys::fill); - QBrush brush(QColor(fill.red(),fill.green(),fill.blue(),fill.alpha())); + QBrush brush(QColor(fill.red(), fill.green(), fill.blue(), fill.alpha())); painter.fillRect(0, 0, 16, 16, brush); return QIcon(pix); } - QIcon operator() (mapnik::point_symbolizer const& sym) const + QIcon operator()(mapnik::point_symbolizer const& sym) const { // FIXME! /* @@ -212,55 +187,57 @@ struct symbolizer_icon */ return QIcon(); } - QIcon operator() (mapnik::line_symbolizer const& sym) const + QIcon operator()(mapnik::line_symbolizer const& sym) const { - QPixmap pix(48,16); + QPixmap pix(48, 16); pix.fill(); QPainter painter(&pix); - //mapnik::stroke const& strk = sym.get_stroke(); + // mapnik::stroke const& strk = sym.get_stroke(); mapnik::color const& col = mapnik::get(sym, mapnik::keys::stroke); - QPen pen(QColor(col.red(),col.green(),col.blue(),col.alpha())); + QPen pen(QColor(col.red(), col.green(), col.blue(), col.alpha())); pen.setWidth(mapnik::get(sym, mapnik::keys::width)); painter.setPen(pen); - painter.drawLine(0,7,47,7); - //painter.drawLine(7,15,12,0); - //painter.drawLine(12,0,8,15); + painter.drawLine(0, 7, 47, 7); + // painter.drawLine(7,15,12,0); + // painter.drawLine(12,0,8,15); return QIcon(pix); } - template - QIcon operator() (T const& ) const + template + QIcon operator()(T const&) const { - return QIcon (":/images/filter.png"); + return QIcon(":/images/filter.png"); } }; class symbolizer_node { -public: - symbolizer_node(mapnik::symbolizer const & sym) - : sym_(sym) {} - ~symbolizer_node(){} + public: + symbolizer_node(mapnik::symbolizer const& sym) + : sym_(sym) + {} + ~symbolizer_node() {} QString name() const { - //return QString("Symbolizer:fixme"); - return mapnik::util::apply_visitor(symbolizer_info(),sym_); + // return QString("Symbolizer:fixme"); + return mapnik::util::apply_visitor(symbolizer_info(), sym_); } QIcon icon() const { - return mapnik::util::apply_visitor(symbolizer_icon(),sym_);//QIcon(":/images/filter.png"); + return mapnik::util::apply_visitor(symbolizer_icon(), sym_); // QIcon(":/images/filter.png"); } mapnik::symbolizer const& sym_; }; class rule_node { -public: - rule_node(QString name,mapnik::rule const & r) - : name_(name), - rule_(r) {} + public: + rule_node(QString name, mapnik::rule const& r) + : name_(name) + , rule_(r) + {} ~rule_node() {} QString name() const { @@ -268,81 +245,68 @@ public: return QString(mapnik::to_expression_string(*filter).c_str()); } - QIcon icon() const - { - return QIcon(":/images/filter.png"); - } + QIcon icon() const { return QIcon(":/images/filter.png"); } -private: + private: QString name_; mapnik::rule const& rule_; }; class style_node { -public: + public: style_node(QString name, mapnik::feature_type_style const& style) - : name_(name), - style_(style) {} + : name_(name) + , style_(style) + {} ~style_node() {} - QString name() const - { - return name_; - } + QString name() const { return name_; } - QIcon icon() const - { - return QIcon(":/images/style.png"); - } + QIcon icon() const { return QIcon(":/images/style.png"); } -private: + private: QString name_; mapnik::feature_type_style const& style_; }; class map_node { -public: + public: explicit map_node(std::shared_ptr map) - : map_(map) {} + : map_(map) + {} ~map_node() {} - QString name() const - { - return QString("Map"); - } + QString name() const { return QString("Map"); } - QIcon icon() const - { - return QIcon(":/images/map.png"); - } + QIcon icon() const { return QIcon(":/images/map.png"); } -private: + private: std::shared_ptr map_; }; -StyleModel::StyleModel(std::shared_ptr map, QObject * parent) - : QAbstractItemModel(parent), - root_(new node(map_node(map))) +StyleModel::StyleModel(std::shared_ptr map, QObject* parent) + : QAbstractItemModel(parent) + , root_(new node(map_node(map))) { - using style_type = std::map; - style_type const & styles = map->styles(); + using style_type = std::map; + style_type const& styles = map->styles(); style_type::const_iterator itr = styles.begin(); style_type::const_iterator end = styles.end(); for (; itr != end; ++itr) { - node * style_n = root_->add_child(new node(style_node(QString(itr->first.c_str()),itr->second),root_.get())); + node* style_n = root_->add_child(new node(style_node(QString(itr->first.c_str()), itr->second), root_.get())); mapnik::rules const& rules = itr->second.get_rules(); mapnik::rules::const_iterator itr2 = rules.begin(); - for ( ; itr2 != rules.end();++itr2) + for (; itr2 != rules.end(); ++itr2) { - node* rule_n = style_n->add_child(new node(rule_node(QString("Rule"),*itr2),style_n)); + node* rule_n = style_n->add_child(new node(rule_node(QString("Rule"), *itr2), style_n)); mapnik::rule::symbolizers::const_iterator itr3 = (*itr2).begin(); - for ( ; itr3 !=itr2->end();++itr3) + for (; itr3 != itr2->end(); ++itr3) { - rule_n->add_child(new node(symbolizer_node(*itr3),rule_n)); + rule_n->add_child(new node(symbolizer_node(*itr3), rule_n)); } } } @@ -351,38 +315,39 @@ StyleModel::StyleModel(std::shared_ptr map, QObject * parent) StyleModel::~StyleModel() {} // interface -QModelIndex StyleModel::index (int row, int col, QModelIndex const& parent) const +QModelIndex StyleModel::index(int row, int col, QModelIndex const& parent) const { -// qDebug("index() row=%d col=%d parent::internalId() = %lld", row,col,parent.internalId()); - node * parent_node; + // qDebug("index() row=%d col=%d parent::internalId() = %lld", row,col,parent.internalId()); + node* parent_node; if (!parent.isValid()) parent_node = root_.get(); else parent_node = static_cast(parent.internalPointer()); - node * child_node = parent_node->child(row); + node* child_node = parent_node->child(row); if (child_node) - return createIndex(row,col,child_node); + return createIndex(row, col, child_node); else return QModelIndex(); } -QModelIndex StyleModel::parent (QModelIndex const& index) const +QModelIndex StyleModel::parent(QModelIndex const& index) const { - node * child_node = static_cast(index.internalPointer()); - node * parent_node = child_node->parent(); + node* child_node = static_cast(index.internalPointer()); + node* parent_node = child_node->parent(); if (parent_node == root_.get()) return QModelIndex(); - return createIndex(parent_node->row(),0,parent_node); + return createIndex(parent_node->row(), 0, parent_node); } int StyleModel::rowCount(QModelIndex const& parent) const { - //qDebug("rowCount"); - node * parent_node; - if (parent.column() > 0) return 0; + // qDebug("rowCount"); + node* parent_node; + if (parent.column() > 0) + return 0; if (!parent.isValid()) parent_node = root_.get(); else @@ -390,25 +355,24 @@ int StyleModel::rowCount(QModelIndex const& parent) const return parent_node->num_children(); } -int StyleModel::columnCount( QModelIndex const&) const +int StyleModel::columnCount(QModelIndex const&) const { return 1; } -QVariant StyleModel::data(const QModelIndex & index, int role) const +QVariant StyleModel::data(const QModelIndex& index, int role) const { - //qDebug("data index::internalId() = %lld", index.internalId()); + // qDebug("data index::internalId() = %lld", index.internalId()); if (!index.isValid()) return QVariant(); - node * cur_node = static_cast(index.internalPointer()); + node* cur_node = static_cast(index.internalPointer()); if (cur_node) { if (role == Qt::DisplayRole) { - return QVariant(cur_node->name()); } - else if ( role == Qt::DecorationRole) + else if (role == Qt::DecorationRole) { return cur_node->icon(); } diff --git a/demo/viewer/styles_model.hpp b/demo/viewer/styles_model.hpp index 13a86d3e1..c22435071 100644 --- a/demo/viewer/styles_model.hpp +++ b/demo/viewer/styles_model.hpp @@ -17,7 +17,6 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ - #ifndef STYLE_MODEL_HPP #define STYLE_MODEL_HPP @@ -27,24 +26,23 @@ #include #endif - - class node; class StyleModel : public QAbstractItemModel { - Q_OBJECT + Q_OBJECT public: - StyleModel(std::shared_ptr map, QObject * parent=0); - ~StyleModel(); - // interface - QModelIndex index (int row, int col, QModelIndex const& parent = QModelIndex()) const; - QModelIndex parent (QModelIndex const& child) const; - int rowCount( QModelIndex const& parent = QModelIndex()) const; - int columnCount( QModelIndex const& parent = QModelIndex()) const; - QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const; - private: - //std::shared_ptr map_; - const std::unique_ptr root_; + StyleModel(std::shared_ptr map, QObject* parent = 0); + ~StyleModel(); + // interface + QModelIndex index(int row, int col, QModelIndex const& parent = QModelIndex()) const; + QModelIndex parent(QModelIndex const& child) const; + int rowCount(QModelIndex const& parent = QModelIndex()) const; + int columnCount(QModelIndex const& parent = QModelIndex()) const; + QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const; + + private: + // std::shared_ptr map_; + const std::unique_ptr root_; }; #endif // STYLE_MODEL_HPP diff --git a/include/mapnik/adaptive_smooth.hpp b/include/mapnik/adaptive_smooth.hpp index 274f42891..0f5748f3c 100644 --- a/include/mapnik/adaptive_smooth.hpp +++ b/include/mapnik/adaptive_smooth.hpp @@ -9,8 +9,7 @@ MAPNIK_DISABLE_WARNING_PUSH #include "agg_conv_smooth_poly1.h" MAPNIK_DISABLE_WARNING_POP -namespace mapnik -{ +namespace mapnik { struct vcgen_smooth_calucate_adaptive { @@ -57,12 +56,8 @@ struct vcgen_smooth_calucate_adaptive } } - return { - {v1.x + s1 * smooth_value * (v2.x - xm1), - v1.y + s1 * smooth_value * (v2.y - ym1)}, - {v2.x + s2 * smooth_value * (v1.x - xm2), - v2.y + s2 * smooth_value * (v1.y - ym2)} - }; + return {{v1.x + s1 * smooth_value * (v2.x - xm1), v1.y + s1 * smooth_value * (v2.y - ym1)}, + {v2.x + s2 * smooth_value * (v1.x - xm2), v2.y + s2 * smooth_value * (v1.y - ym2)}}; } }; @@ -71,7 +66,7 @@ using vcgen_smooth_adaptive = agg::vcgen_smooth; template using conv_smooth_adaptive = agg::conv_smooth_curve; -template +template class smooth_converter { Geometry geom_; @@ -81,9 +76,9 @@ class smooth_converter using impl_type = util::variant; impl_type impl_; - impl_type init_impl(smooth_algorithm_enum algo, Geometry & geom) const + impl_type init_impl(smooth_algorithm_enum algo, Geometry& geom) const { - switch(algo) + switch (algo) { case SMOOTH_ALGORITHM_ADAPTIVE: return adaptive_impl_type(geom); @@ -94,46 +89,35 @@ class smooth_converter return basic_impl_type(geom); } -public: - smooth_converter(Geometry & geom) : - geom_(geom), - impl_(std::move(init_impl(SMOOTH_ALGORITHM_BASIC, geom))) + public: + smooth_converter(Geometry& geom) + : geom_(geom) + , impl_(std::move(init_impl(SMOOTH_ALGORITHM_BASIC, geom))) {} - void algorithm(smooth_algorithm_enum algo) - { - impl_ = init_impl(algo, geom_); - } + void algorithm(smooth_algorithm_enum algo) { impl_ = init_impl(algo, geom_); } void smooth_value(double v) { - return util::apply_visitor([=](auto & impl) { - impl.smooth_value(v); - }, impl_); + return util::apply_visitor([=](auto& impl) { impl.smooth_value(v); }, impl_); } void rewind(unsigned path_id) { - return util::apply_visitor([=](auto & impl) { - return impl.rewind(path_id); - }, impl_); + return util::apply_visitor([=](auto& impl) { return impl.rewind(path_id); }, impl_); } unsigned vertex(double* x, double* y) { - return util::apply_visitor([=](auto & impl) { - return impl.vertex(x, y); - }, impl_); + return util::apply_visitor([=](auto& impl) { return impl.vertex(x, y); }, impl_); } unsigned type() const { - return util::apply_visitor([](auto const& impl) { - return impl.type(); - }, impl_); + return util::apply_visitor([](auto const& impl) { return impl.type(); }, impl_); } }; -} +} // namespace mapnik #endif // MAPNIK_ADAPTIVE_SMOOTH_HPP diff --git a/include/mapnik/agg/render_polygon_pattern.hpp b/include/mapnik/agg/render_polygon_pattern.hpp index b33b8a03e..4a5c2c051 100644 --- a/include/mapnik/agg/render_polygon_pattern.hpp +++ b/include/mapnik/agg/render_polygon_pattern.hpp @@ -69,7 +69,7 @@ struct agg_pattern_base } }; -template +template struct agg_polygon_pattern : agg_pattern_base { using color_type = agg::rgba8; @@ -78,41 +78,40 @@ struct agg_polygon_pattern : agg_pattern_base using pixfmt_type = agg::pixfmt_custom_blend_rgba; using wrap_x_type = agg::wrap_mode_repeat; using wrap_y_type = agg::wrap_mode_repeat; - using img_source_type = agg::image_accessor_wrap; + using img_source_type = agg::image_accessor_wrap; using span_gen_type = agg::span_pattern_rgba; using renderer_base = agg::renderer_base; - using renderer_type = agg::renderer_scanline_aa_alpha, - span_gen_type>; + using renderer_type = + agg::renderer_scanline_aa_alpha, span_gen_type>; agg_polygon_pattern(image_rgba8 const& pattern_img, renderer_common const& common, symbolizer_base const& sym, mapnik::feature_impl const& feature, proj_transform const& prj_trans) - : agg_pattern_base{pattern_img, common, sym, feature, prj_trans}, - clip_(get(sym_, feature_, common_.vars_)), - clip_box_(clipping_extent(common)), - tr_(geom_transform()), - converter_(clip_box_, sym, common.t_, prj_trans, tr_, - feature, common.vars_, common.scale_factor_) + : agg_pattern_base{pattern_img, common, sym, feature, prj_trans} + , clip_(get(sym_, feature_, common_.vars_)) + , clip_box_(clipping_extent(common)) + , tr_(geom_transform()) + , converter_(clip_box_, sym, common.t_, prj_trans, tr_, feature, common.vars_, common.scale_factor_) { value_double simplify_tolerance = get(sym_, feature_, common_.vars_); value_double smooth = get(sym_, feature_, common_.vars_); - if (simplify_tolerance > 0.0) converter_.template set(); + if (simplify_tolerance > 0.0) + converter_.template set(); converter_.template set(); - if (smooth > 0.0) converter_.template set(); + if (smooth > 0.0) + converter_.template set(); } - void render(renderer_base & ren_base, rasterizer & ras) + void render(renderer_base& ren_base, rasterizer& ras) { - coord offset(pattern_offset(sym_, feature_, prj_trans_, common_, - pattern_img_.width(), pattern_img_.height())); + coord offset( + pattern_offset(sym_, feature_, prj_trans_, common_, pattern_img_.width(), pattern_img_.height())); agg::rendering_buffer pattern_rbuf((agg::int8u*)pattern_img_.bytes(), - pattern_img_.width(), pattern_img_.height(), + pattern_img_.width(), + pattern_img_.height(), pattern_img_.width() * 4); agg::pixfmt_rgba32_pre pixf_pattern(pattern_rbuf); img_source_type img_src(pixf_pattern); @@ -122,8 +121,7 @@ struct agg_polygon_pattern : agg_pattern_base value_double opacity = get(sym_, feature_, common_.vars_); renderer_type rp(ren_base, sa, sg, unsigned(opacity * 255)); - using apply_vertex_converter_type = detail::apply_vertex_converter< - VertexConverter, rasterizer>; + using apply_vertex_converter_type = detail::apply_vertex_converter; using vertex_processor_type = geometry::vertex_processor; apply_vertex_converter_type apply(converter_, ras); mapnik::util::apply_visitor(vertex_processor_type(apply), feature_.get_geometry()); @@ -139,5 +137,4 @@ struct agg_polygon_pattern : agg_pattern_base } // namespace mapnik - #endif // MAPNIK_RENDER_POLYGON_PATTERN_HPP diff --git a/include/mapnik/agg_helpers.hpp b/include/mapnik/agg_helpers.hpp index bc5c938ab..00a419287 100644 --- a/include/mapnik/agg_helpers.hpp +++ b/include/mapnik/agg_helpers.hpp @@ -34,31 +34,31 @@ MAPNIK_DISABLE_WARNING_POP namespace mapnik { -template -void set_gamma_method(T & ras_ptr, double gamma, gamma_method_enum method) +template +void set_gamma_method(T& ras_ptr, double gamma, gamma_method_enum method) { switch (method) { - case GAMMA_POWER: - ras_ptr->gamma(agg::gamma_power(gamma)); - break; - case GAMMA_LINEAR: - ras_ptr->gamma(agg::gamma_linear(0.0, gamma)); - break; - case GAMMA_NONE: - ras_ptr->gamma(agg::gamma_none()); - break; - case GAMMA_THRESHOLD: - ras_ptr->gamma(agg::gamma_threshold(gamma)); - break; - case GAMMA_MULTIPLY: - ras_ptr->gamma(agg::gamma_multiply(gamma)); - break; - default: - ras_ptr->gamma(agg::gamma_power(gamma)); + case GAMMA_POWER: + ras_ptr->gamma(agg::gamma_power(gamma)); + break; + case GAMMA_LINEAR: + ras_ptr->gamma(agg::gamma_linear(0.0, gamma)); + break; + case GAMMA_NONE: + ras_ptr->gamma(agg::gamma_none()); + break; + case GAMMA_THRESHOLD: + ras_ptr->gamma(agg::gamma_threshold(gamma)); + break; + case GAMMA_MULTIPLY: + ras_ptr->gamma(agg::gamma_multiply(gamma)); + break; + default: + ras_ptr->gamma(agg::gamma_power(gamma)); } } -} +} // namespace mapnik #endif // MAPNIK_AGG_HELPERS_HPP diff --git a/include/mapnik/agg_pattern_source.hpp b/include/mapnik/agg_pattern_source.hpp index 4eb8a0647..097fe5312 100644 --- a/include/mapnik/agg_pattern_source.hpp +++ b/include/mapnik/agg_pattern_source.hpp @@ -33,36 +33,31 @@ MAPNIK_DISABLE_WARNING_PUSH #include "agg_color_rgba.h" MAPNIK_DISABLE_WARNING_POP -namespace mapnik -{ +namespace mapnik { class pattern_source : private util::noncopyable { -public: + public: pattern_source(image_rgba8 const& pattern, double opacity = 1.0) - : pattern_(pattern), - opacity_(opacity) {} + : pattern_(pattern) + , opacity_(opacity) + {} - unsigned int width() const - { - return pattern_.width(); - } - unsigned int height() const - { - return pattern_.height(); - } + unsigned int width() const { return pattern_.width(); } + unsigned int height() const { return pattern_.height(); } agg::rgba8 pixel(int x, int y) const { - unsigned c = pattern_(x,y); + unsigned c = pattern_(x, y); return agg::rgba8(static_cast((c & 0xff) * opacity_), static_cast(((c >> 8) & 0xff) * opacity_), static_cast(((c >> 16) & 0xff) * opacity_), static_cast(((c >> 24) & 0xff) * opacity_)); } -private: + + private: image_rgba8 const& pattern_; double opacity_; }; -} +} // namespace mapnik #endif // MAPNIK_AGG_PATTERN_SOURCE_HPP diff --git a/include/mapnik/agg_rasterizer.hpp b/include/mapnik/agg_rasterizer.hpp index a369454e1..32cef517a 100644 --- a/include/mapnik/agg_rasterizer.hpp +++ b/include/mapnik/agg_rasterizer.hpp @@ -26,7 +26,6 @@ // mapnik #include - #include MAPNIK_DISABLE_WARNING_PUSH #include @@ -35,8 +34,10 @@ MAPNIK_DISABLE_WARNING_POP namespace mapnik { -struct rasterizer : agg::rasterizer_scanline_aa, util::noncopyable {}; +struct rasterizer : agg::rasterizer_scanline_aa, + util::noncopyable +{}; -} +} // namespace mapnik #endif // MAPNIK_AGG_RASTERIZER_HPP diff --git a/include/mapnik/agg_render_marker.hpp b/include/mapnik/agg_render_marker.hpp index a0101bebe..1be9e2da3 100644 --- a/include/mapnik/agg_render_marker.hpp +++ b/include/mapnik/agg_render_marker.hpp @@ -52,10 +52,14 @@ MAPNIK_DISABLE_WARNING_POP namespace mapnik { -template -void render_vector_marker(SvgRenderer & svg_renderer, RasterizerType & ras, RendererBaseType & renb, - box2d const& bbox, agg::trans_affine const& tr, - double opacity, bool snap_to_pixels) +template +void render_vector_marker(SvgRenderer& svg_renderer, + RasterizerType& ras, + RendererBaseType& renb, + box2d const& bbox, + agg::trans_affine const& tr, + double opacity, + bool snap_to_pixels) { agg::scanline_u8 sl; if (snap_to_pixels) @@ -72,23 +76,25 @@ void render_vector_marker(SvgRenderer & svg_renderer, RasterizerType & ras, Rend } } -template -void render_raster_marker(RendererType renb, RasterizerType & ras, image_rgba8 const& src, - agg::trans_affine const& tr, double opacity, - float scale_factor, bool snap_to_pixels) +template +void render_raster_marker(RendererType renb, + RasterizerType& ras, + image_rgba8 const& src, + agg::trans_affine const& tr, + double opacity, + float scale_factor, + bool snap_to_pixels) { using color_type = agg::rgba8; using const_rendering_buffer = util::rendering_buffer; using pixfmt_pre = agg::pixfmt_alpha_blend_rgba; agg::scanline_u8 sl; - double width = src.width(); + double width = src.width(); double height = src.height(); - if (std::fabs(1.0 - scale_factor) < 0.001 - && (std::fabs(1.0 - tr.sx) < agg::affine_epsilon) - && (std::fabs(0.0 - tr.shy) < agg::affine_epsilon) - && (std::fabs(0.0 - tr.shx) < agg::affine_epsilon) - && (std::fabs(1.0 - tr.sy) < agg::affine_epsilon)) + if (std::fabs(1.0 - scale_factor) < 0.001 && (std::fabs(1.0 - tr.sx) < agg::affine_epsilon) && + (std::fabs(0.0 - tr.shy) < agg::affine_epsilon) && (std::fabs(0.0 - tr.shx) < agg::affine_epsilon) && + (std::fabs(1.0 - tr.sy) < agg::affine_epsilon)) { const_rendering_buffer src_buffer(src); pixfmt_pre pixf_mask(src_buffer); @@ -98,32 +104,31 @@ void render_raster_marker(RendererType renb, RasterizerType & ras, image_rgba8 c 0, static_cast(std::floor(tr.tx + .5)), static_cast(std::floor(tr.ty + .5)), - unsigned(255*opacity)); + unsigned(255 * opacity)); } else { - renb.blend_from(pixf_mask, - 0, - static_cast(tr.tx), - static_cast(tr.ty), - unsigned(255*opacity)); + renb.blend_from(pixf_mask, 0, static_cast(tr.tx), static_cast(tr.ty), unsigned(255 * opacity)); } } else { using img_accessor_type = agg::image_accessor_clone; using interpolator_type = agg::span_interpolator_linear<>; - //using span_gen_type = agg::span_image_filter_rgba_2x2; + // using span_gen_type = agg::span_image_filter_rgba_2x2; using span_gen_type = agg::span_image_resample_rgba_affine; - using renderer_type = agg::renderer_scanline_aa_alpha, - span_gen_type>; + using renderer_type = + agg::renderer_scanline_aa_alpha, span_gen_type>; double p[8]; - p[0] = 0; p[1] = 0; - p[2] = width; p[3] = 0; - p[4] = width; p[5] = height; - p[6] = 0; p[7] = height; + p[0] = 0; + p[1] = 0; + p[2] = width; + p[3] = 0; + p[4] = width; + p[5] = height; + p[6] = 0; + p[7] = height; tr.transform(&p[0], &p[1]); tr.transform(&p[2], &p[3]); tr.transform(&p[4], &p[5]); @@ -137,20 +142,20 @@ void render_raster_marker(RendererType renb, RasterizerType & ras, image_rgba8 c agg::trans_affine final_tr(p, 0, 0, width, height); if (snap_to_pixels) { - final_tr.tx = std::floor(final_tr.tx+.5); - final_tr.ty = std::floor(final_tr.ty+.5); + final_tr.tx = std::floor(final_tr.tx + .5); + final_tr.ty = std::floor(final_tr.ty + .5); } interpolator_type interpolator(final_tr); span_gen_type sg(ia, interpolator, filter); - renderer_type rp(renb, sa, sg, unsigned(opacity*255)); - ras.move_to_d(p[0],p[1]); - ras.line_to_d(p[2],p[3]); - ras.line_to_d(p[4],p[5]); - ras.line_to_d(p[6],p[7]); + renderer_type rp(renb, sa, sg, unsigned(opacity * 255)); + ras.move_to_d(p[0], p[1]); + ras.line_to_d(p[2], p[3]); + ras.line_to_d(p[4], p[5]); + ras.line_to_d(p[6], p[7]); agg::render_scanlines(ras, sl, rp); } } -} +} // namespace mapnik #endif // MAPNIK_AGG_RENDER_MARKER_HPP diff --git a/include/mapnik/agg_renderer.hpp b/include/mapnik/agg_renderer.hpp index 0a60ddd6e..d73ea3e8e 100644 --- a/include/mapnik/agg_renderer.hpp +++ b/include/mapnik/agg_renderer.hpp @@ -24,13 +24,13 @@ #define MAPNIK_AGG_RENDERER_HPP // mapnik -#include // for MAPNIK_DECL +#include // for MAPNIK_DECL #include -#include // for noncopyable +#include // for noncopyable #include // for rule, symbolizers -#include // for box2d +#include // for box2d #include // for view_transform -#include // for composite_mode_e +#include // for composite_mode_e #include #include #include @@ -41,38 +41,40 @@ #include // fwd declaration to avoid dependence on agg headers -namespace agg { struct trans_affine; } +namespace agg { +struct trans_affine; +} // fwd declarations to speed up compile namespace mapnik { - class Map; - class feature_impl; - class feature_type_style; - class label_collision_detector4; - class layer; - class color; - struct marker; - class proj_transform; - struct rasterizer; - struct rgba8_t; - template class image; -} +class Map; +class feature_impl; +class feature_type_style; +class label_collision_detector4; +class layer; +class color; +struct marker; +class proj_transform; +struct rasterizer; +struct rgba8_t; +template +class image; +} // namespace mapnik namespace mapnik { -template +template class buffer_stack { -public: + public: buffer_stack(std::size_t width, std::size_t height) - : width_(width), - height_(height), - buffers_(), - position_(buffers_.begin()) - { - } + : width_(width) + , height_(height) + , buffers_() + , position_(buffers_.begin()) + {} - T & push() + T& push() { if (position_ == buffers_.begin()) { @@ -86,10 +88,7 @@ public: } return *position_; } - bool in_range() const - { - return (position_ != buffers_.end()); - } + bool in_range() const { return (position_ != buffers_.end()); } void pop() { @@ -98,34 +97,44 @@ public: ++position_; } - T & top() const - { - return *position_; - } + T& top() const { return *position_; } -private: + private: const std::size_t width_; const std::size_t height_; std::deque buffers_; typename std::deque::iterator position_; }; -template -class MAPNIK_DECL agg_renderer : public feature_style_processor >, +template +class MAPNIK_DECL agg_renderer : public feature_style_processor>, private util::noncopyable { - -public: + public: using buffer_type = T0; using processor_impl_type = agg_renderer; using detector_type = T1; // create with default, empty placement detector - agg_renderer(Map const& m, buffer_type & pixmap, double scale_factor=1.0, unsigned offset_x=0, unsigned offset_y=0); + agg_renderer(Map const& m, + buffer_type& pixmap, + double scale_factor = 1.0, + unsigned offset_x = 0, + unsigned offset_y = 0); // create with external placement detector, possibly non-empty - agg_renderer(Map const &m, buffer_type & pixmap, std::shared_ptr detector, - double scale_factor=1.0, unsigned offset_x=0, unsigned offset_y=0); + agg_renderer(Map const& m, + buffer_type& pixmap, + std::shared_ptr detector, + double scale_factor = 1.0, + unsigned offset_x = 0, + unsigned offset_y = 0); // pass in mapnik::request object to provide the mutable things per render - agg_renderer(Map const& m, request const& req, attributes const& vars, buffer_type & pixmap, double scale_factor=1.0, unsigned offset_x=0, unsigned offset_y=0); + agg_renderer(Map const& m, + request const& req, + attributes const& vars, + buffer_type& pixmap, + double scale_factor = 1.0, + unsigned offset_x = 0, + unsigned offset_y = 0); ~agg_renderer(); void start_map_processing(Map const& map); void end_map_processing(Map const& map); @@ -135,52 +144,27 @@ public: void start_style_processing(feature_type_style const& st); void end_style_processing(feature_type_style const& st); - void render_marker(pixel_position const& pos, marker const& marker, agg::trans_affine const& tr, - double opacity, composite_mode_e comp_op); + void render_marker(pixel_position const& pos, + marker const& marker, + agg::trans_affine const& tr, + double opacity, + composite_mode_e comp_op); - void process(point_symbolizer const& sym, - mapnik::feature_impl & feature, - proj_transform const& prj_trans); - void process(line_symbolizer const& sym, - mapnik::feature_impl & feature, - proj_transform const& prj_trans); - void process(line_pattern_symbolizer const& sym, - mapnik::feature_impl & feature, - proj_transform const& prj_trans); - void process(polygon_symbolizer const& sym, - mapnik::feature_impl & feature, - proj_transform const& prj_trans); - void process(polygon_pattern_symbolizer const& sym, - mapnik::feature_impl & feature, - proj_transform const& prj_trans); - void process(raster_symbolizer const& sym, - mapnik::feature_impl & feature, - proj_transform const& prj_trans); - void process(shield_symbolizer const& sym, - mapnik::feature_impl & feature, - proj_transform const& prj_trans); - void process(text_symbolizer const& sym, - mapnik::feature_impl & feature, - proj_transform const& prj_trans); - void process(building_symbolizer const& sym, - mapnik::feature_impl & feature, - proj_transform const& prj_trans); - void process(markers_symbolizer const& sym, - mapnik::feature_impl & feature, - proj_transform const& prj_trans); - void process(group_symbolizer const& sym, - mapnik::feature_impl & feature, - proj_transform const& prj_trans); - void process(debug_symbolizer const& sym, - feature_impl & feature, - proj_transform const& prj_trans); - void process(dot_symbolizer const& sym, - mapnik::feature_impl & feature, - proj_transform const& prj_trans); + void process(point_symbolizer const& sym, mapnik::feature_impl& feature, proj_transform const& prj_trans); + void process(line_symbolizer const& sym, mapnik::feature_impl& feature, proj_transform const& prj_trans); + void process(line_pattern_symbolizer const& sym, mapnik::feature_impl& feature, proj_transform const& prj_trans); + void process(polygon_symbolizer const& sym, mapnik::feature_impl& feature, proj_transform const& prj_trans); + void process(polygon_pattern_symbolizer const& sym, mapnik::feature_impl& feature, proj_transform const& prj_trans); + void process(raster_symbolizer const& sym, mapnik::feature_impl& feature, proj_transform const& prj_trans); + void process(shield_symbolizer const& sym, mapnik::feature_impl& feature, proj_transform const& prj_trans); + void process(text_symbolizer const& sym, mapnik::feature_impl& feature, proj_transform const& prj_trans); + void process(building_symbolizer const& sym, mapnik::feature_impl& feature, proj_transform const& prj_trans); + void process(markers_symbolizer const& sym, mapnik::feature_impl& feature, proj_transform const& prj_trans); + void process(group_symbolizer const& sym, mapnik::feature_impl& feature, proj_transform const& prj_trans); + void process(debug_symbolizer const& sym, feature_impl& feature, proj_transform const& prj_trans); + void process(dot_symbolizer const& sym, mapnik::feature_impl& feature, proj_transform const& prj_trans); - inline bool process(rule::symbolizers const&, - mapnik::feature_impl&, - proj_transform const& ) + inline bool process(rule::symbolizers const&, mapnik::feature_impl&, proj_transform const&) { // agg renderer doesn't support processing of multiple symbolizers. return false; @@ -189,29 +173,19 @@ public: void painted(bool painted); bool painted(); - inline eAttributeCollectionPolicy attribute_collection_policy() const - { - return DEFAULT; - } + inline eAttributeCollectionPolicy attribute_collection_policy() const { return DEFAULT; } - inline double scale_factor() const - { - return common_.scale_factor_; - } + inline double scale_factor() const { return common_.scale_factor_; } - inline attributes const& variables() const - { - return common_.vars_; - } -protected: - template - void debug_draw_box(R& buf, box2d const& extent, - double x, double y, double angle = 0.0); - void debug_draw_box(box2d const& extent, - double x, double y, double angle = 0.0); - void draw_geo_extent(box2d const& extent,mapnik::color const& color); + inline attributes const& variables() const { return common_.vars_; } -private: + protected: + template + void debug_draw_box(R& buf, box2d const& extent, double x, double y, double angle = 0.0); + void debug_draw_box(box2d const& extent, double x, double y, double angle = 0.0); + void draw_geo_extent(box2d const& extent, mapnik::color const& color); + + private: std::stack> buffers_; buffer_stack internal_buffers_; std::unique_ptr inflated_buffer_; @@ -219,7 +193,7 @@ private: gamma_method_enum gamma_method_; double gamma_; renderer_common common_; - void setup(Map const & m, buffer_type & pixmap); + void setup(Map const& m, buffer_type& pixmap); }; extern template class MAPNIK_DECL agg_renderer>; diff --git a/include/mapnik/attribute.hpp b/include/mapnik/attribute.hpp index 57db9e013..e4f036579 100644 --- a/include/mapnik/attribute.hpp +++ b/include/mapnik/attribute.hpp @@ -37,20 +37,21 @@ struct attribute { std::string name_; explicit attribute(std::string const& _name) - : name_(_name) {} + : name_(_name) + {} - template + template V const& value(F const& f) const { return f.get(name_); } - std::string const& name() const { return name_;} + std::string const& name() const { return name_; } }; struct geometry_type_attribute { - template + template V value(F const& f) const { return static_cast(util::to_ds_type(f.get_geometry())); @@ -61,10 +62,11 @@ struct global_attribute { std::string name; explicit global_attribute(std::string const& name_) - : name(name_) {} + : name(name_) + {} - template - V const& operator() (C const& ctx) + template + V const& operator()(C const& ctx) { return ctx.get(name); } @@ -72,6 +74,6 @@ struct global_attribute using attributes = std::unordered_map; -} +} // namespace mapnik #endif // MAPNIK_ATTRIBUTE_HPP diff --git a/include/mapnik/attribute_collector.hpp b/include/mapnik/attribute_collector.hpp index 25ee5db8d..771406faf 100644 --- a/include/mapnik/attribute_collector.hpp +++ b/include/mapnik/attribute_collector.hpp @@ -28,11 +28,11 @@ #include #include #include -#include // for expression_ptr, etc +#include // for expression_ptr, etc #include -#include // for path_processor_type -#include // for path_expression_ptr -#include // for text_placements +#include // for path_processor_type +#include // for path_expression_ptr +#include // for text_placements #include #include #include @@ -51,76 +51,71 @@ MAPNIK_DISABLE_WARNING_POP namespace mapnik { -template +template struct expression_attributes { explicit expression_attributes(Container& names) - : names_(names) {} + : names_(names) + {} - void operator() (attribute const& attr) const - { - names_.emplace(attr.name()); - } + void operator()(attribute const& attr) const { names_.emplace(attr.name()); } - template - void operator() (binary_node const& x) const + template + void operator()(binary_node const& x) const { util::apply_visitor(*this, x.left); util::apply_visitor(*this, x.right); } - template - void operator() (unary_node const& x) const + template + void operator()(unary_node const& x) const { util::apply_visitor(*this, x.expr); } - void operator() (regex_match_node const& x) const - { - util::apply_visitor(*this, x.expr); - } + void operator()(regex_match_node const& x) const { util::apply_visitor(*this, x.expr); } - void operator() (regex_replace_node const& x) const - { - util::apply_visitor(*this, x.expr); - } + void operator()(regex_replace_node const& x) const { util::apply_visitor(*this, x.expr); } - template - void operator() (T const&) const {} + template + void operator()(T const&) const + {} -private: + private: Container& names_; }; class group_attribute_collector : public util::noncopyable { -private: + private: std::set& names_; bool expand_index_columns_; -public: - group_attribute_collector(std::set& names, - bool expand_index_columns) - : names_(names), - expand_index_columns_(expand_index_columns) {} - void operator() (group_symbolizer const& sym); + public: + group_attribute_collector(std::set& names, bool expand_index_columns) + : names_(names) + , expand_index_columns_(expand_index_columns) + {} + + void operator()(group_symbolizer const& sym); }; -template +template struct extract_attribute_names { explicit extract_attribute_names(Container& names) - : names_(names), - f_attr_(names) {} + : names_(names) + , f_attr_(names) + {} - void operator() (mapnik::expression_ptr const& expr) const + void operator()(mapnik::expression_ptr const& expr) const { if (expr) { util::apply_visitor(f_attr_, *expr); } } - void operator() (mapnik::transform_type const& expr) const + void operator()(mapnik::transform_type const& expr) const { if (expr) { @@ -128,7 +123,7 @@ struct extract_attribute_names } } - void operator() (mapnik::text_placements_ptr const& expr) const + void operator()(mapnik::text_placements_ptr const& expr) const { if (expr) { @@ -136,39 +131,41 @@ struct extract_attribute_names expression_set expressions; // TODO - optimize (dane) expr->add_expressions(expressions); - for (it=expressions.begin(); it != expressions.end(); ++it) + for (it = expressions.begin(); it != expressions.end(); ++it) { - if (*it) util::apply_visitor(f_attr_, **it); + if (*it) + util::apply_visitor(f_attr_, **it); } } } - void operator() (mapnik::path_expression_ptr const& expr) const + void operator()(mapnik::path_expression_ptr const& expr) const { if (expr) { - path_processor_type::collect_attributes(*expr,names_); + path_processor_type::collect_attributes(*expr, names_); } } - template - void operator() (T const&) const {} + template + void operator()(T const&) const + {} -private: + private: Container& names_; - expression_attributes > f_attr_; + expression_attributes> f_attr_; }; struct symbolizer_attributes { - symbolizer_attributes(std::set& names, - double & filter_factor) - : filter_factor_(filter_factor), - f_attrs_(names), - g_attrs_(names, true) {} + symbolizer_attributes(std::set& names, double& filter_factor) + : filter_factor_(filter_factor) + , f_attrs_(names) + , g_attrs_(names, true) + {} - template - void operator () (T const& sym) + template + void operator()(T const& sym) { for (auto const& prop : sym.properties) { @@ -176,7 +173,7 @@ struct symbolizer_attributes } } - void operator () (raster_symbolizer const& sym) + void operator()(raster_symbolizer const& sym) { boost::optional filter_factor = get_optional(sym, keys::filter_factor); if (filter_factor) @@ -197,57 +194,51 @@ struct symbolizer_attributes } } - void operator () (group_symbolizer const& sym) - { - g_attrs_(sym); - } + void operator()(group_symbolizer const& sym) { g_attrs_(sym); } -private: - double & filter_factor_; - extract_attribute_names > f_attrs_; + private: + double& filter_factor_; + extract_attribute_names> f_attrs_; group_attribute_collector g_attrs_; }; - class attribute_collector : public util::noncopyable { -private: - std::set & names_; + private: + std::set& names_; double filter_factor_; - expression_attributes > f_attr; -public: + expression_attributes> f_attr; + + public: attribute_collector(std::set& names) - : names_(names), - filter_factor_(1.0), - f_attr(names) {} - template - void operator() (RuleType const& r) + : names_(names) + , filter_factor_(1.0) + , f_attr(names) + {} + template + void operator()(RuleType const& r) { typename RuleType::symbolizers const& symbols = r.get_symbolizers(); - symbolizer_attributes s_attr(names_,filter_factor_); + symbolizer_attributes s_attr(names_, filter_factor_); for (auto const& sym : symbols) { util::apply_visitor(std::ref(s_attr), sym); } expression_ptr const& expr = r.get_filter(); - util::apply_visitor(f_attr,*expr); + util::apply_visitor(f_attr, *expr); } - double get_filter_factor() const - { - return filter_factor_; - } + double get_filter_factor() const { return filter_factor_; } }; - -inline void group_attribute_collector::operator() (group_symbolizer const& sym) +inline void group_attribute_collector::operator()(group_symbolizer const& sym) { // find all column names referenced in the group symbolizer std::set group_columns; attribute_collector column_collector(group_columns); - expression_attributes > rk_attr(group_columns); + expression_attributes> rk_attr(group_columns); // get columns from symbolizer repeat key expression_ptr repeat_key = get(sym, keys::repeat_key); @@ -289,7 +280,7 @@ inline void group_attribute_collector::operator() (group_symbolizer const& sym) for (value_integer col_idx = start; col_idx < end; ++col_idx) { std::string col_idx_str; - if (mapnik::util::to_string(col_idx_str,col_idx)) + if (mapnik::util::to_string(col_idx_str, col_idx)) { std::string col_idx_name = col_name; boost::replace_all(col_idx_name, "%", col_idx_str); diff --git a/include/mapnik/attribute_descriptor.hpp b/include/mapnik/attribute_descriptor.hpp index 46a3e21c2..ea9067ef6 100644 --- a/include/mapnik/attribute_descriptor.hpp +++ b/include/mapnik/attribute_descriptor.hpp @@ -27,35 +27,30 @@ namespace mapnik { -enum eAttributeType { - Integer=1, - Float =2, - Double =3, - String =4, - Boolean =5, - Geometry=6, - Object=7 -}; +enum eAttributeType { Integer = 1, Float = 2, Double = 3, String = 4, Boolean = 5, Geometry = 6, Object = 7 }; class attribute_descriptor { -public: - attribute_descriptor(std::string const& name,unsigned type, - bool primary_key=false, - int size=-1, - int precision=-1) - : name_(name), - type_(type), - size_(size), - precision_(precision), - primary_key_(primary_key) {} + public: + attribute_descriptor(std::string const& name, + unsigned type, + bool primary_key = false, + int size = -1, + int precision = -1) + : name_(name) + , type_(type) + , size_(size) + , precision_(precision) + , primary_key_(primary_key) + {} attribute_descriptor(attribute_descriptor const& other) - : name_(other.name_), - type_(other.type_), - size_(other.size_), - precision_(other.precision_), - primary_key_(other.primary_key_) {} + : name_(other.name_) + , type_(other.type_) + , size_(other.size_) + , precision_(other.precision_) + , primary_key_(other.primary_key_) + {} attribute_descriptor& operator=(attribute_descriptor rhs) { @@ -68,32 +63,17 @@ public: return *this; } - std::string const& get_name() const - { - return name_; - } + std::string const& get_name() const { return name_; } - unsigned int get_type() const - { - return type_; - } + unsigned int get_type() const { return type_; } - bool is_primary_key() const - { - return primary_key_; - } + bool is_primary_key() const { return primary_key_; } - int get_size() const - { - return size_; - } + int get_size() const { return size_; } - int get_precision() const - { - return precision_; - } + int get_precision() const { return precision_; } -private: + private: std::string name_; unsigned int type_; int size_; @@ -101,6 +81,6 @@ private: bool primary_key_; }; -} +} // namespace mapnik #endif // MAPNIK_ATTRIBUTE_DESCRIPTOR_HPP diff --git a/include/mapnik/boolean.hpp b/include/mapnik/boolean.hpp index e3d277f80..1e2b2468e 100644 --- a/include/mapnik/boolean.hpp +++ b/include/mapnik/boolean.hpp @@ -30,25 +30,24 @@ #include #include -namespace mapnik -{ +namespace mapnik { class MAPNIK_DECL boolean_type { -public: + public: boolean_type() - : b_(false) {} + : b_(false) + {} boolean_type(bool b) - : b_(b) {} + : b_(b) + {} boolean_type(boolean_type const& b) - : b_(b.b_) {} + : b_(b.b_) + {} - operator bool() const - { - return b_; - } + operator bool() const { return b_; } - boolean_type & operator =(boolean_type const& other) + boolean_type& operator=(boolean_type const& other) { if (this == &other) return *this; @@ -56,33 +55,32 @@ public: return *this; } -private: + private: bool b_; }; // Special stream input operator for boolean_type values -template -std::basic_istream & -operator >> ( std::basic_istream & s, boolean_type & b ) +template +std::basic_istream& operator>>(std::basic_istream& s, boolean_type& b) { - if ( s ) + if (s) { std::string word; s >> word; bool result; - if (util::string2bool(word,result)) b = result; + if (util::string2bool(word, result)) + b = result; } return s; } -template -std::basic_ostream & -operator << ( std::basic_ostream & s, boolean_type const& b ) +template +std::basic_ostream& operator<<(std::basic_ostream& s, boolean_type const& b) { - s << ( b ? "true" : "false" ); + s << (b ? "true" : "false"); return s; } -} +} // namespace mapnik #endif // MAPNIK_BOOLEAN_HPP diff --git a/include/mapnik/boost_spirit_instantiate.hpp b/include/mapnik/boost_spirit_instantiate.hpp index 8e7f16416..7074fc3c0 100644 --- a/include/mapnik/boost_spirit_instantiate.hpp +++ b/include/mapnik/boost_spirit_instantiate.hpp @@ -23,17 +23,21 @@ #ifndef MAPNIK_BOOST_SPIRIT_INSTANTIATE_HPP #define MAPNIK_BOOST_SPIRIT_INSTANTIATE_HPP -namespace boost { namespace spirit { namespace x3 -{ +namespace boost { +namespace spirit { +namespace x3 { // helper macro -#define BOOST_SPIRIT_INSTANTIATE_UNUSED(rule_type, Iterator, Context) \ - template bool parse_rule( \ - rule_type rule_ \ - , Iterator& first, Iterator const& last \ - , Context const& context, boost::spirit::x3::unused_type const& ); \ +#define BOOST_SPIRIT_INSTANTIATE_UNUSED(rule_type, Iterator, Context) \ + template bool parse_rule( \ + rule_type rule_, \ + Iterator & first, \ + Iterator const& last, \ + Context const& context, \ + boost::spirit::x3::unused_type const&); \ /***/ -}}} - +} // namespace x3 +} // namespace spirit +} // namespace boost #endif // MAPNIK_BOOST_SPIRIT_INSTANTIATE_HPP diff --git a/include/mapnik/cairo/cairo_context.hpp b/include/mapnik/cairo/cairo_context.hpp index f429d6afd..15fab8345 100644 --- a/include/mapnik/cairo/cairo_context.hpp +++ b/include/mapnik/cairo/cairo_context.hpp @@ -20,7 +20,6 @@ * *****************************************************************************/ - #ifndef MAPNIK_CAIRO_CONTEXT_HPP #define MAPNIK_CAIRO_CONTEXT_HPP @@ -57,7 +56,8 @@ MAPNIK_DISABLE_WARNING_POP namespace mapnik { -template class box2d; +template +class box2d; using ErrorStatus = cairo_status_t; @@ -67,10 +67,10 @@ inline void throw_exception(ErrorStatus status) throw std::runtime_error(std::string("cairo: ") + cairo_status_to_string(status)); } -//We inline this because it is called so often. +// We inline this because it is called so often. inline void check_status_and_throw_exception(ErrorStatus status) { - if(status != CAIRO_STATUS_SUCCESS) + if (status != CAIRO_STATUS_SUCCESS) throw_exception(status); } @@ -82,60 +82,65 @@ void check_object_status_and_throw_exception(T const& object) class cairo_face : private util::noncopyable { -public: + public: cairo_face(std::shared_ptr const& library, face_ptr const& face); ~cairo_face(); - cairo_font_face_t * face() const; -private: + cairo_font_face_t* face() const; + + private: class handle { - public: + public: handle(std::shared_ptr const& library, face_ptr const& face) - : library_(library), face_(face) {} + : library_(library) + , face_(face) + {} - private: + private: std::shared_ptr library_; face_ptr face_; }; - static void destroy(void *data) + static void destroy(void* data) { - handle *h = static_cast(data); + handle* h = static_cast(data); delete h; } -private: + private: face_ptr face_; - cairo_font_face_t *c_face_; + cairo_font_face_t* c_face_; }; using cairo_face_ptr = std::shared_ptr; class cairo_face_manager : private util::noncopyable { -public: + public: cairo_face_manager(std::shared_ptr library); cairo_face_ptr get_face(face_ptr face); -private: - using cairo_face_cache = std::map; + private: + using cairo_face_cache = std::map; std::shared_ptr font_library_; cairo_face_cache cache_; }; struct cairo_closer { - void operator() (cairo_t * obj) + void operator()(cairo_t* obj) { - if (obj) cairo_destroy(obj); + if (obj) + cairo_destroy(obj); } }; struct cairo_surface_closer { - void operator() (cairo_surface_t * surface) + void operator()(cairo_surface_t* surface) { - if (surface) cairo_surface_destroy(surface); + if (surface) + cairo_surface_destroy(surface); } }; @@ -144,28 +149,25 @@ using cairo_surface_ptr = std::shared_ptr; inline cairo_ptr create_context(cairo_surface_ptr const& surface) { - return cairo_ptr(cairo_create(&*surface),cairo_closer()); + return cairo_ptr(cairo_create(&*surface), cairo_closer()); } class cairo_pattern : private util::noncopyable { -public: + public: explicit cairo_pattern(image_rgba8 const& data, double opacity = 1.0) { std::size_t pixels = data.width() * data.height(); - const unsigned int *in_ptr = data.data(); - const unsigned int *in_end = in_ptr + pixels; - unsigned int *out_ptr; + const unsigned int* in_ptr = data.data(); + const unsigned int* in_end = in_ptr + pixels; + unsigned int* out_ptr; - surface_ = cairo_surface_ptr( - cairo_image_surface_create( - CAIRO_FORMAT_ARGB32, - static_cast(data.width()), - static_cast(data.height())), - cairo_surface_closer()); + surface_ = cairo_surface_ptr(cairo_image_surface_create(CAIRO_FORMAT_ARGB32, + static_cast(data.width()), + static_cast(data.height())), + cairo_surface_closer()); - out_ptr = reinterpret_cast( - cairo_image_surface_get_data(surface_.get())); + out_ptr = reinterpret_cast(cairo_image_surface_get_data(surface_.get())); while (in_ptr < in_end) { @@ -175,9 +177,9 @@ public: unsigned int b = static_cast(((in >> 16) & 0xff) * opacity); unsigned int a = static_cast(((in >> 24) & 0xff) * opacity); - //r = r * a / 255; - //g = g * a / 255; - //b = b * a / 255; + // r = r * a / 255; + // g = g * a / 255; + // b = b * a / 255; *out_ptr++ = (a << 24) | (r << 16) | (g << 8) | b; } @@ -186,78 +188,65 @@ public: pattern_ = cairo_pattern_create_for_surface(surface_.get()); } - cairo_pattern(cairo_surface_ptr const& surface) : - surface_(surface), - pattern_(cairo_pattern_create_for_surface(surface_.get())) - { - } + cairo_pattern(cairo_surface_ptr const& surface) + : surface_(surface) + , pattern_(cairo_pattern_create_for_surface(surface_.get())) + {} ~cairo_pattern() { - if (pattern_) cairo_pattern_destroy(pattern_); + if (pattern_) + cairo_pattern_destroy(pattern_); } - void set_matrix(cairo_matrix_t const& matrix) - { - cairo_pattern_set_matrix(pattern_, &matrix); - } + void set_matrix(cairo_matrix_t const& matrix) { cairo_pattern_set_matrix(pattern_, &matrix); } void set_origin(double x, double y) { cairo_matrix_t matrix; - cairo_pattern_get_matrix(pattern_,&matrix); + cairo_pattern_get_matrix(pattern_, &matrix); matrix.x0 = -x; matrix.y0 = -y; - cairo_pattern_set_matrix(pattern_,&matrix); + cairo_pattern_set_matrix(pattern_, &matrix); } - void set_extend(cairo_extend_t extend) - { - cairo_pattern_set_extend(pattern_, extend); - } + void set_extend(cairo_extend_t extend) { cairo_pattern_set_extend(pattern_, extend); } - void set_filter(cairo_filter_t filter) - { - cairo_pattern_set_filter(pattern_, filter); - } + void set_filter(cairo_filter_t filter) { cairo_pattern_set_filter(pattern_, filter); } - cairo_pattern_t * pattern() const - { - return pattern_; - } + cairo_pattern_t* pattern() const { return pattern_; } -private: + private: cairo_surface_ptr surface_; - cairo_pattern_t * pattern_; + cairo_pattern_t* pattern_; }; - class cairo_gradient : private util::noncopyable { -public: - cairo_gradient(mapnik::gradient const& grad, double opacity=1.0) + public: + cairo_gradient(mapnik::gradient const& grad, double opacity = 1.0) { - double x1,x2,y1,y2,rad; - grad.get_control_points(x1,y1,x2,y2,rad); + double x1, x2, y1, y2, rad; + grad.get_control_points(x1, y1, x2, y2, rad); if (grad.get_gradient_type() == LINEAR) { pattern_ = cairo_pattern_create_linear(x1, y1, x2, y2); } else { - pattern_ = cairo_pattern_create_radial(x1, y1, 0, x2, y2, rad); + pattern_ = cairo_pattern_create_radial(x1, y1, 0, x2, y2, rad); } units_ = grad.get_units(); - for ( mapnik::stop_pair const& st : grad.get_stop_array() ) + for (mapnik::stop_pair const& st : grad.get_stop_array()) { mapnik::color const& stop_color = st.second; - double r= static_cast (stop_color.red())/255.0; - double g= static_cast (stop_color.green())/255.0; - double b= static_cast (stop_color.blue())/255.0; - double a= static_cast (stop_color.alpha())/255.0; - cairo_pattern_add_color_stop_rgba(pattern_,st.first, r, g, b, a*opacity); + double r = static_cast(stop_color.red()) / 255.0; + double g = static_cast(stop_color.green()) / 255.0; + double b = static_cast(stop_color.blue()) / 255.0; + double a = static_cast(stop_color.alpha()) / 255.0; + cairo_pattern_add_color_stop_rgba(pattern_, st.first, r, g, b, a * opacity); } double m[6]; @@ -265,7 +254,7 @@ public: tr.invert(); tr.store_to(m); cairo_matrix_t matrix; - cairo_matrix_init(&matrix,m[0],m[1],m[2],m[3],m[4],m[5]); + cairo_matrix_init(&matrix, m[0], m[1], m[2], m[3], m[4], m[5]); cairo_pattern_set_matrix(pattern_, &matrix); } @@ -275,43 +264,32 @@ public: cairo_pattern_destroy(pattern_); } + cairo_pattern_t* gradient() const { return pattern_; } - cairo_pattern_t * gradient() const - { - return pattern_; - } + gradient_unit_e units() const { return units_; } - gradient_unit_e units() const - { - return units_; - } - -private: - cairo_pattern_t * pattern_; + private: + cairo_pattern_t* pattern_; gradient_unit_e units_; - }; class cairo_context : private util::noncopyable { -public: + public: cairo_context(cairo_ptr const& cairo); - inline ErrorStatus get_status() const - { - return cairo_status(cairo_.get()); - } + inline ErrorStatus get_status() const { return cairo_status(cairo_.get()); } void clip(); void show_page(); - void set_color(color const &color, double opacity = 1.0); + void set_color(color const& color, double opacity = 1.0); void set_color(double r, double g, double b, double opacity = 1.0); void set_operator(composite_mode_e comp_op); void set_line_join(line_join_e join); void set_line_cap(line_cap_e cap); void set_miter_limit(double limit); void set_line_width(double width); - void set_dash(dash_array const &dashes, double scale_factor); + void set_dash(dash_array const& dashes, double scale_factor); void set_fill_rule(cairo_fill_rule_t fill_rule); void move_to(double x, double y); void curve_to(double ct1_x, double ct1_y, double ct2_x, double ct2_y, double end_x, double end_y); @@ -326,7 +304,7 @@ public: void set_gradient(cairo_gradient const& pattern, box2d const& bbox); void add_image(double x, double y, image_rgba8 const& data, double opacity = 1.0); void add_image(agg::trans_affine const& tr, image_rgba8 const& data, double opacity = 1.0); - void set_font_face(cairo_face_manager & manager, face_ptr face); + void set_font_face(cairo_face_manager& manager, face_ptr face); void set_font_matrix(cairo_matrix_t const& matrix); void set_matrix(cairo_matrix_t const& matrix); void transform(cairo_matrix_t const& matrix); @@ -336,7 +314,7 @@ public: void show_glyph(unsigned long index, pixel_position const& pos); void glyph_path(unsigned long index, pixel_position const& pos); void add_text(glyph_positions const& pos, - cairo_face_manager & manager, + cairo_face_manager& manager, composite_mode_e comp_op = src_over, composite_mode_e halo_comp_op = src_over, double scale_factor = 1.0); @@ -344,7 +322,7 @@ public: void push_group(); void pop_group(); - template + template void add_path(T& path, unsigned start_index = 0) { double x, y; @@ -366,11 +344,11 @@ public: } } - template + template void add_agg_path(T& path, unsigned start_index = 0) { - double x=0; - double y=0; + double x = 0; + double y = 0; path.rewind(start_index); @@ -384,26 +362,26 @@ public: { if (agg::is_curve3(cm)) { - double end_x=0; - double end_y=0; + double end_x = 0; + double end_y = 0; MAPNIK_LOG_WARN(cairo_renderer) << "Curve 3 not implemented"; path.vertex(&end_x, &end_y); - curve_to(x,y,x,y,end_x,end_y); + curve_to(x, y, x, y, end_x, end_y); } else if (agg::is_curve4(cm)) { - double ct2_x=0; - double ct2_y=0; - double end_x=0; - double end_y=0; + double ct2_x = 0; + double ct2_y = 0; + double end_x = 0; + double end_y = 0; path.vertex(&ct2_x, &ct2_y); path.vertex(&end_x, &end_y); - curve_to(x,y,ct2_x,ct2_y,end_x,end_y); + curve_to(x, y, ct2_x, ct2_y, end_x, end_y); } else if (agg::is_line_to(cm)) { @@ -426,21 +404,22 @@ public: } } -private: + private: cairo_ptr cairo_; }; -template +template struct line_pattern_rasterizer { - line_pattern_rasterizer(Context & context, cairo_pattern & pattern, unsigned width, unsigned height) - : context_(context), - pattern_(pattern), - width_(width), - height_(height) {} + line_pattern_rasterizer(Context& context, cairo_pattern& pattern, unsigned width, unsigned height) + : context_(context) + , pattern_(pattern) + , width_(width) + , height_(height) + {} - template - void add_path(T & path, unsigned start_index = 0) + template + void add_path(T& path, unsigned start_index = 0) { double length = 0.0; double x0 = 0.0; @@ -479,13 +458,12 @@ struct line_pattern_rasterizer } } - Context & context_; - cairo_pattern & pattern_; + Context& context_; + cairo_pattern& pattern_; unsigned width_; unsigned height_; }; -} - +} // namespace mapnik #endif // MAPNIK_CAIRO_CONTEXT_HPP diff --git a/include/mapnik/cairo/cairo_image_util.hpp b/include/mapnik/cairo/cairo_image_util.hpp index 18c190fbd..dd9afe3d4 100644 --- a/include/mapnik/cairo/cairo_image_util.hpp +++ b/include/mapnik/cairo/cairo_image_util.hpp @@ -20,7 +20,6 @@ * *****************************************************************************/ - #ifndef MAPNIK_CAIRO_IMAGE_UTIL_HPP #define MAPNIK_CAIRO_IMAGE_UTIL_HPP @@ -33,8 +32,7 @@ namespace mapnik { -static inline void cairo_image_to_rgba8(mapnik::image_rgba8 & data, - cairo_surface_ptr const& surface) +static inline void cairo_image_to_rgba8(mapnik::image_rgba8& data, cairo_surface_ptr const& surface) { if (cairo_image_surface_get_format(&*surface) != CAIRO_FORMAT_ARGB32) { @@ -50,7 +48,7 @@ static inline void cairo_image_to_rgba8(mapnik::image_rgba8 & data, int stride = cairo_image_surface_get_stride(&*surface) / 4; const std::unique_ptr out_row(new unsigned int[data.width()]); - const unsigned int *in_row = (const unsigned int *)cairo_image_surface_get_data(&*surface); + const unsigned int* in_row = (const unsigned int*)cairo_image_surface_get_data(&*surface); for (unsigned int row = 0; row < data.height(); row++, in_row += stride) { @@ -62,11 +60,16 @@ static inline void cairo_image_to_rgba8(mapnik::image_rgba8 & data, unsigned int g = (in >> 8) & 0xff; unsigned int b = (in >> 0) & 0xff; -#define DE_ALPHA(x) do { \ - if (a == 0) x = 0; \ - else x = x * 255 / a; \ - if (x > 255) x = 255; \ - } while(0) +#define DE_ALPHA(x) \ + do \ + { \ + if (a == 0) \ + x = 0; \ + else \ + x = x * 255 / a; \ + if (x > 255) \ + x = 255; \ + } while (0) DE_ALPHA(r); DE_ALPHA(g); @@ -78,7 +81,6 @@ static inline void cairo_image_to_rgba8(mapnik::image_rgba8 & data, } } -} - +} // namespace mapnik #endif // MAPNIK_CAIRO_IMAGE_UTIL_HPP diff --git a/include/mapnik/cairo/cairo_render_vector.hpp b/include/mapnik/cairo/cairo_render_vector.hpp index ebadb1d0d..e28f499f4 100644 --- a/include/mapnik/cairo/cairo_render_vector.hpp +++ b/include/mapnik/cairo/cairo_render_vector.hpp @@ -32,12 +32,14 @@ namespace mapnik { class cairo_context; -void render_vector_marker(cairo_context & context, svg_path_adapter & svg_path, +void render_vector_marker(cairo_context& context, + svg_path_adapter& svg_path, svg_attribute_type const& attributes, - box2d const& bbox, agg::trans_affine const& tr, + box2d const& bbox, + agg::trans_affine const& tr, double opacity); -} +} // namespace mapnik #endif // MAPNIK_CAIRO_RENDER_VECTOR_HPP diff --git a/include/mapnik/cairo/cairo_renderer.hpp b/include/mapnik/cairo/cairo_renderer.hpp index 432bd7950..94bbec037 100644 --- a/include/mapnik/cairo/cairo_renderer.hpp +++ b/include/mapnik/cairo/cairo_renderer.hpp @@ -53,42 +53,35 @@ class request; struct pixel_position; struct cairo_save_restore { - cairo_save_restore(cairo_context & context) + cairo_save_restore(cairo_context& context) : context_(context) { context_.save(); } - ~cairo_save_restore() - { - context_.restore(); - } - cairo_context & context_; + ~cairo_save_restore() { context_.restore(); } + cairo_context& context_; }; -template -class MAPNIK_DECL cairo_renderer : public feature_style_processor >, +template +class MAPNIK_DECL cairo_renderer : public feature_style_processor>, private util::noncopyable { -public: + public: using processor_impl_type = cairo_renderer; - cairo_renderer(Map const& m, - T const& obj, - double scale_factor=1.0, - unsigned offset_x=0, - unsigned offset_y=0); + cairo_renderer(Map const& m, T const& obj, double scale_factor = 1.0, unsigned offset_x = 0, unsigned offset_y = 0); cairo_renderer(Map const& m, request const& req, attributes const& vars, T const& obj, - double scale_factor=1.0, - unsigned offset_x=0, - unsigned offset_y=0); + double scale_factor = 1.0, + unsigned offset_x = 0, + unsigned offset_y = 0); cairo_renderer(Map const& m, T const& obj, std::shared_ptr detector, - double scale_factor=1.0, - unsigned offset_x=0, - unsigned offset_y=0); + double scale_factor = 1.0, + unsigned offset_x = 0, + unsigned offset_y = 0); ~cairo_renderer(); void start_map_processing(Map const& map); @@ -97,93 +90,56 @@ public: void end_layer_processing(layer const& lay); void start_style_processing(feature_type_style const& st); void end_style_processing(feature_type_style const& st); - void process(point_symbolizer const& sym, - mapnik::feature_impl & feature, - proj_transform const& prj_trans); - void process(line_symbolizer const& sym, - mapnik::feature_impl & feature, - proj_transform const& prj_trans); - void process(line_pattern_symbolizer const& sym, - mapnik::feature_impl & feature, - proj_transform const& prj_trans); - void process(polygon_symbolizer const& sym, - mapnik::feature_impl & feature, - proj_transform const& prj_trans); - void process(polygon_pattern_symbolizer const& sym, - mapnik::feature_impl & feature, - proj_transform const& prj_trans); - void process(raster_symbolizer const& sym, - mapnik::feature_impl & feature, - proj_transform const& prj_trans); - void process(shield_symbolizer const& sym, - mapnik::feature_impl & feature, - proj_transform const& prj_trans); - void process(text_symbolizer const& sym, - mapnik::feature_impl & feature, - proj_transform const& prj_trans); - void process(building_symbolizer const& sym, - mapnik::feature_impl & feature, - proj_transform const& prj_trans); - void process(markers_symbolizer const& sym, - mapnik::feature_impl & feature, - proj_transform const& prj_trans); - void process(group_symbolizer const& sym, - mapnik::feature_impl & feature, - proj_transform const& prj_trans); - void process(debug_symbolizer const& sym, - mapnik::feature_impl & feature, - proj_transform const& prj_trans); - inline bool process(rule::symbolizers const& /*syms*/, - mapnik::feature_impl & /*feature*/, - proj_transform const& /*prj_trans*/) + void process(point_symbolizer const& sym, mapnik::feature_impl& feature, proj_transform const& prj_trans); + void process(line_symbolizer const& sym, mapnik::feature_impl& feature, proj_transform const& prj_trans); + void process(line_pattern_symbolizer const& sym, mapnik::feature_impl& feature, proj_transform const& prj_trans); + void process(polygon_symbolizer const& sym, mapnik::feature_impl& feature, proj_transform const& prj_trans); + void process(polygon_pattern_symbolizer const& sym, mapnik::feature_impl& feature, proj_transform const& prj_trans); + void process(raster_symbolizer const& sym, mapnik::feature_impl& feature, proj_transform const& prj_trans); + void process(shield_symbolizer const& sym, mapnik::feature_impl& feature, proj_transform const& prj_trans); + void process(text_symbolizer const& sym, mapnik::feature_impl& feature, proj_transform const& prj_trans); + void process(building_symbolizer const& sym, mapnik::feature_impl& feature, proj_transform const& prj_trans); + void process(markers_symbolizer const& sym, mapnik::feature_impl& feature, proj_transform const& prj_trans); + void process(group_symbolizer const& sym, mapnik::feature_impl& feature, proj_transform const& prj_trans); + void process(debug_symbolizer const& sym, mapnik::feature_impl& feature, proj_transform const& prj_trans); + inline bool + process(rule::symbolizers const& /*syms*/, mapnik::feature_impl& /*feature*/, proj_transform const& /*prj_trans*/) { // cairo renderer doesn't support processing of multiple symbolizers. return false; } - bool painted() - { - return true; - } + bool painted() { return true; } void painted(bool /*painted*/) { // nothing to do } - inline eAttributeCollectionPolicy attribute_collection_policy() const - { - return DEFAULT; - } + inline eAttributeCollectionPolicy attribute_collection_policy() const { return DEFAULT; } - inline double scale_factor() const - { - return common_.scale_factor_; - } + inline double scale_factor() const { return common_.scale_factor_; } - inline attributes const& variables() const - { - return common_.vars_; - } + inline attributes const& variables() const { return common_.vars_; } void render_marker(pixel_position const& pos, marker const& marker, agg::trans_affine const& mtx, - double opacity=1.0, - bool recenter=true); -protected: + double opacity = 1.0, + bool recenter = true); + + protected: Map const& m_; cairo_context context_; renderer_common common_; cairo_face_manager face_manager_; bool style_level_compositing_; void setup(Map const& m); - }; extern template class MAPNIK_DECL cairo_renderer; -} +} // namespace mapnik #endif // MAPNIK_CAIRO_RENDERER_HPP diff --git a/include/mapnik/cairo/render_polygon_pattern.hpp b/include/mapnik/cairo/render_polygon_pattern.hpp index c311704ac..89dba18e3 100644 --- a/include/mapnik/cairo/render_polygon_pattern.hpp +++ b/include/mapnik/cairo/render_polygon_pattern.hpp @@ -36,36 +36,31 @@ namespace mapnik { struct cairo_renderer_process_visitor_p { - cairo_renderer_process_visitor_p(agg::trans_affine const& image_tr, - double opacity) - : image_tr_(image_tr), - opacity_(opacity) + cairo_renderer_process_visitor_p(agg::trans_affine const& image_tr, double opacity) + : image_tr_(image_tr) + , opacity_(opacity) {} - cairo_surface_ptr operator()(marker_svg const & marker) const + cairo_surface_ptr operator()(marker_svg const& marker) const { box2d bbox(marker.bounding_box()); agg::trans_affine tr(transform(bbox)); double width = std::max(1.0, std::round(bbox.width())); double height = std::max(1.0, std::round(bbox.height())); - cairo_rectangle_t extent { 0, 0, width, height }; - cairo_surface_ptr surface( - cairo_recording_surface_create( - CAIRO_CONTENT_COLOR_ALPHA, &extent), - cairo_surface_closer()); + cairo_rectangle_t extent{0, 0, width, height}; + cairo_surface_ptr surface(cairo_recording_surface_create(CAIRO_CONTENT_COLOR_ALPHA, &extent), + cairo_surface_closer()); cairo_ptr cairo = create_context(surface); cairo_context context(cairo); - svg_storage_type & svg = *marker.get_data(); + svg_storage_type& svg = *marker.get_data(); svg_attribute_type const& svg_attributes = svg.attributes(); - svg::vertex_stl_adapter stl_storage( - svg.source()); + svg::vertex_stl_adapter stl_storage(svg.source()); svg::svg_path_adapter svg_path(stl_storage); - render_vector_marker(context, svg_path, svg_attributes, - bbox, tr, opacity_); + render_vector_marker(context, svg_path, svg_attributes, bbox, tr, opacity_); return surface; } @@ -75,11 +70,9 @@ struct cairo_renderer_process_visitor_p box2d bbox(marker.bounding_box()); agg::trans_affine tr(transform(bbox)); - cairo_rectangle_t extent { 0, 0, bbox.width(), bbox.height() }; - cairo_surface_ptr surface( - cairo_recording_surface_create( - CAIRO_CONTENT_COLOR_ALPHA, &extent), - cairo_surface_closer()); + cairo_rectangle_t extent{0, 0, bbox.width(), bbox.height()}; + cairo_surface_ptr surface(cairo_recording_surface_create(CAIRO_CONTENT_COLOR_ALPHA, &extent), + cairo_surface_closer()); cairo_ptr cairo = create_context(surface); cairo_context context(cairo); @@ -89,25 +82,21 @@ struct cairo_renderer_process_visitor_p return surface; } - cairo_surface_ptr operator() (marker_null const&) const + cairo_surface_ptr operator()(marker_null const&) const { - cairo_surface_ptr surface( - cairo_recording_surface_create( - CAIRO_CONTENT_COLOR_ALPHA, nullptr), - cairo_surface_closer()); + cairo_surface_ptr surface(cairo_recording_surface_create(CAIRO_CONTENT_COLOR_ALPHA, nullptr), + cairo_surface_closer()); cairo_ptr cairo = create_context(surface); cairo_context context(cairo); return surface; } -private: - agg::trans_affine transform(box2d & bbox) const + private: + agg::trans_affine transform(box2d& bbox) const { bbox *= image_tr_; coord c = bbox.center(); - agg::trans_affine mtx = agg::trans_affine_translation( - 0.5 * bbox.width() - c.x, - 0.5 * bbox.height() - c.y); + agg::trans_affine mtx = agg::trans_affine_translation(0.5 * bbox.width() - c.x, 0.5 * bbox.height() - c.y); return image_tr_ * mtx; } @@ -135,7 +124,7 @@ struct cairo_pattern_base } }; -template +template struct cairo_polygon_pattern : cairo_pattern_base { cairo_polygon_pattern(mapnik::marker const& marker, @@ -143,22 +132,23 @@ struct cairo_polygon_pattern : cairo_pattern_base symbolizer_base const& sym, mapnik::feature_impl const& feature, proj_transform const& prj_trans) - : cairo_pattern_base{marker, common, sym, feature, prj_trans}, - clip_(get(sym_, feature_, common_.vars_)), - clip_box_(clipping_extent(common)), - tr_(geom_transform()), - converter_(clip_box_, sym, common.t_, prj_trans, tr_, - feature, common.vars_, common.scale_factor_) + : cairo_pattern_base{marker, common, sym, feature, prj_trans} + , clip_(get(sym_, feature_, common_.vars_)) + , clip_box_(clipping_extent(common)) + , tr_(geom_transform()) + , converter_(clip_box_, sym, common.t_, prj_trans, tr_, feature, common.vars_, common.scale_factor_) { value_double simplify_tolerance = get(sym, feature, common_.vars_); value_double smooth = get(sym, feature, common_.vars_); converter_.template set(); - if (simplify_tolerance > 0.0) converter_.template set(); - if (smooth > 0.0) converter_.template set(); + if (simplify_tolerance > 0.0) + converter_.template set(); + if (smooth > 0.0) + converter_.template set(); } - void render(cairo_fill_rule_t fill_rule, cairo_context & context) + void render(cairo_fill_rule_t fill_rule, cairo_context& context) { value_double opacity = get(sym_, feature_, common_.vars_); agg::trans_affine image_tr = agg::trans_affine_scaling(common_.scale_factor_); @@ -181,8 +171,12 @@ struct cairo_polygon_pattern : cairo_pattern_base cairo_rectangle_t pattern_surface_extent; if (cairo_recording_surface_get_extents(surface.get(), &pattern_surface_extent)) { - offset = pattern_offset(sym_, feature_, prj_trans_, common_, - pattern_surface_extent.width, pattern_surface_extent.height); + offset = pattern_offset(sym_, + feature_, + prj_trans_, + common_, + pattern_surface_extent.width, + pattern_surface_extent.height); } cairo_pattern pattern(surface); @@ -193,7 +187,7 @@ struct cairo_polygon_pattern : cairo_pattern_base using apply_vertex_converter_type = detail::apply_vertex_converter; using vertex_processor_type = geometry::vertex_processor; apply_vertex_converter_type apply(converter_, context); - mapnik::util::apply_visitor(vertex_processor_type(apply),feature_.get_geometry()); + mapnik::util::apply_visitor(vertex_processor_type(apply), feature_.get_geometry()); // fill polygon context.set_fill_rule(fill_rule); context.fill(); @@ -207,5 +201,4 @@ struct cairo_polygon_pattern : cairo_pattern_base } // namespace mapnik - #endif // MAPNIK_CAIRO_RENDER_POLYGON_PATTERN_HPP diff --git a/include/mapnik/cairo_io.hpp b/include/mapnik/cairo_io.hpp index 705ded1d8..a251db97c 100644 --- a/include/mapnik/cairo_io.hpp +++ b/include/mapnik/cairo_io.hpp @@ -35,15 +35,15 @@ namespace mapnik { #if defined(HAVE_CAIRO) MAPNIK_DECL void save_to_cairo_file(mapnik::Map const& map, std::string const& filename, - double scale_factor=1.0, - double scale_denominator=0.0); + double scale_factor = 1.0, + double scale_denominator = 0.0); MAPNIK_DECL void save_to_cairo_file(mapnik::Map const& map, std::string const& filename, std::string const& type, - double scale_factor=1.0, - double scale_denominator=0.0); + double scale_factor = 1.0, + double scale_denominator = 0.0); #endif -} // end ns +} // namespace mapnik #endif // MAPNIK_CAIRO_IO_HPP diff --git a/include/mapnik/color.hpp b/include/mapnik/color.hpp index 754649017..8ce33e342 100644 --- a/include/mapnik/color.hpp +++ b/include/mapnik/color.hpp @@ -41,7 +41,7 @@ namespace mapnik { class MAPNIK_DECL color : boost::equality_comparable { -public: + public: std::uint8_t red_; std::uint8_t green_; std::uint8_t blue_; @@ -50,46 +50,52 @@ public: // default ctor color() - : red_(0xff), - green_(0xff), - blue_(0xff), - alpha_(0xff), - premultiplied_(false) - {} + : red_(0xff) + , green_(0xff) + , blue_(0xff) + , alpha_(0xff) + , premultiplied_(false) + {} - color(std::uint8_t _red, std::uint8_t _green, std::uint8_t _blue, std::uint8_t _alpha = 0xff, bool premultiplied = false) - : red_(_red), - green_(_green), - blue_(_blue), - alpha_(_alpha), - premultiplied_(premultiplied) - {} + color(std::uint8_t _red, + std::uint8_t _green, + std::uint8_t _blue, + std::uint8_t _alpha = 0xff, + bool premultiplied = false) + : red_(_red) + , green_(_green) + , blue_(_blue) + , alpha_(_alpha) + , premultiplied_(premultiplied) + {} color(std::uint32_t _rgba, bool premultiplied = false) - : red_(_rgba & 0xff), - green_((_rgba >> 8) & 0xff), - blue_((_rgba >> 16) & 0xff), - alpha_((_rgba >> 24) & 0xff), - premultiplied_(premultiplied) {} + : red_(_rgba & 0xff) + , green_((_rgba >> 8) & 0xff) + , blue_((_rgba >> 16) & 0xff) + , alpha_((_rgba >> 24) & 0xff) + , premultiplied_(premultiplied) + {} // copy ctor color(const color& rhs) - : red_(rhs.red_), - green_(rhs.green_), - blue_(rhs.blue_), - alpha_(rhs.alpha_), - premultiplied_(rhs.premultiplied_) - {} + : red_(rhs.red_) + , green_(rhs.green_) + , blue_(rhs.blue_) + , alpha_(rhs.alpha_) + , premultiplied_(rhs.premultiplied_) + {} // move ctor - color(color && rhs) - : red_(std::move(rhs.red_)), - green_(std::move(rhs.green_)), - blue_(std::move(rhs.blue_)), - alpha_(std::move(rhs.alpha_)), - premultiplied_(std::move(rhs.premultiplied_)) {} + color(color&& rhs) + : red_(std::move(rhs.red_)) + , green_(std::move(rhs.green_)) + , blue_(std::move(rhs.blue_)) + , alpha_(std::move(rhs.alpha_)) + , premultiplied_(std::move(rhs.premultiplied_)) + {} - color( std::string const& str, bool premultiplied = false); + color(std::string const& str, bool premultiplied = false); std::string to_string() const; std::string to_hex_string() const; @@ -104,78 +110,45 @@ public: inline bool operator==(color const& rhs) const { - return (red_== rhs.red_) && - (green_ == rhs.green_) && - (blue_ == rhs.blue_) && - (alpha_ == rhs.alpha_) && - (premultiplied_ == rhs.premultiplied_); + return (red_ == rhs.red_) && (green_ == rhs.green_) && (blue_ == rhs.blue_) && (alpha_ == rhs.alpha_) && + (premultiplied_ == rhs.premultiplied_); } - inline std::uint8_t red() const - { - return red_; - } + inline std::uint8_t red() const { return red_; } - inline std::uint8_t green() const - { - return green_; - } + inline std::uint8_t green() const { return green_; } - inline std::uint8_t blue() const - { - return blue_; - } + inline std::uint8_t blue() const { return blue_; } - inline std::uint8_t alpha() const - { - return alpha_; - } + inline std::uint8_t alpha() const { return alpha_; } - inline void set_red(std::uint8_t _red) - { - red_ = _red; - } + inline void set_red(std::uint8_t _red) { red_ = _red; } - inline void set_green(std::uint8_t _green) - { - green_ = _green; - } + inline void set_green(std::uint8_t _green) { green_ = _green; } - inline void set_blue(std::uint8_t _blue) - { - blue_ = _blue; - } - inline void set_alpha(std::uint8_t _alpha) - { - alpha_ = _alpha; - } - inline bool get_premultiplied() const - { - return premultiplied_; - } - inline void set_premultiplied(bool val) - { - premultiplied_ = val; - } + inline void set_blue(std::uint8_t _blue) { blue_ = _blue; } + inline void set_alpha(std::uint8_t _alpha) { alpha_ = _alpha; } + inline bool get_premultiplied() const { return premultiplied_; } + inline void set_premultiplied(bool val) { premultiplied_ = val; } inline unsigned rgba() const { - return static_cast((alpha_ << 24) | (blue_ << 16) | (green_ << 8) | (red_)) ; + return static_cast((alpha_ << 24) | (blue_ << 16) | (green_ << 8) | (red_)); } -private: - void swap(color & rhs) + + private: + void swap(color& rhs) { std::swap(red_, rhs.red_); - std::swap(green_,rhs.green_); - std::swap(blue_,rhs.blue_); - std::swap(alpha_,rhs.alpha_); + std::swap(green_, rhs.green_); + std::swap(blue_, rhs.blue_); + std::swap(alpha_, rhs.alpha_); std::swap(premultiplied_, rhs.premultiplied_); } }; -template -std::basic_ostream & -operator << ( std::basic_ostream & s, mapnik::color const& c ) +template +std::basic_ostream& operator<<(std::basic_ostream& s, mapnik::color const& c) { s << c.to_string(); return s; @@ -187,6 +160,6 @@ inline std::size_t hash_value(color const& c) return c.rgba(); } -} +} // namespace mapnik #endif // MAPNIK_COLOR_HPP diff --git a/include/mapnik/color_factory.hpp b/include/mapnik/color_factory.hpp index 1c8d191e9..ea0014e78 100644 --- a/include/mapnik/color_factory.hpp +++ b/include/mapnik/color_factory.hpp @@ -26,7 +26,7 @@ // mapnik #include -//stl +// stl #include namespace mapnik { diff --git a/include/mapnik/config.hpp b/include/mapnik/config.hpp index fa0129dc1..27ada9b5e 100644 --- a/include/mapnik/config.hpp +++ b/include/mapnik/config.hpp @@ -27,35 +27,43 @@ #ifdef _WIN32 #ifdef MAPNIK_STATIC_DEFINE -# define MAPNIK_DECL -# define MAPNIK_EXP +#define MAPNIK_DECL +#define MAPNIK_EXP #else -# define MAPNIK_EXP __declspec(dllexport) -# ifndef MAPNIK_DECL -# ifdef MAPNIK_EXPORTS - /* We are building this library */ -# define MAPNIK_DECL __declspec(dllexport) -# else - /* We are using this library */ -# define MAPNIK_DECL __declspec(dllimport) -# endif -# endif +#define MAPNIK_EXP __declspec(dllexport) +#ifndef MAPNIK_DECL +#ifdef MAPNIK_EXPORTS +/* We are building this library */ +#define MAPNIK_DECL __declspec(dllexport) +#else +/* We are using this library */ +#define MAPNIK_DECL __declspec(dllimport) +#endif +#endif +#endif +#pragma warning(disable: 4251) +#pragma warning(disable: 4275) +#if (_MSC_VER >= 1400) // vc8 +#pragma warning(disable: 4996) //_CRT_SECURE_NO_DEPRECATE #endif -# pragma warning( disable: 4251 ) -# pragma warning( disable: 4275 ) -# if (_MSC_VER >= 1400) // vc8 -# pragma warning(disable : 4996) //_CRT_SECURE_NO_DEPRECATE -# endif #else -# if __GNUC__ >= 4 -# define MAPNIK_EXP __attribute__ ((visibility ("default"))) -# define MAPNIK_DECL __attribute__ ((visibility ("default"))) -# define MAPNIK_IMP __attribute__ ((visibility ("default"))) -# else -# define MAPNIK_EXP -# define MAPNIK_DECL -# define MAPNIK_IMP -# endif +#define MAPNIK_DECL __declspec(dllimport) +#endif +#pragma warning(disable: 4251) +#pragma warning(disable: 4275) +#if (_MSC_VER >= 1400) // vc8 +#pragma warning(disable: 4996) //_CRT_SECURE_NO_DEPRECATE +#endif +#else +#if __GNUC__ >= 4 +#define MAPNIK_EXP __attribute__((visibility("default"))) +#define MAPNIK_DECL __attribute__((visibility("default"))) +#define MAPNIK_IMP __attribute__((visibility("default"))) +#else +#define MAPNIK_EXP +#define MAPNIK_DECL +#define MAPNIK_IMP +#endif #endif #define PROJ_ENVELOPE_POINTS 20 diff --git a/include/mapnik/config_error.hpp b/include/mapnik/config_error.hpp index 9206ec7f7..8827dc67e 100644 --- a/include/mapnik/config_error.hpp +++ b/include/mapnik/config_error.hpp @@ -34,19 +34,17 @@ class xml_node; class config_error : public std::exception { -public: + public: config_error(std::string const& what); - config_error(std::string const& what, - xml_node const& node); - config_error(std::string const& what, - unsigned line_number, - std::string const& filename); + config_error(std::string const& what, xml_node const& node); + config_error(std::string const& what, unsigned line_number, std::string const& filename); virtual ~config_error() {} - virtual const char * what() const noexcept; + virtual const char* what() const noexcept; void append_context(std::string const& ctx) const; void append_context(std::string const& ctx, xml_node const& node) const; void append_context(xml_node const& node) const; -protected: + + protected: mutable std::string what_; mutable unsigned line_number_; mutable std::string file_; @@ -54,6 +52,6 @@ protected: mutable std::string msg_; }; -} +} // namespace mapnik #endif // MAPNIK_CONFIG_ERROR_HPP diff --git a/include/mapnik/coord.hpp b/include/mapnik/coord.hpp index 15dadeb82..093c18636 100644 --- a/include/mapnik/coord.hpp +++ b/include/mapnik/coord.hpp @@ -30,150 +30,173 @@ MAPNIK_DISABLE_WARNING_PUSH MAPNIK_DISABLE_WARNING_POP namespace mapnik { -template -struct coord { +template +struct coord +{ using type = T; }; -template -struct coord - : boost::addable, - boost::addable2,T, - boost::subtractable, - boost::subtractable2,T, - boost::dividable2, T, - boost::multipliable2, T > > > > > > +template +struct coord + : boost::addable< + coord, + boost::addable2< + coord, + T, + boost::subtractable< + coord, + boost:: + subtractable2, T, boost::dividable2, T, boost::multipliable2, T>>>>>> { using type = T; T x; T y; -public: + + public: coord() - : x(),y() {} - coord(T x_,T y_) - : x(x_),y(y_) {} + : x() + , y() + {} + coord(T x_, T y_) + : x(x_) + , y(y_) + {} - coord(coord const& rhs) - : x(rhs.x), - y(rhs.y) {} + coord(coord const& rhs) + : x(rhs.x) + , y(rhs.y) + {} - template - coord (coord const& rhs) - : x(type(rhs.x)), - y(type(rhs.y)) {} + template + coord(coord const& rhs) + : x(type(rhs.x)) + , y(type(rhs.y)) + {} - coord(coord && rhs) noexcept - : x(std::move(rhs.x)), - y(std::move(rhs.y)) {} + coord(coord&& rhs) noexcept + : x(std::move(rhs.x)) + , y(std::move(rhs.y)) + {} - coord& operator=(coord rhs) + coord& operator=(coord rhs) { swap(rhs); return *this; } - template - coord& operator=(const coord& rhs) + template + coord& operator=(const coord& rhs) { - coord tmp(rhs); + coord tmp(rhs); swap(rhs); return *this; } - template - bool operator==(coord const& rhs) + template + bool operator==(coord const& rhs) { return x == rhs.x && y == rhs.y; } - coord& operator+=(coord const& rhs) + coord& operator+=(coord const& rhs) { - x+=rhs.x; - y+=rhs.y; + x += rhs.x; + y += rhs.y; return *this; } - coord& operator+=(T rhs) + coord& operator+=(T rhs) { - x+=rhs; - y+=rhs; + x += rhs; + y += rhs; return *this; } - coord& operator-=(coord const& rhs) + coord& operator-=(coord const& rhs) { - x-=rhs.x; - y-=rhs.y; + x -= rhs.x; + y -= rhs.y; return *this; } - coord& operator-=(T rhs) + coord& operator-=(T rhs) { - x-=rhs; - y-=rhs; + x -= rhs; + y -= rhs; return *this; } - coord& operator*=(T t) + coord& operator*=(T t) { - x*=t; - y*=t; + x *= t; + y *= t; return *this; } - coord& operator/=(T t) + coord& operator/=(T t) { - x/=t; - y/=t; + x /= t; + y /= t; return *this; } -private: - void swap(coord & rhs) + + private: + void swap(coord& rhs) { std::swap(this->x, rhs.x); std::swap(this->y, rhs.y); } }; -template -struct coord +template +struct coord { using type = T; T x; T y; T z; -public: + + public: coord() - : x(),y(),z() {} - coord(T x_,T y_,T z_) - : x(x_),y(y_),z(z_) {} + : x() + , y() + , z() + {} + coord(T x_, T y_, T z_) + : x(x_) + , y(y_) + , z(z_) + {} - template - coord (coord const& rhs) - : x(type(rhs.x)), - y(type(rhs.y)), - z(type(rhs.z)) {} + template + coord(coord const& rhs) + : x(type(rhs.x)) + , y(type(rhs.y)) + , z(type(rhs.z)) + {} - coord(coord && rhs) noexcept - : x(std::move(rhs.x)), - y(std::move(rhs.y)), - z(std::move(rhs.z)) {} + coord(coord&& rhs) noexcept + : x(std::move(rhs.x)) + , y(std::move(rhs.y)) + , z(std::move(rhs.z)) + {} - coord operator=(coord rhs) + coord operator=(coord rhs) { swap(rhs); return *this; } - template - coord& operator=(coord const& rhs) + template + coord& operator=(coord const& rhs) { - coord tmp(rhs); + coord tmp(rhs); swap(tmp); return *this; } -private: - void swap(coord & rhs) + + private: + void swap(coord& rhs) { std::swap(this->x, rhs.x); std::swap(this->y, rhs.y); @@ -181,10 +204,10 @@ private: } }; -using coord2d = coord; -using coord2f = coord; -using coord2i = coord; +using coord2d = coord; +using coord2f = coord; +using coord2i = coord; -} +} // namespace mapnik #endif // MAPNIK_COORD_HPP diff --git a/include/mapnik/css/css_color_grammar_x3.hpp b/include/mapnik/css/css_color_grammar_x3.hpp index e6d8f2eee..0ed03cbf3 100644 --- a/include/mapnik/css/css_color_grammar_x3.hpp +++ b/include/mapnik/css/css_color_grammar_x3.hpp @@ -31,13 +31,11 @@ MAPNIK_DISABLE_WARNING_PUSH #include MAPNIK_DISABLE_WARNING_POP -namespace mapnik -{ +namespace mapnik { namespace x3 = boost::spirit::x3; -namespace css_color_grammar -{ +namespace css_color_grammar { struct css_color_class; using css_color_grammar_type = x3::rule; @@ -46,6 +44,7 @@ css_color_grammar_type const css_color = "css_color"; BOOST_SPIRIT_DECLARE(css_color_grammar_type); -}} +} // namespace css_color_grammar +} // namespace mapnik #endif // MAPNIK_CSS_COLOR_GRAMMAR_X3_HPP diff --git a/include/mapnik/css/css_color_grammar_x3_def.hpp b/include/mapnik/css/css_color_grammar_x3_def.hpp index 5db0d9c92..2b07f0dea 100644 --- a/include/mapnik/css/css_color_grammar_x3_def.hpp +++ b/include/mapnik/css/css_color_grammar_x3_def.hpp @@ -37,13 +37,8 @@ MAPNIK_DISABLE_WARNING_PUSH #include MAPNIK_DISABLE_WARNING_POP -BOOST_FUSION_ADAPT_STRUCT ( - mapnik::color, - (std::uint8_t, red_) - (std::uint8_t, green_) - (std::uint8_t, blue_) - (std::uint8_t, alpha_) - ) +BOOST_FUSION_ADAPT_STRUCT(mapnik::color, + (std::uint8_t, red_)(std::uint8_t, green_)(std::uint8_t, blue_)(std::uint8_t, alpha_)) namespace mapnik { @@ -51,20 +46,21 @@ namespace x3 = boost::spirit::x3; namespace css_color_grammar { -using x3::lit; -using x3::uint_parser; -using x3::hex; -using x3::symbols; -using x3::omit; using x3::attr; using x3::double_; +using x3::hex; +using x3::lit; using x3::no_case; using x3::no_skip; +using x3::omit; +using x3::symbols; +using x3::uint_parser; struct named_colors_ : x3::symbols { named_colors_() { + // clang-format off add ("aliceblue", color(240, 248, 255)) ("antiquewhite", color(250, 235, 215)) @@ -216,6 +212,7 @@ struct named_colors_ : x3::symbols ("yellowgreen", color(154, 205, 50)) ("transparent", color(0, 0, 0, 0)) ; + // clang-format on } } named_colors; @@ -226,7 +223,7 @@ x3::uint_parser dec3; // rules x3::rule const hex2_color("hex2_color"); x3::rule const hex1_color("hex1_color"); -x3::rule const rgb_color("rgb_color"); +x3::rule const rgb_color("rgb_color"); x3::rule const rgba_color("rgba_color"); x3::rule const rgb_color_percent("rgb_color_percent"); x3::rule const rgba_color_percent("rgba_color_percent"); @@ -235,97 +232,80 @@ struct clip_opacity { static double call(double val) { - if (val > 1.0) return 1.0; - if (val < 0.0) return 0.0; + if (val > 1.0) + return 1.0; + if (val < 0.0) + return 0.0; return val; } }; struct percent_converter { - static std::uint8_t call(double val) - { - return safe_cast(std::lround((255.0 * val)/100.0)); - } + static std::uint8_t call(double val) { return safe_cast(std::lround((255.0 * val) / 100.0)); } }; -auto dec_red = [](auto& ctx) -{ +auto dec_red = [](auto& ctx) { _val(ctx).red_ = _attr(ctx); }; -auto dec_green = [](auto& ctx) -{ +auto dec_green = [](auto& ctx) { _val(ctx).green_ = _attr(ctx); }; -auto dec_blue = [](auto& ctx) -{ +auto dec_blue = [](auto& ctx) { _val(ctx).blue_ = _attr(ctx); }; -auto opacity = [](auto& ctx) -{ +auto opacity = [](auto& ctx) { _val(ctx).alpha_ = uint8_t((255.0 * clip_opacity::call(_attr(ctx))) + 0.5); }; -auto percent_red = [] (auto & ctx) -{ +auto percent_red = [](auto& ctx) { _val(ctx).red_ = percent_converter::call(_attr(ctx)); }; -auto percent_green = [] (auto & ctx) -{ +auto percent_green = [](auto& ctx) { _val(ctx).green_ = percent_converter::call(_attr(ctx)); }; -auto percent_blue = [] (auto & ctx) -{ +auto percent_blue = [](auto& ctx) { _val(ctx).blue_ = percent_converter::call(_attr(ctx)); }; -auto hex1_red = [](auto& ctx) -{ +auto hex1_red = [](auto& ctx) { _val(ctx).red_ = _attr(ctx) | _attr(ctx) << 4; }; -auto hex1_green = [](auto& ctx) -{ +auto hex1_green = [](auto& ctx) { _val(ctx).green_ = _attr(ctx) | _attr(ctx) << 4; }; -auto hex1_blue = [](auto& ctx) -{ +auto hex1_blue = [](auto& ctx) { _val(ctx).blue_ = _attr(ctx) | _attr(ctx) << 4; }; -auto hex1_opacity = [](auto& ctx) -{ +auto hex1_opacity = [](auto& ctx) { _val(ctx).alpha_ = _attr(ctx) | _attr(ctx) << 4; }; -auto hex2_red = [](auto& ctx) -{ +auto hex2_red = [](auto& ctx) { _val(ctx).red_ = _attr(ctx); }; -auto hex2_green = [](auto& ctx) -{ +auto hex2_green = [](auto& ctx) { _val(ctx).green_ = _attr(ctx); }; -auto hex2_blue = [](auto& ctx) -{ +auto hex2_blue = [](auto& ctx) { _val(ctx).blue_ = _attr(ctx); }; -auto hex2_opacity = [](auto& ctx) -{ +auto hex2_opacity = [](auto& ctx) { _val(ctx).alpha_ = _attr(ctx); }; -auto hsl_to_rgba = [] (auto& ctx) -{ +auto hsl_to_rgba = [](auto& ctx) { double h = std::get<0>(_attr(ctx)); double s = std::get<1>(_attr(ctx)); double l = std::get<2>(_attr(ctx)); @@ -341,20 +321,20 @@ auto hsl_to_rgba = [] (auto& ctx) } else { - m2 = l + s - l*s; + m2 = l + s - l * s; } m1 = l * 2 - m2; - double r = hue_to_rgb(m1, m2, h + 1.0/3.0); + double r = hue_to_rgb(m1, m2, h + 1.0 / 3.0); double g = hue_to_rgb(m1, m2, h); - double b = hue_to_rgb(m1, m2, h - 1.0/3.0); + double b = hue_to_rgb(m1, m2, h - 1.0 / 3.0); uint8_t alpha = uint8_t((255.0 * clip_opacity::call(std::get<3>(_attr(ctx)))) + 0.5); _val(ctx) = color(safe_cast(std::lround(255.0 * r)), safe_cast(std::lround(255.0 * g)), safe_cast(std::lround(255.0 * b)), alpha); }; - +// clang-format off auto const hex2_color_def = no_skip[lit('#') >> hex2[hex2_red] >> hex2[hex2_green] @@ -429,21 +409,13 @@ auto const css_color_def = | hsla_color ; - +// clang-format on MAPNIK_DISABLE_WARNING_PUSH #include -BOOST_SPIRIT_DEFINE( - css_color, - hex2_color, - hex1_color, - rgb_color, - rgba_color, - rgb_color_percent, - rgba_color_percent - ); +BOOST_SPIRIT_DEFINE(css_color, hex2_color, hex1_color, rgb_color, rgba_color, rgb_color_percent, rgba_color_percent); MAPNIK_DISABLE_WARNING_POP -} // ns -} //ns mapnik +} // namespace css_color_grammar +} // namespace mapnik -#endif //MAPNIK_CSS_COLOR_GRAMMAR_X3_DEF_HPP +#endif // MAPNIK_CSS_COLOR_GRAMMAR_X3_DEF_HPP diff --git a/include/mapnik/css/css_grammar_x3.hpp b/include/mapnik/css/css_grammar_x3.hpp index b182e9993..8f8a92d1e 100644 --- a/include/mapnik/css/css_grammar_x3.hpp +++ b/include/mapnik/css/css_grammar_x3.hpp @@ -1,4 +1,4 @@ - /***************************************************************************** +/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * @@ -31,8 +31,7 @@ MAPNIK_DISABLE_WARNING_PUSH #include MAPNIK_DISABLE_WARNING_POP -namespace mapnik -{ +namespace mapnik { using property_value_type = boost::iterator_range; using css_key_value = std::pair; using definition_type = std::vector; @@ -40,8 +39,7 @@ using css_data = std::unordered_multimap; namespace x3 = boost::spirit::x3; -namespace css_grammar -{ +namespace css_grammar { class css_tag; class ident_tag; @@ -58,17 +56,14 @@ css_grammar_type const css_grammar{"css"}; css_skipper_type const css_skipper{"css skipper"}; css_classes_type const css_classes{"css classes"}; -BOOST_SPIRIT_DECLARE(ident_grammar_type, - css_classes_type, - css_grammar_type, - css_skipper_type); +BOOST_SPIRIT_DECLARE(ident_grammar_type, css_classes_type, css_grammar_type, css_skipper_type); -} +} // namespace css_grammar css_grammar::ident_grammar_type const ident_grammar(); css_grammar::css_classes_type const classes(); css_grammar::css_grammar_type const grammar(); css_grammar::css_skipper_type const skipper(); -} +} // namespace mapnik #endif // MAPNIK_CSS_GRAMMAR_X3_HPP diff --git a/include/mapnik/css/css_grammar_x3_def.hpp b/include/mapnik/css/css_grammar_x3_def.hpp index 1105f2ffa..a4f533c47 100644 --- a/include/mapnik/css/css_grammar_x3_def.hpp +++ b/include/mapnik/css/css_grammar_x3_def.hpp @@ -20,7 +20,6 @@ * *****************************************************************************/ - #ifndef MAPNIK_CSS_GRAMMAR_X3_DEF_HPP #define MAPNIK_CSS_GRAMMAR_X3_DEF_HPP @@ -33,9 +32,10 @@ MAPNIK_DISABLE_WARNING_PUSH #include MAPNIK_DISABLE_WARNING_POP - /* -The grammar below is LL(1) (but note that most UA's should not use it directly, since it doesn't express the parsing conventions, only the CSS1 syntax). The format of the productions is optimized for human consumption and some shorthand notation beyond yacc [15] is used: +The grammar below is LL(1) (but note that most UA's should not use it directly, since it doesn't express the parsing +conventions, only the CSS1 syntax). The format of the productions is optimized for human consumption and some shorthand +notation beyond yacc [15] is used: * : 0 or more + : 1 or more @@ -148,46 +148,48 @@ namespace x3 = boost::spirit::x3; namespace css_grammar { -using x3::lit; +using x3::alnum; +using x3::alpha; using x3::attr; +using x3::char_; +using x3::lexeme; +using x3::lit; using x3::no_case; using x3::no_skip; -using x3::lexeme; -using x3::alpha; -using x3::alnum; -using x3::char_; using x3::raw; using x3::standard::space; // import unicode string rule -namespace { auto const& css_string = mapnik::json::grammar::unicode_string; } +namespace { +auto const& css_string = mapnik::json::grammar::unicode_string; +} -auto assign_def = [] (auto const& ctx) -{ +auto assign_def = [](auto const& ctx) { for (auto const& k : std::get<0>(_attr(ctx))) { _val(ctx).emplace(k, std::get<1>(_attr(ctx))); } }; -auto assign_key = [] (auto const& ctx) -{ +auto assign_key = [](auto const& ctx) { _val(ctx).first = std::move(_attr(ctx)); }; -auto assign_value = [] (auto const& ctx) {_val(ctx).second = std::move(_attr(ctx));}; +auto assign_value = [](auto const& ctx) { + _val(ctx).second = std::move(_attr(ctx)); +}; // rules -x3::rule const simple_selector {"Simple selector"}; -x3::rule> const selector {"Selector"}; -x3::rule const value {"Value"}; -x3::rule const key_value {"CSS Key/Value"}; -x3::rule, definition_type>> const definition {"CSS Definition"}; +x3::rule const simple_selector{"Simple selector"}; +x3::rule> const selector{"Selector"}; +x3::rule const value{"Value"}; +x3::rule const key_value{"CSS Key/Value"}; +x3::rule, definition_type>> const definition{"CSS Definition"}; auto const ident_def = alpha >> *(alnum | char_('-')); -auto const simple_selector_def = lexeme[ident >> -((char_('.') | char_('#') | char_(':')) >> ident)] - | lexeme[char_('#') >> ident >> -((char_('.') | char_(':')) >> ident)] - | lexeme[char_('.') >> ident >> -(char_(':') >> ident)]; +auto const simple_selector_def = lexeme[ident >> -((char_('.') | char_('#') | char_(':')) >> ident)] | + lexeme[char_('#') >> ident >> -((char_('.') | char_(':')) >> ident)] | + lexeme[char_('.') >> ident >> -(char_(':') >> ident)]; auto const selector_def = simple_selector % lit(','); auto const value_def = raw[lexeme[+~char_(";}")]]; @@ -202,21 +204,19 @@ auto const css_classes_def = +lexeme[ident]; #include MAPNIK_DISABLE_WARNING_PUSH #include -BOOST_SPIRIT_DEFINE( - ident, - css_classes, - simple_selector, - selector, - value, - key_value, - definition, - css_grammar, - css_skipper - ); +BOOST_SPIRIT_DEFINE(ident, + css_classes, + simple_selector, + selector, + value, + key_value, + definition, + css_grammar, + css_skipper); MAPNIK_DISABLE_WARNING_POP -} //css_grammar -} //mapnik +} // namespace css_grammar +} // namespace mapnik -#endif //MAPNIK_CSS_GRAMMAR_X3_DEF_HPP +#endif // MAPNIK_CSS_GRAMMAR_X3_DEF_HPP diff --git a/include/mapnik/css/css_unit_value.hpp b/include/mapnik/css/css_unit_value.hpp index 2bf99d421..537e59b89 100644 --- a/include/mapnik/css/css_unit_value.hpp +++ b/include/mapnik/css/css_unit_value.hpp @@ -20,7 +20,6 @@ * *****************************************************************************/ - #ifndef MAPNIK_CSS_UNIT_VALUE_HPP #define MAPNIK_CSS_UNIT_VALUE_HPP @@ -36,15 +35,15 @@ struct css_unit_value : x3::symbols constexpr static double DPI = 96; css_unit_value() { - add - ("px", 1.0) // pixels - ("pt", DPI/72.0) // points - ("pc", DPI/6.0) // picas - ("mm", DPI/25.4) // milimeters - ("Q" , DPI/101.6)// quarter-milimeters - ("cm", DPI/2.54) // centimeters - ("in", static_cast(DPI)) // inches - ; + add // + ("px", 1.0) // pixels + ("pt", DPI / 72.0) // points + ("pc", DPI / 6.0) // picas + ("mm", DPI / 25.4) // milimeters + ("Q", DPI / 101.6) // quarter-milimeters + ("cm", DPI / 2.54) // centimeters + ("in", static_cast(DPI)) // inches + ; } }; @@ -53,15 +52,15 @@ struct css_absolute_size : x3::symbols constexpr static double EM = 10.0; // 1em == 10px css_absolute_size() { - add - ("xx-small", 0.6 * EM) - ("x-small", 0.75 * EM) - ("small", 0.88 * EM) - ("medium", 1.0 * EM) - ("large", 1.2 * EM) - ("x-large", 1.5 * EM) - ("xx-large", 2.0 * EM) - ; + add // + ("xx-small", 0.6 * EM) // + ("x-small", 0.75 * EM) // + ("small", 0.88 * EM) // + ("medium", 1.0 * EM) // + ("large", 1.2 * EM) // + ("x-large", 1.5 * EM) // + ("xx-large", 2.0 * EM) // + ; } }; @@ -69,13 +68,12 @@ struct css_relative_size : x3::symbols { css_relative_size() { - add - ("larger", 1.2) - ("smaller", 0.8) - ; + add // + ("larger", 1.2) // + ("smaller", 0.8); } }; -} //mapnik +} // namespace mapnik -#endif //MAPNIK_CSS_GRAMMAR_X3_DEF_HPP +#endif // MAPNIK_CSS_GRAMMAR_X3_DEF_HPP diff --git a/include/mapnik/csv/csv_grammar_x3.hpp b/include/mapnik/csv/csv_grammar_x3.hpp index 55a30f63d..72806a7dd 100644 --- a/include/mapnik/csv/csv_grammar_x3.hpp +++ b/include/mapnik/csv/csv_grammar_x3.hpp @@ -35,9 +35,8 @@ struct csv_white_space_skipper : x3::parser using attribute_type = x3::unused_type; static bool const has_attribute = false; - template - bool parse(Iterator& first, Iterator const& last, - Context const& context, x3::unused_type, Attribute& ) const + template + bool parse(Iterator& first, Iterator const& last, Context const& context, x3::unused_type, Attribute&) const { x3::skip_over(first, last, context); if (first != last && *first == ' ') @@ -64,6 +63,7 @@ csv_line_grammar_type const line = "csv-line"; BOOST_SPIRIT_DECLARE(csv_line_grammar_type); -}} +} // namespace grammar +} // namespace mapnik #endif // MAPNIK_CSV_GRAMMAR_X3_HPP diff --git a/include/mapnik/csv/csv_grammar_x3_def.hpp b/include/mapnik/csv/csv_grammar_x3_def.hpp index c4dcb0f6b..2fc1f021e 100644 --- a/include/mapnik/csv/csv_grammar_x3_def.hpp +++ b/include/mapnik/csv/csv_grammar_x3_def.hpp @@ -29,45 +29,44 @@ MAPNIK_DISABLE_WARNING_PUSH #include MAPNIK_DISABLE_WARNING_POP - -namespace mapnik { namespace grammar { +namespace mapnik { +namespace grammar { namespace x3 = boost::spirit::x3; namespace standard = boost::spirit::x3::standard; -using x3::lit; -using x3::lexeme; using standard::char_; +using x3::lexeme; +using x3::lit; struct unesc_char_ : x3::symbols { unesc_char_() { - add("\\a", '\a') - ("\\b", '\b') - ("\\f", '\f') - ("\\n", '\n') - ("\\r", '\r') - ("\\t", '\t') - ("\\v", '\v') - ("\\\\",'\\') - ("\\\'", '\'') - ("\\\"", '\"') - ("\"\"", '\"') // double quote - ; + add("\\a", '\a') // + ("\\b", '\b') // + ("\\f", '\f') // + ("\\n", '\n') // + ("\\r", '\r') // + ("\\t", '\t') // + ("\\v", '\v') // + ("\\\\", '\\') // + ("\\\'", '\'') // + ("\\\"", '\"') // + ("\"\"", '\"') // double quote + ; } } unesc_char; -template +template struct literal : x3::parser> { using attribute_type = x3::unused_type; using context_tag = T; static bool const has_attribute = false; - template - bool parse(Iterator& first, Iterator const& last, - Context const& context, x3::unused_type, Attribute& ) const + template + bool parse(Iterator& first, Iterator const& last, Context const& context, x3::unused_type, Attribute&) const { x3::skip_over(first, last, context); if (first != last && *first == x3::get(context)) @@ -87,27 +86,18 @@ x3::rule const column("csv-column"); x3::rule const text("csv-text"); x3::rule const quoted_text("csv-quoted-text"); -auto const line_def = -lit('\r') > -lit('\n') > lexeme[column] % separator - ; +auto const line_def = -lit('\r') > -lit('\n') > lexeme[column] % separator; -auto const column_def = quoted_text | *(char_ - separator) - ; +auto const column_def = quoted_text | *(char_ - separator); auto const quoted_text_def = quote > text > quote // support unmatched quotes or not (??) - ; + ; -auto const text_def = *(unesc_char | (char_ - quote)) - ; +auto const text_def = *(unesc_char | (char_ - quote)); -BOOST_SPIRIT_DEFINE ( - line, - column, - quoted_text, - text - ); +BOOST_SPIRIT_DEFINE(line, column, quoted_text, text); -} // grammar +} // namespace grammar } // namespace mapnik - #endif // MAPNIK_CSV_GRAMMAR_X3_DEF_HPP diff --git a/include/mapnik/csv/csv_types.hpp b/include/mapnik/csv/csv_types.hpp index 1e8695ca8..1f1618f25 100644 --- a/include/mapnik/csv/csv_types.hpp +++ b/include/mapnik/csv/csv_types.hpp @@ -32,6 +32,6 @@ using csv_value = std::string; using csv_line = std::vector; using csv_data = std::vector; -} +} // namespace mapnik #endif // MAPNIK_CSV_TYPES_HPP diff --git a/include/mapnik/cxx11_support.hpp b/include/mapnik/cxx11_support.hpp deleted file mode 100644 index f298a2074..000000000 --- a/include/mapnik/cxx11_support.hpp +++ /dev/null @@ -1,43 +0,0 @@ -/***************************************************************************** - * - * This file is part of Mapnik (c++ mapping toolkit) - * - * Copyright (C) 2021 Artem Pavlenko - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - *****************************************************************************/ - -#ifndef MAPNIK_CXX11_SUPPORT_HPP -#define MAPNIK_CXX11_SUPPORT_HPP - -#include - -namespace mapnik { -namespace detail { - -template -using conditional_t = typename std::conditional::type; - -template -using decay_t = typename std::decay::type; - -template -using enable_if_t = typename std::enable_if::type; - -} // namespace detail -} // namespace mapnik - -#endif // MAPNIK_CXX11_SUPPORT_HPP diff --git a/include/mapnik/datasource.hpp b/include/mapnik/datasource.hpp index 0099ce5a4..b08a5f993 100644 --- a/include/mapnik/datasource.hpp +++ b/include/mapnik/datasource.hpp @@ -43,31 +43,27 @@ namespace mapnik { class MAPNIK_DECL datasource_exception : public std::exception { -public: + public: datasource_exception(std::string const& message) - : message_(message) + : message_(message) {} ~datasource_exception() {} - virtual const char* what() const noexcept - { - return message_.c_str(); - } -private: + virtual const char* what() const noexcept { return message_.c_str(); } + + private: std::string message_; }; class MAPNIK_DECL datasource : private util::noncopyable { -public: - enum datasource_t : std::uint8_t { - Vector, - Raster - }; + public: + enum datasource_t : std::uint8_t { Vector, Raster }; - datasource (parameters const& _params) - : params_(_params) {} + datasource(parameters const& _params) + : params_(_params) + {} /*! * @brief Get the configuration parameters of the data source. @@ -76,25 +72,13 @@ public: * * @return The configuration parameters of the data source. */ - parameters const& params() const - { - return params_; - } + parameters const& params() const { return params_; } - parameters & params() - { - return params_; - } + parameters& params() { return params_; } - bool operator==(datasource const& rhs) const - { - return params_ == rhs.params(); - } + bool operator==(datasource const& rhs) const { return params_ == rhs.params(); } - bool operator!=(datasource const& rhs) const - { - return !(*this == rhs); - } + bool operator!=(datasource const& rhs) const { return !(*this == rhs); } /*! * @brief Get the type of the datasource @@ -113,43 +97,22 @@ public: virtual box2d envelope() const = 0; virtual layer_descriptor get_descriptor() const = 0; virtual ~datasource() {} -protected: + + protected: parameters params_; }; using datasource_name = const char* (*)(); -using create_ds = datasource* (*) (parameters const&); -using destroy_ds = void (*) (datasource *); +using create_ds = datasource* (*)(parameters const&); +using destroy_ds = void (*)(datasource*); class datasource_deleter { -public: - void operator() (datasource* ds) - { - delete ds; - } + public: + void operator()(datasource* ds) { delete ds; } }; using datasource_ptr = std::shared_ptr; - -#ifdef MAPNIK_STATIC_PLUGINS - #define DATASOURCE_PLUGIN(classname) -#else - #define DATASOURCE_PLUGIN(classname) \ - extern "C" MAPNIK_DECL const char * datasource_name() \ - { \ - return classname::name(); \ - } \ - extern "C" MAPNIK_DECL datasource* create(parameters const& params) \ - { \ - return new classname(params); \ - } \ - extern "C" MAPNIK_DECL void destroy(datasource *ds) \ - { \ - delete ds; \ - } -#endif - -} +} // namespace mapnik #endif // MAPNIK_DATASOURCE_HPP diff --git a/include/mapnik/datasource_cache.hpp b/include/mapnik/datasource_cache.hpp index c9353612d..8504b05c2 100644 --- a/include/mapnik/datasource_cache.hpp +++ b/include/mapnik/datasource_cache.hpp @@ -41,21 +41,22 @@ class datasource; class parameters; class PluginInfo; -class MAPNIK_DECL datasource_cache - : public singleton, - private util::noncopyable +class MAPNIK_DECL datasource_cache : public singleton, + private util::noncopyable { friend class CreateStatic; -public: + + public: std::vector plugin_names(); std::string plugin_directories(); bool register_datasources(std::string const& path, bool recurse = false); bool register_datasource(std::string const& path); std::shared_ptr create(parameters const& params); -private: + + private: datasource_cache(); ~datasource_cache(); - std::map > plugins_; + std::map> plugins_; std::set plugin_directories_; // the singleton has a mutex protecting the instance pointer, // but the instance also needs its own mutex to protect the @@ -66,6 +67,6 @@ private: extern template class MAPNIK_DECL singleton; -} +} // namespace mapnik #endif // MAPNIK_DATASOURCE_CACHE_HPP diff --git a/include/mapnik/datasource_geometry_type.hpp b/include/mapnik/datasource_geometry_type.hpp index 56a3eb817..9185798d8 100644 --- a/include/mapnik/datasource_geometry_type.hpp +++ b/include/mapnik/datasource_geometry_type.hpp @@ -27,15 +27,8 @@ namespace mapnik { -enum datasource_geometry_t : std::uint8_t { - Unknown = 0, - Point = 1, - LineString = 2, - Polygon = 3, - Collection = 4 -}; +enum datasource_geometry_t : std::uint8_t { Unknown = 0, Point = 1, LineString = 2, Polygon = 3, Collection = 4 }; } - #endif // MAPNIK_DATASOURCE_GEOMETRY_TYPE_HPP diff --git a/include/mapnik/debug.hpp b/include/mapnik/debug.hpp index b56e50710..33f0f1ff1 100644 --- a/include/mapnik/debug.hpp +++ b/include/mapnik/debug.hpp @@ -42,35 +42,21 @@ namespace mapnik { - // Global logger class that holds the configuration of severity, format // and file/console redirection. -class MAPNIK_DECL logger : - public singleton, - private util::noncopyable +class MAPNIK_DECL logger : public singleton, + private util::noncopyable { -public: - enum severity_type - { - debug = 0, - warn = 1, - error = 2, - none = 3 - }; + public: + enum severity_type { debug = 0, warn = 1, error = 2, none = 3 }; using severity_map = std::unordered_map; // global security level - static severity_type get_severity() - { - return severity_level_; - } + static severity_type get_severity() { return severity_level_; } - static void set_severity(severity_type severity_level) - { - severity_level_ = severity_level; - } + static void set_severity(severity_type severity_level) { severity_level_ = severity_level; } // per object security levels static severity_type get_object_severity(std::string const& object_name) @@ -89,8 +75,7 @@ public: } } - static void set_object_severity(std::string const& object_name, - severity_type const& security_level) + static void set_object_severity(std::string const& object_name, severity_type const& security_level) { if (!object_name.empty()) { @@ -111,10 +96,7 @@ public: } // format - static std::string const& get_format() - { - return format_; - } + static std::string const& get_format() { return format_; } static void set_format(std::string const& format) { @@ -131,7 +113,7 @@ public: static void use_file(std::string const& filepath); static void use_console(); -private: + private: static severity_map object_severity_level_; static std::string format_; static std::ofstream file_output_; @@ -151,7 +133,6 @@ private: #endif }; - namespace detail { // Default sink, it regulates access to clog @@ -159,7 +140,7 @@ namespace detail { template class clog_sink { -public: + public: using stream_buffer = std::basic_ostringstream; void operator()(logger::severity_type const& /*severity*/, stream_buffer const& s) @@ -177,14 +158,14 @@ public: // This is used for debug/warn reporting that should not output // anything when not compiling for speed. -template