Welcome to mirror list, hosted at ThFree Co, Russian Federation.

github.com/Ultimaker/CuraEngine.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJelle Spijker <j.spijker@ultimaker.com>2021-11-14 02:05:02 +0300
committerJelle Spijker <spijker.jelle@gmail.com>2021-11-17 22:19:32 +0300
commit7f6a1824bc6e6bb2311d03e316aa084448b8ef2a (patch)
tree30f518d73cb5270bc709d8fabf3c0d1d69730344
parent82669988d8b3f8717904bee7ae7783b880e9a620 (diff)
use conan as dependency managerconan/libArachne_rebased
-rw-r--r--.gitignore2
-rw-r--r--CMakeLists.txt584
-rw-r--r--clang-format2
-rw-r--r--cmake/FindGMock.cmake515
-rw-r--r--cmake/FindPolyclipping.cmake67
-rw-r--r--cmake/FindStb.cmake69
-rw-r--r--cmake/StandardProjectSettings.cmake321
-rw-r--r--conanfile.py108
-rw-r--r--libs/DO_NOT_CHANGE_THESE3
-rw-r--r--libs/clipper/License.txt24
-rw-r--r--libs/clipper/README413
-rw-r--r--libs/clipper/clipper.cpp4630
-rw-r--r--libs/clipper/clipper.hpp406
-rw-r--r--libs/rapidjson/allocators.h249
-rw-r--r--libs/rapidjson/document.h1965
-rw-r--r--libs/rapidjson/encodedstream.h261
-rw-r--r--libs/rapidjson/encodings.h625
-rw-r--r--libs/rapidjson/error/en.h65
-rw-r--r--libs/rapidjson/error/error.h144
-rw-r--r--libs/rapidjson/filereadstream.h88
-rw-r--r--libs/rapidjson/filewritestream.h91
-rw-r--r--libs/rapidjson/internal/biginteger.h280
-rw-r--r--libs/rapidjson/internal/diyfp.h247
-rw-r--r--libs/rapidjson/internal/dtoa.h217
-rw-r--r--libs/rapidjson/internal/ieee754.h77
-rw-r--r--libs/rapidjson/internal/itoa.h304
-rw-r--r--libs/rapidjson/internal/meta.h183
-rw-r--r--libs/rapidjson/internal/pow10.h53
-rw-r--r--libs/rapidjson/internal/stack.h177
-rw-r--r--libs/rapidjson/internal/strfunc.h37
-rw-r--r--libs/rapidjson/internal/strtod.h265
-rw-r--r--libs/rapidjson/license.txt57
-rw-r--r--libs/rapidjson/memorybuffer.h70
-rw-r--r--libs/rapidjson/memorystream.h61
-rw-r--r--libs/rapidjson/msinttypes/inttypes.h316
-rw-r--r--libs/rapidjson/msinttypes/stdint.h300
-rw-r--r--libs/rapidjson/prettywriter.h207
-rw-r--r--libs/rapidjson/rapidjson.h620
-rw-r--r--libs/rapidjson/reader.h1440
-rw-r--r--libs/rapidjson/stringbuffer.h93
-rw-r--r--libs/rapidjson/writer.h395
-rw-r--r--src/infill/ImageBasedDensityProvider.cpp2
-rw-r--r--src/raft.cpp2
-rw-r--r--src/utils/Coord_t.h2
-rw-r--r--src/utils/IntPoint.h2
-rw-r--r--src/utils/polygon.h2
-rw-r--r--tests/CMakeLists.txt103
-rw-r--r--tests/PathOrderMonotonicTest.cpp2
-rw-r--r--tests/utils/AABB3DTest.cpp2
-rw-r--r--tests/utils/AABBTest.cpp2
50 files changed, 733 insertions, 15417 deletions
diff --git a/.gitignore b/.gitignore
index 2e9b72c03..378557a38 100644
--- a/.gitignore
+++ b/.gitignore
@@ -63,3 +63,5 @@ documentation/latex/*
## Test results.
tests/output.xml
callgrind.out.*
+
+cmake-build-*/
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 4f8b7cace..e79beb770 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,427 +1,223 @@
#Copyright (c) 2021 Ultimaker B.V.
#CuraEngine is released under the terms of the AGPLv3 or higher.
-cmake_minimum_required(VERSION 3.8.0)
-
+cmake_minimum_required(VERSION 3.13)
project(CuraEngine)
-list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
-
+set(CURA_ENGINE_VERSION "master" CACHE STRING "Version name of Cura")
option(ENABLE_ARCUS "Enable support for ARCUS" ON)
-
-if (MSVC)
- option(MSVC_STATIC_RUNTIME "Link the MSVC runtime statically" OFF)
-endif()
-
-if(ENABLE_ARCUS)
- message(STATUS "Building with Arcus")
- # We want to have access to protobuf_generate_cpp and other FindProtobuf features.
- # However, if ProtobufConfig is used instead, there is a CMake option that controls
- # this, which defaults to OFF. We need to force this option to ON instead.
- set(protobuf_MODULE_COMPATIBLE ON CACHE INTERNAL "" FORCE)
- find_package(Protobuf 3.0.0 REQUIRED)
- find_package(Arcus REQUIRED)
- add_definitions(-DARCUS)
- find_program(PROTOC "protoc")
- if(${PROTOC} STREQUAL "PROTOC-NOTFOUND")
- message(FATAL_ERROR "Protobuf compiler missing")
- endif()
-endif()
-
-#For reading image files.
-find_package(Stb REQUIRED)
-include_directories(${Stb_INCLUDE_DIRS})
-
-#arachne needs boost polygon/voronoi
-find_package(Boost REQUIRED)
-include_directories(${Boost_INCLUDE_DIRS})
-
+option(BUILD_TESTS "Build with unit tests" OFF)
+option(ENABLE_OPENMP "Use OpenMP for parallel code" ON)
+option(ENABLE_MORE_COMPILER_OPTIMIZATION_FLAGS "Enable more optimization flags" ON)
option(USE_SYSTEM_LIBS "Use the system libraries if available" OFF)
-if(USE_SYSTEM_LIBS)
- find_package(RapidJSON CONFIG REQUIRED)
- find_package(Polyclipping REQUIRED)
-endif()
-
-# convert build type to upper case letters
-if(CMAKE_BUILD_TYPE)
- string(TOUPPER ${CMAKE_BUILD_TYPE} CMAKE_BUILD_TYPE_UPPER)
-endif()
+option (ENABLE_MORE_COMPILER_OPTIMIZATION_FLAGS "Enable more optimization flags" ON)
-if(CMAKE_BUILD_TYPE_UPPER MATCHES "DEBUG")
- set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CMAKE_CXX_FLAGS_DEBUG_INIT}")
-else()
- set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CMAKE_CXX_FLAGS_RELEASE_INIT}")
-endif()
-
-set(CMAKE_CXX_STANDARD 17)
-
-if(APPLE AND CMAKE_CXX_COMPILER_ID MATCHES "Clang")
- set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -stdlib=libc++")
-endif()
+include(cmake/StandardProjectSettings.cmake)
-if(NOT DEFINED LIB_SUFFIX)
- set(LIB_SUFFIX "")
-endif()
-set(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib${LIB_SUFFIX}")
+# Create Protobuf files if Arcus is used
+if (ENABLE_ARCUS)
+ message(STATUS "Building with Arcus")
-set(CURA_ENGINE_VERSION "master" CACHE STRING "Version name of Cura")
+ find_package(arcus REQUIRED)
+ find_package(Protobuf 3.17.1 REQUIRED)
-option(BUILD_TESTS OFF)
+ protobuf_generate_cpp(engine_PB_SRCS engine_PB_HEADERS Cura.proto)
+endif ()
-# Add a compiler flag to check the output for insane values if we are in debug mode.
-if(CMAKE_BUILD_TYPE_UPPER MATCHES "DEBUG" OR CMAKE_BUILD_TYPE_UPPER MATCHES "RELWITHDEBINFO")
- message(STATUS "Building debug release of CuraEngine.")
- if (NOT MSVC)
- set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wextra -O0 -g -fno-omit-frame-pointer")
- endif()
- add_definitions(-DASSERT_INSANE_OUTPUT)
- add_definitions(-DUSE_CPU_TIME)
- add_definitions(-DDEBUG)
-endif()
+### Compiling CuraEngine ###
+# First compile all of CuraEngine as library, allowing this to be re-used for tests.
-if (MSVC)
- set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /permissive- /Zc:twoPhase- /EHsc /W3")
- if (MSVC_STATIC_RUNTIME)
- foreach(flag_var
- CMAKE_CXX_FLAGS
- CMAKE_CXX_FLAGS_DEBUG
- CMAKE_CXX_FLAGS_RELEASE
- CMAKE_CXX_FLAGS_MINSIZEREL
- CMAKE_CXX_FLAGS_RELWITHDEBINFO
+set(engine_SRCS # Except main.cpp.
+ src/Application.cpp
+ src/bridge.cpp
+ src/ConicalOverhang.cpp
+ src/ExtruderTrain.cpp
+ src/FffGcodeWriter.cpp
+ src/FffPolygonGenerator.cpp
+ src/FffProcessor.cpp
+ src/gcodeExport.cpp
+ src/GCodePathConfig.cpp
+ src/infill.cpp
+ src/InsetOrderOptimizer.cpp
+ src/layerPart.cpp
+ src/LayerPlan.cpp
+ src/LayerPlanBuffer.cpp
+ src/mesh.cpp
+ src/MeshGroup.cpp
+ src/Mold.cpp
+ src/multiVolumes.cpp
+ src/PathOrderOptimizer.cpp
+ src/PathOrder.cpp
+ src/Preheat.cpp
+ src/PrimeTower.cpp
+ src/raft.cpp
+ src/Scene.cpp
+ src/SkeletalTrapezoidation.cpp
+ src/SkeletalTrapezoidationGraph.cpp
+ src/skin.cpp
+ src/SkirtBrim.cpp
+ src/SupportInfillPart.cpp
+ src/Slice.cpp
+ src/sliceDataStorage.cpp
+ src/slicer.cpp
+ src/support.cpp
+ src/timeEstimate.cpp
+ src/TopSurface.cpp
+ src/TreeSupport.cpp
+ src/WallsComputation.cpp
+ src/Weaver.cpp
+ src/Wireframe2gcode.cpp
+ src/WallToolPaths.cpp
+
+ src/BeadingStrategy/BeadingOrderOptimizer.cpp
+ src/BeadingStrategy/BeadingStrategy.cpp
+ src/BeadingStrategy/BeadingStrategyFactory.cpp
+ src/BeadingStrategy/CenterDeviationBeadingStrategy.cpp
+ src/BeadingStrategy/DistributedBeadingStrategy.cpp
+ src/BeadingStrategy/LimitedBeadingStrategy.cpp
+ src/BeadingStrategy/RedistributeBeadingStrategy.cpp
+ src/BeadingStrategy/WideningBeadingStrategy.cpp
+ src/BeadingStrategy/OuterWallInsetBeadingStrategy.cpp
+
+ src/communication/ArcusCommunication.cpp
+ src/communication/ArcusCommunicationPrivate.cpp
+ src/communication/CommandLine.cpp
+ src/communication/Listener.cpp
+
+ src/infill/ImageBasedDensityProvider.cpp
+ src/infill/NoZigZagConnectorProcessor.cpp
+ src/infill/ZigzagConnectorProcessor.cpp
+ src/infill/LightningDistanceField.cpp
+ src/infill/LightningGenerator.cpp
+ src/infill/LightningLayer.cpp
+ src/infill/LightningTreeNode.cpp
+ src/infill/SierpinskiFill.cpp
+ src/infill/SierpinskiFillProvider.cpp
+ src/infill/SubDivCube.cpp
+ src/infill/GyroidInfill.cpp
+
+ src/pathPlanning/Comb.cpp
+ src/pathPlanning/GCodePath.cpp
+ src/pathPlanning/LinePolygonsCrossings.cpp
+ src/pathPlanning/NozzleTempInsert.cpp
+ src/pathPlanning/TimeMaterialEstimates.cpp
+
+ src/progress/Progress.cpp
+ src/progress/ProgressStageEstimator.cpp
+
+ src/settings/AdaptiveLayerHeights.cpp
+ src/settings/FlowTempGraph.cpp
+ src/settings/PathConfigStorage.cpp
+ src/settings/Settings.cpp
+ src/settings/ZSeamConfig.cpp
+
+ src/utils/AABB.cpp
+ src/utils/AABB3D.cpp
+ src/utils/Date.cpp
+ src/utils/ExtrusionJunction.cpp
+ src/utils/ExtrusionLine.cpp
+ src/utils/ExtrusionSegment.cpp
+ src/utils/FMatrix4x3.cpp
+ src/utils/gettime.cpp
+ src/utils/getpath.cpp
+ src/utils/LinearAlg2D.cpp
+ src/utils/ListPolyIt.cpp
+ src/utils/logoutput.cpp
+ src/utils/MinimumSpanningTree.cpp
+ src/utils/Point3.cpp
+ src/utils/PolygonConnector.cpp
+ src/utils/PolygonsPointIndex.cpp
+ src/utils/PolygonsSegmentIndex.cpp
+ src/utils/polygonUtils.cpp
+ src/utils/polygon.cpp
+ src/utils/ProximityPointLink.cpp
+ src/utils/SVG.cpp
+ src/utils/socket.cpp
+ src/utils/SquareGrid.cpp
+ src/utils/ToolpathVisualizer.cpp
+ src/utils/VoronoiUtils.cpp
+ )
+add_library(_CuraEngine STATIC ${engine_SRCS} ${engine_PB_SRCS})
+use_threads(_CuraEngine)
+
+target_include_directories(_CuraEngine
+ PUBLIC
+ $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/src>
+ $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>
+ $<BUILD_INTERFACE:${CMAKE_CURRENT_BINARY_DIR}> # Include Cura.pb.h
+ )
+target_compile_definitions(_CuraEngine
+ PUBLIC
+ $<$<BOOL:${BUILD_TESTS}>:BUILD_TESTS=1>
+ $<$<BOOL:${BUILD_TESTS}>:BUILD_TESTS>
+ $<$<BOOL:${ENABLE_ARCUS}>:ARCUS>
+ PRIVATE
+ VERSION=\"${CURA_ENGINE_VERSION}\"
+ $<$<BOOL:${WIN32}>:NOMINMAX>
+ $<$<CONFIG:Debug>:ASSERT_INSANE_OUTPUT>
+ $<$<CONFIG:Debug>:USE_CPU_TIME>
+ $<$<CONFIG:Debug>:DEBUG>
+ $<$<CONFIG:RelWithDebInfo>:ASSERT_INSANE_OUTPUT>
+ $<$<CONFIG:RelWithDebInfo>:USE_CPU_TIME>
+ $<$<CONFIG:RelWithDebInfo>:DEBUG>
+ )
+if(MSVC)
+ target_compile_options(_CuraEngine
+ PRIVATE
+ $<$<AND:$<BOOL:${ENABLE_MORE_COMPILER_OPTIMIZATION_FLAGS}>,$<CONFIG:Release>>:/fp:fast>
)
- if(${flag_var} MATCHES "/MD")
- string(REGEX REPLACE "/MD" "/MT" ${flag_var} "${${flag_var}}")
- endif()
- endforeach()
- endif()
else()
- set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall") # Add warnings
-endif()
-
-option (ENABLE_MORE_COMPILER_OPTIMIZATION_FLAGS
- "Enable more optimization flags" ON)
-if (ENABLE_MORE_COMPILER_OPTIMIZATION_FLAGS AND NOT (CMAKE_BUILD_TYPE_UPPER MATCHES "DEBUG"))
- message (STATUS "Compile with more optimization flags")
- if (MSVC)
- set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS} /fp:fast")
- else()
- set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS} -Ofast -funroll-loops")
- endif()
-endif ()
-
-if(NOT APPLE AND NOT WIN32)
- set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -static-libstdc++")
-endif()
-
-if (WIN32)
- add_definitions(-DNOMINMAX)
+ target_compile_options(_CuraEngine
+ PRIVATE
+ $<$<CONFIG:Debug>:-fno-omit-frame-pointer>
+ $<$<CONFIG:RelWithDebInfo>:-fno-omit-frame-pointer>
+ $<$<AND:$<BOOL:${ENABLE_MORE_COMPILER_OPTIMIZATION_FLAGS}>,$<CONFIG:Release>>:-Ofast>
+ $<$<AND:$<BOOL:${ENABLE_MORE_COMPILER_OPTIMIZATION_FLAGS}>,$<CONFIG:Release>>:-funroll-loops>
+ )
endif()
-option (ENABLE_OPENMP
- "Use OpenMP for parallel code" ON)
-
-if (ENABLE_OPENMP)
- FIND_PACKAGE( OpenMP )
- if( OPENMP_FOUND )
- set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}" )
- endif()
-endif()
+set_project_standards(_CuraEngine)
+set_project_warnings(_CuraEngine)
+enable_sanitizers(_CuraEngine)
-if(USE_SYSTEM_LIBS)
- include_directories(${Polyclipping_INCLUDE_DIRS} "${CMAKE_BINARY_DIR}" ${RAPIDJSON_INCLUDE_DIRS})
-else()
- include_directories("${CMAKE_CURRENT_BINARY_DIR}" libs libs/clipper)
- add_library(clipper STATIC libs/clipper/clipper.cpp)
+if(ENABLE_OPENMP)
+ find_package(OpenMP REQUIRED)
+ target_link_libraries(_CuraEngine PUBLIC OpenMP::OpenMP_CXX)
endif()
-set(engine_SRCS # Except main.cpp.
- src/Application.cpp
- src/bridge.cpp
- src/ConicalOverhang.cpp
- src/ExtruderTrain.cpp
- src/FffGcodeWriter.cpp
- src/FffPolygonGenerator.cpp
- src/FffProcessor.cpp
- src/gcodeExport.cpp
- src/GCodePathConfig.cpp
- src/infill.cpp
- src/InsetOrderOptimizer.cpp
- src/layerPart.cpp
- src/LayerPlan.cpp
- src/LayerPlanBuffer.cpp
- src/mesh.cpp
- src/MeshGroup.cpp
- src/Mold.cpp
- src/multiVolumes.cpp
- src/PathOrderOptimizer.cpp
- src/PathOrder.cpp
- src/Preheat.cpp
- src/PrimeTower.cpp
- src/raft.cpp
- src/Scene.cpp
- src/SkeletalTrapezoidation.cpp
- src/SkeletalTrapezoidationGraph.cpp
- src/skin.cpp
- src/SkirtBrim.cpp
- src/SupportInfillPart.cpp
- src/Slice.cpp
- src/sliceDataStorage.cpp
- src/slicer.cpp
- src/support.cpp
- src/timeEstimate.cpp
- src/TopSurface.cpp
- src/TreeSupport.cpp
- src/WallsComputation.cpp
- src/Weaver.cpp
- src/Wireframe2gcode.cpp
- src/WallToolPaths.cpp
-
- src/BeadingStrategy/BeadingOrderOptimizer.cpp
- src/BeadingStrategy/BeadingStrategy.cpp
- src/BeadingStrategy/BeadingStrategyFactory.cpp
- src/BeadingStrategy/CenterDeviationBeadingStrategy.cpp
- src/BeadingStrategy/DistributedBeadingStrategy.cpp
- src/BeadingStrategy/LimitedBeadingStrategy.cpp
- src/BeadingStrategy/RedistributeBeadingStrategy.cpp
- src/BeadingStrategy/WideningBeadingStrategy.cpp
- src/BeadingStrategy/OuterWallInsetBeadingStrategy.cpp
-
- src/communication/ArcusCommunication.cpp
- src/communication/ArcusCommunicationPrivate.cpp
- src/communication/CommandLine.cpp
- src/communication/Listener.cpp
-
- src/infill/ImageBasedDensityProvider.cpp
- src/infill/NoZigZagConnectorProcessor.cpp
- src/infill/ZigzagConnectorProcessor.cpp
- src/infill/LightningDistanceField.cpp
- src/infill/LightningGenerator.cpp
- src/infill/LightningLayer.cpp
- src/infill/LightningTreeNode.cpp
- src/infill/SierpinskiFill.cpp
- src/infill/SierpinskiFillProvider.cpp
- src/infill/SubDivCube.cpp
- src/infill/GyroidInfill.cpp
-
- src/pathPlanning/Comb.cpp
- src/pathPlanning/GCodePath.cpp
- src/pathPlanning/LinePolygonsCrossings.cpp
- src/pathPlanning/NozzleTempInsert.cpp
- src/pathPlanning/TimeMaterialEstimates.cpp
-
- src/progress/Progress.cpp
- src/progress/ProgressStageEstimator.cpp
-
- src/settings/AdaptiveLayerHeights.cpp
- src/settings/FlowTempGraph.cpp
- src/settings/PathConfigStorage.cpp
- src/settings/Settings.cpp
- src/settings/ZSeamConfig.cpp
-
- src/utils/AABB.cpp
- src/utils/AABB3D.cpp
- src/utils/Date.cpp
- src/utils/ExtrusionJunction.cpp
- src/utils/ExtrusionLine.cpp
- src/utils/ExtrusionSegment.cpp
- src/utils/FMatrix4x3.cpp
- src/utils/gettime.cpp
- src/utils/getpath.cpp
- src/utils/LinearAlg2D.cpp
- src/utils/ListPolyIt.cpp
- src/utils/logoutput.cpp
- src/utils/MinimumSpanningTree.cpp
- src/utils/Point3.cpp
- src/utils/PolygonConnector.cpp
- src/utils/PolygonsPointIndex.cpp
- src/utils/PolygonsSegmentIndex.cpp
- src/utils/polygonUtils.cpp
- src/utils/polygon.cpp
- src/utils/ProximityPointLink.cpp
- src/utils/SVG.cpp
- src/utils/socket.cpp
- src/utils/SquareGrid.cpp
- src/utils/ToolpathVisualizer.cpp
- src/utils/VoronoiUtils.cpp
-)
-
-# List of tests. For each test there must be a file tests/${NAME}.cpp.
-set(engine_TEST
- ExtruderPlanTest
- GCodeExportTest
- InfillTest
- LayerPlanTest
- PathOrderOptimizerTest
- PathOrderMonotonicTest
- TimeEstimateCalculatorTest
- WallsComputationTest
-)
-if (ENABLE_ARCUS)
- set(engine_TEST_ARCUS
- ArcusCommunicationTest
- ArcusCommunicationPrivateTest
- )
-endif ()
-set(engine_TEST_BEADING_STRATEGY
- CenterDeviationBeadingStrategyTest
-)
-set(engine_TEST_INFILL
-)
-set(engine_TEST_INTEGRATION
- SlicePhaseTest
-)
-set(engine_TEST_SETTINGS
- SettingsTest
-)
-set(engine_TEST_UTILS
- AABBTest
- AABB3DTest
- ExtrusionLineTest
- IntPointTest
- LinearAlg2DTest
- MinimumSpanningTreeTest
- PolygonConnectorTest
- PolygonTest
- PolygonUtilsTest
- SparseGridTest
- StringTest
- UnionFindTest
-)
-
-# Helper classes for some tests.
-set(engine_TEST_ARCUS_HELPERS
- tests/arcus/MockSocket.cpp
-)
-set(engine_TEST_HELPERS
- tests/ReadTestPolygons.cpp
-)
-
-# Generating ProtoBuf protocol
-if (ENABLE_ARCUS)
- protobuf_generate_cpp(engine_PB_SRCS engine_PB_HEADERS Cura.proto)
-endif ()
-
-# Compiling CuraEngine itself.
-add_library(_CuraEngine STATIC ${engine_SRCS} ${engine_PB_SRCS}) #First compile all of CuraEngine as library, allowing this to be re-used for tests.
-
-if (CuraEngine_Download_Stb)
- add_dependencies(_CuraEngine stb)
-endif()
-if(USE_SYSTEM_LIBS)
- target_link_libraries(_CuraEngine ${Polyclipping_LIBRARIES})
-else()
- target_link_libraries(_CuraEngine clipper)
+if(ENABLE_ARCUS)
+ target_link_libraries(_CuraEngine PRIVATE arcus::arcus protobuf::libprotobuf)
endif()
-if (ENABLE_ARCUS)
- target_link_libraries(_CuraEngine Arcus)
-endif ()
-
-set_target_properties(_CuraEngine PROPERTIES COMPILE_DEFINITIONS "VERSION=\"${CURA_ENGINE_VERSION}\"")
+find_package(clipper REQUIRED)
+find_package(RapidJSON REQUIRED)
+find_package(stb REQUIRED)
+find_package(boost REQUIRED)
+target_link_libraries(_CuraEngine PRIVATE clipper::clipper rapidjson::rapidjson stb::stb boost::boost)
+### Compile the CLI ###
if(WIN32)
- message(STATUS "Using windres")
- set(RES_FILES "CuraEngine.rc")
- ENABLE_LANGUAGE(RC)
- if(NOT MSVC)
- SET(CMAKE_RC_COMPILER_INIT windres)
- SET(CMAKE_RC_COMPILE_OBJECT
- "<CMAKE_RC_COMPILER> <FLAGS> -O coff <DEFINES> -i <SOURCE> -o <OBJECT>"
- )
- endif()
+ message(STATUS "Using windres")
+ set(RES_FILES "CuraEngine.rc")
+ ENABLE_LANGUAGE(RC)
+ if(NOT MSVC)
+ SET(CMAKE_RC_COMPILER_INIT windres)
+ SET(CMAKE_RC_COMPILE_OBJECT "<CMAKE_RC_COMPILER> <FLAGS> -O coff <DEFINES> -i <SOURCE> -o <OBJECT>")
+ endif()
endif(WIN32)
-if (UNIX)
- target_link_libraries(_CuraEngine pthread)
-endif()
-
+# Then compile main.cpp as separate executable, and link the library to it.
if (NOT WIN32)
- add_executable(CuraEngine src/main.cpp) # Then compile main.cpp as separate executable, and link the library to it.
+ add_executable(CuraEngine src/main.cpp)
else()
- add_executable(CuraEngine src/main.cpp ${RES_FILES}) # ..., but don't forget the glitter!
+ add_executable(CuraEngine src/main.cpp ${RES_FILES}) # ..., but don't forget the glitter!
endif(NOT WIN32)
-
-target_link_libraries(CuraEngine _CuraEngine)
-set_target_properties(CuraEngine PROPERTIES COMPILE_DEFINITIONS "VERSION=\"${CURA_ENGINE_VERSION}\"")
+target_link_libraries(CuraEngine PRIVATE _CuraEngine)
+set_project_standards(CuraEngine)
+set_project_warnings(CuraEngine)
+use_threads(CuraEngine)
# Compiling the test environment.
if (BUILD_TESTS)
- include(CTest)
-
- message(STATUS "Building tests...")
- set(GTEST_USE_STATIC_LIBS true)
- set(GMOCK_ROOT "${CMAKE_CURRENT_BINARY_DIR}/gmock")
- set(GMOCK_VER "1.8.0")
- find_package(GMock REQUIRED)
- include_directories(${GTEST_INCLUDE_DIRS})
- include_directories(${GMOCK_INCLUDE_DIRS})
- add_dependencies(_CuraEngine GTest::GTest GTest::Main GMock::GMock GMock::Main)
- add_definitions(-DBUILD_TESTS)
-
- target_compile_definitions(_CuraEngine PUBLIC BUILD_TESTS=1)
-
- #To make sure that the tests are built before running them, add the building of these tests as an additional test.
- add_custom_target(build_all_tests)
- add_test(BuildTests "${CMAKE_COMMAND}" --build "${CMAKE_CURRENT_BINARY_DIR}" --target build_all_tests)
-
- foreach (test ${engine_TEST})
- add_executable(${test} tests/main.cpp ${engine_TEST_HELPERS} tests/${test}.cpp)
- target_link_libraries(${test} _CuraEngine ${GTEST_BOTH_LIBRARIES} ${GMOCK_BOTH_LIBRARIES})
- add_test(NAME ${test} COMMAND "${test}" WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/tests/")
- add_dependencies(build_all_tests ${test}) #Make sure that this gets built as part of the build_all_tests target.
- endforeach()
- if (ENABLE_ARCUS)
- foreach(test ${engine_TEST_ARCUS})
- add_executable(${test} tests/main.cpp ${engine_TEST_ARCUS_HELPERS} tests/arcus/${test}.cpp)
- target_link_libraries(${test} _CuraEngine ${GTEST_BOTH_LIBRARIES} ${GMOCK_BOTH_LIBRARIES})
- add_test(NAME ${test} COMMAND "${test}" WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/tests/")
- add_dependencies(build_all_tests ${test}) #Make sure that this gets built as part of the build_all_tests target.
- endforeach()
- endif()
- foreach(test ${engine_TEST_BEADING_STRATEGY})
- add_executable(${test} tests/main.cpp tests/beading_strategy/${test}.cpp)
- target_link_libraries(${test} _CuraEngine ${GTEST_BOTH_LIBRARIES} ${GMOCK_BOTH_LIBRARIES})
- add_test(NAME ${test} COMMAND "${test}" WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/tests/")
- add_dependencies(build_all_tests ${test}) #Make sure that this gets built as part of the build_all_tests target.
- endforeach()
- foreach (test ${engine_TEST_INFILL})
- add_executable(${test} tests/main.cpp tests/infill/${test}.cpp)
- target_link_libraries(${test} _CuraEngine ${GTEST_BOTH_LIBRARIES} ${GMOCK_BOTH_LIBRARIES})
- add_test(NAME ${test} COMMAND "${test}" WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/tests/")
- add_dependencies(build_all_tests ${test}) #Make sure that this gets built as part of the build_all_tests target.
- endforeach()
- foreach (test ${engine_TEST_INTEGRATION})
- add_executable(${test} tests/main.cpp tests/integration/${test}.cpp)
- target_link_libraries(${test} _CuraEngine ${GTEST_BOTH_LIBRARIES} ${GMOCK_BOTH_LIBRARIES})
- add_test(NAME ${test} COMMAND "${test}" WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/tests/")
- add_dependencies(build_all_tests ${test}) #Make sure that this gets built as part of the build_all_tests target.
- endforeach()
- foreach (test ${engine_TEST_SETTINGS})
- add_executable(${test} tests/main.cpp tests/settings/${test}.cpp)
- target_link_libraries(${test} _CuraEngine ${GTEST_BOTH_LIBRARIES} ${GMOCK_BOTH_LIBRARIES})
- add_test(NAME ${test} COMMAND "${test}" WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/tests/")
- add_dependencies(build_all_tests ${test}) #Make sure that this gets built as part of the build_all_tests target.
- endforeach()
- foreach (test ${engine_TEST_UTILS})
- add_executable(${test} tests/main.cpp tests/utils/${test}.cpp)
- target_link_libraries(${test} _CuraEngine ${GTEST_BOTH_LIBRARIES} ${GMOCK_BOTH_LIBRARIES})
- add_test(NAME ${test} COMMAND "${test}" WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/tests/")
- add_dependencies(build_all_tests ${test}) #Make sure that this gets built as part of the build_all_tests target.
- endforeach()
+ add_subdirectory(tests)
endif()
-
-# Installing CuraEngine.
-include(GNUInstallDirs)
-install(TARGETS CuraEngine DESTINATION "${CMAKE_INSTALL_BINDIR}")
-# For MinGW64 cross compiling on Debian, we create a ZIP package instead of a DEB
-# Because it's the Windows build system that should install the files.
-if (CMAKE_CROSSCOMPILING AND CMAKE_SYSTEM_NAME MATCHES "Windows")
- message(STATUS "Include MinGW64 posix DLLs for installation.")
- install(FILES
- /usr/lib/gcc/x86_64-w64-mingw32/8.3-posix/libgcc_s_seh-1.dll
- /usr/lib/gcc/x86_64-w64-mingw32/8.3-posix/libgomp-1.dll
- /usr/lib/gcc/x86_64-w64-mingw32/8.3-posix/libstdc++-6.dll
- DESTINATION bin
- COMPONENT runtime)
-endif ()
-include(CPackConfig.cmake)
diff --git a/clang-format b/clang-format
index e3c247c51..dc8beeb4b 100644
--- a/clang-format
+++ b/clang-format
@@ -1,4 +1,4 @@
----
+---
AllowAllParametersOfDeclarationOnNextLine: 'true'
AllowShortBlocksOnASingleLine: 'true'
AllowShortFunctionsOnASingleLine: None
diff --git a/cmake/FindGMock.cmake b/cmake/FindGMock.cmake
deleted file mode 100644
index 8d7324242..000000000
--- a/cmake/FindGMock.cmake
+++ /dev/null
@@ -1,515 +0,0 @@
-# Get the Google C++ Mocking Framework.
-# (This file is almost an copy of the original FindGTest.cmake file,
-# altered to download and compile GMock and GTest if not found
-# in GMOCK_ROOT or GTEST_ROOT respectively,
-# feel free to use it as it is or modify it for your own needs.)
-#
-# Defines the following variables:
-#
-# GMOCK_FOUND - Found or got the Google Mocking framework
-# GTEST_FOUND - Found or got the Google Testing framework
-# GMOCK_INCLUDE_DIRS - GMock include directory
-# GTEST_INCLUDE_DIRS - GTest include direcotry
-#
-# Also defines the library variables below as normal variables
-#
-# GMOCK_BOTH_LIBRARIES - Both libgmock & libgmock_main
-# GMOCK_LIBRARIES - libgmock
-# GMOCK_MAIN_LIBRARIES - libgmock-main
-#
-# GTEST_BOTH_LIBRARIES - Both libgtest & libgtest_main
-# GTEST_LIBRARIES - libgtest
-# GTEST_MAIN_LIBRARIES - libgtest_main
-#
-# Accepts the following variables as input:
-#
-# GMOCK_ROOT - The root directory of the gmock install prefix
-# GTEST_ROOT - The root directory of the gtest install prefix
-# GMOCK_SRC_DIR -The directory of the gmock sources
-# GMOCK_VER - The version of the gmock sources to be downloaded
-#
-#-----------------------
-# Example Usage:
-#
-# set(GMOCK_ROOT "~/gmock")
-# find_package(GMock REQUIRED)
-# include_directories(${GMOCK_INCLUDE_DIRS})
-#
-# add_executable(foo foo.cc)
-# target_link_libraries(foo ${GMOCK_BOTH_LIBRARIES})
-#
-#=============================================================================
-# Copyright (c) 2016 Michel Estermann
-# Copyright (c) 2016 Kamil Strzempowicz
-# Copyright (c) 2011 Matej Svec
-#
-# CMake - Cross Platform Makefile Generator
-# Copyright 2000-2016 Kitware, Inc.
-# Copyright 2000-2011 Insight Software Consortium
-# All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions
-# are met:
-#
-# * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-#
-# * Redistributions in binary form must reproduce the above copyright
-# notice, this list of conditions and the following disclaimer in the
-# documentation and/or other materials provided with the distribution.
-#
-# * Neither the names of Kitware, Inc., the Insight Software Consortium,
-# nor the names of their contributors may be used to endorse or promote
-# products derived from this software without specific prior written
-# permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-#
-# ------------------------------------------------------------------------------
-#
-# The above copyright and license notice applies to distributions of
-# CMake in source and binary form. Some source files contain additional
-# notices of original copyright by their contributors; see each source
-# for details. Third-party software packages supplied with CMake under
-# compatible licenses provide their own copyright notices documented in
-# corresponding subdirectories.
-#
-# ------------------------------------------------------------------------------
-#
-# CMake was initially developed by Kitware with the following sponsorship:
-#
-# * National Library of Medicine at the National Institutes of Health
-# as part of the Insight Segmentation and Registration Toolkit (ITK).
-#
-# * US National Labs (Los Alamos, Livermore, Sandia) ASC Parallel
-# Visualization Initiative.
-#
-# * National Alliance for Medical Image Computing (NAMIC) is funded by the
-# National Institutes of Health through the NIH Roadmap for Medical Research,
-# Grant U54 EB005149.
-#
-# * Kitware, Inc.
-#=============================================================================
-# Thanks to Daniel Blezek <blezek@gmail.com> for the GTEST_ADD_TESTS code
-
-function(gtest_add_tests executable extra_args)
- if(NOT ARGN)
- message(FATAL_ERROR "Missing ARGN: Read the documentation for GTEST_ADD_TESTS")
- endif()
- if(ARGN STREQUAL "AUTO")
- # obtain sources used for building that executable
- get_property(ARGN TARGET ${executable} PROPERTY SOURCES)
- endif()
- set(gtest_case_name_regex ".*\\( *([A-Za-z_0-9]+) *, *([A-Za-z_0-9]+) *\\).*")
- set(gtest_test_type_regex "(TYPED_TEST|TEST_?[FP]?)")
- foreach(source ${ARGN})
- file(READ "${source}" contents)
- string(REGEX MATCHALL "${gtest_test_type_regex} *\\(([A-Za-z_0-9 ,]+)\\)" found_tests ${contents})
- foreach(hit ${found_tests})
- string(REGEX MATCH "${gtest_test_type_regex}" test_type ${hit})
-
- # Parameterized tests have a different signature for the filter
- if("x${test_type}" STREQUAL "xTEST_P")
- string(REGEX REPLACE ${gtest_case_name_regex} "*/\\1.\\2/*" test_name ${hit})
- elseif("x${test_type}" STREQUAL "xTEST_F" OR "x${test_type}" STREQUAL "xTEST")
- string(REGEX REPLACE ${gtest_case_name_regex} "\\1.\\2" test_name ${hit})
- elseif("x${test_type}" STREQUAL "xTYPED_TEST")
- string(REGEX REPLACE ${gtest_case_name_regex} "\\1/*.\\2" test_name ${hit})
- else()
- message(WARNING "Could not parse GTest ${hit} for adding to CTest.")
- continue()
- endif()
- add_test(NAME ${test_name} COMMAND ${executable} --gtest_filter=${test_name} ${extra_args})
- endforeach()
- endforeach()
-endfunction()
-
-function(_append_debugs _endvar _library)
- if(${_library} AND ${_library}_DEBUG)
- set(_output optimized ${${_library}} debug ${${_library}_DEBUG})
- else()
- set(_output ${${_library}})
- endif()
- set(${_endvar} ${_output} PARENT_SCOPE)
-endfunction()
-
-function(_gmock_find_library _name)
- find_library(${_name}
- NAMES ${ARGN}
- HINTS
- ENV GMOCK_ROOT
- ${GMOCK_ROOT}
- PATH_SUFFIXES ${_gmock_libpath_suffixes}
- )
- mark_as_advanced(${_name})
-endfunction()
-
-function(_gtest_find_library _name)
- find_library(${_name}
- NAMES ${ARGN}
- HINTS
- ENV GTEST_ROOT
- ${GTEST_ROOT}
- PATH_SUFFIXES ${_gtest_libpath_suffixes}
- )
- mark_as_advanced(${_name})
-endfunction()
-
-if(NOT DEFINED GMOCK_MSVC_SEARCH)
- set(GMOCK_MSVC_SEARCH MD)
-endif()
-
-set(_gmock_libpath_suffixes lib)
-set(_gtest_libpath_suffixes lib)
-if(MSVC)
- if(GMOCK_MSVC_SEARCH STREQUAL "MD")
- list(APPEND _gmock_libpath_suffixes
- msvc/gmock-md/Debug
- msvc/gmock-md/Release)
- list(APPEND _gtest_libpath_suffixes
- msvc/gtest-md/Debug
- msvc/gtest-md/Release)
- elseif(GMOCK_MSVC_SEARCH STREQUAL "MT")
- list(APPEND _gmock_libpath_suffixes
- msvc/gmock/Debug
- msvc/gmock/Release)
- list(APPEND _gtest_libpath_suffixes
- msvc/gtest/Debug
- msvc/gtest/Release)
- endif()
-endif()
-
-find_path(GMOCK_INCLUDE_DIR gmock/gmock.h
- HINTS
- $ENV{GMOCK_ROOT}/include
- ${GMOCK_ROOT}/include
- )
-mark_as_advanced(GMOCK_INCLUDE_DIR)
-
-find_path(GTEST_INCLUDE_DIR gtest/gtest.h
- HINTS
- $ENV{GTEST_ROOT}/include
- ${GTEST_ROOT}/include
- )
-mark_as_advanced(GTEST_INCLUDE_DIR)
-
-if(MSVC AND GMOCK_MSVC_SEARCH STREQUAL "MD")
- # The provided /MD project files for Google Mock add -md suffixes to the
- # library names.
- _gmock_find_library(GMOCK_LIBRARY gmock-md gmock)
- _gmock_find_library(GMOCK_LIBRARY_DEBUG gmock-mdd gmockd)
- _gmock_find_library(GMOCK_MAIN_LIBRARY gmock_main-md gmock_main)
- _gmock_find_library(GMOCK_MAIN_LIBRARY_DEBUG gmock_main-mdd gmock_maind)
-
- _gtest_find_library(GTEST_LIBRARY gtest-md gtest)
- _gtest_find_library(GTEST_LIBRARY_DEBUG gtest-mdd gtestd)
- _gtest_find_library(GTEST_MAIN_LIBRARY gtest_main-md gtest_main)
- _gtest_find_library(GTEST_MAIN_LIBRARY_DEBUG gtest_main-mdd gtest_maind)
-else()
- _gmock_find_library(GMOCK_LIBRARY gmock)
- _gmock_find_library(GMOCK_LIBRARY_DEBUG gmockd)
- _gmock_find_library(GMOCK_MAIN_LIBRARY gmock_main)
- _gmock_find_library(GMOCK_MAIN_LIBRARY_DEBUG gmock_maind)
-
- _gtest_find_library(GTEST_LIBRARY gtest)
- _gtest_find_library(GTEST_LIBRARY_DEBUG gtestd)
- _gtest_find_library(GTEST_MAIN_LIBRARY gtest_main)
- _gtest_find_library(GTEST_MAIN_LIBRARY_DEBUG gtest_maind)
-endif()
-
-if(NOT TARGET GTest::GTest)
- add_library(GTest::GTest UNKNOWN IMPORTED)
-endif()
-if(NOT TARGET GTest::Main)
- add_library(GTest::Main UNKNOWN IMPORTED)
-endif()
-
-if(NOT TARGET GMock::GMock)
- add_library(GMock::GMock UNKNOWN IMPORTED)
-endif()
-
-if(NOT TARGET GMock::Main)
- add_library(GMock::Main UNKNOWN IMPORTED)
-endif()
-
-set(GMOCK_LIBRARY_EXISTS OFF)
-set(GTEST_LIBRARY_EXISTS OFF)
-
-if(EXISTS "${GMOCK_LIBRARY}" OR EXISTS "${GMOCK_LIBRARY_DEBUG}" AND GMOCK_INCLUDE_DIR)
- set(GMOCK_LIBRARY_EXISTS ON)
-endif()
-
-if(EXISTS "${GTEST_LIBRARY}" OR EXISTS "${GTEST_LIBRARY_DEBUG}" AND GTEST_INCLUDE_DIR)
- set(GTEST_LIBRARY_EXISTS ON)
-endif()
-
-if(NOT (${GMOCK_LIBRARY_EXISTS} AND ${GTEST_LIBRARY_EXISTS}))
-
- include(ExternalProject)
-
- if(GTEST_USE_STATIC_LIBS)
- set(GTEST_CMAKE_ARGS -Dgtest_force_shared_crt:BOOL=ON -DBUILD_SHARED_LIBS=OFF)
- if(BUILD_SHARED_LIBS)
- list(APPEND GTEST_CMAKE_ARGS
- -DCMAKE_POSITION_INDEPENDENT_CODE=ON
- -Dgtest_hide_internal_symbols=ON
- -DCMAKE_CXX_VISIBILITY_PRESET=hidden
- -DCMAKE_VISIBILITY_INLINES_HIDDEN=ON
- -DCMAKE_POLICY_DEFAULT_CMP0063=NEW
- )
- endif()
- set(GTEST_LIBRARY_PREFIX ${CMAKE_STATIC_LIBRARY_PREFIX})
- else()
- set(GTEST_CMAKE_ARGS -DBUILD_SHARED_LIBS=ON)
- set(GTEST_LIBRARY_PREFIX ${CMAKE_SHARED_LIBRARY_PREFIX})
- endif()
- if(WIN32)
- list(APPEND GTEST_CMAKE_ARGS -Dgtest_disable_pthreads=ON)
- endif()
-
- if("${GMOCK_SRC_DIR}" STREQUAL "")
- message(STATUS "Downloading GMock / GTest version ${GMOCK_VER} from git")
- if("${GMOCK_VER}" STREQUAL "1.6.0" OR "${GMOCK_VER}" STREQUAL "1.7.0")
- set(GTEST_BIN_DIR "${GMOCK_ROOT}/src/gtest-build")
- set(GTEST_LIBRARY "${GTEST_BIN_DIR}/${CMAKE_CFG_INTDIR}/${GTEST_LIBRARY_PREFIX}gtest${CMAKE_STATIC_LIBRARY_SUFFIX}")
- set(GTEST_MAIN_LIBRARY "${GTEST_BIN_DIR}/${CMAKE_CFG_INTDIR}/${GTEST_LIBRARY_PREFIX}gtest_main${CMAKE_STATIC_LIBRARY_SUFFIX}")
- mark_as_advanced(GTEST_LIBRARY)
- mark_as_advanced(GTEST_MAIN_LIBRARY)
-
- externalproject_add(
- gtest
- GIT_REPOSITORY "https://github.com/google/googletest.git"
- GIT_TAG "release-${GMOCK_VER}"
- PREFIX ${GMOCK_ROOT}
- INSTALL_COMMAND ""
- LOG_DOWNLOAD ON
- LOG_CONFIGURE ON
- LOG_BUILD ON
- CMAKE_ARGS
- ${GTEST_CMAKE_ARGS}
- BINARY_DIR ${GTEST_BIN_DIR}
- BUILD_BYPRODUCTS
- "${GTEST_LIBRARY}"
- "${GTEST_MAIN_LIBRARY}"
- )
-
- set(GMOCK_BIN_DIR "${GMOCK_ROOT}/src/gmock-build")
- set(GMOCK_LIBRARY "${GMOCK_BIN_DIR}/${CMAKE_CFG_INTDIR}/${GTEST_LIBRARY_PREFIX}gmock${CMAKE_STATIC_LIBRARY_SUFFIX}")
- set(GMOCK_MAIN_LIBRARY "${GMOCK_BIN_DIR}/${CMAKE_CFG_INTDIR}/${GTEST_LIBRARY_PREFIX}gmock_main${CMAKE_STATIC_LIBRARY_SUFFIX}")
- mark_as_advanced(GMOCK_LIBRARY)
- mark_as_advanced(GMOCK_MAIN_LIBRARY)
-
- externalproject_add(
- gmock
- GIT_REPOSITORY "https://github.com/google/googlemock.git"
- GIT_TAG "release-${GMOCK_VER}"
- PREFIX ${GMOCK_ROOT}
- INSTALL_COMMAND ""
- LOG_DOWNLOAD ON
- LOG_CONFIGURE ON
- LOG_BUILD ON
- CMAKE_ARGS
- ${GTEST_CMAKE_ARGS}
- BINARY_DIR ${GMOCK_BIN_DIR}
- BUILD_BYPRODUCTS
- "${GMOCK_LIBRARY}"
- "${GMOCK_MAIN_LIBRARY}"
- )
-
- add_dependencies(gmock gtest)
-
- add_dependencies(GTest::GTest gtest)
- add_dependencies(GTest::Main gtest)
- add_dependencies(GMock::GMock gmock)
- add_dependencies(GMock::Main gmock)
-
- externalproject_get_property(gtest source_dir)
- set(GTEST_INCLUDE_DIR "${source_dir}/include")
- mark_as_advanced(GTEST_INCLUDE_DIR)
- externalproject_get_property(gmock source_dir)
- set(GMOCK_INCLUDE_DIR "${source_dir}/include")
- mark_as_advanced(GMOCK_INCLUDE_DIR)
- else() #1.8.0
- set(GMOCK_BIN_DIR "${GMOCK_ROOT}/src/gmock-build")
- set(GTEST_LIBRARY "${GMOCK_BIN_DIR}/googlemock/gtest/${CMAKE_CFG_INTDIR}/${GTEST_LIBRARY_PREFIX}gtest${CMAKE_STATIC_LIBRARY_SUFFIX}")
- set(GTEST_MAIN_LIBRARY "${GMOCK_BIN_DIR}/googlemock/gtest/${CMAKE_CFG_INTDIR}/${GTEST_LIBRARY_PREFIX}gtest_main${CMAKE_STATIC_LIBRARY_SUFFIX}")
- set(GMOCK_LIBRARY "${GMOCK_BIN_DIR}/googlemock/${CMAKE_CFG_INTDIR}/${GTEST_LIBRARY_PREFIX}gmock${CMAKE_STATIC_LIBRARY_SUFFIX}")
- set(GMOCK_MAIN_LIBRARY "${GMOCK_BIN_DIR}/googlemock/${CMAKE_CFG_INTDIR}/${GTEST_LIBRARY_PREFIX}gmock_main${CMAKE_STATIC_LIBRARY_SUFFIX}")
- mark_as_advanced(GTEST_LIBRARY)
- mark_as_advanced(GTEST_MAIN_LIBRARY)
- mark_as_advanced(GMOCK_LIBRARY)
- mark_as_advanced(GMOCK_MAIN_LIBRARY)
-
- externalproject_add(
- gmock
- GIT_REPOSITORY "https://github.com/google/googletest.git"
- GIT_TAG "release-${GMOCK_VER}"
- PREFIX ${GMOCK_ROOT}
- INSTALL_COMMAND ""
- LOG_DOWNLOAD ON
- LOG_CONFIGURE ON
- LOG_BUILD ON
- CMAKE_ARGS
- ${GTEST_CMAKE_ARGS}
- BINARY_DIR "${GMOCK_BIN_DIR}"
- BUILD_BYPRODUCTS
- "${GTEST_LIBRARY}"
- "${GTEST_MAIN_LIBRARY}"
- "${GMOCK_LIBRARY}"
- "${GMOCK_MAIN_LIBRARY}"
- )
-
- add_dependencies(GTest::GTest gmock)
- add_dependencies(GTest::Main gmock)
- add_dependencies(GMock::GMock gmock)
- add_dependencies(GMock::Main gmock)
-
- externalproject_get_property(gmock source_dir)
- set(GTEST_INCLUDE_DIR "${source_dir}/googletest/include")
- set(GMOCK_INCLUDE_DIR "${source_dir}/googlemock/include")
- mark_as_advanced(GMOCK_INCLUDE_DIR)
- mark_as_advanced(GTEST_INCLUDE_DIR)
- endif()
-
- # Prevent CMake from complaining about these directories missing when the libgtest/libgmock targets get used as dependencies
- file(MAKE_DIRECTORY ${GTEST_INCLUDE_DIR} ${GMOCK_INCLUDE_DIR})
- else()
- message(STATUS "Building Gmock / Gtest from dir ${GMOCK_SRC_DIR}")
-
- set(GMOCK_BIN_DIR "${GMOCK_ROOT}/src/gmock-build")
- set(GTEST_LIBRARY "${GMOCK_BIN_DIR}/gtest/${CMAKE_CFG_INTDIR}/${GTEST_LIBRARY_PREFIX}gtest${CMAKE_STATIC_LIBRARY_SUFFIX}")
- set(GTEST_MAIN_LIBRARY "${GMOCK_BIN_DIR}/gtest/${CMAKE_CFG_INTDIR}/${GTEST_LIBRARY_PREFIX}gtest_main${CMAKE_STATIC_LIBRARY_SUFFIX}")
- set(GMOCK_LIBRARY "${GMOCK_BIN_DIR}/${CMAKE_CFG_INTDIR}/${GTEST_LIBRARY_PREFIX}gmock${CMAKE_STATIC_LIBRARY_SUFFIX}")
- set(GMOCK_MAIN_LIBRARY "${GMOCK_BIN_DIR}/${CMAKE_CFG_INTDIR}/${GTEST_LIBRARY_PREFIX}gmock_main${CMAKE_STATIC_LIBRARY_SUFFIX}")
- mark_as_advanced(GTEST_LIBRARY)
- mark_as_advanced(GTEST_MAIN_LIBRARY)
- mark_as_advanced(GMOCK_LIBRARY)
- mark_as_advanced(GMOCK_MAIN_LIBRARY)
-
- if(EXISTS "${GMOCK_SRC_DIR}/gtest/include/gtest/gtest.h")
- set(GTEST_INCLUDE_DIR "${GMOCK_SRC_DIR}/gtest/include")
- mark_as_advanced(GTEST_INCLUDE_DIR)
- endif()
- if(EXISTS "${GMOCK_SRC_DIR}/include/gmock/gmock.h")
- set(GMOCK_INCLUDE_DIR "${GMOCK_SRC_DIR}/include")
- mark_as_advanced(GMOCK_INCLUDE_DIR)
- elseif(EXISTS "${GMOCK_SRC_DIR}/../../include/gmock/gmock.h")
- set(GMOCK_INCLUDE_DIR "${GMOCK_SRC_DIR}/../../include")
- if(IS_ABSOLUTE "${GMOCK_INCLUDE_DIR}")
- get_filename_component(GMOCK_INCLUDE_DIR "${GMOCK_INCLUDE_DIR}" ABSOLUTE)
- endif()
- mark_as_advanced(GMOCK_INCLUDE_DIR)
- endif()
-
- externalproject_add(
- gmock
- SOURCE_DIR ${GMOCK_SRC_DIR}
- PREFIX ${GMOCK_ROOT}
- INSTALL_COMMAND ""
- LOG_DOWNLOAD ON
- LOG_CONFIGURE ON
- LOG_BUILD ON
- CMAKE_ARGS
- ${GTEST_CMAKE_ARGS}
- BINARY_DIR "${GMOCK_BIN_DIR}"
- BUILD_BYPRODUCTS
- "${GTEST_LIBRARY}"
- "${GTEST_MAIN_LIBRARY}"
- "${GMOCK_LIBRARY}"
- "${GMOCK_MAIN_LIBRARY}"
- )
-
- add_dependencies(GTest::GTest gmock)
- add_dependencies(GTest::Main gmock)
- add_dependencies(GMock::GMock gmock)
- add_dependencies(GMock::Main gmock)
- endif()
-endif()
-
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(GTest DEFAULT_MSG GTEST_LIBRARY GTEST_INCLUDE_DIR GTEST_MAIN_LIBRARY)
-find_package_handle_standard_args(GMock DEFAULT_MSG GMOCK_LIBRARY GMOCK_INCLUDE_DIR GMOCK_MAIN_LIBRARY)
-
-include(CMakeFindDependencyMacro)
-find_dependency(Threads)
-
-set_target_properties(GTest::GTest PROPERTIES
- INTERFACE_LINK_LIBRARIES "Threads::Threads"
- IMPORTED_LINK_INTERFACE_LANGUAGES "CXX"
- IMPORTED_LOCATION "${GTEST_LIBRARY}"
- )
-
-if(GTEST_INCLUDE_DIR)
- set_target_properties(GTest::GTest PROPERTIES
- INTERFACE_INCLUDE_DIRECTORIES "${GTEST_INCLUDE_DIR}"
- INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "${GTEST_INCLUDE_DIR}"
- )
-endif()
-
-set_target_properties(GTest::Main PROPERTIES
- INTERFACE_LINK_LIBRARIES "GTest::GTest"
- IMPORTED_LINK_INTERFACE_LANGUAGES "CXX"
- IMPORTED_LOCATION "${GTEST_MAIN_LIBRARY}")
-
-set_target_properties(GMock::GMock PROPERTIES
- INTERFACE_LINK_LIBRARIES "Threads::Threads"
- IMPORTED_LINK_INTERFACE_LANGUAGES "CXX"
- IMPORTED_LOCATION "${GMOCK_LIBRARY}")
-
-if(GMOCK_INCLUDE_DIR)
- set_target_properties(GMock::GMock PROPERTIES
- INTERFACE_INCLUDE_DIRECTORIES "${GMOCK_INCLUDE_DIR}"
- INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "${GMOCK_INCLUDE_DIR}"
- )
- if(GMOCK_VER VERSION_LESS "1.7")
- # GMock 1.6 still has GTest as an external link-time dependency,
- # so just specify it on the link interface.
- set_property(TARGET GMock::GMock APPEND PROPERTY
- INTERFACE_LINK_LIBRARIES GTest::GTest)
- elseif(GTEST_INCLUDE_DIR)
- # GMock 1.7 and beyond doesn't have it as a link-time dependency anymore,
- # so merge it's compile-time interface (include dirs) with ours.
- set_property(TARGET GMock::GMock APPEND PROPERTY
- INTERFACE_INCLUDE_DIRECTORIES "${GTEST_INCLUDE_DIR}")
- set_property(TARGET GMock::GMock APPEND PROPERTY
- INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "${GTEST_INCLUDE_DIR}")
- endif()
-endif()
-
-set_target_properties(GMock::Main PROPERTIES
- INTERFACE_LINK_LIBRARIES "GMock::GMock"
- IMPORTED_LINK_INTERFACE_LANGUAGES "CXX"
- IMPORTED_LOCATION "${GMOCK_MAIN_LIBRARY}")
-
-if(GTEST_FOUND)
- set(GTEST_INCLUDE_DIRS ${GTEST_INCLUDE_DIR})
- set(GTEST_LIBRARIES GTest::GTest)
- set(GTEST_MAIN_LIBRARIES GTest::Main)
- set(GTEST_BOTH_LIBRARIES ${GTEST_LIBRARIES} ${GTEST_MAIN_LIBRARIES})
- if(VERBOSE)
- message(STATUS "GTest includes: ${GTEST_INCLUDE_DIRS}")
- message(STATUS "GTest libs: ${GTEST_BOTH_LIBRARIES}")
- endif()
-endif()
-
-if(GMOCK_FOUND)
- set(GMOCK_INCLUDE_DIRS ${GMOCK_INCLUDE_DIR})
- set(GMOCK_LIBRARIES GMock::GMock)
- set(GMOCK_MAIN_LIBRARIES GMock::Main)
- set(GMOCK_BOTH_LIBRARIES ${GMOCK_LIBRARIES} ${GMOCK_MAIN_LIBRARIES})
- if(VERBOSE)
- message(STATUS "GMock includes: ${GMOCK_INCLUDE_DIRS}")
- message(STATUS "GMock libs: ${GMOCK_BOTH_LIBRARIES}")
- endif()
-endif()
diff --git a/cmake/FindPolyclipping.cmake b/cmake/FindPolyclipping.cmake
deleted file mode 100644
index 7c88ab630..000000000
--- a/cmake/FindPolyclipping.cmake
+++ /dev/null
@@ -1,67 +0,0 @@
-#
-# - Try to find the polyclipping library
-# this will define
-#
-# Polyclipping_FOUND - polyclipping was found
-# Polyclipping_INCLUDE_DIRS - the polyclipping include directory
-# Polyclipping_LIBRARIES - The libraries needed to use polyclipping
-# Polyclipping_VERSION - The polyclipping library version
-
-#=============================================================================
-# Copyright (c) 2017 Christophe Giboudeaux <christophe@krop.fr>
-#
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions
-# are met:
-#
-# 1. Redistributions of source code must retain the copyright
-# notice, this list of conditions and the following disclaimer.
-# 2. Redistributions in binary form must reproduce the copyright
-# notice, this list of conditions and the following disclaimer in the
-# documentation and/or other materials provided with the distribution.
-# 3. The name of the author may not be used to endorse or promote products
-# derived from this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
-# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
-# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
-# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
-# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
-# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
-# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-#=============================================================================
-
-
-find_package(PkgConfig QUIET)
-pkg_check_modules(PC_Polyclipping QUIET polyclipping)
-
-find_path(Polyclipping_INCLUDE_DIRS
- NAMES clipper.hpp
- HINTS ${PC_Polyclipping_INCLUDE_DIRS}
-)
-
-find_library(Polyclipping_LIBRARIES
- NAMES polyclipping
- HINTS ${PC_Polyclipping_LIBRARY_DIRS}
-)
-
-if(EXISTS ${Polyclipping_INCLUDE_DIRS}/clipper.hpp)
- file(READ ${Polyclipping_INCLUDE_DIRS}/clipper.hpp CLIPPER_H_CONTENT)
- string(REGEX MATCH "#define CLIPPER_VERSION[ ]+\"[0-9]+.[0-9]+.[0-9]+\"" CLIPPER_H_VERSION_MATCH ${CLIPPER_H_CONTENT})
- string(REGEX REPLACE "^.*CLIPPER_VERSION[ ]+\"([0-9]+.[0-9]+.[0-9]+).*$" "\\1" Polyclipping_VERSION "${CLIPPER_H_VERSION_MATCH}")
-endif()
-
-include(FindPackageHandleStandardArgs)
-
-find_package_handle_standard_args(Polyclipping
- FOUND_VAR Polyclipping_FOUND
- REQUIRED_VARS Polyclipping_LIBRARIES Polyclipping_INCLUDE_DIRS
- VERSION_VAR Polyclipping_VERSION
-)
-
-mark_as_advanced(Polyclipping_LIBRARIES Polyclipping_INCLUDE_DIRS Polyclipping_VERSION)
-
diff --git a/cmake/FindStb.cmake b/cmake/FindStb.cmake
deleted file mode 100644
index b510d6b0e..000000000
--- a/cmake/FindStb.cmake
+++ /dev/null
@@ -1,69 +0,0 @@
-## Finds the Stb utility library on your computer.
-#
-# If Stb is not found on your computer, this script also gives the option to
-# download the library and build it from source.
-#
-# This script exports the following parameters for use if you find the Stb
-# package:
-# - Stb_FOUND: Whether Stb has been found on your computer (or built from
-# source).
-# - Stb_INCLUDE_DIRS: The directory where the header files of Stb are located.
-
-#First try to find a PackageConfig for this library.
-find_package(PkgConfig QUIET)
-pkg_check_modules(PC_Stb QUIET Stb)
-
-find_path(Stb_INCLUDE_DIRS stb/stb_image_resize.h #Search for something that is a little less prone to false positives than just stb.h.
- HINTS ${PC_Stb_INCLUDEDIR} ${PC_Stb_INCLUDE_DIRS}
- PATHS "$ENV{PROGRAMFILES}" "$ENV{PROGRAMW6432}" "/usr/include"
- PATH_SUFFIXES include/stb stb include
-)
-
-include(FindPackageHandleStandardArgs)
-set(_stb_find_required ${Stb_FIND_REQUIRED}) #Temporarily set to optional so that we don't get a message when it's not found but you want to build from source.
-set(_stb_find_quietly ${Stb_FIND_QUIETLY})
-set(Stb_FIND_REQUIRED FALSE)
-set(Stb_FIND_QUIETLY TRUE)
-find_package_handle_standard_args(Stb DEFAULT_MSG Stb_INCLUDE_DIRS)
-set(Stb_FIND_REQUIRED ${_stb_find_required})
-set(Stb_FIND_QUIETLY ${_stb_find_quietly})
-
-set(CuraEngine_Download_Stb FALSE)
-if(Stb_FOUND) #Found an existing installation.
- if(NOT Stb_FIND_QUIETLY)
- message(STATUS "Found Stb installation at: ${Stb_INCLUDE_DIRS}")
- endif()
-else()
- #Then optionally clone Stb ourselves.
- option(BUILD_Stb "Build Stb from source." ON) #This is a lie actually, since Stb is header-only and doesn't need any building. We don't build the docs or tests.
- if(BUILD_Stb)
- if(NOT Stb_FIND_QUIETLY)
- message(STATUS "Building Stb from source.")
- endif()
-
- include(ExternalProject)
- # Stb's commits in early February seems to cause the engine to fail compilation on Mac.
- ExternalProject_Add(stb
- GIT_REPOSITORY "https://github.com/nothings/stb.git"
- GIT_TAG d5d052c806eee2ca1f858cb58b2f062d9fa25b90
- UPDATE_DISCONNECTED TRUE
- CONFIGURE_COMMAND "" #We don't want to actually go and build/test/generate it. Just need to download the headers.
- BUILD_COMMAND ""
- INSTALL_COMMAND "" #Assume that the user doesn't want to install all dependencies on his system. We just need to get them for building the application.
- )
- set(CuraEngine_Download_Stb TRUE)
- set(Stb_INCLUDE_DIRS "${CMAKE_CURRENT_BINARY_DIR}/stb-prefix/src")
- set(Stb_FOUND TRUE)
- if(NOT Stb_FIND_QUIETLY)
- message(STATUS "Created Stb installation at: ${Stb_INCLUDE_DIRS}")
- endif()
- elseif(NOT Stb_FIND_QUIETLY) #Don't have an installation but don't want us to build it either? Screw you, then.
- if(Stb_FIND_REQUIRED)
- message(FATAL_ERROR "Could NOT find Stb.")
- else()
- message(WARNING "Could NOT find Stb.")
- endif()
- endif()
-endif()
-
-mark_as_advanced(Stb_INCLUDE_DIRS)
diff --git a/cmake/StandardProjectSettings.cmake b/cmake/StandardProjectSettings.cmake
new file mode 100644
index 000000000..0d5dedeae
--- /dev/null
+++ b/cmake/StandardProjectSettings.cmake
@@ -0,0 +1,321 @@
+include(GNUInstallDirs) # Standard install dirs
+set(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_FULL_LIBDIR}") # TODO: Check if this is still needed
+
+# Uniform how we define BUILD_STATIC or BUILD_SHARED_LIBS (common practice)
+if(DEFINED BUILD_STATIC)
+ if(DEFINED BUILD_SHARED_LIBS)
+ if(${BUILD_SHARED_LIBS} AND ${BUILD_STATIC})
+ message(FATAL_ERROR "Conflicting arguments for BUILD_SHARED_LIBS=${BUILD_SHARED_LIBS} and BUILD_STATIC=${BUILD_STATIC}")
+ endif()
+ else()
+ set(BUILD_SHARED_LIBS NOT ${BUILD_STATIC})
+ endif()
+else()
+ if(NOT DEFINED BUILD_SHARED_LIBS)
+ set(BUILD_SHARED_LIBS ON)
+ endif()
+endif()
+message(STATUS "Setting BUILD_SHARED_LIBS to ${BUILD_SHARED_LIBS}")
+
+# Set a default build type if none was specified
+if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
+ message(STATUS "Setting build type to 'Release' as none was specified.")
+ set(CMAKE_BUILD_TYPE
+ Release
+ CACHE STRING "Choose the type of build." FORCE)
+ # Set the possible values of build type for cmake-gui, ccmake
+ set_property(
+ CACHE CMAKE_BUILD_TYPE
+ PROPERTY STRINGS
+ "Debug"
+ "Release"
+ "MinSizeRel"
+ "RelWithDebInfo")
+endif()
+
+# Generate compile_commands.json to make it easier to work with clang based tools
+message(STATUS "Generating compile commands to ${CMAKE_CURRENT_BINARY_DIR}/compile_commands.json")
+set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
+
+option(ENABLE_IPO "Enable Interprocedural Optimization, aka Link Time Optimization (LTO)" ON)
+if(ENABLE_IPO)
+ include(CheckIPOSupported)
+ check_ipo_supported(
+ RESULT
+ result
+ OUTPUT
+ output)
+ if(result)
+ set(CMAKE_INTERPROCEDURAL_OPTIMIZATION TRUE)
+ else()
+ message(SEND_ERROR "IPO is not supported: ${output}")
+ endif()
+endif()
+
+if (NOT MSVC)
+ # Compile with the -fPIC options if supported
+ if(DEFINED POSITION_INDEPENDENT_CODE) # Use the user/Conan set value
+ message(STATUS "Using POSITION_INDEPENDENT_CODE: ${POSITION_INDEPENDENT_CODE}")
+ else()
+ set(POSITION_INDEPENDENT_CODE ON) # Defaults to on
+ message(STATUS "Setting POSITION_INDEPENDENT_CODE: ${POSITION_INDEPENDENT_CODE}")
+ endif()
+else()
+ # Set Visual Studio flags MD/MDd or MT/MTd
+ if(NOT DEFINED CMAKE_MSVC_RUNTIME_LIBRARY)
+ if(BUILD_STATIC OR NOT BUILD_SHARED_LIBS)
+ message(STATUS "Setting MT/MTd flags")
+ set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
+ else()
+ message(STATUS "Setting MD/MDd flags")
+ set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>DLL")
+ endif()
+ endif()
+endif()
+
+# Use C++17 Standard
+message(STATUS "Setting C++17 support with extensions off and standard required")
+set(CMAKE_CXX_STANDARD 17)
+set(CMAKE_CXX_EXTENSIONS OFF)
+set(CMAKE_CXX_STANDARD_REQUIRED ON)
+
+# Set common project options for the target
+function(set_project_standards project_name)
+ if(CMAKE_CXX_COMPILER_ID MATCHES ".*Clang")
+ option(ENABLE_BUILD_WITH_TIME_TRACE "Enable -ftime-trace to generate time tracing .json files on clang" OFF)
+ if(ENABLE_BUILD_WITH_TIME_TRACE)
+ message(STATUS "Enabling time tracing for ${project_name}")
+ add_compile_definitions(${project_name} PRIVATE -ftime-trace)
+ endif()
+ if (APPLE)
+ message(STATUS "Compiling ${project_name} against libc++")
+ target_compile_options(${project_name} PRIVATE "-stdlib=libc++")
+ endif()
+ endif()
+endfunction()
+
+# Ultimaker uniform Python linking method
+function(use_python project_name)
+ set(COMPONENTS ${ARGN})
+ if(NOT DEFINED Python_VERSION)
+ set(Python_VERSION
+ 3.8
+ CACHE STRING "Python Version" FORCE)
+ message(STATUS "Setting Python version to ${Python_VERSION}. Set Python_VERSION if you want to compile against an other version.")
+ endif()
+ if(APPLE)
+ set(Python_FIND_FRAMEWORK NEVER)
+ endif()
+ find_package(Python ${Python_VERSION} EXACT REQUIRED COMPONENTS ${COMPONENTS})
+ target_link_libraries(${project_name} PRIVATE Python::Python)
+ target_include_directories(${project_name} PUBLIC ${Python_INCLUDE_DIRS})
+ message(STATUS "Linking and building ${project_name} against Python ${Python_VERSION}")
+endfunction()
+
+# Ultimaker uniform Thread linking method
+function(use_threads project_name)
+ message(STATUS "Enabling threading support for ${project_name}")
+ set(CMAKE_THREAD_PREFER_PTHREAD TRUE)
+ set(THREADS_PREFER_PTHREAD_FLAG TRUE)
+ find_package(Threads)
+ target_link_libraries(${project_name} PRIVATE Threads::Threads)
+endfunction()
+
+# https://github.com/lefticus/cppbestpractices/blob/master/02-Use_the_Tools_Available.md
+function(set_project_warnings project_name)
+ message(STATUS "Setting warnings for ${project_name}")
+ set(MSVC_WARNINGS
+ /W4 # Baseline reasonable warnings
+ /w14242 # 'identifier': conversion from 'type1' to 'type1', possible loss of data
+ /w14254 # 'operator': conversion from 'type1:field_bits' to 'type2:field_bits', possible loss of data
+ /w14263 # 'function': member function does not override any base class virtual member function
+ /w14265 # 'classname': class has virtual functions, but destructor is not virtual instances of this class may not
+ # be destructed correctly
+ /w14287 # 'operator': unsigned/negative constant mismatch
+ /we4289 # nonstandard extension used: 'variable': loop control variable declared in the for-loop is used outside
+ # the for-loop scope
+ /w14296 # 'operator': expression is always 'boolean_value'
+ /w14311 # 'variable': pointer truncation from 'type1' to 'type2'
+ /w14545 # expression before comma evaluates to a function which is missing an argument list
+ /w14546 # function call before comma missing argument list
+ /w14547 # 'operator': operator before comma has no effect; expected operator with side-effect
+ /w14549 # 'operator': operator before comma has no effect; did you intend 'operator'?
+ /w14555 # expression has no effect; expected expression with side- effect
+ /w14619 # pragma warning: there is no warning number 'number'
+ /w14640 # Enable warning on thread un-safe static member initialization
+ /w14826 # Conversion from 'type1' to 'type_2' is sign-extended. This may cause unexpected runtime behavior.
+ /w14905 # wide string literal cast to 'LPSTR'
+ /w14906 # string literal cast to 'LPWSTR'
+ /w14928 # illegal copy-initialization; more than one user-defined conversion has been implicitly applied
+ /permissive- # standards conformance mode for MSVC compiler.
+ )
+
+ set(CLANG_WARNINGS
+ -Wall
+ -Wextra # reasonable and standard
+ -Wshadow # warn the user if a variable declaration shadows one from a parent context
+ -Wnon-virtual-dtor # warn the user if a class with virtual functions has a non-virtual destructor. This helps
+ # catch hard to track down memory errors
+ -Wold-style-cast # warn for c-style casts
+ -Wcast-align # warn for potential performance problem casts
+ -Wunused # warn on anything being unused
+ -Woverloaded-virtual # warn if you overload (not override) a virtual function
+ -Wpedantic # warn if non-standard C++ is used
+ -Wconversion # warn on type conversions that may lose data
+ -Wsign-conversion # warn on sign conversions
+ -Wnull-dereference # warn if a null dereference is detected
+ -Wdouble-promotion # warn if float is implicit promoted to double
+ -Wformat=2 # warn on security issues around functions that format output (ie printf)
+ )
+
+ set(GCC_WARNINGS
+ ${CLANG_WARNINGS}
+ -Wmisleading-indentation # warn if indentation implies blocks where blocks do not exist
+ -Wduplicated-cond # warn if if / else chain has duplicated conditions
+ -Wduplicated-branches # warn if if / else branches have duplicated code
+ -Wlogical-op # warn about logical operations being used where bitwise were probably wanted
+ -Wuseless-cast # warn if you perform a cast to the same type
+ )
+
+ if(MSVC)
+ set(PROJECT_WARNINGS ${MSVC_WARNINGS})
+ elseif(CMAKE_CXX_COMPILER_ID MATCHES ".*Clang")
+ set(PROJECT_WARNINGS ${CLANG_WARNINGS})
+ elseif(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
+ set(PROJECT_WARNINGS ${GCC_WARNINGS})
+ else()
+ message(AUTHOR_WARNING "No compiler warnings set for '${CMAKE_CXX_COMPILER_ID}' compiler.")
+ endif()
+
+ target_compile_options(${project_name} PRIVATE ${PROJECT_WARNINGS})
+
+endfunction()
+
+# This function will prevent in-source builds
+function(AssureOutOfSourceBuilds)
+ # make sure the user doesn't play dirty with symlinks
+ get_filename_component(srcdir "${CMAKE_SOURCE_DIR}" REALPATH)
+ get_filename_component(bindir "${CMAKE_BINARY_DIR}" REALPATH)
+
+ # disallow in-source builds
+ if("${srcdir}" STREQUAL "${bindir}")
+ message("######################################################")
+ message("Warning: in-source builds are disabled")
+ message("Please create a separate build directory and run cmake from there")
+ message("######################################################")
+ message(FATAL_ERROR "Quitting configuration")
+ endif()
+endfunction()
+
+option(ALLOW_IN_SOURCE_BUILD "Allow building in your source folder. Strongly discouraged" OFF)
+if(NOT ALLOW_IN_SOURCE_BUILD)
+ assureoutofsourcebuilds()
+endif()
+
+function(enable_sanitizers project_name)
+
+ if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" OR CMAKE_CXX_COMPILER_ID MATCHES ".*Clang")
+ option(ENABLE_COVERAGE "Enable coverage reporting for gcc/clang" FALSE)
+
+ if(ENABLE_COVERAGE)
+ target_compile_options(${project_name} INTERFACE --coverage -O0 -g)
+ target_link_libraries(${project_name} INTERFACE --coverage)
+ endif()
+
+ set(SANITIZERS "")
+
+ option(ENABLE_SANITIZER_ADDRESS "Enable address sanitizer" FALSE)
+ if(ENABLE_SANITIZER_ADDRESS)
+ list(APPEND SANITIZERS "address")
+ endif()
+
+ option(ENABLE_SANITIZER_LEAK "Enable leak sanitizer" FALSE)
+ if(ENABLE_SANITIZER_LEAK)
+ list(APPEND SANITIZERS "leak")
+ endif()
+
+ option(ENABLE_SANITIZER_UNDEFINED_BEHAVIOR "Enable undefined behavior sanitizer" FALSE)
+ if(ENABLE_SANITIZER_UNDEFINED_BEHAVIOR)
+ list(APPEND SANITIZERS "undefined")
+ endif()
+
+ option(ENABLE_SANITIZER_THREAD "Enable thread sanitizer" FALSE)
+ if(ENABLE_SANITIZER_THREAD)
+ if("address" IN_LIST SANITIZERS OR "leak" IN_LIST SANITIZERS)
+ message(WARNING "Thread sanitizer does not work with Address and Leak sanitizer enabled")
+ else()
+ list(APPEND SANITIZERS "thread")
+ endif()
+ endif()
+
+ option(ENABLE_SANITIZER_MEMORY "Enable memory sanitizer" FALSE)
+ if(ENABLE_SANITIZER_MEMORY AND CMAKE_CXX_COMPILER_ID MATCHES ".*Clang")
+ if("address" IN_LIST SANITIZERS
+ OR "thread" IN_LIST SANITIZERS
+ OR "leak" IN_LIST SANITIZERS)
+ message(WARNING "Memory sanitizer does not work with Address, Thread and Leak sanitizer enabled")
+ else()
+ list(APPEND SANITIZERS "memory")
+ endif()
+ endif()
+
+ list(
+ JOIN
+ SANITIZERS
+ ","
+ LIST_OF_SANITIZERS)
+
+ endif()
+
+ if(LIST_OF_SANITIZERS)
+ if(NOT
+ "${LIST_OF_SANITIZERS}"
+ STREQUAL
+ "")
+ target_compile_options(${project_name} INTERFACE -fsanitize=${LIST_OF_SANITIZERS})
+ target_link_options(${project_name} INTERFACE -fsanitize=${LIST_OF_SANITIZERS})
+ endif()
+ endif()
+
+endfunction()
+
+option(ENABLE_CPPCHECK "Enable static analysis with cppcheck" OFF)
+option(ENABLE_CLANG_TIDY "Enable static analysis with clang-tidy" OFF)
+option(ENABLE_INCLUDE_WHAT_YOU_USE "Enable static analysis with include-what-you-use" OFF)
+
+if(ENABLE_CPPCHECK)
+ find_program(CPPCHECK cppcheck)
+ if(CPPCHECK)
+ message(STATUS "Using cppcheck")
+ set(CMAKE_CXX_CPPCHECK
+ ${CPPCHECK}
+ --suppress=missingInclude
+ --enable=all
+ --inline-suppr
+ --inconclusive
+ -i
+ ${CMAKE_SOURCE_DIR}/imgui/lib)
+ else()
+ message(WARNING "cppcheck requested but executable not found")
+ endif()
+endif()
+
+if(ENABLE_CLANG_TIDY)
+ find_program(CLANGTIDY clang-tidy)
+ if(CLANGTIDY)
+ message(STATUS "Using clang-tidy")
+ set(CMAKE_CXX_CLANG_TIDY ${CLANGTIDY} -extra-arg=-Wno-unknown-warning-option)
+ else()
+ message(WARNING "clang-tidy requested but executable not found")
+ endif()
+endif()
+
+if(ENABLE_INCLUDE_WHAT_YOU_USE)
+ find_program(INCLUDE_WHAT_YOU_USE include-what-you-use)
+ if(INCLUDE_WHAT_YOU_USE)
+ message(STATUS "Using include-what-you-use")
+ set(CMAKE_CXX_INCLUDE_WHAT_YOU_USE ${INCLUDE_WHAT_YOU_USE})
+ else()
+ message(WARNING "include-what-you-use requested but executable not found")
+ endif()
+endif() \ No newline at end of file
diff --git a/conanfile.py b/conanfile.py
new file mode 100644
index 000000000..89b44a579
--- /dev/null
+++ b/conanfile.py
@@ -0,0 +1,108 @@
+import os
+import pathlib
+
+from conans import ConanFile, tools
+from conan.tools.cmake import CMakeToolchain, CMakeDeps, CMake
+from conan.tools.layout import cmake_layout
+from conan.tools.files import AutoPackager
+
+required_conan_version = ">=1.42"
+
+class CuraEngineConan(ConanFile):
+ name = "curaengine"
+ version = "99.9.2-alpha+001"
+ license = "AGPL-3.0"
+ author = "Ultimaker B.V."
+ url = "https://github.com/Ultimaker/CuraEngine"
+ description = "Powerful, fast and robust engine for converting 3D models into g-code instructions for 3D printers. It is part of the larger open source project Cura."
+ topics = ("conan", "cura", "protobuf", "gcode", "c++", "curaengine", "libarcus", "gcode-generation")
+ settings = "os", "compiler", "build_type", "arch"
+ revision_mode = "scm"
+ build_policy = "missing"
+ default_user = "ultimaker"
+ default_channel = "testing"
+ exports = "LICENSE*"
+ options = {
+ "enable_arcus": [True, False],
+ "enable_openmp": [True, False],
+ "tests": [True, False]
+ }
+ default_options = {
+ "enable_arcus": True,
+ "enable_openmp": True,
+ "tests": False
+ }
+ scm = {
+ "type": "git",
+ "subfolder": ".",
+ "url": "auto",
+ "revision": "auto"
+ }
+
+ def config_options(self):
+ if self.settings.os == "Macos":
+ self.options.enable_openmp = False
+
+ def configure(self):
+ if self.options.enable_arcus:
+ self.options["arcus"].shared = True
+ self.options["protobuf"].shared = self.settings.os != "Macos"
+ self.options["clipper"].shared = True
+
+ def build_requirements(self):
+ if self.options.enable_arcus:
+ self.build_requires("protobuf/3.17.1")
+ if self.options.tests:
+ self.build_requires("gtest/[>=1.10.0]", force_host_context = True)
+
+ def requirements(self):
+ self.requires("stb/20200203")
+ if self.options.enable_arcus:
+ self.requires(f"arcus/4.13.0-alpha+001@ultimaker/testing")
+ self.requires("protobuf/3.17.1")
+ self.requires("clipper/6.4.2")
+ self.requires("rapidjson/1.1.0")
+ self.requires("boost/1.70.0")
+
+ def validate(self):
+ if self.settings.compiler.get_safe("cppstd"):
+ tools.check_min_cppstd(self, 17)
+
+ def layout(self):
+ cmake_layout(self)
+
+ def generate(self):
+ cmake = CMakeDeps(self)
+ cmake.generate()
+
+ tc = CMakeToolchain(self)
+
+ # FIXME: This shouldn't be necessary (maybe a bug in Conan????)
+ if self.settings.compiler == "Visual Studio":
+ tc.blocks["generic_system"].values["generator_platform"] = None
+ tc.blocks["generic_system"].values["toolset"] = None
+
+ tc.variables["ALLOW_IN_SOURCE_BUILD"] = True
+ tc.variables["ENABLE_ARCUS"] = self.options.enable_arcus
+ tc.variables["BUILD_TESTS"] = self.options.tests
+ tc.variables["ENABLE_OPENMP"] = self.options.enable_openmp
+ tc.generate()
+
+ def build(self):
+ cmake = CMake(self)
+ cmake.configure()
+ cmake.build()
+
+ def package(self):
+ packager = AutoPackager(self)
+ packager.patterns.build.bin = ["CuraEngine", "CuraEngine.exe"]
+ packager.run()
+
+ def package_info(self):
+ if self.in_local_cache:
+ self.runenv_info.prepend_path("PATH", os.path.join(self.folders.package, "bin"))
+ else:
+ self.runenv_info.prepend_path("PATH", self.folders.build)
+
+ def package_id(self):
+ self.info.requires.full_version_mode()
diff --git a/libs/DO_NOT_CHANGE_THESE b/libs/DO_NOT_CHANGE_THESE
deleted file mode 100644
index 768cf535f..000000000
--- a/libs/DO_NOT_CHANGE_THESE
+++ /dev/null
@@ -1,3 +0,0 @@
-These libraries are extern, and while they're utilized by this project,
-they are in fact not actually developed on this repository.
-If changes are desired for these projects, please refer to their official repositories.
diff --git a/libs/clipper/License.txt b/libs/clipper/License.txt
deleted file mode 100644
index 3d9479710..000000000
--- a/libs/clipper/License.txt
+++ /dev/null
@@ -1,24 +0,0 @@
-Boost Software License - Version 1.0 - August 17th, 2003
-http://www.boost.org/LICENSE_1_0.txt
-
-Permission is hereby granted, free of charge, to any person or organization
-obtaining a copy of the software and accompanying documentation covered by
-this license (the "Software") to use, reproduce, display, distribute,
-execute, and transmit the Software, and to prepare derivative works of the
-Software, and to permit third-parties to whom the Software is furnished to
-do so, all subject to the following:
-
-The copyright notices in the Software and this entire statement, including
-the above license grant, this restriction and the following disclaimer,
-must be included in all copies of the Software, in whole or in part, and
-all derivative works of the Software, unless such copies or derivative
-works are solely in the form of machine-executable object code generated by
-a source language processor.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
-SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
-FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
-ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-DEALINGS IN THE SOFTWARE. \ No newline at end of file
diff --git a/libs/clipper/README b/libs/clipper/README
deleted file mode 100644
index a3ed26f3d..000000000
--- a/libs/clipper/README
+++ /dev/null
@@ -1,413 +0,0 @@
-=====================================================================
-Clipper Change Log
-=====================================================================
-v6.4.2 (27 February 2017) Rev 512
-* Several minor bugfixes: #152 #160 #161 #162
-
-v6.4 (2 July 2015) Rev 495
-* Numerous generally minor bugfixes
-
-v6.2.1 (31 October 2014) Rev 482
-* Bugfix in ClipperOffset.Execute where the Polytree.IsHole property
- was returning incorrect values with negative offsets
-* Very minor improvement to join rounding in ClipperOffset
-* Fixed CPP OpenGL demo.
-
-v6.2.0 (17 October 2014) Rev 477
-* Numerous minor bugfixes, too many to list.
- (See revisions 454-475 in Sourceforge Repository)
-* The ZFillFunction (custom callback function) has had its parameters
- changed.
-* Curves demo removed (temporarily).
-* Deprecated functions have been removed.
-
-v6.1.5 (26 February 2014) Rev 460
-* Improved the joining of output polygons sharing a common edge
- when those common edges are horizontal.
-* Fixed a bug in ClipperOffset.AddPath() which would produce
- incorrect solutions when open paths were added before closed paths.
-* Minor code tidy and performance improvement
-
-v6.1.4 (6 February 2014)
-* Fixed bugs in MinkowskiSum
-* Fixed minor bug when using Clipper.ForceSimplify.
-* Modified use_xyz callback so that all 4 vertices around an
- intersection point are now passed to the callback function.
-
-v6.1.3a (22 January 2014) Rev 453
-* Fixed buggy PointInPolygon function (C++ and C# only).
- Note this bug only affected the newly exported function, the
- internal PointInPolygon function used by Clipper was OK.
-
-v6.1.3 (19 January 2014) Rev 452
-* Fixed potential endless loop condition when adding open
- paths to Clipper.
-* Fixed missing implementation of SimplifyPolygon function
- in C++ code.
-* Fixed incorrect upper range constant for polygon coordinates
- in Delphi code.
-* Added PointInPolygon function.
-* Overloaded MinkowskiSum function to accommodate multi-contour
- paths.
-
-v6.1.2 (15 December 2013) Rev 444
-* Fixed broken C++ header file.
-* Minor improvement to joining polygons.
-
-v6.1.1 (13 December 2013) Rev 441
-* Fixed a couple of bugs affecting open paths that could
- raise unhandled exceptions.
-
-v6.1.0 (12 December 2013)
-* Deleted: Previously deprecated code has been removed.
-* Modified: The OffsetPaths function is now deprecated as it has
- been replaced by the ClipperOffset class which is much more
- flexible.
-* Bugfixes: Several minor bugs have been fixed including
- occasionally an incorrect nesting within the PolyTree structure.
-
-v6.0.0 (30 October 2013)
-* Added: Open path (polyline) clipping. A new 'Curves' demo
- application showcases this (see the 'Curves' directory).
-* Update: Major improvement in the merging of
- shared/collinear edges in clip solutions (see Execute).
-* Added: The IntPoint structure now has an optional 'Z' member.
- (See the precompiler directive use_xyz.)
-* Added: Users can now force Clipper to use 32bit integers
- (via the precompiler directive use_int32) instead of using
- 64bit integers.
-* Modified: To accommodate open paths, the Polygon and Polygons
- structures have been renamed Path and Paths respectively. The
- AddPolygon and AddPolygons methods of the ClipperBase class
- have been renamed AddPath and AddPaths respectively. Several
- other functions have been similarly renamed.
-* Modified: The PolyNode Class has a new IsOpen property.
-* Modified: The Clipper class has a new ZFillFunction property.
-* Added: MinkowskiSum and MinkowskiDiff functions added.
-* Added: Several other new functions have been added including
- PolyTreeToPaths, OpenPathsFromPolyTree and ClosedPathsFromPolyTree.
-* Added: The Clipper constructor now accepts an optional InitOptions
- parameter to simplify setting properties.
-* Bugfixes: Numerous minor bugs have been fixed.
-* Deprecated: Version 6 is a major upgrade from previous versions
- and quite a number of changes have been made to exposed structures
- and functions. To minimize inconvenience to existing library users,
- some code has been retained and some added to maintain backward
- compatibility. However, because this code will be removed in a
- future update, it has been marked as deprecated and a precompiler
- directive use_deprecated has been defined.
-
-v5.1.6 (23 May 2013)
-* BugFix: CleanPolygon function was buggy.
-* Changed: The behaviour of the 'miter' JoinType has been
- changed so that when squaring occurs, it's no longer
- extended up to the miter limit but is squared off at
- exactly 'delta' units. (This improves the look of mitering
- with larger limits at acute angles.)
-* Added: New OffsetPolyLines function
-* Update: Minor code refactoring and optimisations
-
-v5.1.5 (5 May 2013)
-* Added: ForceSimple property to Clipper class
-* Update: Improved documentation
-
-v5.1.4 (24 March 2013)
-* Update: CleanPolygon function enhanced.
-* Update: Documentation improved.
-
-v5.1.3 (14 March 2013)
-* Bugfix: Minor bugfixes.
-* Update: Documentation significantly improved.
-
-v5.1.2 (26 February 2013)
-* Bugfix: PolyNode class was missing a constructor.
-* Update: The MiterLimit parameter in the OffsetPolygons
- function has been renamed Limit and can now also be used to
- limit the number of vertices used to construct arcs when
- JoinType is set to jtRound.
-
-v5.1.0 (17 February 2013)
-* Update: ExPolygons has been replaced with the PolyTree &
- PolyNode classes to more fully represent the parent-child
- relationships of the polygons returned by Clipper.
-* Added: New CleanPolygon and CleanPolygons functions.
-* Bugfix: Another orientation bug fixed.
-
-v5.0.2 - 30 December 2012
-* Bugfix: Significant fixes in and tidy of the internal
- Int128 class (which is used only when polygon coordinate
- values are greater than ±0x3FFFFFFF (~1.07e9)).
-* Update: The Area algorithm has been updated and is faster.
-* Update: Documentation updates. The newish but undocumented
- 'CheckInputs' parameter of the OffsetPolygons function has been
- renamed 'AutoFix' and documented too. The comments on rounding
- have also been improved (ie clearer and expanded).
-
-v4.10.0 - 25 December 2012
-* Bugfix: Orientation bugs should now be resolved (finally!).
-* Bugfix: Bug in Int128 class
-
-v4.9.8 - 2 December 2012
-* Bugfix: Further fixes to rare Orientation bug.
-
-v4.9.7 - 29 November 2012
-* Bugfix: Bug that very rarely returned the wrong polygon
- orientation.
-* Bugfix: Obscure bug affecting OffsetPolygons when using
- jtRound for the JoinType parameter and when polygons also
- contain very large coordinate values (> +/-100000000000).
-
-v4.9.6 - 9 November 2012
-* Bugfix: Another obscure bug related to joining polygons.
-
-v4.9.4 - 2 November 2012
-* Bugfix: Bugs in Int128 class occasionally causing
- wrong orientations.
-* Bugfix: Further fixes related to joining polygons.
-
-v4.9.0 - 9 October 2012
-* Bugfix: Obscure bug related to joining polygons.
-
-v4.8.9 - 25 September 2012
-* Bugfix: Obscure bug related to precision of intersections.
-
-v4.8.8 - 30 August 2012
-* Bugfix: Fixed bug in OffsetPolygons function introduced in
- version 4.8.5.
-
-v4.8.7 - 24 August 2012
-* Bugfix: ReversePolygon function in C++ translation was broken.
-* Bugfix: Two obscure bugs affecting orientation fixed too.
-
-v4.8.6 - 11 August 2012
-* Bugfix: Potential for memory overflow errors when using
- ExPolygons structure.
-* Bugfix: The polygon coordinate range has been reduced to
- +/- 0x3FFFFFFFFFFFFFFF (4.6e18).
-* Update: ReversePolygons function was misnamed ReversePoints in C++.
-* Update: SimplifyPolygon function now takes a PolyFillType parameter.
-
-v4.8.5 - 15 July 2012
-* Bugfix: Potential for memory overflow errors in OffsetPolygons().
-
-v4.8.4 - 1 June 2012
-* Bugfix: Another obscure bug affecting ExPolygons structure.
-
-v4.8.3 - 27 May 2012
-* Bugfix: Obscure bug causing incorrect removal of a vertex.
-
-v4.8.2 - 21 May 2012
-* Bugfix: Obscure bug could cause an exception when using
- ExPolygon structure.
-
-v4.8.1 - 12 May 2012
-* Update: Cody tidy and minor bug fixes.
-
-v4.8.0 - 30 April 2012
-* Bugfix: Occasional errors in orientation fixed.
-* Update: Added notes on rounding to the documentation.
-
-v4.7.6 - 11 April 2012
-* Fixed a bug in Orientation function (affecting C# translations only).
-* Minor documentation update.
-
-v4.7.5 - 28 March 2012
-* Bugfix: Fixed a recently introduced bug that occasionally caused an
- unhandled exception in C++ and C# translations.
-
-v4.7.4 - 15 March 2012
-* Bugfix: Another minor bugfix.
-
-v4.7.2 - 4 March 2012
-* Bugfix: Fixed bug introduced in ver 4.7 which sometimes caused
- an exception if ExPolygon structure was passed to Clipper's
- Execute method.
-
-v4.7.1 - 3 March 2012
-* Bugfix: Rare crash when JoinCommonEdges joined polygons that
- 'cancelled' each other.
-* Bugfix: Clipper's internal Orientation method occasionally
- returned wrong result.
-* Update: Improved C# code (thanks to numerous excellent suggestions
- from David Piepgrass)
-
-v4.7 - 10 February 2012
-* Improved the joining of output polygons sharing a common edge.
-
-v4.6.6 - 3 February 2012
-* Bugfix: Another obscure bug occasionally causing incorrect
- polygon orientation.
-
-v4.6.5 - 17 January 2012
-* Bugfix: Obscure bug occasionally causing incorrect hole
- assignment in ExPolygon structure.
-
-v4.6.4 - 8 November 2011
-* Added: SimplifyPolygon and SimplifyPolygons functions.
-
-v4.6.3 - 11 November 2011
-* Bugfix: Fixed another minor mitering bug in OffsetPolygons.
-
-v4.6.2 - 10 November 2011
-* Bugfix: Fixed a rare bug in the orientation of polygons
- returned by Clipper's Execute() method.
-* Bugfix: Previous update introduced a mitering bug in the
- OffsetPolygons function.
-
-v4.6 - 29 October 2011
-* Added: Support for Positive and Negative polygon fill
- types (in addition to the EvenOdd and NonZero fill types).
-* Bugfix: The OffsetPolygons function was generating the
- occasional artefact when 'shrinking' polygons.
-
-v4.5.5 - 8 October 2011
-* Bugfix: Fixed an obscure bug in Clipper's JoinCommonEdges
- method.
-* Update: Replaced IsClockwise function with Orientation
- function. The orientation issues affecting OffsetPolygons
- should now be finally resolved.
-* Change: The Area function once again returns a signed value.
-
-v4.5.1 - 28 September 2011
-* Deleted: The UseFullCoordinateRange property has been
- deleted since integer range is now managed implicitly.
-* BugFix: Minor bug in OffsetPolygon mitering.
-* Change: C# JoinType enum moved from Clipper class to
- ClipperLib namespace.
-* Change: The Area function now returns the absolute area
- (irrespective of orientation).
-* Change: The IsClockwise function now requires a second
- parameter - YAxisPositiveUpward - to accommodate displays
- with Y-axis oriented in either direction
-
-v4.4.4 - 10 September 2011
-* Change: Deleted jtButt from JoinType (used by the
- OffsetPolygons function).
-* BugFix: Fixed another minor bug in OffsetPolygons function.
-* Update: Further improvements to the help file
-
-v4.4.3 - 29 August 2011
-* BugFix: fixed a minor rounding issue in OffsetPolygons
- function (affected C++ & C# translations).
-* BugFix: fixed a minor bug in OffsetPolygons' function
- declaration (affected C++ translation only).
-* Change: 'clipper' namespace changed to 'ClipperLib'
- namespace in both C++ and C# code to remove the ambiguity
- between the Clipper class and the namespace. (This also
- required numerous updates to the accompanying demos.)
-
-v4.4.2 - 26 August 2011
-* BugFix: minor bugfixes in Clipper.
-* Update: the OffsetPolygons function has been significantly
- improved by offering 4 different join styles.
-
-v4.4.0 - 6 August 2011
-* BugFix: A number of minor bugs have been fixed that mostly
- affected the new ExPolygons structure.
-
-v4.3.0 - 17 June 2011
-* New: ExPolygons structure that explicitly associates 'hole'
- polygons with their 'outer' container polygons.
-* New: Execute method overloaded so the solution parameter
- can now be either Polygons or ExPolygons.
-* BugFix: Fixed a rare bug in solution polygons orientation.
-
-v4.2.8 - 21 May 2011
-* Update: JoinCommonEdges() improved once more.
-* BugFix: Several minor bugs fixed.
-
-v4.2.6 - 1 May 2011
-* Bugfix: minor bug in SlopesEqual function.
-* Update: Merging of output polygons sharing common edges
- has been significantly inproved
-
-v4.2.4 - 26 April 2011
- Input polygon coordinates can now contain the full range of
- signed 64bit integers (ie +/-9,223,372,036,854,775,807). This
- means that floating point values can be converted to and from
- Clipper's 64bit integer coordinates structure (IntPoint) and
- still retain a precision of up to 18 decimal places. However,
- since the large-integer math that supports this expanded range
- imposes a small cost on performance (~15%), a new property
- UseFullCoordinateRange has been added to the Clipper class to
- allow users the choice of whether or not to use this expanded
- coordinate range. If this property is disabled, coordinate values
- are restricted to +/-1,500,000,000.
-
-v4.2 - 12 April 2011
- JoinCommonEdges() code significantly improved plus other minor
- improvements.
-
-v4.1.2 - 9 April 2011
-* Update: Minor code tidy.
-* Bugfix: Possible endless loop in JoinCommonEdges() in clipper.pas.
-
-v4.1.1 - 8 April 2011
-* Update: All polygon coordinates are now stored as 64bit integers
- (though they're still restricted to range -1.5e9 to +1.5e9 pending
- the inclusion of code supporting 64bit math).
-* Change: AddPolygon and AddPolygons methods now return boolean
- values.
-* Bugfix: Bug in JoinCommonEdges() caused potential endless loop.
-* Bugfix: Bug in IsClockwise(). (C++ code only)
-
-v4.0 - 5 April 2011
-* Clipper 4 is a major rewrite of earlier versions. The biggest
- change is that floating point values are no longer used,
- except for the storing of edge slope values. The main benefit
- of this is the issue of numerical robustness has been
- addressed. Due to other major code improvements Clipper v4
- is approximately 40% faster than Clipper v3.
-* The AddPolyPolygon method has been renamed to AddPolygons.
-* The IgnoreOrientation property has been removed.
-* The clipper_misc library has been merged back into the
- main clipper library.
-
-v3.1.0 - 17 February 2011
-* Bugfix: Obscure bug in TClipperBase.SetDx method that caused
- problems with very small edges ( edges <1/1000th pixel in size).
-
-v3.0.3 - 9 February 2011
-* Bugfix: Significant bug, but only in C# code.
-* Update: Minor refactoring.
-
-v3.0 - 31 January 2011
-* Update: Major rewrite of the portion of code that calculates
- the output polygons' orientation.
-* Update: Help file significantly improved.
-* Change: Renamed ForceOrientation property to IgnoreOrientation.
- If the orientation of output polygons is not important, or can
- be managed separately, clipping routines can be sped up by about
- 60% by setting IgnoreOrientation to true. Defaults to false.
-* Change: The OffsetPolygon and Area functions have been moved to
- the new unit - clipper_misc.
-
-2.99 - 15 January 2011
-* Bugfix: Obscure bug in AddPolygon method could cause an endless loop.
-
-2.8 - 20 November 2010
-* Updated: Output polygons which previously shared a common
- edge are now merged.
-* Changed: The orientation of outer polygons is now clockwise
- when the display's Y axis is positive downwards (as is
- typical for most Windows applications). Inner polygons
- (holes) have the opposite orientation.
-* Added: Support module for Cairo Graphics Library (with demo).
-* Updated: C# and C++ demos.
-
-2.522 - 15 October 2010
-* Added C# translation (thanks to Olivier Lejeune) and
- a link to Ruby bindings (thanks to Mike Owens).
-
-2.0 - 30 July 2010
-* Clipper now clips using both the Even-Odd (alternate) and
- Non-Zero (winding) polygon filling rules. (Previously Clipper
- assumed the Even-Odd rule for polygon filling.)
-
-1.4c - 16 June 2010
-* Added C++ support for AGG graphics library
-
-1.2s - 2 June 2010
-* Added C++ translation of clipper.pas
-
-1.0 - 9 May 2010 \ No newline at end of file
diff --git a/libs/clipper/clipper.cpp b/libs/clipper/clipper.cpp
deleted file mode 100644
index 9d5caa18b..000000000
--- a/libs/clipper/clipper.cpp
+++ /dev/null
@@ -1,4630 +0,0 @@
-/*******************************************************************************
-* *
-* Author : Angus Johnson *
-* Version : 6.4.2 *
-* Date : 27 February 2017 *
-* Website : http://www.angusj.com *
-* Copyright : Angus Johnson 2010-2017 *
-* *
-* License: *
-* Use, modification & distribution is subject to Boost Software License Ver 1. *
-* http://www.boost.org/LICENSE_1_0.txt *
-* *
-* Attributions: *
-* The code in this library is an extension of Bala Vatti's clipping algorithm: *
-* "A generic solution to polygon clipping" *
-* Communications of the ACM, Vol 35, Issue 7 (July 1992) pp 56-63. *
-* http://portal.acm.org/citation.cfm?id=129906 *
-* *
-* Computer graphics and geometric modeling: implementation and algorithms *
-* By Max K. Agoston *
-* Springer; 1 edition (January 4, 2005) *
-* http://books.google.com/books?q=vatti+clipping+agoston *
-* *
-* See also: *
-* "Polygon Offsetting by Computing Winding Numbers" *
-* Paper no. DETC2005-85513 pp. 565-575 *
-* ASME 2005 International Design Engineering Technical Conferences *
-* and Computers and Information in Engineering Conference (IDETC/CIE2005) *
-* September 24-28, 2005 , Long Beach, California, USA *
-* http://www.me.berkeley.edu/~mcmains/pubs/DAC05OffsetPolygon.pdf *
-* *
-*******************************************************************************/
-
-/*******************************************************************************
-* *
-* This is a translation of the Delphi Clipper library and the naming style *
-* used has retained a Delphi flavour. *
-* *
-*******************************************************************************/
-
-#include "clipper.hpp"
-#include <cmath>
-#include <vector>
-#include <algorithm>
-#include <stdexcept>
-#include <cstring>
-#include <cstdlib>
-#include <ostream>
-#include <functional>
-
-namespace ClipperLib {
-
-static double const pi = 3.141592653589793238;
-static double const two_pi = pi *2;
-static double const def_arc_tolerance = 0.25;
-
-enum Direction { dRightToLeft, dLeftToRight };
-
-static int const Unassigned = -1; //edge not currently 'owning' a solution
-static int const Skip = -2; //edge that would otherwise close a path
-
-#define HORIZONTAL (-1.0E+40)
-#define TOLERANCE (1.0e-20)
-#define NEAR_ZERO(val) (((val) > -TOLERANCE) && ((val) < TOLERANCE))
-
-struct TEdge {
- IntPoint Bot;
- IntPoint Curr; //current (updated for every new scanbeam)
- IntPoint Top;
- double Dx;
- PolyType PolyTyp;
- EdgeSide Side; //side only refers to current side of solution poly
- int WindDelta; //1 or -1 depending on winding direction
- int WindCnt;
- int WindCnt2; //winding count of the opposite polytype
- int OutIdx;
- TEdge *Next;
- TEdge *Prev;
- TEdge *NextInLML;
- TEdge *NextInAEL;
- TEdge *PrevInAEL;
- TEdge *NextInSEL;
- TEdge *PrevInSEL;
-};
-
-struct IntersectNode {
- TEdge *Edge1;
- TEdge *Edge2;
- IntPoint Pt;
-};
-
-struct LocalMinimum {
- cInt Y;
- TEdge *LeftBound;
- TEdge *RightBound;
-};
-
-struct OutPt;
-
-//OutRec: contains a path in the clipping solution. Edges in the AEL will
-//carry a pointer to an OutRec when they are part of the clipping solution.
-struct OutRec {
- int Idx;
- bool IsHole;
- bool IsOpen;
- OutRec *FirstLeft; //see comments in clipper.pas
- PolyNode *PolyNd;
- OutPt *Pts;
- OutPt *BottomPt;
-};
-
-struct OutPt {
- int Idx;
- IntPoint Pt;
- OutPt *Next;
- OutPt *Prev;
-};
-
-struct Join {
- OutPt *OutPt1;
- OutPt *OutPt2;
- IntPoint OffPt;
-};
-
-struct LocMinSorter
-{
- inline bool operator()(const LocalMinimum& locMin1, const LocalMinimum& locMin2)
- {
- return locMin2.Y < locMin1.Y;
- }
-};
-
-//------------------------------------------------------------------------------
-//------------------------------------------------------------------------------
-
-inline cInt Round(double val)
-{
- if ((val < 0)) return static_cast<cInt>(val - 0.5);
- else return static_cast<cInt>(val + 0.5);
-}
-//------------------------------------------------------------------------------
-
-inline cInt Abs(cInt val)
-{
- return val < 0 ? -val : val;
-}
-
-//------------------------------------------------------------------------------
-// PolyTree methods ...
-//------------------------------------------------------------------------------
-
-void PolyTree::Clear()
-{
- for (PolyNodes::size_type i = 0; i < AllNodes.size(); ++i)
- delete AllNodes[i];
- AllNodes.resize(0);
- Childs.resize(0);
-}
-//------------------------------------------------------------------------------
-
-PolyNode* PolyTree::GetFirst() const
-{
- if (!Childs.empty())
- return Childs[0];
- else
- return 0;
-}
-//------------------------------------------------------------------------------
-
-int PolyTree::Total() const
-{
- int result = (int)AllNodes.size();
- //with negative offsets, ignore the hidden outer polygon ...
- if (result > 0 && Childs[0] != AllNodes[0]) result--;
- return result;
-}
-
-//------------------------------------------------------------------------------
-// PolyNode methods ...
-//------------------------------------------------------------------------------
-
-PolyNode::PolyNode(): Parent(0), Index(0), m_IsOpen(false)
-{
-}
-//------------------------------------------------------------------------------
-
-int PolyNode::ChildCount() const
-{
- return (int)Childs.size();
-}
-//------------------------------------------------------------------------------
-
-void PolyNode::AddChild(PolyNode& child)
-{
- unsigned cnt = (unsigned)Childs.size();
- Childs.push_back(&child);
- child.Parent = this;
- child.Index = cnt;
-}
-//------------------------------------------------------------------------------
-
-PolyNode* PolyNode::GetNext() const
-{
- if (!Childs.empty())
- return Childs[0];
- else
- return GetNextSiblingUp();
-}
-//------------------------------------------------------------------------------
-
-PolyNode* PolyNode::GetNextSiblingUp() const
-{
- if (!Parent) //protects against PolyTree.GetNextSiblingUp()
- return 0;
- else if (Index == Parent->Childs.size() - 1)
- return Parent->GetNextSiblingUp();
- else
- return Parent->Childs[Index + 1];
-}
-//------------------------------------------------------------------------------
-
-bool PolyNode::IsHole() const
-{
- bool result = true;
- PolyNode* node = Parent;
- while (node)
- {
- result = !result;
- node = node->Parent;
- }
- return result;
-}
-//------------------------------------------------------------------------------
-
-bool PolyNode::IsOpen() const
-{
- return m_IsOpen;
-}
-//------------------------------------------------------------------------------
-
-#ifndef use_int32
-
-//------------------------------------------------------------------------------
-// Int128 class (enables safe math on signed 64bit integers)
-// eg Int128 val1((long64)9223372036854775807); //ie 2^63 -1
-// Int128 val2((long64)9223372036854775807);
-// Int128 val3 = val1 * val2;
-// val3.AsString => "85070591730234615847396907784232501249" (8.5e+37)
-//------------------------------------------------------------------------------
-
-class Int128
-{
- public:
- ulong64 lo;
- long64 hi;
-
- Int128(long64 _lo = 0)
- {
- lo = (ulong64)_lo;
- if (_lo < 0) hi = -1; else hi = 0;
- }
-
-
- Int128(const Int128 &val): lo(val.lo), hi(val.hi){}
-
- Int128(const long64& _hi, const ulong64& _lo): lo(_lo), hi(_hi){}
-
- Int128& operator = (const long64 &val)
- {
- lo = (ulong64)val;
- if (val < 0) hi = -1; else hi = 0;
- return *this;
- }
- Int128& operator = (const Int128 &val) = default;
-
- bool operator == (const Int128 &val) const
- {return (hi == val.hi && lo == val.lo);}
-
- bool operator != (const Int128 &val) const
- { return !(*this == val);}
-
- bool operator > (const Int128 &val) const
- {
- if (hi != val.hi)
- return hi > val.hi;
- else
- return lo > val.lo;
- }
-
- bool operator < (const Int128 &val) const
- {
- if (hi != val.hi)
- return hi < val.hi;
- else
- return lo < val.lo;
- }
-
- bool operator >= (const Int128 &val) const
- { return !(*this < val);}
-
- bool operator <= (const Int128 &val) const
- { return !(*this > val);}
-
- Int128& operator += (const Int128 &rhs)
- {
- hi += rhs.hi;
- lo += rhs.lo;
- if (lo < rhs.lo) hi++;
- return *this;
- }
-
- Int128 operator + (const Int128 &rhs) const
- {
- Int128 result(*this);
- result+= rhs;
- return result;
- }
-
- Int128& operator -= (const Int128 &rhs)
- {
- *this += -rhs;
- return *this;
- }
-
- Int128 operator - (const Int128 &rhs) const
- {
- Int128 result(*this);
- result -= rhs;
- return result;
- }
-
- Int128 operator-() const //unary negation
- {
- if (lo == 0)
- return Int128(-hi, 0);
- else
- return Int128(~hi, ~lo + 1);
- }
-
- operator double() const
- {
- const double shift64 = 18446744073709551616.0; //2^64
- if (hi < 0)
- {
- if (lo == 0) return (double)hi * shift64;
- else return -(double)(~lo + ~hi * shift64);
- }
- else
- return (double)(lo + hi * shift64);
- }
-
-};
-//------------------------------------------------------------------------------
-
-Int128 Int128Mul (long64 lhs, long64 rhs)
-{
- bool negate = (lhs < 0) != (rhs < 0);
-
- if (lhs < 0) lhs = -lhs;
- ulong64 int1Hi = ulong64(lhs) >> 32;
- ulong64 int1Lo = ulong64(lhs & 0xFFFFFFFF);
-
- if (rhs < 0) rhs = -rhs;
- ulong64 int2Hi = ulong64(rhs) >> 32;
- ulong64 int2Lo = ulong64(rhs & 0xFFFFFFFF);
-
- //nb: see comments in clipper.pas
- ulong64 a = int1Hi * int2Hi;
- ulong64 b = int1Lo * int2Lo;
- ulong64 c = int1Hi * int2Lo + int1Lo * int2Hi;
-
- Int128 tmp;
- tmp.hi = long64(a + (c >> 32));
- tmp.lo = long64(c << 32);
- tmp.lo += long64(b);
- if (tmp.lo < b) tmp.hi++;
- if (negate) tmp = -tmp;
- return tmp;
-};
-#endif
-
-//------------------------------------------------------------------------------
-// Miscellaneous global functions
-//------------------------------------------------------------------------------
-
-bool Orientation(const Path &poly)
-{
- return Area(poly) >= 0;
-}
-//------------------------------------------------------------------------------
-
-double Area(const Path &poly)
-{
- int size = (int)poly.size();
- if (size < 3) return 0;
-
- double a = 0;
- for (int i = 0, j = size -1; i < size; ++i)
- {
- a += ((double)poly[j].X + poly[i].X) * ((double)poly[j].Y - poly[i].Y);
- j = i;
- }
- return -a * 0.5;
-}
-//------------------------------------------------------------------------------
-
-double Area(const OutPt *op)
-{
- const OutPt *startOp = op;
- if (!op) return 0;
- double a = 0;
- do {
- a += (double)(op->Prev->Pt.X + op->Pt.X) * (double)(op->Prev->Pt.Y - op->Pt.Y);
- op = op->Next;
- } while (op != startOp);
- return a * 0.5;
-}
-//------------------------------------------------------------------------------
-
-double Area(const OutRec &outRec)
-{
- return Area(outRec.Pts);
-}
-//------------------------------------------------------------------------------
-
-bool PointIsVertex(const IntPoint &Pt, OutPt *pp)
-{
- OutPt *pp2 = pp;
- do
- {
- if (pp2->Pt == Pt) return true;
- pp2 = pp2->Next;
- }
- while (pp2 != pp);
- return false;
-}
-//------------------------------------------------------------------------------
-
-//See "The Point in Polygon Problem for Arbitrary Polygons" by Hormann & Agathos
-//http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.88.5498&rep=rep1&type=pdf
-int PointInPolygon(const IntPoint &pt, const Path &path)
-{
- //returns 0 if false, +1 if true, -1 if pt ON polygon boundary
- int result = 0;
- size_t cnt = path.size();
- if (cnt < 3) return 0;
- IntPoint ip = path[0];
- for(size_t i = 1; i <= cnt; ++i)
- {
- IntPoint ipNext = (i == cnt ? path[0] : path[i]);
- if (ipNext.Y == pt.Y)
- {
- if ((ipNext.X == pt.X) || (ip.Y == pt.Y &&
- ((ipNext.X > pt.X) == (ip.X < pt.X)))) return -1;
- }
- if ((ip.Y < pt.Y) != (ipNext.Y < pt.Y))
- {
- if (ip.X >= pt.X)
- {
- if (ipNext.X > pt.X) result = 1 - result;
- else
- {
- double d = (double)(ip.X - pt.X) * (ipNext.Y - pt.Y) -
- (double)(ipNext.X - pt.X) * (ip.Y - pt.Y);
- if (!d) return -1;
- if ((d > 0) == (ipNext.Y > ip.Y)) result = 1 - result;
- }
- } else
- {
- if (ipNext.X > pt.X)
- {
- double d = (double)(ip.X - pt.X) * (ipNext.Y - pt.Y) -
- (double)(ipNext.X - pt.X) * (ip.Y - pt.Y);
- if (!d) return -1;
- if ((d > 0) == (ipNext.Y > ip.Y)) result = 1 - result;
- }
- }
- }
- ip = ipNext;
- }
- return result;
-}
-//------------------------------------------------------------------------------
-
-int PointInPolygon (const IntPoint &pt, OutPt *op)
-{
- //returns 0 if false, +1 if true, -1 if pt ON polygon boundary
- int result = 0;
- OutPt* startOp = op;
- for(;;)
- {
- if (op->Next->Pt.Y == pt.Y)
- {
- if ((op->Next->Pt.X == pt.X) || (op->Pt.Y == pt.Y &&
- ((op->Next->Pt.X > pt.X) == (op->Pt.X < pt.X)))) return -1;
- }
- if ((op->Pt.Y < pt.Y) != (op->Next->Pt.Y < pt.Y))
- {
- if (op->Pt.X >= pt.X)
- {
- if (op->Next->Pt.X > pt.X) result = 1 - result;
- else
- {
- double d = (double)(op->Pt.X - pt.X) * (op->Next->Pt.Y - pt.Y) -
- (double)(op->Next->Pt.X - pt.X) * (op->Pt.Y - pt.Y);
- if (!d) return -1;
- if ((d > 0) == (op->Next->Pt.Y > op->Pt.Y)) result = 1 - result;
- }
- } else
- {
- if (op->Next->Pt.X > pt.X)
- {
- double d = (double)(op->Pt.X - pt.X) * (op->Next->Pt.Y - pt.Y) -
- (double)(op->Next->Pt.X - pt.X) * (op->Pt.Y - pt.Y);
- if (!d) return -1;
- if ((d > 0) == (op->Next->Pt.Y > op->Pt.Y)) result = 1 - result;
- }
- }
- }
- op = op->Next;
- if (startOp == op) break;
- }
- return result;
-}
-//------------------------------------------------------------------------------
-
-bool Poly2ContainsPoly1(OutPt *OutPt1, OutPt *OutPt2)
-{
- OutPt* op = OutPt1;
- do
- {
- //nb: PointInPolygon returns 0 if false, +1 if true, -1 if pt on polygon
- int res = PointInPolygon(op->Pt, OutPt2);
- if (res >= 0) return res > 0;
- op = op->Next;
- }
- while (op != OutPt1);
- return true;
-}
-//----------------------------------------------------------------------
-
-bool SlopesEqual(const TEdge &e1, const TEdge &e2, bool UseFullInt64Range)
-{
-#ifndef use_int32
- if (UseFullInt64Range)
- return Int128Mul(e1.Top.Y - e1.Bot.Y, e2.Top.X - e2.Bot.X) ==
- Int128Mul(e1.Top.X - e1.Bot.X, e2.Top.Y - e2.Bot.Y);
- else
-#endif
- return (e1.Top.Y - e1.Bot.Y) * (e2.Top.X - e2.Bot.X) ==
- (e1.Top.X - e1.Bot.X) * (e2.Top.Y - e2.Bot.Y);
-}
-//------------------------------------------------------------------------------
-
-bool SlopesEqual(const IntPoint pt1, const IntPoint pt2,
- const IntPoint pt3, bool UseFullInt64Range)
-{
-#ifndef use_int32
- if (UseFullInt64Range)
- return Int128Mul(pt1.Y-pt2.Y, pt2.X-pt3.X) == Int128Mul(pt1.X-pt2.X, pt2.Y-pt3.Y);
- else
-#endif
- return (pt1.Y-pt2.Y)*(pt2.X-pt3.X) == (pt1.X-pt2.X)*(pt2.Y-pt3.Y);
-}
-//------------------------------------------------------------------------------
-
-bool SlopesEqual(const IntPoint pt1, const IntPoint pt2,
- const IntPoint pt3, const IntPoint pt4, bool UseFullInt64Range)
-{
-#ifndef use_int32
- if (UseFullInt64Range)
- return Int128Mul(pt1.Y-pt2.Y, pt3.X-pt4.X) == Int128Mul(pt1.X-pt2.X, pt3.Y-pt4.Y);
- else
-#endif
- return (pt1.Y-pt2.Y)*(pt3.X-pt4.X) == (pt1.X-pt2.X)*(pt3.Y-pt4.Y);
-}
-//------------------------------------------------------------------------------
-
-inline bool IsHorizontal(TEdge &e)
-{
- return e.Dx == HORIZONTAL;
-}
-//------------------------------------------------------------------------------
-
-inline double GetDx(const IntPoint pt1, const IntPoint pt2)
-{
- return (pt1.Y == pt2.Y) ?
- HORIZONTAL : (double)(pt2.X - pt1.X) / (pt2.Y - pt1.Y);
-}
-//---------------------------------------------------------------------------
-
-inline void SetDx(TEdge &e)
-{
- cInt dy = (e.Top.Y - e.Bot.Y);
- if (dy == 0) e.Dx = HORIZONTAL;
- else e.Dx = (double)(e.Top.X - e.Bot.X) / dy;
-}
-//---------------------------------------------------------------------------
-
-inline void SwapSides(TEdge &Edge1, TEdge &Edge2)
-{
- EdgeSide Side = Edge1.Side;
- Edge1.Side = Edge2.Side;
- Edge2.Side = Side;
-}
-//------------------------------------------------------------------------------
-
-inline void SwapPolyIndexes(TEdge &Edge1, TEdge &Edge2)
-{
- int OutIdx = Edge1.OutIdx;
- Edge1.OutIdx = Edge2.OutIdx;
- Edge2.OutIdx = OutIdx;
-}
-//------------------------------------------------------------------------------
-
-inline cInt TopX(TEdge &edge, const cInt currentY)
-{
- return ( currentY == edge.Top.Y ) ?
- edge.Top.X : edge.Bot.X + Round(edge.Dx *(currentY - edge.Bot.Y));
-}
-//------------------------------------------------------------------------------
-
-void IntersectPoint(TEdge &Edge1, TEdge &Edge2, IntPoint &ip)
-{
-#ifdef use_xyz
- ip.Z = 0;
-#endif
-
- double b1, b2;
- if (Edge1.Dx == Edge2.Dx)
- {
- ip.Y = Edge1.Curr.Y;
- ip.X = TopX(Edge1, ip.Y);
- return;
- }
- else if (Edge1.Dx == 0)
- {
- ip.X = Edge1.Bot.X;
- if (IsHorizontal(Edge2))
- ip.Y = Edge2.Bot.Y;
- else
- {
- b2 = Edge2.Bot.Y - (Edge2.Bot.X / Edge2.Dx);
- ip.Y = Round(ip.X / Edge2.Dx + b2);
- }
- }
- else if (Edge2.Dx == 0)
- {
- ip.X = Edge2.Bot.X;
- if (IsHorizontal(Edge1))
- ip.Y = Edge1.Bot.Y;
- else
- {
- b1 = Edge1.Bot.Y - (Edge1.Bot.X / Edge1.Dx);
- ip.Y = Round(ip.X / Edge1.Dx + b1);
- }
- }
- else
- {
- b1 = Edge1.Bot.X - Edge1.Bot.Y * Edge1.Dx;
- b2 = Edge2.Bot.X - Edge2.Bot.Y * Edge2.Dx;
- double q = (b2-b1) / (Edge1.Dx - Edge2.Dx);
- ip.Y = Round(q);
- if (std::fabs(Edge1.Dx) < std::fabs(Edge2.Dx))
- ip.X = Round(Edge1.Dx * q + b1);
- else
- ip.X = Round(Edge2.Dx * q + b2);
- }
-
- if (ip.Y < Edge1.Top.Y || ip.Y < Edge2.Top.Y)
- {
- if (Edge1.Top.Y > Edge2.Top.Y)
- ip.Y = Edge1.Top.Y;
- else
- ip.Y = Edge2.Top.Y;
- if (std::fabs(Edge1.Dx) < std::fabs(Edge2.Dx))
- ip.X = TopX(Edge1, ip.Y);
- else
- ip.X = TopX(Edge2, ip.Y);
- }
- //finally, don't allow 'ip' to be BELOW curr.Y (ie bottom of scanbeam) ...
- if (ip.Y > Edge1.Curr.Y)
- {
- ip.Y = Edge1.Curr.Y;
- //use the more vertical edge to derive X ...
- if (std::fabs(Edge1.Dx) > std::fabs(Edge2.Dx))
- ip.X = TopX(Edge2, ip.Y); else
- ip.X = TopX(Edge1, ip.Y);
- }
-}
-//------------------------------------------------------------------------------
-
-void ReversePolyPtLinks(OutPt *pp)
-{
- if (!pp) return;
- OutPt *pp1, *pp2;
- pp1 = pp;
- do {
- pp2 = pp1->Next;
- pp1->Next = pp1->Prev;
- pp1->Prev = pp2;
- pp1 = pp2;
- } while( pp1 != pp );
-}
-//------------------------------------------------------------------------------
-
-void DisposeOutPts(OutPt*& pp)
-{
- if (pp == 0) return;
- pp->Prev->Next = 0;
- while( pp )
- {
- OutPt *tmpPp = pp;
- pp = pp->Next;
- delete tmpPp;
- }
-}
-//------------------------------------------------------------------------------
-
-inline void InitEdge(TEdge* e, TEdge* eNext, TEdge* ePrev, const IntPoint& Pt)
-{
- std::memset(e, 0, sizeof(TEdge));
- e->Next = eNext;
- e->Prev = ePrev;
- e->Curr = Pt;
- e->OutIdx = Unassigned;
-}
-//------------------------------------------------------------------------------
-
-void InitEdge2(TEdge& e, PolyType Pt)
-{
- if (e.Curr.Y >= e.Next->Curr.Y)
- {
- e.Bot = e.Curr;
- e.Top = e.Next->Curr;
- } else
- {
- e.Top = e.Curr;
- e.Bot = e.Next->Curr;
- }
- SetDx(e);
- e.PolyTyp = Pt;
-}
-//------------------------------------------------------------------------------
-
-TEdge* RemoveEdge(TEdge* e)
-{
- //removes e from double_linked_list (but without removing from memory)
- e->Prev->Next = e->Next;
- e->Next->Prev = e->Prev;
- TEdge* result = e->Next;
- e->Prev = 0; //flag as removed (see ClipperBase.Clear)
- return result;
-}
-//------------------------------------------------------------------------------
-
-inline void ReverseHorizontal(TEdge &e)
-{
- //swap horizontal edges' Top and Bottom x's so they follow the natural
- //progression of the bounds - ie so their xbots will align with the
- //adjoining lower edge. [Helpful in the ProcessHorizontal() method.]
- std::swap(e.Top.X, e.Bot.X);
-#ifdef use_xyz
- std::swap(e.Top.Z, e.Bot.Z);
-#endif
-}
-//------------------------------------------------------------------------------
-
-void SwapPoints(IntPoint &pt1, IntPoint &pt2)
-{
- IntPoint tmp = pt1;
- pt1 = pt2;
- pt2 = tmp;
-}
-//------------------------------------------------------------------------------
-
-bool GetOverlapSegment(IntPoint pt1a, IntPoint pt1b, IntPoint pt2a,
- IntPoint pt2b, IntPoint &pt1, IntPoint &pt2)
-{
- //precondition: segments are Collinear.
- if (Abs(pt1a.X - pt1b.X) > Abs(pt1a.Y - pt1b.Y))
- {
- if (pt1a.X > pt1b.X) SwapPoints(pt1a, pt1b);
- if (pt2a.X > pt2b.X) SwapPoints(pt2a, pt2b);
- if (pt1a.X > pt2a.X) pt1 = pt1a; else pt1 = pt2a;
- if (pt1b.X < pt2b.X) pt2 = pt1b; else pt2 = pt2b;
- return pt1.X < pt2.X;
- } else
- {
- if (pt1a.Y < pt1b.Y) SwapPoints(pt1a, pt1b);
- if (pt2a.Y < pt2b.Y) SwapPoints(pt2a, pt2b);
- if (pt1a.Y < pt2a.Y) pt1 = pt1a; else pt1 = pt2a;
- if (pt1b.Y > pt2b.Y) pt2 = pt1b; else pt2 = pt2b;
- return pt1.Y > pt2.Y;
- }
-}
-//------------------------------------------------------------------------------
-
-bool FirstIsBottomPt(const OutPt* btmPt1, const OutPt* btmPt2)
-{
- OutPt *p = btmPt1->Prev;
- while ((p->Pt == btmPt1->Pt) && (p != btmPt1)) p = p->Prev;
- double dx1p = std::fabs(GetDx(btmPt1->Pt, p->Pt));
- p = btmPt1->Next;
- while ((p->Pt == btmPt1->Pt) && (p != btmPt1)) p = p->Next;
- double dx1n = std::fabs(GetDx(btmPt1->Pt, p->Pt));
-
- p = btmPt2->Prev;
- while ((p->Pt == btmPt2->Pt) && (p != btmPt2)) p = p->Prev;
- double dx2p = std::fabs(GetDx(btmPt2->Pt, p->Pt));
- p = btmPt2->Next;
- while ((p->Pt == btmPt2->Pt) && (p != btmPt2)) p = p->Next;
- double dx2n = std::fabs(GetDx(btmPt2->Pt, p->Pt));
-
- if (std::max(dx1p, dx1n) == std::max(dx2p, dx2n) &&
- std::min(dx1p, dx1n) == std::min(dx2p, dx2n))
- return Area(btmPt1) > 0; //if otherwise identical use orientation
- else
- return (dx1p >= dx2p && dx1p >= dx2n) || (dx1n >= dx2p && dx1n >= dx2n);
-}
-//------------------------------------------------------------------------------
-
-OutPt* GetBottomPt(OutPt *pp)
-{
- OutPt* dups = 0;
- OutPt* p = pp->Next;
- while (p != pp)
- {
- if (p->Pt.Y > pp->Pt.Y)
- {
- pp = p;
- dups = 0;
- }
- else if (p->Pt.Y == pp->Pt.Y && p->Pt.X <= pp->Pt.X)
- {
- if (p->Pt.X < pp->Pt.X)
- {
- dups = 0;
- pp = p;
- } else
- {
- if (p->Next != pp && p->Prev != pp) dups = p;
- }
- }
- p = p->Next;
- }
- if (dups)
- {
- //there appears to be at least 2 vertices at BottomPt so ...
- while (dups != p)
- {
- if (!FirstIsBottomPt(p, dups)) pp = dups;
- dups = dups->Next;
- while (dups->Pt != pp->Pt) dups = dups->Next;
- }
- }
- return pp;
-}
-//------------------------------------------------------------------------------
-
-bool Pt2IsBetweenPt1AndPt3(const IntPoint pt1,
- const IntPoint pt2, const IntPoint pt3)
-{
- if ((pt1 == pt3) || (pt1 == pt2) || (pt3 == pt2))
- return false;
- else if (pt1.X != pt3.X)
- return (pt2.X > pt1.X) == (pt2.X < pt3.X);
- else
- return (pt2.Y > pt1.Y) == (pt2.Y < pt3.Y);
-}
-//------------------------------------------------------------------------------
-
-bool HorzSegmentsOverlap(cInt seg1a, cInt seg1b, cInt seg2a, cInt seg2b)
-{
- if (seg1a > seg1b) std::swap(seg1a, seg1b);
- if (seg2a > seg2b) std::swap(seg2a, seg2b);
- return (seg1a < seg2b) && (seg2a < seg1b);
-}
-
-//------------------------------------------------------------------------------
-// ClipperBase class methods ...
-//------------------------------------------------------------------------------
-
-ClipperBase::ClipperBase() //constructor
-{
- m_CurrentLM = m_MinimaList.begin(); //begin() == end() here
- m_UseFullRange = false;
-}
-//------------------------------------------------------------------------------
-
-ClipperBase::~ClipperBase() //destructor
-{
- Clear();
-}
-//------------------------------------------------------------------------------
-
-void RangeTest(const IntPoint& Pt, bool& useFullRange)
-{
- if (useFullRange)
- {
- if (Pt.X > hiRange || Pt.Y > hiRange || -Pt.X > hiRange || -Pt.Y > hiRange)
- throw clipperException("Coordinate outside allowed range");
- }
- else if (Pt.X > loRange|| Pt.Y > loRange || -Pt.X > loRange || -Pt.Y > loRange)
- {
- useFullRange = true;
- RangeTest(Pt, useFullRange);
- }
-}
-//------------------------------------------------------------------------------
-
-TEdge* FindNextLocMin(TEdge* E)
-{
- for (;;)
- {
- while (E->Bot != E->Prev->Bot || E->Curr == E->Top) E = E->Next;
- if (!IsHorizontal(*E) && !IsHorizontal(*E->Prev)) break;
- while (IsHorizontal(*E->Prev)) E = E->Prev;
- TEdge* E2 = E;
- while (IsHorizontal(*E)) E = E->Next;
- if (E->Top.Y == E->Prev->Bot.Y) continue; //ie just an intermediate horz.
- if (E2->Prev->Bot.X < E->Bot.X) E = E2;
- break;
- }
- return E;
-}
-//------------------------------------------------------------------------------
-
-TEdge* ClipperBase::ProcessBound(TEdge* E, bool NextIsForward)
-{
- TEdge *Result = E;
- TEdge *Horz = 0;
-
- if (E->OutIdx == Skip)
- {
- //if edges still remain in the current bound beyond the skip edge then
- //create another LocMin and call ProcessBound once more
- if (NextIsForward)
- {
- while (E->Top.Y == E->Next->Bot.Y) E = E->Next;
- //don't include top horizontals when parsing a bound a second time,
- //they will be contained in the opposite bound ...
- while (E != Result && IsHorizontal(*E)) E = E->Prev;
- }
- else
- {
- while (E->Top.Y == E->Prev->Bot.Y) E = E->Prev;
- while (E != Result && IsHorizontal(*E)) E = E->Next;
- }
-
- if (E == Result)
- {
- if (NextIsForward) Result = E->Next;
- else Result = E->Prev;
- }
- else
- {
- //there are more edges in the bound beyond result starting with E
- if (NextIsForward)
- E = Result->Next;
- else
- E = Result->Prev;
- MinimaList::value_type locMin;
- locMin.Y = E->Bot.Y;
- locMin.LeftBound = 0;
- locMin.RightBound = E;
- E->WindDelta = 0;
- Result = ProcessBound(E, NextIsForward);
- m_MinimaList.push_back(locMin);
- }
- return Result;
- }
-
- TEdge *EStart;
-
- if (IsHorizontal(*E))
- {
- //We need to be careful with open paths because this may not be a
- //true local minima (ie E may be following a skip edge).
- //Also, consecutive horz. edges may start heading left before going right.
- if (NextIsForward)
- EStart = E->Prev;
- else
- EStart = E->Next;
- if (IsHorizontal(*EStart)) //ie an adjoining horizontal skip edge
- {
- if (EStart->Bot.X != E->Bot.X && EStart->Top.X != E->Bot.X)
- ReverseHorizontal(*E);
- }
- else if (EStart->Bot.X != E->Bot.X)
- ReverseHorizontal(*E);
- }
-
- EStart = E;
- if (NextIsForward)
- {
- while (Result->Top.Y == Result->Next->Bot.Y && Result->Next->OutIdx != Skip)
- Result = Result->Next;
- if (IsHorizontal(*Result) && Result->Next->OutIdx != Skip)
- {
- //nb: at the top of a bound, horizontals are added to the bound
- //only when the preceding edge attaches to the horizontal's left vertex
- //unless a Skip edge is encountered when that becomes the top divide
- Horz = Result;
- while (IsHorizontal(*Horz->Prev)) Horz = Horz->Prev;
- if (Horz->Prev->Top.X > Result->Next->Top.X) Result = Horz->Prev;
- }
- while (E != Result)
- {
- E->NextInLML = E->Next;
- if (IsHorizontal(*E) && E != EStart &&
- E->Bot.X != E->Prev->Top.X) ReverseHorizontal(*E);
- E = E->Next;
- }
- if (IsHorizontal(*E) && E != EStart && E->Bot.X != E->Prev->Top.X)
- ReverseHorizontal(*E);
- Result = Result->Next; //move to the edge just beyond current bound
- } else
- {
- while (Result->Top.Y == Result->Prev->Bot.Y && Result->Prev->OutIdx != Skip)
- Result = Result->Prev;
- if (IsHorizontal(*Result) && Result->Prev->OutIdx != Skip)
- {
- Horz = Result;
- while (IsHorizontal(*Horz->Next)) Horz = Horz->Next;
- if (Horz->Next->Top.X == Result->Prev->Top.X ||
- Horz->Next->Top.X > Result->Prev->Top.X) Result = Horz->Next;
- }
-
- while (E != Result)
- {
- E->NextInLML = E->Prev;
- if (IsHorizontal(*E) && E != EStart && E->Bot.X != E->Next->Top.X)
- ReverseHorizontal(*E);
- E = E->Prev;
- }
- if (IsHorizontal(*E) && E != EStart && E->Bot.X != E->Next->Top.X)
- ReverseHorizontal(*E);
- Result = Result->Prev; //move to the edge just beyond current bound
- }
-
- return Result;
-}
-//------------------------------------------------------------------------------
-
-bool ClipperBase::AddPath(const Path &pg, PolyType PolyTyp, bool Closed)
-{
-#ifdef use_lines
- if (!Closed && PolyTyp == ptClip)
- throw clipperException("AddPath: Open paths must be subject.");
-#else
- if (!Closed)
- throw clipperException("AddPath: Open paths have been disabled.");
-#endif
-
- int highI = (int)pg.size() -1;
- if (Closed) while (highI > 0 && (pg[highI] == pg[0])) --highI;
- while (highI > 0 && (pg[highI] == pg[highI -1])) --highI;
- if ((Closed && highI < 2) || (!Closed && highI < 1)) return false;
-
- //create a new edge array ...
- TEdge *edges = new TEdge [highI +1];
-
- bool IsFlat = true;
- //1. Basic (first) edge initialization ...
- try
- {
- edges[1].Curr = pg[1];
- RangeTest(pg[0], m_UseFullRange);
- RangeTest(pg[highI], m_UseFullRange);
- InitEdge(&edges[0], &edges[1], &edges[highI], pg[0]);
- InitEdge(&edges[highI], &edges[0], &edges[highI-1], pg[highI]);
- for (int i = highI - 1; i >= 1; --i)
- {
- RangeTest(pg[i], m_UseFullRange);
- InitEdge(&edges[i], &edges[i+1], &edges[i-1], pg[i]);
- }
- }
- catch(...)
- {
- delete [] edges;
- throw; //range test fails
- }
- TEdge *eStart = &edges[0];
-
- //2. Remove duplicate vertices, and (when closed) collinear edges ...
- TEdge *E = eStart, *eLoopStop = eStart;
- for (;;)
- {
- //nb: allows matching start and end points when not Closed ...
- if (E->Curr == E->Next->Curr && (Closed || E->Next != eStart))
- {
- if (E == E->Next) break;
- if (E == eStart) eStart = E->Next;
- E = RemoveEdge(E);
- eLoopStop = E;
- continue;
- }
- if (E->Prev == E->Next)
- break; //only two vertices
- else if (Closed &&
- SlopesEqual(E->Prev->Curr, E->Curr, E->Next->Curr, m_UseFullRange) &&
- (!m_PreserveCollinear ||
- !Pt2IsBetweenPt1AndPt3(E->Prev->Curr, E->Curr, E->Next->Curr)))
- {
- //Collinear edges are allowed for open paths but in closed paths
- //the default is to merge adjacent collinear edges into a single edge.
- //However, if the PreserveCollinear property is enabled, only overlapping
- //collinear edges (ie spikes) will be removed from closed paths.
- if (E == eStart) eStart = E->Next;
- E = RemoveEdge(E);
- E = E->Prev;
- eLoopStop = E;
- continue;
- }
- E = E->Next;
- if ((E == eLoopStop) || (!Closed && E->Next == eStart)) break;
- }
-
- if ((!Closed && (E == E->Next)) || (Closed && (E->Prev == E->Next)))
- {
- delete [] edges;
- return false;
- }
-
- if (!Closed)
- {
- m_HasOpenPaths = true;
- eStart->Prev->OutIdx = Skip;
- }
-
- //3. Do second stage of edge initialization ...
- E = eStart;
- do
- {
- InitEdge2(*E, PolyTyp);
- E = E->Next;
- if (IsFlat && E->Curr.Y != eStart->Curr.Y) IsFlat = false;
- }
- while (E != eStart);
-
- //4. Finally, add edge bounds to LocalMinima list ...
-
- //Totally flat paths must be handled differently when adding them
- //to LocalMinima list to avoid endless loops etc ...
- if (IsFlat)
- {
- if (Closed)
- {
- delete [] edges;
- return false;
- }
- E->Prev->OutIdx = Skip;
- MinimaList::value_type locMin;
- locMin.Y = E->Bot.Y;
- locMin.LeftBound = 0;
- locMin.RightBound = E;
- locMin.RightBound->Side = esRight;
- locMin.RightBound->WindDelta = 0;
- for (;;)
- {
- if (E->Bot.X != E->Prev->Top.X) ReverseHorizontal(*E);
- if (E->Next->OutIdx == Skip) break;
- E->NextInLML = E->Next;
- E = E->Next;
- }
- m_MinimaList.push_back(locMin);
- m_edges.push_back(edges);
- return true;
- }
-
- m_edges.push_back(edges);
- bool leftBoundIsForward;
- TEdge* EMin = 0;
-
- //workaround to avoid an endless loop in the while loop below when
- //open paths have matching start and end points ...
- if (E->Prev->Bot == E->Prev->Top) E = E->Next;
-
- for (;;)
- {
- E = FindNextLocMin(E);
- if (E == EMin) break;
- else if (!EMin) EMin = E;
-
- //E and E.Prev now share a local minima (left aligned if horizontal).
- //Compare their slopes to find which starts which bound ...
- MinimaList::value_type locMin;
- locMin.Y = E->Bot.Y;
- if (E->Dx < E->Prev->Dx)
- {
- locMin.LeftBound = E->Prev;
- locMin.RightBound = E;
- leftBoundIsForward = false; //Q.nextInLML = Q.prev
- } else
- {
- locMin.LeftBound = E;
- locMin.RightBound = E->Prev;
- leftBoundIsForward = true; //Q.nextInLML = Q.next
- }
-
- if (!Closed) locMin.LeftBound->WindDelta = 0;
- else if (locMin.LeftBound->Next == locMin.RightBound)
- locMin.LeftBound->WindDelta = -1;
- else locMin.LeftBound->WindDelta = 1;
- locMin.RightBound->WindDelta = -locMin.LeftBound->WindDelta;
-
- E = ProcessBound(locMin.LeftBound, leftBoundIsForward);
- if (E->OutIdx == Skip) E = ProcessBound(E, leftBoundIsForward);
-
- TEdge* E2 = ProcessBound(locMin.RightBound, !leftBoundIsForward);
- if (E2->OutIdx == Skip) E2 = ProcessBound(E2, !leftBoundIsForward);
-
- if (locMin.LeftBound->OutIdx == Skip)
- locMin.LeftBound = 0;
- else if (locMin.RightBound->OutIdx == Skip)
- locMin.RightBound = 0;
- m_MinimaList.push_back(locMin);
- if (!leftBoundIsForward) E = E2;
- }
- return true;
-}
-//------------------------------------------------------------------------------
-
-bool ClipperBase::AddPaths(const Paths &ppg, PolyType PolyTyp, bool Closed)
-{
- bool result = false;
- for (Paths::size_type i = 0; i < ppg.size(); ++i)
- if (AddPath(ppg[i], PolyTyp, Closed)) result = true;
- return result;
-}
-//------------------------------------------------------------------------------
-
-void ClipperBase::Clear()
-{
- DisposeLocalMinimaList();
- for (EdgeList::size_type i = 0; i < m_edges.size(); ++i)
- {
- TEdge* edges = m_edges[i];
- delete [] edges;
- }
- m_edges.clear();
- m_UseFullRange = false;
- m_HasOpenPaths = false;
-}
-//------------------------------------------------------------------------------
-
-void ClipperBase::Reset()
-{
- m_CurrentLM = m_MinimaList.begin();
- if (m_CurrentLM == m_MinimaList.end()) return; //ie nothing to process
- std::sort(m_MinimaList.begin(), m_MinimaList.end(), LocMinSorter());
-
- m_Scanbeam = ScanbeamList(); //clears/resets priority_queue
- //reset all edges ...
- for (MinimaList::iterator lm = m_MinimaList.begin(); lm != m_MinimaList.end(); ++lm)
- {
- InsertScanbeam(lm->Y);
- TEdge* e = lm->LeftBound;
- if (e)
- {
- e->Curr = e->Bot;
- e->Side = esLeft;
- e->OutIdx = Unassigned;
- }
-
- e = lm->RightBound;
- if (e)
- {
- e->Curr = e->Bot;
- e->Side = esRight;
- e->OutIdx = Unassigned;
- }
- }
- m_ActiveEdges = 0;
- m_CurrentLM = m_MinimaList.begin();
-}
-//------------------------------------------------------------------------------
-
-void ClipperBase::DisposeLocalMinimaList()
-{
- m_MinimaList.clear();
- m_CurrentLM = m_MinimaList.begin();
-}
-//------------------------------------------------------------------------------
-
-bool ClipperBase::PopLocalMinima(cInt Y, const LocalMinimum *&locMin)
-{
- if (m_CurrentLM == m_MinimaList.end() || (*m_CurrentLM).Y != Y) return false;
- locMin = &(*m_CurrentLM);
- ++m_CurrentLM;
- return true;
-}
-//------------------------------------------------------------------------------
-
-IntRect ClipperBase::GetBounds()
-{
- IntRect result;
- MinimaList::iterator lm = m_MinimaList.begin();
- if (lm == m_MinimaList.end())
- {
- result.left = result.top = result.right = result.bottom = 0;
- return result;
- }
- result.left = lm->LeftBound->Bot.X;
- result.top = lm->LeftBound->Bot.Y;
- result.right = lm->LeftBound->Bot.X;
- result.bottom = lm->LeftBound->Bot.Y;
- while (lm != m_MinimaList.end())
- {
- //todo - needs fixing for open paths
- result.bottom = std::max(result.bottom, lm->LeftBound->Bot.Y);
- TEdge* e = lm->LeftBound;
- for (;;) {
- TEdge* bottomE = e;
- while (e->NextInLML)
- {
- if (e->Bot.X < result.left) result.left = e->Bot.X;
- if (e->Bot.X > result.right) result.right = e->Bot.X;
- e = e->NextInLML;
- }
- result.left = std::min(result.left, e->Bot.X);
- result.right = std::max(result.right, e->Bot.X);
- result.left = std::min(result.left, e->Top.X);
- result.right = std::max(result.right, e->Top.X);
- result.top = std::min(result.top, e->Top.Y);
- if (bottomE == lm->LeftBound) e = lm->RightBound;
- else break;
- }
- ++lm;
- }
- return result;
-}
-//------------------------------------------------------------------------------
-
-void ClipperBase::InsertScanbeam(const cInt Y)
-{
- m_Scanbeam.push(Y);
-}
-//------------------------------------------------------------------------------
-
-bool ClipperBase::PopScanbeam(cInt &Y)
-{
- if (m_Scanbeam.empty()) return false;
- Y = m_Scanbeam.top();
- m_Scanbeam.pop();
- while (!m_Scanbeam.empty() && Y == m_Scanbeam.top()) { m_Scanbeam.pop(); } // Pop duplicates.
- return true;
-}
-//------------------------------------------------------------------------------
-
-void ClipperBase::DisposeAllOutRecs(){
- for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
- DisposeOutRec(i);
- m_PolyOuts.clear();
-}
-//------------------------------------------------------------------------------
-
-void ClipperBase::DisposeOutRec(PolyOutList::size_type index)
-{
- OutRec *outRec = m_PolyOuts[index];
- if (outRec->Pts) DisposeOutPts(outRec->Pts);
- delete outRec;
- m_PolyOuts[index] = 0;
-}
-//------------------------------------------------------------------------------
-
-void ClipperBase::DeleteFromAEL(TEdge *e)
-{
- TEdge* AelPrev = e->PrevInAEL;
- TEdge* AelNext = e->NextInAEL;
- if (!AelPrev && !AelNext && (e != m_ActiveEdges)) return; //already deleted
- if (AelPrev) AelPrev->NextInAEL = AelNext;
- else m_ActiveEdges = AelNext;
- if (AelNext) AelNext->PrevInAEL = AelPrev;
- e->NextInAEL = 0;
- e->PrevInAEL = 0;
-}
-//------------------------------------------------------------------------------
-
-OutRec* ClipperBase::CreateOutRec()
-{
- OutRec* result = new OutRec;
- result->IsHole = false;
- result->IsOpen = false;
- result->FirstLeft = 0;
- result->Pts = 0;
- result->BottomPt = 0;
- result->PolyNd = 0;
- m_PolyOuts.push_back(result);
- result->Idx = (int)m_PolyOuts.size() - 1;
- return result;
-}
-//------------------------------------------------------------------------------
-
-void ClipperBase::SwapPositionsInAEL(TEdge *Edge1, TEdge *Edge2)
-{
- //check that one or other edge hasn't already been removed from AEL ...
- if (Edge1->NextInAEL == Edge1->PrevInAEL ||
- Edge2->NextInAEL == Edge2->PrevInAEL) return;
-
- if (Edge1->NextInAEL == Edge2)
- {
- TEdge* Next = Edge2->NextInAEL;
- if (Next) Next->PrevInAEL = Edge1;
- TEdge* Prev = Edge1->PrevInAEL;
- if (Prev) Prev->NextInAEL = Edge2;
- Edge2->PrevInAEL = Prev;
- Edge2->NextInAEL = Edge1;
- Edge1->PrevInAEL = Edge2;
- Edge1->NextInAEL = Next;
- }
- else if (Edge2->NextInAEL == Edge1)
- {
- TEdge* Next = Edge1->NextInAEL;
- if (Next) Next->PrevInAEL = Edge2;
- TEdge* Prev = Edge2->PrevInAEL;
- if (Prev) Prev->NextInAEL = Edge1;
- Edge1->PrevInAEL = Prev;
- Edge1->NextInAEL = Edge2;
- Edge2->PrevInAEL = Edge1;
- Edge2->NextInAEL = Next;
- }
- else
- {
- TEdge* Next = Edge1->NextInAEL;
- TEdge* Prev = Edge1->PrevInAEL;
- Edge1->NextInAEL = Edge2->NextInAEL;
- if (Edge1->NextInAEL) Edge1->NextInAEL->PrevInAEL = Edge1;
- Edge1->PrevInAEL = Edge2->PrevInAEL;
- if (Edge1->PrevInAEL) Edge1->PrevInAEL->NextInAEL = Edge1;
- Edge2->NextInAEL = Next;
- if (Edge2->NextInAEL) Edge2->NextInAEL->PrevInAEL = Edge2;
- Edge2->PrevInAEL = Prev;
- if (Edge2->PrevInAEL) Edge2->PrevInAEL->NextInAEL = Edge2;
- }
-
- if (!Edge1->PrevInAEL) m_ActiveEdges = Edge1;
- else if (!Edge2->PrevInAEL) m_ActiveEdges = Edge2;
-}
-//------------------------------------------------------------------------------
-
-void ClipperBase::UpdateEdgeIntoAEL(TEdge *&e)
-{
- if (!e->NextInLML)
- throw clipperException("UpdateEdgeIntoAEL: invalid call");
-
- e->NextInLML->OutIdx = e->OutIdx;
- TEdge* AelPrev = e->PrevInAEL;
- TEdge* AelNext = e->NextInAEL;
- if (AelPrev) AelPrev->NextInAEL = e->NextInLML;
- else m_ActiveEdges = e->NextInLML;
- if (AelNext) AelNext->PrevInAEL = e->NextInLML;
- e->NextInLML->Side = e->Side;
- e->NextInLML->WindDelta = e->WindDelta;
- e->NextInLML->WindCnt = e->WindCnt;
- e->NextInLML->WindCnt2 = e->WindCnt2;
- e = e->NextInLML;
- e->Curr = e->Bot;
- e->PrevInAEL = AelPrev;
- e->NextInAEL = AelNext;
- if (!IsHorizontal(*e)) InsertScanbeam(e->Top.Y);
-}
-//------------------------------------------------------------------------------
-
-bool ClipperBase::LocalMinimaPending()
-{
- return (m_CurrentLM != m_MinimaList.end());
-}
-
-//------------------------------------------------------------------------------
-// TClipper methods ...
-//------------------------------------------------------------------------------
-
-Clipper::Clipper(int initOptions) : ClipperBase() //constructor
-{
- m_ExecuteLocked = false;
- m_UseFullRange = false;
- m_ReverseOutput = ((initOptions & ioReverseSolution) != 0);
- m_StrictSimple = ((initOptions & ioStrictlySimple) != 0);
- m_PreserveCollinear = ((initOptions & ioPreserveCollinear) != 0);
- m_HasOpenPaths = false;
-#ifdef use_xyz
- m_ZFill = 0;
-#endif
-}
-//------------------------------------------------------------------------------
-
-#ifdef use_xyz
-void Clipper::ZFillFunction(ZFillCallback zFillFunc)
-{
- m_ZFill = zFillFunc;
-}
-//------------------------------------------------------------------------------
-#endif
-
-bool Clipper::Execute(ClipType clipType, Paths &solution, PolyFillType fillType)
-{
- return Execute(clipType, solution, fillType, fillType);
-}
-//------------------------------------------------------------------------------
-
-bool Clipper::Execute(ClipType clipType, PolyTree &polytree, PolyFillType fillType)
-{
- return Execute(clipType, polytree, fillType, fillType);
-}
-//------------------------------------------------------------------------------
-
-bool Clipper::Execute(ClipType clipType, Paths &solution,
- PolyFillType subjFillType, PolyFillType clipFillType)
-{
- if( m_ExecuteLocked ) return false;
- if (m_HasOpenPaths)
- throw clipperException("Error: PolyTree struct is needed for open path clipping.");
- m_ExecuteLocked = true;
- solution.resize(0);
- m_SubjFillType = subjFillType;
- m_ClipFillType = clipFillType;
- m_ClipType = clipType;
- m_UsingPolyTree = false;
- bool succeeded = ExecuteInternal();
- if (succeeded) BuildResult(solution);
- DisposeAllOutRecs();
- m_ExecuteLocked = false;
- return succeeded;
-}
-//------------------------------------------------------------------------------
-
-bool Clipper::Execute(ClipType clipType, PolyTree& polytree,
- PolyFillType subjFillType, PolyFillType clipFillType)
-{
- if( m_ExecuteLocked ) return false;
- m_ExecuteLocked = true;
- m_SubjFillType = subjFillType;
- m_ClipFillType = clipFillType;
- m_ClipType = clipType;
- m_UsingPolyTree = true;
- bool succeeded = ExecuteInternal();
- if (succeeded) BuildResult2(polytree);
- DisposeAllOutRecs();
- m_ExecuteLocked = false;
- return succeeded;
-}
-//------------------------------------------------------------------------------
-
-void Clipper::FixHoleLinkage(OutRec &outrec)
-{
- //skip OutRecs that (a) contain outermost polygons or
- //(b) already have the correct owner/child linkage ...
- if (!outrec.FirstLeft ||
- (outrec.IsHole != outrec.FirstLeft->IsHole &&
- outrec.FirstLeft->Pts)) return;
-
- OutRec* orfl = outrec.FirstLeft;
- while (orfl && ((orfl->IsHole == outrec.IsHole) || !orfl->Pts))
- orfl = orfl->FirstLeft;
- outrec.FirstLeft = orfl;
-}
-//------------------------------------------------------------------------------
-
-bool Clipper::ExecuteInternal()
-{
- bool succeeded = true;
- try {
- Reset();
- m_Maxima = MaximaList();
- m_SortedEdges = 0;
-
- succeeded = true;
- cInt botY, topY;
- if (!PopScanbeam(botY)) return false;
- InsertLocalMinimaIntoAEL(botY);
- while (PopScanbeam(topY) || LocalMinimaPending())
- {
- ProcessHorizontals();
- ClearGhostJoins();
- if (!ProcessIntersections(topY))
- {
- succeeded = false;
- break;
- }
- ProcessEdgesAtTopOfScanbeam(topY);
- botY = topY;
- InsertLocalMinimaIntoAEL(botY);
- }
- }
- catch(...)
- {
- succeeded = false;
- }
-
- if (succeeded)
- {
- //fix orientations ...
- for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
- {
- OutRec *outRec = m_PolyOuts[i];
- if (!outRec->Pts || outRec->IsOpen) continue;
- if ((outRec->IsHole ^ m_ReverseOutput) == (Area(*outRec) > 0))
- ReversePolyPtLinks(outRec->Pts);
- }
-
- if (!m_Joins.empty()) JoinCommonEdges();
-
- //unfortunately FixupOutPolygon() must be done after JoinCommonEdges()
- for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
- {
- OutRec *outRec = m_PolyOuts[i];
- if (!outRec->Pts) continue;
- if (outRec->IsOpen)
- FixupOutPolyline(*outRec);
- else
- FixupOutPolygon(*outRec);
- }
-
- if (m_StrictSimple) DoSimplePolygons();
- }
-
- ClearJoins();
- ClearGhostJoins();
- return succeeded;
-}
-//------------------------------------------------------------------------------
-
-void Clipper::SetWindingCount(TEdge &edge)
-{
- TEdge *e = edge.PrevInAEL;
- //find the edge of the same polytype that immediately preceeds 'edge' in AEL
- while (e && ((e->PolyTyp != edge.PolyTyp) || (e->WindDelta == 0))) e = e->PrevInAEL;
- if (!e)
- {
- if (edge.WindDelta == 0)
- {
- PolyFillType pft = (edge.PolyTyp == ptSubject ? m_SubjFillType : m_ClipFillType);
- edge.WindCnt = (pft == pftNegative ? -1 : 1);
- }
- else
- edge.WindCnt = edge.WindDelta;
- edge.WindCnt2 = 0;
- e = m_ActiveEdges; //ie get ready to calc WindCnt2
- }
- else if (edge.WindDelta == 0 && m_ClipType != ctUnion)
- {
- edge.WindCnt = 1;
- edge.WindCnt2 = e->WindCnt2;
- e = e->NextInAEL; //ie get ready to calc WindCnt2
- }
- else if (IsEvenOddFillType(edge))
- {
- //EvenOdd filling ...
- if (edge.WindDelta == 0)
- {
- //are we inside a subj polygon ...
- bool Inside = true;
- TEdge *e2 = e->PrevInAEL;
- while (e2)
- {
- if (e2->PolyTyp == e->PolyTyp && e2->WindDelta != 0)
- Inside = !Inside;
- e2 = e2->PrevInAEL;
- }
- edge.WindCnt = (Inside ? 0 : 1);
- }
- else
- {
- edge.WindCnt = edge.WindDelta;
- }
- edge.WindCnt2 = e->WindCnt2;
- e = e->NextInAEL; //ie get ready to calc WindCnt2
- }
- else
- {
- //nonZero, Positive or Negative filling ...
- if (e->WindCnt * e->WindDelta < 0)
- {
- //prev edge is 'decreasing' WindCount (WC) toward zero
- //so we're outside the previous polygon ...
- if (Abs(e->WindCnt) > 1)
- {
- //outside prev poly but still inside another.
- //when reversing direction of prev poly use the same WC
- if (e->WindDelta * edge.WindDelta < 0) edge.WindCnt = e->WindCnt;
- //otherwise continue to 'decrease' WC ...
- else edge.WindCnt = e->WindCnt + edge.WindDelta;
- }
- else
- //now outside all polys of same polytype so set own WC ...
- edge.WindCnt = (edge.WindDelta == 0 ? 1 : edge.WindDelta);
- } else
- {
- //prev edge is 'increasing' WindCount (WC) away from zero
- //so we're inside the previous polygon ...
- if (edge.WindDelta == 0)
- edge.WindCnt = (e->WindCnt < 0 ? e->WindCnt - 1 : e->WindCnt + 1);
- //if wind direction is reversing prev then use same WC
- else if (e->WindDelta * edge.WindDelta < 0) edge.WindCnt = e->WindCnt;
- //otherwise add to WC ...
- else edge.WindCnt = e->WindCnt + edge.WindDelta;
- }
- edge.WindCnt2 = e->WindCnt2;
- e = e->NextInAEL; //ie get ready to calc WindCnt2
- }
-
- //update WindCnt2 ...
- if (IsEvenOddAltFillType(edge))
- {
- //EvenOdd filling ...
- while (e != &edge)
- {
- if (e->WindDelta != 0)
- edge.WindCnt2 = (edge.WindCnt2 == 0 ? 1 : 0);
- e = e->NextInAEL;
- }
- } else
- {
- //nonZero, Positive or Negative filling ...
- while ( e != &edge )
- {
- edge.WindCnt2 += e->WindDelta;
- e = e->NextInAEL;
- }
- }
-}
-//------------------------------------------------------------------------------
-
-bool Clipper::IsEvenOddFillType(const TEdge& edge) const
-{
- if (edge.PolyTyp == ptSubject)
- return m_SubjFillType == pftEvenOdd; else
- return m_ClipFillType == pftEvenOdd;
-}
-//------------------------------------------------------------------------------
-
-bool Clipper::IsEvenOddAltFillType(const TEdge& edge) const
-{
- if (edge.PolyTyp == ptSubject)
- return m_ClipFillType == pftEvenOdd; else
- return m_SubjFillType == pftEvenOdd;
-}
-//------------------------------------------------------------------------------
-
-bool Clipper::IsContributing(const TEdge& edge) const
-{
- PolyFillType pft, pft2;
- if (edge.PolyTyp == ptSubject)
- {
- pft = m_SubjFillType;
- pft2 = m_ClipFillType;
- } else
- {
- pft = m_ClipFillType;
- pft2 = m_SubjFillType;
- }
-
- switch(pft)
- {
- case pftEvenOdd:
- //return false if a subj line has been flagged as inside a subj polygon
- if (edge.WindDelta == 0 && edge.WindCnt != 1) return false;
- break;
- case pftNonZero:
- if (Abs(edge.WindCnt) != 1) return false;
- break;
- case pftPositive:
- if (edge.WindCnt != 1) return false;
- break;
- default: //pftNegative
- if (edge.WindCnt != -1) return false;
- }
-
- switch(m_ClipType)
- {
- case ctIntersection:
- switch(pft2)
- {
- case pftEvenOdd:
- case pftNonZero:
- return (edge.WindCnt2 != 0);
- case pftPositive:
- return (edge.WindCnt2 > 0);
- default:
- return (edge.WindCnt2 < 0);
- }
- break;
- case ctUnion:
- switch(pft2)
- {
- case pftEvenOdd:
- case pftNonZero:
- return (edge.WindCnt2 == 0);
- case pftPositive:
- return (edge.WindCnt2 <= 0);
- default:
- return (edge.WindCnt2 >= 0);
- }
- break;
- case ctDifference:
- if (edge.PolyTyp == ptSubject)
- switch(pft2)
- {
- case pftEvenOdd:
- case pftNonZero:
- return (edge.WindCnt2 == 0);
- case pftPositive:
- return (edge.WindCnt2 <= 0);
- default:
- return (edge.WindCnt2 >= 0);
- }
- else
- switch(pft2)
- {
- case pftEvenOdd:
- case pftNonZero:
- return (edge.WindCnt2 != 0);
- case pftPositive:
- return (edge.WindCnt2 > 0);
- default:
- return (edge.WindCnt2 < 0);
- }
- break;
- case ctXor:
- if (edge.WindDelta == 0) //XOr always contributing unless open
- switch(pft2)
- {
- case pftEvenOdd:
- case pftNonZero:
- return (edge.WindCnt2 == 0);
- case pftPositive:
- return (edge.WindCnt2 <= 0);
- default:
- return (edge.WindCnt2 >= 0);
- }
- else
- return true;
- break;
- default:
- return true;
- }
-}
-//------------------------------------------------------------------------------
-
-OutPt* Clipper::AddLocalMinPoly(TEdge *e1, TEdge *e2, const IntPoint &Pt)
-{
- OutPt* result;
- TEdge *e, *prevE;
- if (IsHorizontal(*e2) || ( e1->Dx > e2->Dx ))
- {
- result = AddOutPt(e1, Pt);
- e2->OutIdx = e1->OutIdx;
- e1->Side = esLeft;
- e2->Side = esRight;
- e = e1;
- if (e->PrevInAEL == e2)
- prevE = e2->PrevInAEL;
- else
- prevE = e->PrevInAEL;
- } else
- {
- result = AddOutPt(e2, Pt);
- e1->OutIdx = e2->OutIdx;
- e1->Side = esRight;
- e2->Side = esLeft;
- e = e2;
- if (e->PrevInAEL == e1)
- prevE = e1->PrevInAEL;
- else
- prevE = e->PrevInAEL;
- }
-
- if (prevE && prevE->OutIdx >= 0 && prevE->Top.Y < Pt.Y && e->Top.Y < Pt.Y)
- {
- cInt xPrev = TopX(*prevE, Pt.Y);
- cInt xE = TopX(*e, Pt.Y);
- if (xPrev == xE && (e->WindDelta != 0) && (prevE->WindDelta != 0) &&
- SlopesEqual(IntPoint(xPrev, Pt.Y), prevE->Top, IntPoint(xE, Pt.Y), e->Top, m_UseFullRange))
- {
- OutPt* outPt = AddOutPt(prevE, Pt);
- AddJoin(result, outPt, e->Top);
- }
- }
- return result;
-}
-//------------------------------------------------------------------------------
-
-void Clipper::AddLocalMaxPoly(TEdge *e1, TEdge *e2, const IntPoint &Pt)
-{
- AddOutPt( e1, Pt );
- if (e2->WindDelta == 0) AddOutPt(e2, Pt);
- if( e1->OutIdx == e2->OutIdx )
- {
- e1->OutIdx = Unassigned;
- e2->OutIdx = Unassigned;
- }
- else if (e1->OutIdx < e2->OutIdx)
- AppendPolygon(e1, e2);
- else
- AppendPolygon(e2, e1);
-}
-//------------------------------------------------------------------------------
-
-void Clipper::AddEdgeToSEL(TEdge *edge)
-{
- //SEL pointers in PEdge are reused to build a list of horizontal edges.
- //However, we don't need to worry about order with horizontal edge processing.
- if( !m_SortedEdges )
- {
- m_SortedEdges = edge;
- edge->PrevInSEL = 0;
- edge->NextInSEL = 0;
- }
- else
- {
- edge->NextInSEL = m_SortedEdges;
- edge->PrevInSEL = 0;
- m_SortedEdges->PrevInSEL = edge;
- m_SortedEdges = edge;
- }
-}
-//------------------------------------------------------------------------------
-
-bool Clipper::PopEdgeFromSEL(TEdge *&edge)
-{
- if (!m_SortedEdges) return false;
- edge = m_SortedEdges;
- DeleteFromSEL(m_SortedEdges);
- return true;
-}
-//------------------------------------------------------------------------------
-
-void Clipper::CopyAELToSEL()
-{
- TEdge* e = m_ActiveEdges;
- m_SortedEdges = e;
- while ( e )
- {
- e->PrevInSEL = e->PrevInAEL;
- e->NextInSEL = e->NextInAEL;
- e = e->NextInAEL;
- }
-}
-//------------------------------------------------------------------------------
-
-void Clipper::AddJoin(OutPt *op1, OutPt *op2, const IntPoint OffPt)
-{
- Join* j = new Join;
- j->OutPt1 = op1;
- j->OutPt2 = op2;
- j->OffPt = OffPt;
- m_Joins.push_back(j);
-}
-//------------------------------------------------------------------------------
-
-void Clipper::ClearJoins()
-{
- for (JoinList::size_type i = 0; i < m_Joins.size(); i++)
- delete m_Joins[i];
- m_Joins.resize(0);
-}
-//------------------------------------------------------------------------------
-
-void Clipper::ClearGhostJoins()
-{
- for (JoinList::size_type i = 0; i < m_GhostJoins.size(); i++)
- delete m_GhostJoins[i];
- m_GhostJoins.resize(0);
-}
-//------------------------------------------------------------------------------
-
-void Clipper::AddGhostJoin(OutPt *op, const IntPoint OffPt)
-{
- Join* j = new Join;
- j->OutPt1 = op;
- j->OutPt2 = 0;
- j->OffPt = OffPt;
- m_GhostJoins.push_back(j);
-}
-//------------------------------------------------------------------------------
-
-void Clipper::InsertLocalMinimaIntoAEL(const cInt botY)
-{
- const LocalMinimum *lm;
- while (PopLocalMinima(botY, lm))
- {
- TEdge* lb = lm->LeftBound;
- TEdge* rb = lm->RightBound;
-
- OutPt *Op1 = 0;
- if (!lb)
- {
- //nb: don't insert LB into either AEL or SEL
- InsertEdgeIntoAEL(rb, 0);
- SetWindingCount(*rb);
- if (IsContributing(*rb))
- Op1 = AddOutPt(rb, rb->Bot);
- }
- else if (!rb)
- {
- InsertEdgeIntoAEL(lb, 0);
- SetWindingCount(*lb);
- if (IsContributing(*lb))
- Op1 = AddOutPt(lb, lb->Bot);
- InsertScanbeam(lb->Top.Y);
- }
- else
- {
- InsertEdgeIntoAEL(lb, 0);
- InsertEdgeIntoAEL(rb, lb);
- SetWindingCount( *lb );
- rb->WindCnt = lb->WindCnt;
- rb->WindCnt2 = lb->WindCnt2;
- if (IsContributing(*lb))
- Op1 = AddLocalMinPoly(lb, rb, lb->Bot);
- InsertScanbeam(lb->Top.Y);
- }
-
- if (rb)
- {
- if (IsHorizontal(*rb))
- {
- AddEdgeToSEL(rb);
- if (rb->NextInLML)
- InsertScanbeam(rb->NextInLML->Top.Y);
- }
- else InsertScanbeam( rb->Top.Y );
- }
-
- if (!lb || !rb) continue;
-
- //if any output polygons share an edge, they'll need joining later ...
- if (Op1 && IsHorizontal(*rb) &&
- m_GhostJoins.size() > 0 && (rb->WindDelta != 0))
- {
- for (JoinList::size_type i = 0; i < m_GhostJoins.size(); ++i)
- {
- Join* jr = m_GhostJoins[i];
- //if the horizontal Rb and a 'ghost' horizontal overlap, then convert
- //the 'ghost' join to a real join ready for later ...
- if (HorzSegmentsOverlap(jr->OutPt1->Pt.X, jr->OffPt.X, rb->Bot.X, rb->Top.X))
- AddJoin(jr->OutPt1, Op1, jr->OffPt);
- }
- }
-
- if (lb->OutIdx >= 0 && lb->PrevInAEL &&
- lb->PrevInAEL->Curr.X == lb->Bot.X &&
- lb->PrevInAEL->OutIdx >= 0 &&
- SlopesEqual(lb->PrevInAEL->Bot, lb->PrevInAEL->Top, lb->Curr, lb->Top, m_UseFullRange) &&
- (lb->WindDelta != 0) && (lb->PrevInAEL->WindDelta != 0))
- {
- OutPt *Op2 = AddOutPt(lb->PrevInAEL, lb->Bot);
- AddJoin(Op1, Op2, lb->Top);
- }
-
- if(lb->NextInAEL != rb)
- {
-
- if (rb->OutIdx >= 0 && rb->PrevInAEL->OutIdx >= 0 &&
- SlopesEqual(rb->PrevInAEL->Curr, rb->PrevInAEL->Top, rb->Curr, rb->Top, m_UseFullRange) &&
- (rb->WindDelta != 0) && (rb->PrevInAEL->WindDelta != 0))
- {
- OutPt *Op2 = AddOutPt(rb->PrevInAEL, rb->Bot);
- AddJoin(Op1, Op2, rb->Top);
- }
-
- TEdge* e = lb->NextInAEL;
- if (e)
- {
- while( e != rb )
- {
- //nb: For calculating winding counts etc, IntersectEdges() assumes
- //that param1 will be to the Right of param2 ABOVE the intersection ...
- IntersectEdges(rb , e , lb->Curr); //order important here
- e = e->NextInAEL;
- }
- }
- }
-
- }
-}
-//------------------------------------------------------------------------------
-
-void Clipper::DeleteFromSEL(TEdge *e)
-{
- TEdge* SelPrev = e->PrevInSEL;
- TEdge* SelNext = e->NextInSEL;
- if( !SelPrev && !SelNext && (e != m_SortedEdges) ) return; //already deleted
- if( SelPrev ) SelPrev->NextInSEL = SelNext;
- else m_SortedEdges = SelNext;
- if( SelNext ) SelNext->PrevInSEL = SelPrev;
- e->NextInSEL = 0;
- e->PrevInSEL = 0;
-}
-//------------------------------------------------------------------------------
-
-#ifdef use_xyz
-void Clipper::SetZ(IntPoint& pt, TEdge& e1, TEdge& e2)
-{
- if (pt.Z != 0 || !m_ZFill) return;
- else if (pt == e1.Bot) pt.Z = e1.Bot.Z;
- else if (pt == e1.Top) pt.Z = e1.Top.Z;
- else if (pt == e2.Bot) pt.Z = e2.Bot.Z;
- else if (pt == e2.Top) pt.Z = e2.Top.Z;
- else (*m_ZFill)(e1.Bot, e1.Top, e2.Bot, e2.Top, pt);
-}
-//------------------------------------------------------------------------------
-#endif
-
-void Clipper::IntersectEdges(TEdge *e1, TEdge *e2, IntPoint &Pt)
-{
- bool e1Contributing = ( e1->OutIdx >= 0 );
- bool e2Contributing = ( e2->OutIdx >= 0 );
-
-#ifdef use_xyz
- SetZ(Pt, *e1, *e2);
-#endif
-
-#ifdef use_lines
- //if either edge is on an OPEN path ...
- if (e1->WindDelta == 0 || e2->WindDelta == 0)
- {
- //ignore subject-subject open path intersections UNLESS they
- //are both open paths, AND they are both 'contributing maximas' ...
- if (e1->WindDelta == 0 && e2->WindDelta == 0) return;
-
- //if intersecting a subj line with a subj poly ...
- else if (e1->PolyTyp == e2->PolyTyp &&
- e1->WindDelta != e2->WindDelta && m_ClipType == ctUnion)
- {
- if (e1->WindDelta == 0)
- {
- if (e2Contributing)
- {
- AddOutPt(e1, Pt);
- if (e1Contributing) e1->OutIdx = Unassigned;
- }
- }
- else
- {
- if (e1Contributing)
- {
- AddOutPt(e2, Pt);
- if (e2Contributing) e2->OutIdx = Unassigned;
- }
- }
- }
- else if (e1->PolyTyp != e2->PolyTyp)
- {
- //toggle subj open path OutIdx on/off when Abs(clip.WndCnt) == 1 ...
- if ((e1->WindDelta == 0) && abs(e2->WindCnt) == 1 &&
- (m_ClipType != ctUnion || e2->WindCnt2 == 0))
- {
- AddOutPt(e1, Pt);
- if (e1Contributing) e1->OutIdx = Unassigned;
- }
- else if ((e2->WindDelta == 0) && (abs(e1->WindCnt) == 1) &&
- (m_ClipType != ctUnion || e1->WindCnt2 == 0))
- {
- AddOutPt(e2, Pt);
- if (e2Contributing) e2->OutIdx = Unassigned;
- }
- }
- return;
- }
-#endif
-
- //update winding counts...
- //assumes that e1 will be to the Right of e2 ABOVE the intersection
- if ( e1->PolyTyp == e2->PolyTyp )
- {
- if ( IsEvenOddFillType( *e1) )
- {
- int oldE1WindCnt = e1->WindCnt;
- e1->WindCnt = e2->WindCnt;
- e2->WindCnt = oldE1WindCnt;
- } else
- {
- if (e1->WindCnt + e2->WindDelta == 0 ) e1->WindCnt = -e1->WindCnt;
- else e1->WindCnt += e2->WindDelta;
- if ( e2->WindCnt - e1->WindDelta == 0 ) e2->WindCnt = -e2->WindCnt;
- else e2->WindCnt -= e1->WindDelta;
- }
- } else
- {
- if (!IsEvenOddFillType(*e2)) e1->WindCnt2 += e2->WindDelta;
- else e1->WindCnt2 = ( e1->WindCnt2 == 0 ) ? 1 : 0;
- if (!IsEvenOddFillType(*e1)) e2->WindCnt2 -= e1->WindDelta;
- else e2->WindCnt2 = ( e2->WindCnt2 == 0 ) ? 1 : 0;
- }
-
- PolyFillType e1FillType, e2FillType, e1FillType2, e2FillType2;
- if (e1->PolyTyp == ptSubject)
- {
- e1FillType = m_SubjFillType;
- e1FillType2 = m_ClipFillType;
- } else
- {
- e1FillType = m_ClipFillType;
- e1FillType2 = m_SubjFillType;
- }
- if (e2->PolyTyp == ptSubject)
- {
- e2FillType = m_SubjFillType;
- e2FillType2 = m_ClipFillType;
- } else
- {
- e2FillType = m_ClipFillType;
- e2FillType2 = m_SubjFillType;
- }
-
- cInt e1Wc, e2Wc;
- switch (e1FillType)
- {
- case pftPositive: e1Wc = e1->WindCnt; break;
- case pftNegative: e1Wc = -e1->WindCnt; break;
- default: e1Wc = Abs(e1->WindCnt);
- }
- switch(e2FillType)
- {
- case pftPositive: e2Wc = e2->WindCnt; break;
- case pftNegative: e2Wc = -e2->WindCnt; break;
- default: e2Wc = Abs(e2->WindCnt);
- }
-
- if ( e1Contributing && e2Contributing )
- {
- if ((e1Wc != 0 && e1Wc != 1) || (e2Wc != 0 && e2Wc != 1) ||
- (e1->PolyTyp != e2->PolyTyp && m_ClipType != ctXor) )
- {
- AddLocalMaxPoly(e1, e2, Pt);
- }
- else
- {
- AddOutPt(e1, Pt);
- AddOutPt(e2, Pt);
- SwapSides( *e1 , *e2 );
- SwapPolyIndexes( *e1 , *e2 );
- }
- }
- else if ( e1Contributing )
- {
- if (e2Wc == 0 || e2Wc == 1)
- {
- AddOutPt(e1, Pt);
- SwapSides(*e1, *e2);
- SwapPolyIndexes(*e1, *e2);
- }
- }
- else if ( e2Contributing )
- {
- if (e1Wc == 0 || e1Wc == 1)
- {
- AddOutPt(e2, Pt);
- SwapSides(*e1, *e2);
- SwapPolyIndexes(*e1, *e2);
- }
- }
- else if ( (e1Wc == 0 || e1Wc == 1) && (e2Wc == 0 || e2Wc == 1))
- {
- //neither edge is currently contributing ...
-
- cInt e1Wc2, e2Wc2;
- switch (e1FillType2)
- {
- case pftPositive: e1Wc2 = e1->WindCnt2; break;
- case pftNegative : e1Wc2 = -e1->WindCnt2; break;
- default: e1Wc2 = Abs(e1->WindCnt2);
- }
- switch (e2FillType2)
- {
- case pftPositive: e2Wc2 = e2->WindCnt2; break;
- case pftNegative: e2Wc2 = -e2->WindCnt2; break;
- default: e2Wc2 = Abs(e2->WindCnt2);
- }
-
- if (e1->PolyTyp != e2->PolyTyp)
- {
- AddLocalMinPoly(e1, e2, Pt);
- }
- else if (e1Wc == 1 && e2Wc == 1)
- switch( m_ClipType ) {
- case ctIntersection:
- if (e1Wc2 > 0 && e2Wc2 > 0)
- AddLocalMinPoly(e1, e2, Pt);
- break;
- case ctUnion:
- if ( e1Wc2 <= 0 && e2Wc2 <= 0 )
- AddLocalMinPoly(e1, e2, Pt);
- break;
- case ctDifference:
- if (((e1->PolyTyp == ptClip) && (e1Wc2 > 0) && (e2Wc2 > 0)) ||
- ((e1->PolyTyp == ptSubject) && (e1Wc2 <= 0) && (e2Wc2 <= 0)))
- AddLocalMinPoly(e1, e2, Pt);
- break;
- case ctXor:
- AddLocalMinPoly(e1, e2, Pt);
- }
- else
- SwapSides( *e1, *e2 );
- }
-}
-//------------------------------------------------------------------------------
-
-void Clipper::SetHoleState(TEdge *e, OutRec *outrec)
-{
- TEdge *e2 = e->PrevInAEL;
- TEdge *eTmp = 0;
- while (e2)
- {
- if (e2->OutIdx >= 0 && e2->WindDelta != 0)
- {
- if (!eTmp) eTmp = e2;
- else if (eTmp->OutIdx == e2->OutIdx) eTmp = 0;
- }
- e2 = e2->PrevInAEL;
- }
- if (!eTmp)
- {
- outrec->FirstLeft = 0;
- outrec->IsHole = false;
- }
- else
- {
- outrec->FirstLeft = m_PolyOuts[eTmp->OutIdx];
- outrec->IsHole = !outrec->FirstLeft->IsHole;
- }
-}
-//------------------------------------------------------------------------------
-
-OutRec* GetLowermostRec(OutRec *outRec1, OutRec *outRec2)
-{
- //work out which polygon fragment has the correct hole state ...
- if (!outRec1->BottomPt)
- outRec1->BottomPt = GetBottomPt(outRec1->Pts);
- if (!outRec2->BottomPt)
- outRec2->BottomPt = GetBottomPt(outRec2->Pts);
- OutPt *OutPt1 = outRec1->BottomPt;
- OutPt *OutPt2 = outRec2->BottomPt;
- if (OutPt1->Pt.Y > OutPt2->Pt.Y) return outRec1;
- else if (OutPt1->Pt.Y < OutPt2->Pt.Y) return outRec2;
- else if (OutPt1->Pt.X < OutPt2->Pt.X) return outRec1;
- else if (OutPt1->Pt.X > OutPt2->Pt.X) return outRec2;
- else if (OutPt1->Next == OutPt1) return outRec2;
- else if (OutPt2->Next == OutPt2) return outRec1;
- else if (FirstIsBottomPt(OutPt1, OutPt2)) return outRec1;
- else return outRec2;
-}
-//------------------------------------------------------------------------------
-
-bool OutRec1RightOfOutRec2(OutRec* outRec1, OutRec* outRec2)
-{
- do
- {
- outRec1 = outRec1->FirstLeft;
- if (outRec1 == outRec2) return true;
- } while (outRec1);
- return false;
-}
-//------------------------------------------------------------------------------
-
-OutRec* Clipper::GetOutRec(int Idx)
-{
- OutRec* outrec = m_PolyOuts[Idx];
- while (outrec != m_PolyOuts[outrec->Idx])
- outrec = m_PolyOuts[outrec->Idx];
- return outrec;
-}
-//------------------------------------------------------------------------------
-
-void Clipper::AppendPolygon(TEdge *e1, TEdge *e2)
-{
- //get the start and ends of both output polygons ...
- OutRec *outRec1 = m_PolyOuts[e1->OutIdx];
- OutRec *outRec2 = m_PolyOuts[e2->OutIdx];
-
- OutRec *holeStateRec;
- if (OutRec1RightOfOutRec2(outRec1, outRec2))
- holeStateRec = outRec2;
- else if (OutRec1RightOfOutRec2(outRec2, outRec1))
- holeStateRec = outRec1;
- else
- holeStateRec = GetLowermostRec(outRec1, outRec2);
-
- //get the start and ends of both output polygons and
- //join e2 poly onto e1 poly and delete pointers to e2 ...
-
- OutPt* p1_lft = outRec1->Pts;
- OutPt* p1_rt = p1_lft->Prev;
- OutPt* p2_lft = outRec2->Pts;
- OutPt* p2_rt = p2_lft->Prev;
-
- //join e2 poly onto e1 poly and delete pointers to e2 ...
- if( e1->Side == esLeft )
- {
- if( e2->Side == esLeft )
- {
- //z y x a b c
- ReversePolyPtLinks(p2_lft);
- p2_lft->Next = p1_lft;
- p1_lft->Prev = p2_lft;
- p1_rt->Next = p2_rt;
- p2_rt->Prev = p1_rt;
- outRec1->Pts = p2_rt;
- } else
- {
- //x y z a b c
- p2_rt->Next = p1_lft;
- p1_lft->Prev = p2_rt;
- p2_lft->Prev = p1_rt;
- p1_rt->Next = p2_lft;
- outRec1->Pts = p2_lft;
- }
- } else
- {
- if( e2->Side == esRight )
- {
- //a b c z y x
- ReversePolyPtLinks(p2_lft);
- p1_rt->Next = p2_rt;
- p2_rt->Prev = p1_rt;
- p2_lft->Next = p1_lft;
- p1_lft->Prev = p2_lft;
- } else
- {
- //a b c x y z
- p1_rt->Next = p2_lft;
- p2_lft->Prev = p1_rt;
- p1_lft->Prev = p2_rt;
- p2_rt->Next = p1_lft;
- }
- }
-
- outRec1->BottomPt = 0;
- if (holeStateRec == outRec2)
- {
- if (outRec2->FirstLeft != outRec1)
- outRec1->FirstLeft = outRec2->FirstLeft;
- outRec1->IsHole = outRec2->IsHole;
- }
- outRec2->Pts = 0;
- outRec2->BottomPt = 0;
- outRec2->FirstLeft = outRec1;
-
- int OKIdx = e1->OutIdx;
- int ObsoleteIdx = e2->OutIdx;
-
- e1->OutIdx = Unassigned; //nb: safe because we only get here via AddLocalMaxPoly
- e2->OutIdx = Unassigned;
-
- TEdge* e = m_ActiveEdges;
- while( e )
- {
- if( e->OutIdx == ObsoleteIdx )
- {
- e->OutIdx = OKIdx;
- e->Side = e1->Side;
- break;
- }
- e = e->NextInAEL;
- }
-
- outRec2->Idx = outRec1->Idx;
-}
-//------------------------------------------------------------------------------
-
-OutPt* Clipper::AddOutPt(TEdge *e, const IntPoint &pt)
-{
- if( e->OutIdx < 0 )
- {
- OutRec *outRec = CreateOutRec();
- outRec->IsOpen = (e->WindDelta == 0);
- OutPt* newOp = new OutPt;
- outRec->Pts = newOp;
- newOp->Idx = outRec->Idx;
- newOp->Pt = pt;
- newOp->Next = newOp;
- newOp->Prev = newOp;
- if (!outRec->IsOpen)
- SetHoleState(e, outRec);
- e->OutIdx = outRec->Idx;
- return newOp;
- } else
- {
- OutRec *outRec = m_PolyOuts[e->OutIdx];
- //OutRec.Pts is the 'Left-most' point & OutRec.Pts.Prev is the 'Right-most'
- OutPt* op = outRec->Pts;
-
- bool ToFront = (e->Side == esLeft);
- if (ToFront && (pt == op->Pt)) return op;
- else if (!ToFront && (pt == op->Prev->Pt)) return op->Prev;
-
- OutPt* newOp = new OutPt;
- newOp->Idx = outRec->Idx;
- newOp->Pt = pt;
- newOp->Next = op;
- newOp->Prev = op->Prev;
- newOp->Prev->Next = newOp;
- op->Prev = newOp;
- if (ToFront) outRec->Pts = newOp;
- return newOp;
- }
-}
-//------------------------------------------------------------------------------
-
-OutPt* Clipper::GetLastOutPt(TEdge *e)
-{
- OutRec *outRec = m_PolyOuts[e->OutIdx];
- if (e->Side == esLeft)
- return outRec->Pts;
- else
- return outRec->Pts->Prev;
-}
-//------------------------------------------------------------------------------
-
-void Clipper::ProcessHorizontals()
-{
- TEdge* horzEdge;
- while (PopEdgeFromSEL(horzEdge))
- ProcessHorizontal(horzEdge);
-}
-//------------------------------------------------------------------------------
-
-inline bool IsMinima(TEdge *e)
-{
- return e && (e->Prev->NextInLML != e) && (e->Next->NextInLML != e);
-}
-//------------------------------------------------------------------------------
-
-inline bool IsMaxima(TEdge *e, const cInt Y)
-{
- return e && e->Top.Y == Y && !e->NextInLML;
-}
-//------------------------------------------------------------------------------
-
-inline bool IsIntermediate(TEdge *e, const cInt Y)
-{
- return e->Top.Y == Y && e->NextInLML;
-}
-//------------------------------------------------------------------------------
-
-TEdge *GetMaximaPair(TEdge *e)
-{
- if ((e->Next->Top == e->Top) && !e->Next->NextInLML)
- return e->Next;
- else if ((e->Prev->Top == e->Top) && !e->Prev->NextInLML)
- return e->Prev;
- else return 0;
-}
-//------------------------------------------------------------------------------
-
-TEdge *GetMaximaPairEx(TEdge *e)
-{
- //as GetMaximaPair() but returns 0 if MaxPair isn't in AEL (unless it's horizontal)
- TEdge* result = GetMaximaPair(e);
- if (result && (result->OutIdx == Skip ||
- (result->NextInAEL == result->PrevInAEL && !IsHorizontal(*result)))) return 0;
- return result;
-}
-//------------------------------------------------------------------------------
-
-void Clipper::SwapPositionsInSEL(TEdge *Edge1, TEdge *Edge2)
-{
- if( !( Edge1->NextInSEL ) && !( Edge1->PrevInSEL ) ) return;
- if( !( Edge2->NextInSEL ) && !( Edge2->PrevInSEL ) ) return;
-
- if( Edge1->NextInSEL == Edge2 )
- {
- TEdge* Next = Edge2->NextInSEL;
- if( Next ) Next->PrevInSEL = Edge1;
- TEdge* Prev = Edge1->PrevInSEL;
- if( Prev ) Prev->NextInSEL = Edge2;
- Edge2->PrevInSEL = Prev;
- Edge2->NextInSEL = Edge1;
- Edge1->PrevInSEL = Edge2;
- Edge1->NextInSEL = Next;
- }
- else if( Edge2->NextInSEL == Edge1 )
- {
- TEdge* Next = Edge1->NextInSEL;
- if( Next ) Next->PrevInSEL = Edge2;
- TEdge* Prev = Edge2->PrevInSEL;
- if( Prev ) Prev->NextInSEL = Edge1;
- Edge1->PrevInSEL = Prev;
- Edge1->NextInSEL = Edge2;
- Edge2->PrevInSEL = Edge1;
- Edge2->NextInSEL = Next;
- }
- else
- {
- TEdge* Next = Edge1->NextInSEL;
- TEdge* Prev = Edge1->PrevInSEL;
- Edge1->NextInSEL = Edge2->NextInSEL;
- if( Edge1->NextInSEL ) Edge1->NextInSEL->PrevInSEL = Edge1;
- Edge1->PrevInSEL = Edge2->PrevInSEL;
- if( Edge1->PrevInSEL ) Edge1->PrevInSEL->NextInSEL = Edge1;
- Edge2->NextInSEL = Next;
- if( Edge2->NextInSEL ) Edge2->NextInSEL->PrevInSEL = Edge2;
- Edge2->PrevInSEL = Prev;
- if( Edge2->PrevInSEL ) Edge2->PrevInSEL->NextInSEL = Edge2;
- }
-
- if( !Edge1->PrevInSEL ) m_SortedEdges = Edge1;
- else if( !Edge2->PrevInSEL ) m_SortedEdges = Edge2;
-}
-//------------------------------------------------------------------------------
-
-TEdge* GetNextInAEL(TEdge *e, Direction dir)
-{
- return dir == dLeftToRight ? e->NextInAEL : e->PrevInAEL;
-}
-//------------------------------------------------------------------------------
-
-void GetHorzDirection(TEdge& HorzEdge, Direction& Dir, cInt& Left, cInt& Right)
-{
- if (HorzEdge.Bot.X < HorzEdge.Top.X)
- {
- Left = HorzEdge.Bot.X;
- Right = HorzEdge.Top.X;
- Dir = dLeftToRight;
- } else
- {
- Left = HorzEdge.Top.X;
- Right = HorzEdge.Bot.X;
- Dir = dRightToLeft;
- }
-}
-//------------------------------------------------------------------------
-
-/*******************************************************************************
-* Notes: Horizontal edges (HEs) at scanline intersections (ie at the Top or *
-* Bottom of a scanbeam) are processed as if layered. The order in which HEs *
-* are processed doesn't matter. HEs intersect with other HE Bot.Xs only [#] *
-* (or they could intersect with Top.Xs only, ie EITHER Bot.Xs OR Top.Xs), *
-* and with other non-horizontal edges [*]. Once these intersections are *
-* processed, intermediate HEs then 'promote' the Edge above (NextInLML) into *
-* the AEL. These 'promoted' edges may in turn intersect [%] with other HEs. *
-*******************************************************************************/
-
-void Clipper::ProcessHorizontal(TEdge *horzEdge)
-{
- Direction dir;
- cInt horzLeft, horzRight;
- bool IsOpen = (horzEdge->WindDelta == 0);
-
- GetHorzDirection(*horzEdge, dir, horzLeft, horzRight);
-
- TEdge* eLastHorz = horzEdge, *eMaxPair = 0;
- while (eLastHorz->NextInLML && IsHorizontal(*eLastHorz->NextInLML))
- eLastHorz = eLastHorz->NextInLML;
- if (!eLastHorz->NextInLML)
- eMaxPair = GetMaximaPair(eLastHorz);
-
- MaximaList::const_iterator maxIt;
- MaximaList::const_reverse_iterator maxRit;
- if (m_Maxima.size() > 0)
- {
- //get the first maxima in range (X) ...
- if (dir == dLeftToRight)
- {
- maxIt = m_Maxima.begin();
- while (maxIt != m_Maxima.end() && *maxIt <= horzEdge->Bot.X) maxIt++;
- if (maxIt != m_Maxima.end() && *maxIt >= eLastHorz->Top.X)
- maxIt = m_Maxima.end();
- }
- else
- {
- maxRit = m_Maxima.rbegin();
- while (maxRit != m_Maxima.rend() && *maxRit > horzEdge->Bot.X) maxRit++;
- if (maxRit != m_Maxima.rend() && *maxRit <= eLastHorz->Top.X)
- maxRit = m_Maxima.rend();
- }
- }
-
- OutPt* op1 = 0;
-
- for (;;) //loop through consec. horizontal edges
- {
-
- bool IsLastHorz = (horzEdge == eLastHorz);
- TEdge* e = GetNextInAEL(horzEdge, dir);
- while(e)
- {
-
- //this code block inserts extra coords into horizontal edges (in output
- //polygons) whereever maxima touch these horizontal edges. This helps
- //'simplifying' polygons (ie if the Simplify property is set).
- if (m_Maxima.size() > 0)
- {
- if (dir == dLeftToRight)
- {
- while (maxIt != m_Maxima.end() && *maxIt < e->Curr.X)
- {
- if (horzEdge->OutIdx >= 0 && !IsOpen)
- AddOutPt(horzEdge, IntPoint(*maxIt, horzEdge->Bot.Y));
- maxIt++;
- }
- }
- else
- {
- while (maxRit != m_Maxima.rend() && *maxRit > e->Curr.X)
- {
- if (horzEdge->OutIdx >= 0 && !IsOpen)
- AddOutPt(horzEdge, IntPoint(*maxRit, horzEdge->Bot.Y));
- maxRit++;
- }
- }
- };
-
- if ((dir == dLeftToRight && e->Curr.X > horzRight) ||
- (dir == dRightToLeft && e->Curr.X < horzLeft)) break;
-
- //Also break if we've got to the end of an intermediate horizontal edge ...
- //nb: Smaller Dx's are to the right of larger Dx's ABOVE the horizontal.
- if (e->Curr.X == horzEdge->Top.X && horzEdge->NextInLML &&
- e->Dx < horzEdge->NextInLML->Dx) break;
-
- if (horzEdge->OutIdx >= 0 && !IsOpen) //note: may be done multiple times
- {
-#ifdef use_xyz
- if (dir == dLeftToRight) SetZ(e->Curr, *horzEdge, *e);
- else SetZ(e->Curr, *e, *horzEdge);
-#endif
- op1 = AddOutPt(horzEdge, e->Curr);
- TEdge* eNextHorz = m_SortedEdges;
- while (eNextHorz)
- {
- if (eNextHorz->OutIdx >= 0 &&
- HorzSegmentsOverlap(horzEdge->Bot.X,
- horzEdge->Top.X, eNextHorz->Bot.X, eNextHorz->Top.X))
- {
- OutPt* op2 = GetLastOutPt(eNextHorz);
- AddJoin(op2, op1, eNextHorz->Top);
- }
- eNextHorz = eNextHorz->NextInSEL;
- }
- AddGhostJoin(op1, horzEdge->Bot);
- }
-
- //OK, so far we're still in range of the horizontal Edge but make sure
- //we're at the last of consec. horizontals when matching with eMaxPair
- if(e == eMaxPair && IsLastHorz)
- {
- if (horzEdge->OutIdx >= 0)
- AddLocalMaxPoly(horzEdge, eMaxPair, horzEdge->Top);
- DeleteFromAEL(horzEdge);
- DeleteFromAEL(eMaxPair);
- return;
- }
-
- if(dir == dLeftToRight)
- {
- IntPoint Pt = IntPoint(e->Curr.X, horzEdge->Curr.Y);
- IntersectEdges(horzEdge, e, Pt);
- }
- else
- {
- IntPoint Pt = IntPoint(e->Curr.X, horzEdge->Curr.Y);
- IntersectEdges( e, horzEdge, Pt);
- }
- TEdge* eNext = GetNextInAEL(e, dir);
- SwapPositionsInAEL( horzEdge, e );
- e = eNext;
- } //end while(e)
-
- //Break out of loop if HorzEdge.NextInLML is not also horizontal ...
- if (!horzEdge->NextInLML || !IsHorizontal(*horzEdge->NextInLML)) break;
-
- UpdateEdgeIntoAEL(horzEdge);
- if (horzEdge->OutIdx >= 0) AddOutPt(horzEdge, horzEdge->Bot);
- GetHorzDirection(*horzEdge, dir, horzLeft, horzRight);
-
- } //end for (;;)
-
- if (horzEdge->OutIdx >= 0 && !op1)
- {
- op1 = GetLastOutPt(horzEdge);
- TEdge* eNextHorz = m_SortedEdges;
- while (eNextHorz)
- {
- if (eNextHorz->OutIdx >= 0 &&
- HorzSegmentsOverlap(horzEdge->Bot.X,
- horzEdge->Top.X, eNextHorz->Bot.X, eNextHorz->Top.X))
- {
- OutPt* op2 = GetLastOutPt(eNextHorz);
- AddJoin(op2, op1, eNextHorz->Top);
- }
- eNextHorz = eNextHorz->NextInSEL;
- }
- AddGhostJoin(op1, horzEdge->Top);
- }
-
- if (horzEdge->NextInLML)
- {
- if(horzEdge->OutIdx >= 0)
- {
- op1 = AddOutPt( horzEdge, horzEdge->Top);
- UpdateEdgeIntoAEL(horzEdge);
- if (horzEdge->WindDelta == 0) return;
- //nb: HorzEdge is no longer horizontal here
- TEdge* ePrev = horzEdge->PrevInAEL;
- TEdge* eNext = horzEdge->NextInAEL;
- if (ePrev && ePrev->Curr.X == horzEdge->Bot.X &&
- ePrev->Curr.Y == horzEdge->Bot.Y && ePrev->WindDelta != 0 &&
- (ePrev->OutIdx >= 0 && ePrev->Curr.Y > ePrev->Top.Y &&
- SlopesEqual(*horzEdge, *ePrev, m_UseFullRange)))
- {
- OutPt* op2 = AddOutPt(ePrev, horzEdge->Bot);
- AddJoin(op1, op2, horzEdge->Top);
- }
- else if (eNext && eNext->Curr.X == horzEdge->Bot.X &&
- eNext->Curr.Y == horzEdge->Bot.Y && eNext->WindDelta != 0 &&
- eNext->OutIdx >= 0 && eNext->Curr.Y > eNext->Top.Y &&
- SlopesEqual(*horzEdge, *eNext, m_UseFullRange))
- {
- OutPt* op2 = AddOutPt(eNext, horzEdge->Bot);
- AddJoin(op1, op2, horzEdge->Top);
- }
- }
- else
- UpdateEdgeIntoAEL(horzEdge);
- }
- else
- {
- if (horzEdge->OutIdx >= 0) AddOutPt(horzEdge, horzEdge->Top);
- DeleteFromAEL(horzEdge);
- }
-}
-//------------------------------------------------------------------------------
-
-bool Clipper::ProcessIntersections(const cInt topY)
-{
- if( !m_ActiveEdges ) return true;
- try {
- BuildIntersectList(topY);
- size_t IlSize = m_IntersectList.size();
- if (IlSize == 0) return true;
- if (IlSize == 1 || FixupIntersectionOrder()) ProcessIntersectList();
- else return false;
- }
- catch(...)
- {
- m_SortedEdges = 0;
- DisposeIntersectNodes();
- throw clipperException("ProcessIntersections error");
- }
- m_SortedEdges = 0;
- return true;
-}
-//------------------------------------------------------------------------------
-
-void Clipper::DisposeIntersectNodes()
-{
- for (size_t i = 0; i < m_IntersectList.size(); ++i )
- delete m_IntersectList[i];
- m_IntersectList.clear();
-}
-//------------------------------------------------------------------------------
-
-void Clipper::BuildIntersectList(const cInt topY)
-{
- if ( !m_ActiveEdges ) return;
-
- //prepare for sorting ...
- TEdge* e = m_ActiveEdges;
- m_SortedEdges = e;
- while( e )
- {
- e->PrevInSEL = e->PrevInAEL;
- e->NextInSEL = e->NextInAEL;
- e->Curr.X = TopX( *e, topY );
- e = e->NextInAEL;
- }
-
- //bubblesort ...
- bool isModified;
- do
- {
- isModified = false;
- e = m_SortedEdges;
- while( e->NextInSEL )
- {
- TEdge *eNext = e->NextInSEL;
- IntPoint Pt;
- if(e->Curr.X > eNext->Curr.X)
- {
- IntersectPoint(*e, *eNext, Pt);
- if (Pt.Y < topY) Pt = IntPoint(TopX(*e, topY), topY);
- IntersectNode * newNode = new IntersectNode;
- newNode->Edge1 = e;
- newNode->Edge2 = eNext;
- newNode->Pt = Pt;
- m_IntersectList.push_back(newNode);
-
- SwapPositionsInSEL(e, eNext);
- isModified = true;
- }
- else
- e = eNext;
- }
- if( e->PrevInSEL ) e->PrevInSEL->NextInSEL = 0;
- else break;
- }
- while ( isModified );
- m_SortedEdges = 0; //important
-}
-//------------------------------------------------------------------------------
-
-
-void Clipper::ProcessIntersectList()
-{
- for (size_t i = 0; i < m_IntersectList.size(); ++i)
- {
- IntersectNode* iNode = m_IntersectList[i];
- {
- IntersectEdges( iNode->Edge1, iNode->Edge2, iNode->Pt);
- SwapPositionsInAEL( iNode->Edge1 , iNode->Edge2 );
- }
- delete iNode;
- }
- m_IntersectList.clear();
-}
-//------------------------------------------------------------------------------
-
-bool IntersectListSort(IntersectNode* node1, IntersectNode* node2)
-{
- return node2->Pt.Y < node1->Pt.Y;
-}
-//------------------------------------------------------------------------------
-
-inline bool EdgesAdjacent(const IntersectNode &inode)
-{
- return (inode.Edge1->NextInSEL == inode.Edge2) ||
- (inode.Edge1->PrevInSEL == inode.Edge2);
-}
-//------------------------------------------------------------------------------
-
-bool Clipper::FixupIntersectionOrder()
-{
- //pre-condition: intersections are sorted Bottom-most first.
- //Now it's crucial that intersections are made only between adjacent edges,
- //so to ensure this the order of intersections may need adjusting ...
- CopyAELToSEL();
- std::sort(m_IntersectList.begin(), m_IntersectList.end(), IntersectListSort);
- size_t cnt = m_IntersectList.size();
- for (size_t i = 0; i < cnt; ++i)
- {
- if (!EdgesAdjacent(*m_IntersectList[i]))
- {
- size_t j = i + 1;
- while (j < cnt && !EdgesAdjacent(*m_IntersectList[j])) j++;
- if (j == cnt) return false;
- std::swap(m_IntersectList[i], m_IntersectList[j]);
- }
- SwapPositionsInSEL(m_IntersectList[i]->Edge1, m_IntersectList[i]->Edge2);
- }
- return true;
-}
-//------------------------------------------------------------------------------
-
-void Clipper::DoMaxima(TEdge *e)
-{
- TEdge* eMaxPair = GetMaximaPairEx(e);
- if (!eMaxPair)
- {
- if (e->OutIdx >= 0)
- AddOutPt(e, e->Top);
- DeleteFromAEL(e);
- return;
- }
-
- TEdge* eNext = e->NextInAEL;
- while(eNext && eNext != eMaxPair)
- {
- IntersectEdges(e, eNext, e->Top);
- SwapPositionsInAEL(e, eNext);
- eNext = e->NextInAEL;
- }
-
- if(e->OutIdx == Unassigned && eMaxPair->OutIdx == Unassigned)
- {
- DeleteFromAEL(e);
- DeleteFromAEL(eMaxPair);
- }
- else if( e->OutIdx >= 0 && eMaxPair->OutIdx >= 0 )
- {
- if (e->OutIdx >= 0) AddLocalMaxPoly(e, eMaxPair, e->Top);
- DeleteFromAEL(e);
- DeleteFromAEL(eMaxPair);
- }
-#ifdef use_lines
- else if (e->WindDelta == 0)
- {
- if (e->OutIdx >= 0)
- {
- AddOutPt(e, e->Top);
- e->OutIdx = Unassigned;
- }
- DeleteFromAEL(e);
-
- if (eMaxPair->OutIdx >= 0)
- {
- AddOutPt(eMaxPair, e->Top);
- eMaxPair->OutIdx = Unassigned;
- }
- DeleteFromAEL(eMaxPair);
- }
-#endif
- else throw clipperException("DoMaxima error");
-}
-//------------------------------------------------------------------------------
-
-void Clipper::ProcessEdgesAtTopOfScanbeam(const cInt topY)
-{
- TEdge* e = m_ActiveEdges;
- while( e )
- {
- //1. process maxima, treating them as if they're 'bent' horizontal edges,
- // but exclude maxima with horizontal edges. nb: e can't be a horizontal.
- bool IsMaximaEdge = IsMaxima(e, topY);
-
- if(IsMaximaEdge)
- {
- TEdge* eMaxPair = GetMaximaPairEx(e);
- IsMaximaEdge = (!eMaxPair || !IsHorizontal(*eMaxPair));
- }
-
- if(IsMaximaEdge)
- {
- if (m_StrictSimple) m_Maxima.push_back(e->Top.X);
- TEdge* ePrev = e->PrevInAEL;
- DoMaxima(e);
- if( !ePrev ) e = m_ActiveEdges;
- else e = ePrev->NextInAEL;
- }
- else
- {
- //2. promote horizontal edges, otherwise update Curr.X and Curr.Y ...
- if (IsIntermediate(e, topY) && IsHorizontal(*e->NextInLML))
- {
- UpdateEdgeIntoAEL(e);
- if (e->OutIdx >= 0)
- AddOutPt(e, e->Bot);
- AddEdgeToSEL(e);
- }
- else
- {
- e->Curr.X = TopX( *e, topY );
- e->Curr.Y = topY;
-#ifdef use_xyz
- e->Curr.Z = topY == e->Top.Y ? e->Top.Z : (topY == e->Bot.Y ? e->Bot.Z : 0);
-#endif
- }
-
- //When StrictlySimple and 'e' is being touched by another edge, then
- //make sure both edges have a vertex here ...
- if (m_StrictSimple)
- {
- TEdge* ePrev = e->PrevInAEL;
- if ((e->OutIdx >= 0) && (e->WindDelta != 0) && ePrev && (ePrev->OutIdx >= 0) &&
- (ePrev->Curr.X == e->Curr.X) && (ePrev->WindDelta != 0))
- {
- IntPoint pt = e->Curr;
-#ifdef use_xyz
- SetZ(pt, *ePrev, *e);
-#endif
- OutPt* op = AddOutPt(ePrev, pt);
- OutPt* op2 = AddOutPt(e, pt);
- AddJoin(op, op2, pt); //StrictlySimple (type-3) join
- }
- }
-
- e = e->NextInAEL;
- }
- }
-
- //3. Process horizontals at the Top of the scanbeam ...
- m_Maxima.sort();
- ProcessHorizontals();
- m_Maxima.clear();
-
- //4. Promote intermediate vertices ...
- e = m_ActiveEdges;
- while(e)
- {
- if(IsIntermediate(e, topY))
- {
- OutPt* op = 0;
- if( e->OutIdx >= 0 )
- op = AddOutPt(e, e->Top);
- UpdateEdgeIntoAEL(e);
-
- //if output polygons share an edge, they'll need joining later ...
- TEdge* ePrev = e->PrevInAEL;
- TEdge* eNext = e->NextInAEL;
- if (ePrev && ePrev->Curr.X == e->Bot.X &&
- ePrev->Curr.Y == e->Bot.Y && op &&
- ePrev->OutIdx >= 0 && ePrev->Curr.Y > ePrev->Top.Y &&
- SlopesEqual(e->Curr, e->Top, ePrev->Curr, ePrev->Top, m_UseFullRange) &&
- (e->WindDelta != 0) && (ePrev->WindDelta != 0))
- {
- OutPt* op2 = AddOutPt(ePrev, e->Bot);
- AddJoin(op, op2, e->Top);
- }
- else if (eNext && eNext->Curr.X == e->Bot.X &&
- eNext->Curr.Y == e->Bot.Y && op &&
- eNext->OutIdx >= 0 && eNext->Curr.Y > eNext->Top.Y &&
- SlopesEqual(e->Curr, e->Top, eNext->Curr, eNext->Top, m_UseFullRange) &&
- (e->WindDelta != 0) && (eNext->WindDelta != 0))
- {
- OutPt* op2 = AddOutPt(eNext, e->Bot);
- AddJoin(op, op2, e->Top);
- }
- }
- e = e->NextInAEL;
- }
-}
-//------------------------------------------------------------------------------
-
-void Clipper::FixupOutPolyline(OutRec &outrec)
-{
- OutPt *pp = outrec.Pts;
- OutPt *lastPP = pp->Prev;
- while (pp != lastPP)
- {
- pp = pp->Next;
- if (pp->Pt == pp->Prev->Pt)
- {
- if (pp == lastPP) lastPP = pp->Prev;
- OutPt *tmpPP = pp->Prev;
- tmpPP->Next = pp->Next;
- pp->Next->Prev = tmpPP;
- delete pp;
- pp = tmpPP;
- }
- }
-
- if (pp == pp->Prev)
- {
- DisposeOutPts(pp);
- outrec.Pts = 0;
- return;
- }
-}
-//------------------------------------------------------------------------------
-
-void Clipper::FixupOutPolygon(OutRec &outrec)
-{
- //FixupOutPolygon() - removes duplicate points and simplifies consecutive
- //parallel edges by removing the middle vertex.
- OutPt *lastOK = 0;
- outrec.BottomPt = 0;
- OutPt *pp = outrec.Pts;
- bool preserveCol = m_PreserveCollinear || m_StrictSimple;
-
- for (;;)
- {
- if (pp->Prev == pp || pp->Prev == pp->Next)
- {
- DisposeOutPts(pp);
- outrec.Pts = 0;
- return;
- }
-
- //test for duplicate points and collinear edges ...
- if ((pp->Pt == pp->Next->Pt) || (pp->Pt == pp->Prev->Pt) ||
- (SlopesEqual(pp->Prev->Pt, pp->Pt, pp->Next->Pt, m_UseFullRange) &&
- (!preserveCol || !Pt2IsBetweenPt1AndPt3(pp->Prev->Pt, pp->Pt, pp->Next->Pt))))
- {
- lastOK = 0;
- OutPt *tmp = pp;
- pp->Prev->Next = pp->Next;
- pp->Next->Prev = pp->Prev;
- pp = pp->Prev;
- delete tmp;
- }
- else if (pp == lastOK) break;
- else
- {
- if (!lastOK) lastOK = pp;
- pp = pp->Next;
- }
- }
- outrec.Pts = pp;
-}
-//------------------------------------------------------------------------------
-
-int PointCount(OutPt *Pts)
-{
- if (!Pts) return 0;
- int result = 0;
- OutPt* p = Pts;
- do
- {
- result++;
- p = p->Next;
- }
- while (p != Pts);
- return result;
-}
-//------------------------------------------------------------------------------
-
-void Clipper::BuildResult(Paths &polys)
-{
- polys.reserve(m_PolyOuts.size());
- for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
- {
- if (!m_PolyOuts[i]->Pts) continue;
- Path pg;
- OutPt* p = m_PolyOuts[i]->Pts->Prev;
- int cnt = PointCount(p);
- if (cnt < 2) continue;
- pg.reserve(cnt);
- for (int i = 0; i < cnt; ++i)
- {
- pg.push_back(p->Pt);
- p = p->Prev;
- }
- polys.push_back(pg);
- }
-}
-//------------------------------------------------------------------------------
-
-void Clipper::BuildResult2(PolyTree& polytree)
-{
- polytree.Clear();
- polytree.AllNodes.reserve(m_PolyOuts.size());
- //add each output polygon/contour to polytree ...
- for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); i++)
- {
- OutRec* outRec = m_PolyOuts[i];
- int cnt = PointCount(outRec->Pts);
- if ((outRec->IsOpen && cnt < 2) || (!outRec->IsOpen && cnt < 3)) continue;
- FixHoleLinkage(*outRec);
- PolyNode* pn = new PolyNode();
- //nb: polytree takes ownership of all the PolyNodes
- polytree.AllNodes.push_back(pn);
- outRec->PolyNd = pn;
- pn->Parent = 0;
- pn->Index = 0;
- pn->Contour.reserve(cnt);
- OutPt *op = outRec->Pts->Prev;
- for (int j = 0; j < cnt; j++)
- {
- pn->Contour.push_back(op->Pt);
- op = op->Prev;
- }
- }
-
- //fixup PolyNode links etc ...
- polytree.Childs.reserve(m_PolyOuts.size());
- for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); i++)
- {
- OutRec* outRec = m_PolyOuts[i];
- if (!outRec->PolyNd) continue;
- if (outRec->IsOpen)
- {
- outRec->PolyNd->m_IsOpen = true;
- polytree.AddChild(*outRec->PolyNd);
- }
- else if (outRec->FirstLeft && outRec->FirstLeft->PolyNd)
- outRec->FirstLeft->PolyNd->AddChild(*outRec->PolyNd);
- else
- polytree.AddChild(*outRec->PolyNd);
- }
-}
-//------------------------------------------------------------------------------
-
-void SwapIntersectNodes(IntersectNode &int1, IntersectNode &int2)
-{
- //just swap the contents (because fIntersectNodes is a single-linked-list)
- IntersectNode inode = int1; //gets a copy of Int1
- int1.Edge1 = int2.Edge1;
- int1.Edge2 = int2.Edge2;
- int1.Pt = int2.Pt;
- int2.Edge1 = inode.Edge1;
- int2.Edge2 = inode.Edge2;
- int2.Pt = inode.Pt;
-}
-//------------------------------------------------------------------------------
-
-inline bool E2InsertsBeforeE1(TEdge &e1, TEdge &e2)
-{
- if (e2.Curr.X == e1.Curr.X)
- {
- if (e2.Top.Y > e1.Top.Y)
- return e2.Top.X < TopX(e1, e2.Top.Y);
- else return e1.Top.X > TopX(e2, e1.Top.Y);
- }
- else return e2.Curr.X < e1.Curr.X;
-}
-//------------------------------------------------------------------------------
-
-bool GetOverlap(const cInt a1, const cInt a2, const cInt b1, const cInt b2,
- cInt& Left, cInt& Right)
-{
- if (a1 < a2)
- {
- if (b1 < b2) {Left = std::max(a1,b1); Right = std::min(a2,b2);}
- else {Left = std::max(a1,b2); Right = std::min(a2,b1);}
- }
- else
- {
- if (b1 < b2) {Left = std::max(a2,b1); Right = std::min(a1,b2);}
- else {Left = std::max(a2,b2); Right = std::min(a1,b1);}
- }
- return Left < Right;
-}
-//------------------------------------------------------------------------------
-
-inline void UpdateOutPtIdxs(OutRec& outrec)
-{
- OutPt* op = outrec.Pts;
- do
- {
- op->Idx = outrec.Idx;
- op = op->Prev;
- }
- while(op != outrec.Pts);
-}
-//------------------------------------------------------------------------------
-
-void Clipper::InsertEdgeIntoAEL(TEdge *edge, TEdge* startEdge)
-{
- if(!m_ActiveEdges)
- {
- edge->PrevInAEL = 0;
- edge->NextInAEL = 0;
- m_ActiveEdges = edge;
- }
- else if(!startEdge && E2InsertsBeforeE1(*m_ActiveEdges, *edge))
- {
- edge->PrevInAEL = 0;
- edge->NextInAEL = m_ActiveEdges;
- m_ActiveEdges->PrevInAEL = edge;
- m_ActiveEdges = edge;
- }
- else
- {
- if(!startEdge) startEdge = m_ActiveEdges;
- while(startEdge->NextInAEL &&
- !E2InsertsBeforeE1(*startEdge->NextInAEL , *edge))
- startEdge = startEdge->NextInAEL;
- edge->NextInAEL = startEdge->NextInAEL;
- if(startEdge->NextInAEL) startEdge->NextInAEL->PrevInAEL = edge;
- edge->PrevInAEL = startEdge;
- startEdge->NextInAEL = edge;
- }
-}
-//----------------------------------------------------------------------
-
-OutPt* DupOutPt(OutPt* outPt, bool InsertAfter)
-{
- OutPt* result = new OutPt;
- result->Pt = outPt->Pt;
- result->Idx = outPt->Idx;
- if (InsertAfter)
- {
- result->Next = outPt->Next;
- result->Prev = outPt;
- outPt->Next->Prev = result;
- outPt->Next = result;
- }
- else
- {
- result->Prev = outPt->Prev;
- result->Next = outPt;
- outPt->Prev->Next = result;
- outPt->Prev = result;
- }
- return result;
-}
-//------------------------------------------------------------------------------
-
-bool JoinHorz(OutPt* op1, OutPt* op1b, OutPt* op2, OutPt* op2b,
- const IntPoint Pt, bool DiscardLeft)
-{
- Direction Dir1 = (op1->Pt.X > op1b->Pt.X ? dRightToLeft : dLeftToRight);
- Direction Dir2 = (op2->Pt.X > op2b->Pt.X ? dRightToLeft : dLeftToRight);
- if (Dir1 == Dir2) return false;
-
- //When DiscardLeft, we want Op1b to be on the Left of Op1, otherwise we
- //want Op1b to be on the Right. (And likewise with Op2 and Op2b.)
- //So, to facilitate this while inserting Op1b and Op2b ...
- //when DiscardLeft, make sure we're AT or RIGHT of Pt before adding Op1b,
- //otherwise make sure we're AT or LEFT of Pt. (Likewise with Op2b.)
- if (Dir1 == dLeftToRight)
- {
- while (op1->Next->Pt.X <= Pt.X &&
- op1->Next->Pt.X >= op1->Pt.X && op1->Next->Pt.Y == Pt.Y)
- op1 = op1->Next;
- if (DiscardLeft && (op1->Pt.X != Pt.X)) op1 = op1->Next;
- op1b = DupOutPt(op1, !DiscardLeft);
- if (op1b->Pt != Pt)
- {
- op1 = op1b;
- op1->Pt = Pt;
- op1b = DupOutPt(op1, !DiscardLeft);
- }
- }
- else
- {
- while (op1->Next->Pt.X >= Pt.X &&
- op1->Next->Pt.X <= op1->Pt.X && op1->Next->Pt.Y == Pt.Y)
- op1 = op1->Next;
- if (!DiscardLeft && (op1->Pt.X != Pt.X)) op1 = op1->Next;
- op1b = DupOutPt(op1, DiscardLeft);
- if (op1b->Pt != Pt)
- {
- op1 = op1b;
- op1->Pt = Pt;
- op1b = DupOutPt(op1, DiscardLeft);
- }
- }
-
- if (Dir2 == dLeftToRight)
- {
- while (op2->Next->Pt.X <= Pt.X &&
- op2->Next->Pt.X >= op2->Pt.X && op2->Next->Pt.Y == Pt.Y)
- op2 = op2->Next;
- if (DiscardLeft && (op2->Pt.X != Pt.X)) op2 = op2->Next;
- op2b = DupOutPt(op2, !DiscardLeft);
- if (op2b->Pt != Pt)
- {
- op2 = op2b;
- op2->Pt = Pt;
- op2b = DupOutPt(op2, !DiscardLeft);
- };
- } else
- {
- while (op2->Next->Pt.X >= Pt.X &&
- op2->Next->Pt.X <= op2->Pt.X && op2->Next->Pt.Y == Pt.Y)
- op2 = op2->Next;
- if (!DiscardLeft && (op2->Pt.X != Pt.X)) op2 = op2->Next;
- op2b = DupOutPt(op2, DiscardLeft);
- if (op2b->Pt != Pt)
- {
- op2 = op2b;
- op2->Pt = Pt;
- op2b = DupOutPt(op2, DiscardLeft);
- };
- };
-
- if ((Dir1 == dLeftToRight) == DiscardLeft)
- {
- op1->Prev = op2;
- op2->Next = op1;
- op1b->Next = op2b;
- op2b->Prev = op1b;
- }
- else
- {
- op1->Next = op2;
- op2->Prev = op1;
- op1b->Prev = op2b;
- op2b->Next = op1b;
- }
- return true;
-}
-//------------------------------------------------------------------------------
-
-bool Clipper::JoinPoints(Join *j, OutRec* outRec1, OutRec* outRec2)
-{
- OutPt *op1 = j->OutPt1, *op1b;
- OutPt *op2 = j->OutPt2, *op2b;
-
- //There are 3 kinds of joins for output polygons ...
- //1. Horizontal joins where Join.OutPt1 & Join.OutPt2 are vertices anywhere
- //along (horizontal) collinear edges (& Join.OffPt is on the same horizontal).
- //2. Non-horizontal joins where Join.OutPt1 & Join.OutPt2 are at the same
- //location at the Bottom of the overlapping segment (& Join.OffPt is above).
- //3. StrictSimple joins where edges touch but are not collinear and where
- //Join.OutPt1, Join.OutPt2 & Join.OffPt all share the same point.
- bool isHorizontal = (j->OutPt1->Pt.Y == j->OffPt.Y);
-
- if (isHorizontal && (j->OffPt == j->OutPt1->Pt) &&
- (j->OffPt == j->OutPt2->Pt))
- {
- //Strictly Simple join ...
- if (outRec1 != outRec2) return false;
- op1b = j->OutPt1->Next;
- while (op1b != op1 && (op1b->Pt == j->OffPt))
- op1b = op1b->Next;
- bool reverse1 = (op1b->Pt.Y > j->OffPt.Y);
- op2b = j->OutPt2->Next;
- while (op2b != op2 && (op2b->Pt == j->OffPt))
- op2b = op2b->Next;
- bool reverse2 = (op2b->Pt.Y > j->OffPt.Y);
- if (reverse1 == reverse2) return false;
- if (reverse1)
- {
- op1b = DupOutPt(op1, false);
- op2b = DupOutPt(op2, true);
- op1->Prev = op2;
- op2->Next = op1;
- op1b->Next = op2b;
- op2b->Prev = op1b;
- j->OutPt1 = op1;
- j->OutPt2 = op1b;
- return true;
- } else
- {
- op1b = DupOutPt(op1, true);
- op2b = DupOutPt(op2, false);
- op1->Next = op2;
- op2->Prev = op1;
- op1b->Prev = op2b;
- op2b->Next = op1b;
- j->OutPt1 = op1;
- j->OutPt2 = op1b;
- return true;
- }
- }
- else if (isHorizontal)
- {
- //treat horizontal joins differently to non-horizontal joins since with
- //them we're not yet sure where the overlapping is. OutPt1.Pt & OutPt2.Pt
- //may be anywhere along the horizontal edge.
- op1b = op1;
- while (op1->Prev->Pt.Y == op1->Pt.Y && op1->Prev != op1b && op1->Prev != op2)
- op1 = op1->Prev;
- while (op1b->Next->Pt.Y == op1b->Pt.Y && op1b->Next != op1 && op1b->Next != op2)
- op1b = op1b->Next;
- if (op1b->Next == op1 || op1b->Next == op2) return false; //a flat 'polygon'
-
- op2b = op2;
- while (op2->Prev->Pt.Y == op2->Pt.Y && op2->Prev != op2b && op2->Prev != op1b)
- op2 = op2->Prev;
- while (op2b->Next->Pt.Y == op2b->Pt.Y && op2b->Next != op2 && op2b->Next != op1)
- op2b = op2b->Next;
- if (op2b->Next == op2 || op2b->Next == op1) return false; //a flat 'polygon'
-
- cInt Left, Right;
- //Op1 --> Op1b & Op2 --> Op2b are the extremites of the horizontal edges
- if (!GetOverlap(op1->Pt.X, op1b->Pt.X, op2->Pt.X, op2b->Pt.X, Left, Right))
- return false;
-
- //DiscardLeftSide: when overlapping edges are joined, a spike will created
- //which needs to be cleaned up. However, we don't want Op1 or Op2 caught up
- //on the discard Side as either may still be needed for other joins ...
- IntPoint Pt;
- bool DiscardLeftSide;
- if (op1->Pt.X >= Left && op1->Pt.X <= Right)
- {
- Pt = op1->Pt; DiscardLeftSide = (op1->Pt.X > op1b->Pt.X);
- }
- else if (op2->Pt.X >= Left&& op2->Pt.X <= Right)
- {
- Pt = op2->Pt; DiscardLeftSide = (op2->Pt.X > op2b->Pt.X);
- }
- else if (op1b->Pt.X >= Left && op1b->Pt.X <= Right)
- {
- Pt = op1b->Pt; DiscardLeftSide = op1b->Pt.X > op1->Pt.X;
- }
- else
- {
- Pt = op2b->Pt; DiscardLeftSide = (op2b->Pt.X > op2->Pt.X);
- }
- j->OutPt1 = op1; j->OutPt2 = op2;
- return JoinHorz(op1, op1b, op2, op2b, Pt, DiscardLeftSide);
- } else
- {
- //nb: For non-horizontal joins ...
- // 1. Jr.OutPt1.Pt.Y == Jr.OutPt2.Pt.Y
- // 2. Jr.OutPt1.Pt > Jr.OffPt.Y
-
- //make sure the polygons are correctly oriented ...
- op1b = op1->Next;
- while ((op1b->Pt == op1->Pt) && (op1b != op1)) op1b = op1b->Next;
- bool Reverse1 = ((op1b->Pt.Y > op1->Pt.Y) ||
- !SlopesEqual(op1->Pt, op1b->Pt, j->OffPt, m_UseFullRange));
- if (Reverse1)
- {
- op1b = op1->Prev;
- while ((op1b->Pt == op1->Pt) && (op1b != op1)) op1b = op1b->Prev;
- if ((op1b->Pt.Y > op1->Pt.Y) ||
- !SlopesEqual(op1->Pt, op1b->Pt, j->OffPt, m_UseFullRange)) return false;
- };
- op2b = op2->Next;
- while ((op2b->Pt == op2->Pt) && (op2b != op2))op2b = op2b->Next;
- bool Reverse2 = ((op2b->Pt.Y > op2->Pt.Y) ||
- !SlopesEqual(op2->Pt, op2b->Pt, j->OffPt, m_UseFullRange));
- if (Reverse2)
- {
- op2b = op2->Prev;
- while ((op2b->Pt == op2->Pt) && (op2b != op2)) op2b = op2b->Prev;
- if ((op2b->Pt.Y > op2->Pt.Y) ||
- !SlopesEqual(op2->Pt, op2b->Pt, j->OffPt, m_UseFullRange)) return false;
- }
-
- if ((op1b == op1) || (op2b == op2) || (op1b == op2b) ||
- ((outRec1 == outRec2) && (Reverse1 == Reverse2))) return false;
-
- if (Reverse1)
- {
- op1b = DupOutPt(op1, false);
- op2b = DupOutPt(op2, true);
- op1->Prev = op2;
- op2->Next = op1;
- op1b->Next = op2b;
- op2b->Prev = op1b;
- j->OutPt1 = op1;
- j->OutPt2 = op1b;
- return true;
- } else
- {
- op1b = DupOutPt(op1, true);
- op2b = DupOutPt(op2, false);
- op1->Next = op2;
- op2->Prev = op1;
- op1b->Prev = op2b;
- op2b->Next = op1b;
- j->OutPt1 = op1;
- j->OutPt2 = op1b;
- return true;
- }
- }
-}
-//----------------------------------------------------------------------
-
-static OutRec* ParseFirstLeft(OutRec* FirstLeft)
-{
- while (FirstLeft && !FirstLeft->Pts)
- FirstLeft = FirstLeft->FirstLeft;
- return FirstLeft;
-}
-//------------------------------------------------------------------------------
-
-void Clipper::FixupFirstLefts1(OutRec* OldOutRec, OutRec* NewOutRec)
-{
- //tests if NewOutRec contains the polygon before reassigning FirstLeft
- for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
- {
- OutRec* outRec = m_PolyOuts[i];
- OutRec* firstLeft = ParseFirstLeft(outRec->FirstLeft);
- if (outRec->Pts && firstLeft == OldOutRec)
- {
- if (Poly2ContainsPoly1(outRec->Pts, NewOutRec->Pts))
- outRec->FirstLeft = NewOutRec;
- }
- }
-}
-//----------------------------------------------------------------------
-
-void Clipper::FixupFirstLefts2(OutRec* InnerOutRec, OutRec* OuterOutRec)
-{
- //A polygon has split into two such that one is now the inner of the other.
- //It's possible that these polygons now wrap around other polygons, so check
- //every polygon that's also contained by OuterOutRec's FirstLeft container
- //(including 0) to see if they've become inner to the new inner polygon ...
- OutRec* orfl = OuterOutRec->FirstLeft;
- for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
- {
- OutRec* outRec = m_PolyOuts[i];
-
- if (!outRec->Pts || outRec == OuterOutRec || outRec == InnerOutRec)
- continue;
- OutRec* firstLeft = ParseFirstLeft(outRec->FirstLeft);
- if (firstLeft != orfl && firstLeft != InnerOutRec && firstLeft != OuterOutRec)
- continue;
- if (Poly2ContainsPoly1(outRec->Pts, InnerOutRec->Pts))
- outRec->FirstLeft = InnerOutRec;
- else if (Poly2ContainsPoly1(outRec->Pts, OuterOutRec->Pts))
- outRec->FirstLeft = OuterOutRec;
- else if (outRec->FirstLeft == InnerOutRec || outRec->FirstLeft == OuterOutRec)
- outRec->FirstLeft = orfl;
- }
-}
-//----------------------------------------------------------------------
-void Clipper::FixupFirstLefts3(OutRec* OldOutRec, OutRec* NewOutRec)
-{
- //reassigns FirstLeft WITHOUT testing if NewOutRec contains the polygon
- for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
- {
- OutRec* outRec = m_PolyOuts[i];
- OutRec* firstLeft = ParseFirstLeft(outRec->FirstLeft);
- if (outRec->Pts && firstLeft == OldOutRec)
- outRec->FirstLeft = NewOutRec;
- }
-}
-//----------------------------------------------------------------------
-
-void Clipper::JoinCommonEdges()
-{
- for (JoinList::size_type i = 0; i < m_Joins.size(); i++)
- {
- Join* join = m_Joins[i];
-
- OutRec *outRec1 = GetOutRec(join->OutPt1->Idx);
- OutRec *outRec2 = GetOutRec(join->OutPt2->Idx);
-
- if (!outRec1->Pts || !outRec2->Pts) continue;
- if (outRec1->IsOpen || outRec2->IsOpen) continue;
-
- //get the polygon fragment with the correct hole state (FirstLeft)
- //before calling JoinPoints() ...
- OutRec *holeStateRec;
- if (outRec1 == outRec2) holeStateRec = outRec1;
- else if (OutRec1RightOfOutRec2(outRec1, outRec2)) holeStateRec = outRec2;
- else if (OutRec1RightOfOutRec2(outRec2, outRec1)) holeStateRec = outRec1;
- else holeStateRec = GetLowermostRec(outRec1, outRec2);
-
- if (!JoinPoints(join, outRec1, outRec2)) continue;
-
- if (outRec1 == outRec2)
- {
- //instead of joining two polygons, we've just created a new one by
- //splitting one polygon into two.
- outRec1->Pts = join->OutPt1;
- outRec1->BottomPt = 0;
- outRec2 = CreateOutRec();
- outRec2->Pts = join->OutPt2;
-
- //update all OutRec2.Pts Idx's ...
- UpdateOutPtIdxs(*outRec2);
-
- if (Poly2ContainsPoly1(outRec2->Pts, outRec1->Pts))
- {
- //outRec1 contains outRec2 ...
- outRec2->IsHole = !outRec1->IsHole;
- outRec2->FirstLeft = outRec1;
-
- if (m_UsingPolyTree) FixupFirstLefts2(outRec2, outRec1);
-
- if ((outRec2->IsHole ^ m_ReverseOutput) == (Area(*outRec2) > 0))
- ReversePolyPtLinks(outRec2->Pts);
-
- } else if (Poly2ContainsPoly1(outRec1->Pts, outRec2->Pts))
- {
- //outRec2 contains outRec1 ...
- outRec2->IsHole = outRec1->IsHole;
- outRec1->IsHole = !outRec2->IsHole;
- outRec2->FirstLeft = outRec1->FirstLeft;
- outRec1->FirstLeft = outRec2;
-
- if (m_UsingPolyTree) FixupFirstLefts2(outRec1, outRec2);
-
- if ((outRec1->IsHole ^ m_ReverseOutput) == (Area(*outRec1) > 0))
- ReversePolyPtLinks(outRec1->Pts);
- }
- else
- {
- //the 2 polygons are completely separate ...
- outRec2->IsHole = outRec1->IsHole;
- outRec2->FirstLeft = outRec1->FirstLeft;
-
- //fixup FirstLeft pointers that may need reassigning to OutRec2
- if (m_UsingPolyTree) FixupFirstLefts1(outRec1, outRec2);
- }
-
- } else
- {
- //joined 2 polygons together ...
-
- outRec2->Pts = 0;
- outRec2->BottomPt = 0;
- outRec2->Idx = outRec1->Idx;
-
- outRec1->IsHole = holeStateRec->IsHole;
- if (holeStateRec == outRec2)
- outRec1->FirstLeft = outRec2->FirstLeft;
- outRec2->FirstLeft = outRec1;
-
- if (m_UsingPolyTree) FixupFirstLefts3(outRec2, outRec1);
- }
- }
-}
-
-//------------------------------------------------------------------------------
-// ClipperOffset support functions ...
-//------------------------------------------------------------------------------
-
-DoublePoint GetUnitNormal(const IntPoint &pt1, const IntPoint &pt2)
-{
- if(pt2.X == pt1.X && pt2.Y == pt1.Y)
- return DoublePoint(0, 0);
-
- double Dx = (double)(pt2.X - pt1.X);
- double dy = (double)(pt2.Y - pt1.Y);
- double f = 1 *1.0/ std::sqrt( Dx*Dx + dy*dy );
- Dx *= f;
- dy *= f;
- return DoublePoint(dy, -Dx);
-}
-
-//------------------------------------------------------------------------------
-// ClipperOffset class
-//------------------------------------------------------------------------------
-
-ClipperOffset::ClipperOffset(double miterLimit, double arcTolerance)
-{
- this->MiterLimit = miterLimit;
- this->ArcTolerance = arcTolerance;
- m_lowest.X = -1;
-}
-//------------------------------------------------------------------------------
-
-ClipperOffset::~ClipperOffset()
-{
- Clear();
-}
-//------------------------------------------------------------------------------
-
-void ClipperOffset::Clear()
-{
- for (int i = 0; i < m_polyNodes.ChildCount(); ++i)
- delete m_polyNodes.Childs[i];
- m_polyNodes.Childs.clear();
- m_lowest.X = -1;
-}
-//------------------------------------------------------------------------------
-
-void ClipperOffset::AddPath(const Path& path, JoinType joinType, EndType endType)
-{
- int highI = (int)path.size() - 1;
- if (highI < 0) return;
- PolyNode* newNode = new PolyNode();
- newNode->m_jointype = joinType;
- newNode->m_endtype = endType;
-
- //strip duplicate points from path and also get index to the lowest point ...
- if (endType == etClosedLine || endType == etClosedPolygon)
- while (highI > 0 && path[0] == path[highI]) highI--;
- newNode->Contour.reserve(highI + 1);
- newNode->Contour.push_back(path[0]);
- int j = 0, k = 0;
- for (int i = 1; i <= highI; i++)
- if (newNode->Contour[j] != path[i])
- {
- j++;
- newNode->Contour.push_back(path[i]);
- if (path[i].Y > newNode->Contour[k].Y ||
- (path[i].Y == newNode->Contour[k].Y &&
- path[i].X < newNode->Contour[k].X)) k = j;
- }
- if (endType == etClosedPolygon && j < 2)
- {
- delete newNode;
- return;
- }
- m_polyNodes.AddChild(*newNode);
-
- //if this path's lowest pt is lower than all the others then update m_lowest
- if (endType != etClosedPolygon) return;
- if (m_lowest.X < 0)
- m_lowest = IntPoint(m_polyNodes.ChildCount() - 1, k);
- else
- {
- IntPoint ip = m_polyNodes.Childs[(int)m_lowest.X]->Contour[(int)m_lowest.Y];
- if (newNode->Contour[k].Y > ip.Y ||
- (newNode->Contour[k].Y == ip.Y &&
- newNode->Contour[k].X < ip.X))
- m_lowest = IntPoint(m_polyNodes.ChildCount() - 1, k);
- }
-}
-//------------------------------------------------------------------------------
-
-void ClipperOffset::AddPaths(const Paths& paths, JoinType joinType, EndType endType)
-{
- for (Paths::size_type i = 0; i < paths.size(); ++i)
- AddPath(paths[i], joinType, endType);
-}
-//------------------------------------------------------------------------------
-
-void ClipperOffset::FixOrientations()
-{
- //fixup orientations of all closed paths if the orientation of the
- //closed path with the lowermost vertex is wrong ...
- if (m_lowest.X >= 0 &&
- !Orientation(m_polyNodes.Childs[(int)m_lowest.X]->Contour))
- {
- for (int i = 0; i < m_polyNodes.ChildCount(); ++i)
- {
- PolyNode& node = *m_polyNodes.Childs[i];
- if (node.m_endtype == etClosedPolygon ||
- (node.m_endtype == etClosedLine && Orientation(node.Contour)))
- ReversePath(node.Contour);
- }
- } else
- {
- for (int i = 0; i < m_polyNodes.ChildCount(); ++i)
- {
- PolyNode& node = *m_polyNodes.Childs[i];
- if (node.m_endtype == etClosedLine && !Orientation(node.Contour))
- ReversePath(node.Contour);
- }
- }
-}
-//------------------------------------------------------------------------------
-
-void ClipperOffset::Execute(Paths& solution, double delta)
-{
- solution.clear();
- FixOrientations();
- DoOffset(delta);
-
- //now clean up 'corners' ...
- Clipper clpr;
- clpr.AddPaths(m_destPolys, ptSubject, true);
- if (delta > 0)
- {
- clpr.Execute(ctUnion, solution, pftPositive, pftPositive);
- }
- else
- {
- IntRect r = clpr.GetBounds();
- Path outer(4);
- outer[0] = IntPoint(r.left - 10, r.bottom + 10);
- outer[1] = IntPoint(r.right + 10, r.bottom + 10);
- outer[2] = IntPoint(r.right + 10, r.top - 10);
- outer[3] = IntPoint(r.left - 10, r.top - 10);
-
- clpr.AddPath(outer, ptSubject, true);
- clpr.ReverseSolution(true);
- clpr.Execute(ctUnion, solution, pftNegative, pftNegative);
- if (solution.size() > 0) solution.erase(solution.begin());
- }
-}
-//------------------------------------------------------------------------------
-
-void ClipperOffset::Execute(PolyTree& solution, double delta)
-{
- solution.Clear();
- FixOrientations();
- DoOffset(delta);
-
- //now clean up 'corners' ...
- Clipper clpr;
- clpr.AddPaths(m_destPolys, ptSubject, true);
- if (delta > 0)
- {
- clpr.Execute(ctUnion, solution, pftPositive, pftPositive);
- }
- else
- {
- IntRect r = clpr.GetBounds();
- Path outer(4);
- outer[0] = IntPoint(r.left - 10, r.bottom + 10);
- outer[1] = IntPoint(r.right + 10, r.bottom + 10);
- outer[2] = IntPoint(r.right + 10, r.top - 10);
- outer[3] = IntPoint(r.left - 10, r.top - 10);
-
- clpr.AddPath(outer, ptSubject, true);
- clpr.ReverseSolution(true);
- clpr.Execute(ctUnion, solution, pftNegative, pftNegative);
- //remove the outer PolyNode rectangle ...
- if (solution.ChildCount() == 1 && solution.Childs[0]->ChildCount() > 0)
- {
- PolyNode* outerNode = solution.Childs[0];
- solution.Childs.reserve(outerNode->ChildCount());
- solution.Childs[0] = outerNode->Childs[0];
- solution.Childs[0]->Parent = outerNode->Parent;
- for (int i = 1; i < outerNode->ChildCount(); ++i)
- solution.AddChild(*outerNode->Childs[i]);
- }
- else
- solution.Clear();
- }
-}
-//------------------------------------------------------------------------------
-
-void ClipperOffset::DoOffset(double delta)
-{
- m_destPolys.clear();
- m_delta = delta;
-
- //if Zero offset, just copy any CLOSED polygons to m_p and return ...
- if (NEAR_ZERO(delta))
- {
- m_destPolys.reserve(m_polyNodes.ChildCount());
- for (int i = 0; i < m_polyNodes.ChildCount(); i++)
- {
- PolyNode& node = *m_polyNodes.Childs[i];
- if (node.m_endtype == etClosedPolygon)
- m_destPolys.push_back(node.Contour);
- }
- return;
- }
-
- //see offset_triginometry3.svg in the documentation folder ...
- if (MiterLimit > 2) m_miterLim = 2/(MiterLimit * MiterLimit);
- else m_miterLim = 0.5;
-
- double y;
- if (ArcTolerance <= 0.0) y = def_arc_tolerance;
- else if (ArcTolerance > std::fabs(delta) * def_arc_tolerance)
- y = std::fabs(delta) * def_arc_tolerance;
- else y = ArcTolerance;
- //see offset_triginometry2.svg in the documentation folder ...
- double steps = pi / std::acos(1 - y / std::fabs(delta));
- if (steps > std::fabs(delta) * pi)
- steps = std::fabs(delta) * pi; //ie excessive precision check
- m_sin = std::sin(two_pi / steps);
- m_cos = std::cos(two_pi / steps);
- m_StepsPerRad = steps / two_pi;
- if (delta < 0.0) m_sin = -m_sin;
-
- m_destPolys.reserve(m_polyNodes.ChildCount() * 2);
- for (int i = 0; i < m_polyNodes.ChildCount(); i++)
- {
- PolyNode& node = *m_polyNodes.Childs[i];
- m_srcPoly = node.Contour;
-
- int len = (int)m_srcPoly.size();
- if (len == 0 || (delta <= 0 && (len < 3 || node.m_endtype != etClosedPolygon)))
- continue;
-
- m_destPoly.clear();
- if (len == 1)
- {
- if (node.m_jointype == jtRound)
- {
- double X = 1.0, Y = 0.0;
- for (cInt j = 1; j <= steps; j++)
- {
- m_destPoly.push_back(IntPoint(
- Round(m_srcPoly[0].X + X * delta),
- Round(m_srcPoly[0].Y + Y * delta)));
- double X2 = X;
- X = X * m_cos - m_sin * Y;
- Y = X2 * m_sin + Y * m_cos;
- }
- }
- else
- {
- double X = -1.0, Y = -1.0;
- for (int j = 0; j < 4; ++j)
- {
- m_destPoly.push_back(IntPoint(
- Round(m_srcPoly[0].X + X * delta),
- Round(m_srcPoly[0].Y + Y * delta)));
- if (X < 0) X = 1;
- else if (Y < 0) Y = 1;
- else X = -1;
- }
- }
- m_destPolys.push_back(m_destPoly);
- continue;
- }
- //build m_normals ...
- m_normals.clear();
- m_normals.reserve(len);
- for (int j = 0; j < len - 1; ++j)
- m_normals.push_back(GetUnitNormal(m_srcPoly[j], m_srcPoly[j + 1]));
- if (node.m_endtype == etClosedLine || node.m_endtype == etClosedPolygon)
- m_normals.push_back(GetUnitNormal(m_srcPoly[len - 1], m_srcPoly[0]));
- else
- m_normals.push_back(DoublePoint(m_normals[len - 2]));
-
- if (node.m_endtype == etClosedPolygon)
- {
- int k = len - 1;
- for (int j = 0; j < len; ++j)
- OffsetPoint(j, k, node.m_jointype);
- m_destPolys.push_back(m_destPoly);
- }
- else if (node.m_endtype == etClosedLine)
- {
- int k = len - 1;
- for (int j = 0; j < len; ++j)
- OffsetPoint(j, k, node.m_jointype);
- m_destPolys.push_back(m_destPoly);
- m_destPoly.clear();
- //re-build m_normals ...
- DoublePoint n = m_normals[len -1];
- for (int j = len - 1; j > 0; j--)
- m_normals[j] = DoublePoint(-m_normals[j - 1].X, -m_normals[j - 1].Y);
- m_normals[0] = DoublePoint(-n.X, -n.Y);
- k = 0;
- for (int j = len - 1; j >= 0; j--)
- OffsetPoint(j, k, node.m_jointype);
- m_destPolys.push_back(m_destPoly);
- }
- else
- {
- int k = 0;
- for (int j = 1; j < len - 1; ++j)
- OffsetPoint(j, k, node.m_jointype);
-
- IntPoint pt1;
- if (node.m_endtype == etOpenButt)
- {
- int j = len - 1;
- pt1 = IntPoint((cInt)Round(m_srcPoly[j].X + m_normals[j].X *
- delta), (cInt)Round(m_srcPoly[j].Y + m_normals[j].Y * delta));
- m_destPoly.push_back(pt1);
- pt1 = IntPoint((cInt)Round(m_srcPoly[j].X - m_normals[j].X *
- delta), (cInt)Round(m_srcPoly[j].Y - m_normals[j].Y * delta));
- m_destPoly.push_back(pt1);
- }
- else
- {
- int j = len - 1;
- k = len - 2;
- m_sinA = 0;
- m_normals[j] = DoublePoint(-m_normals[j].X, -m_normals[j].Y);
- if (node.m_endtype == etOpenSquare)
- DoSquare(j, k);
- else
- DoRound(j, k);
- }
-
- //re-build m_normals ...
- for (int j = len - 1; j > 0; j--)
- m_normals[j] = DoublePoint(-m_normals[j - 1].X, -m_normals[j - 1].Y);
- m_normals[0] = DoublePoint(-m_normals[1].X, -m_normals[1].Y);
-
- k = len - 1;
- for (int j = k - 1; j > 0; --j) OffsetPoint(j, k, node.m_jointype);
-
- if (node.m_endtype == etOpenButt)
- {
- pt1 = IntPoint((cInt)Round(m_srcPoly[0].X - m_normals[0].X * delta),
- (cInt)Round(m_srcPoly[0].Y - m_normals[0].Y * delta));
- m_destPoly.push_back(pt1);
- pt1 = IntPoint((cInt)Round(m_srcPoly[0].X + m_normals[0].X * delta),
- (cInt)Round(m_srcPoly[0].Y + m_normals[0].Y * delta));
- m_destPoly.push_back(pt1);
- }
- else
- {
- k = 1;
- m_sinA = 0;
- if (node.m_endtype == etOpenSquare)
- DoSquare(0, 1);
- else
- DoRound(0, 1);
- }
- m_destPolys.push_back(m_destPoly);
- }
- }
-}
-//------------------------------------------------------------------------------
-
-void ClipperOffset::OffsetPoint(int j, int& k, JoinType jointype)
-{
- //cross product ...
- m_sinA = (m_normals[k].X * m_normals[j].Y - m_normals[j].X * m_normals[k].Y);
- if (std::fabs(m_sinA * m_delta) < 1.0)
- {
- //dot product ...
- double cosA = (m_normals[k].X * m_normals[j].X + m_normals[j].Y * m_normals[k].Y );
- if (cosA > 0) // angle => 0 degrees
- {
- m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + m_normals[k].X * m_delta),
- Round(m_srcPoly[j].Y + m_normals[k].Y * m_delta)));
- return;
- }
- //else angle => 180 degrees
- }
- else if (m_sinA > 1.0) m_sinA = 1.0;
- else if (m_sinA < -1.0) m_sinA = -1.0;
-
- if (m_sinA * m_delta < 0)
- {
- m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + m_normals[k].X * m_delta),
- Round(m_srcPoly[j].Y + m_normals[k].Y * m_delta)));
- m_destPoly.push_back(m_srcPoly[j]);
- m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + m_normals[j].X * m_delta),
- Round(m_srcPoly[j].Y + m_normals[j].Y * m_delta)));
- }
- else
- switch (jointype)
- {
- case jtMiter:
- {
- double r = 1 + (m_normals[j].X * m_normals[k].X +
- m_normals[j].Y * m_normals[k].Y);
- if (r >= m_miterLim) DoMiter(j, k, r); else DoSquare(j, k);
- break;
- }
- case jtSquare: DoSquare(j, k); break;
- case jtRound: DoRound(j, k); break;
- }
- k = j;
-}
-//------------------------------------------------------------------------------
-
-void ClipperOffset::DoSquare(int j, int k)
-{
- double dx = std::tan(std::atan2(m_sinA,
- m_normals[k].X * m_normals[j].X + m_normals[k].Y * m_normals[j].Y) / 4);
- m_destPoly.push_back(IntPoint(
- Round(m_srcPoly[j].X + m_delta * (m_normals[k].X - m_normals[k].Y * dx)),
- Round(m_srcPoly[j].Y + m_delta * (m_normals[k].Y + m_normals[k].X * dx))));
- m_destPoly.push_back(IntPoint(
- Round(m_srcPoly[j].X + m_delta * (m_normals[j].X + m_normals[j].Y * dx)),
- Round(m_srcPoly[j].Y + m_delta * (m_normals[j].Y - m_normals[j].X * dx))));
-}
-//------------------------------------------------------------------------------
-
-void ClipperOffset::DoMiter(int j, int k, double r)
-{
- double q = m_delta / r;
- m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + (m_normals[k].X + m_normals[j].X) * q),
- Round(m_srcPoly[j].Y + (m_normals[k].Y + m_normals[j].Y) * q)));
-}
-//------------------------------------------------------------------------------
-
-void ClipperOffset::DoRound(int j, int k)
-{
- double a = std::atan2(m_sinA,
- m_normals[k].X * m_normals[j].X + m_normals[k].Y * m_normals[j].Y);
- int steps = std::max((int)Round(m_StepsPerRad * std::fabs(a)), 1);
-
- double X = m_normals[k].X, Y = m_normals[k].Y, X2;
- for (int i = 0; i < steps; ++i)
- {
- m_destPoly.push_back(IntPoint(
- Round(m_srcPoly[j].X + X * m_delta),
- Round(m_srcPoly[j].Y + Y * m_delta)));
- X2 = X;
- X = X * m_cos - m_sin * Y;
- Y = X2 * m_sin + Y * m_cos;
- }
- m_destPoly.push_back(IntPoint(
- Round(m_srcPoly[j].X + m_normals[j].X * m_delta),
- Round(m_srcPoly[j].Y + m_normals[j].Y * m_delta)));
-}
-
-//------------------------------------------------------------------------------
-// Miscellaneous public functions
-//------------------------------------------------------------------------------
-
-void Clipper::DoSimplePolygons()
-{
- PolyOutList::size_type i = 0;
- while (i < m_PolyOuts.size())
- {
- OutRec* outrec = m_PolyOuts[i++];
- OutPt* op = outrec->Pts;
- if (!op || outrec->IsOpen) continue;
- do //for each Pt in Polygon until duplicate found do ...
- {
- OutPt* op2 = op->Next;
- while (op2 != outrec->Pts)
- {
- if ((op->Pt == op2->Pt) && op2->Next != op && op2->Prev != op)
- {
- //split the polygon into two ...
- OutPt* op3 = op->Prev;
- OutPt* op4 = op2->Prev;
- op->Prev = op4;
- op4->Next = op;
- op2->Prev = op3;
- op3->Next = op2;
-
- outrec->Pts = op;
- OutRec* outrec2 = CreateOutRec();
- outrec2->Pts = op2;
- UpdateOutPtIdxs(*outrec2);
- if (Poly2ContainsPoly1(outrec2->Pts, outrec->Pts))
- {
- //OutRec2 is contained by OutRec1 ...
- outrec2->IsHole = !outrec->IsHole;
- outrec2->FirstLeft = outrec;
- if (m_UsingPolyTree) FixupFirstLefts2(outrec2, outrec);
- }
- else
- if (Poly2ContainsPoly1(outrec->Pts, outrec2->Pts))
- {
- //OutRec1 is contained by OutRec2 ...
- outrec2->IsHole = outrec->IsHole;
- outrec->IsHole = !outrec2->IsHole;
- outrec2->FirstLeft = outrec->FirstLeft;
- outrec->FirstLeft = outrec2;
- if (m_UsingPolyTree) FixupFirstLefts2(outrec, outrec2);
- }
- else
- {
- //the 2 polygons are separate ...
- outrec2->IsHole = outrec->IsHole;
- outrec2->FirstLeft = outrec->FirstLeft;
- if (m_UsingPolyTree) FixupFirstLefts1(outrec, outrec2);
- }
- op2 = op; //ie get ready for the Next iteration
- }
- op2 = op2->Next;
- }
- op = op->Next;
- }
- while (op != outrec->Pts);
- }
-}
-//------------------------------------------------------------------------------
-
-void ReversePath(Path& p)
-{
- std::reverse(p.begin(), p.end());
-}
-//------------------------------------------------------------------------------
-
-void ReversePaths(Paths& p)
-{
- for (Paths::size_type i = 0; i < p.size(); ++i)
- ReversePath(p[i]);
-}
-//------------------------------------------------------------------------------
-
-void SimplifyPolygon(const Path &in_poly, Paths &out_polys, PolyFillType fillType)
-{
- Clipper c;
- c.StrictlySimple(true);
- c.AddPath(in_poly, ptSubject, true);
- c.Execute(ctUnion, out_polys, fillType, fillType);
-}
-//------------------------------------------------------------------------------
-
-void SimplifyPolygons(const Paths &in_polys, Paths &out_polys, PolyFillType fillType)
-{
- Clipper c;
- c.StrictlySimple(true);
- c.AddPaths(in_polys, ptSubject, true);
- c.Execute(ctUnion, out_polys, fillType, fillType);
-}
-//------------------------------------------------------------------------------
-
-void SimplifyPolygons(Paths &polys, PolyFillType fillType)
-{
- SimplifyPolygons(polys, polys, fillType);
-}
-//------------------------------------------------------------------------------
-
-inline double DistanceSqrd(const IntPoint& pt1, const IntPoint& pt2)
-{
- double Dx = ((double)pt1.X - pt2.X);
- double dy = ((double)pt1.Y - pt2.Y);
- return (Dx*Dx + dy*dy);
-}
-//------------------------------------------------------------------------------
-
-double DistanceFromLineSqrd(
- const IntPoint& pt, const IntPoint& ln1, const IntPoint& ln2)
-{
- //The equation of a line in general form (Ax + By + C = 0)
- //given 2 points (x�,y�) & (x�,y�) is ...
- //(y� - y�)x + (x� - x�)y + (y� - y�)x� - (x� - x�)y� = 0
- //A = (y� - y�); B = (x� - x�); C = (y� - y�)x� - (x� - x�)y�
- //perpendicular distance of point (x�,y�) = (Ax� + By� + C)/Sqrt(A� + B�)
- //see http://en.wikipedia.org/wiki/Perpendicular_distance
- double A = double(ln1.Y - ln2.Y);
- double B = double(ln2.X - ln1.X);
- double C = A * ln1.X + B * ln1.Y;
- C = A * pt.X + B * pt.Y - C;
- return (C * C) / (A * A + B * B);
-}
-//---------------------------------------------------------------------------
-
-bool SlopesNearCollinear(const IntPoint& pt1,
- const IntPoint& pt2, const IntPoint& pt3, double distSqrd)
-{
- //this function is more accurate when the point that's geometrically
- //between the other 2 points is the one that's tested for distance.
- //ie makes it more likely to pick up 'spikes' ...
- if (Abs(pt1.X - pt2.X) > Abs(pt1.Y - pt2.Y))
- {
- if ((pt1.X > pt2.X) == (pt1.X < pt3.X))
- return DistanceFromLineSqrd(pt1, pt2, pt3) < distSqrd;
- else if ((pt2.X > pt1.X) == (pt2.X < pt3.X))
- return DistanceFromLineSqrd(pt2, pt1, pt3) < distSqrd;
- else
- return DistanceFromLineSqrd(pt3, pt1, pt2) < distSqrd;
- }
- else
- {
- if ((pt1.Y > pt2.Y) == (pt1.Y < pt3.Y))
- return DistanceFromLineSqrd(pt1, pt2, pt3) < distSqrd;
- else if ((pt2.Y > pt1.Y) == (pt2.Y < pt3.Y))
- return DistanceFromLineSqrd(pt2, pt1, pt3) < distSqrd;
- else
- return DistanceFromLineSqrd(pt3, pt1, pt2) < distSqrd;
- }
-}
-//------------------------------------------------------------------------------
-
-bool PointsAreClose(IntPoint pt1, IntPoint pt2, double distSqrd)
-{
- double Dx = (double)pt1.X - pt2.X;
- double dy = (double)pt1.Y - pt2.Y;
- return ((Dx * Dx) + (dy * dy) <= distSqrd);
-}
-//------------------------------------------------------------------------------
-
-OutPt* ExcludeOp(OutPt* op)
-{
- OutPt* result = op->Prev;
- result->Next = op->Next;
- op->Next->Prev = result;
- result->Idx = 0;
- return result;
-}
-//------------------------------------------------------------------------------
-
-void CleanPolygon(const Path& in_poly, Path& out_poly, double distance)
-{
- //distance = proximity in units/pixels below which vertices
- //will be stripped. Default ~= sqrt(2).
-
- size_t size = in_poly.size();
-
- if (size == 0)
- {
- out_poly.clear();
- return;
- }
-
- OutPt* outPts = new OutPt[size];
- for (size_t i = 0; i < size; ++i)
- {
- outPts[i].Pt = in_poly[i];
- outPts[i].Next = &outPts[(i + 1) % size];
- outPts[i].Next->Prev = &outPts[i];
- outPts[i].Idx = 0;
- }
-
- double distSqrd = distance * distance;
- OutPt* op = &outPts[0];
- while (op->Idx == 0 && op->Next != op->Prev)
- {
- if (PointsAreClose(op->Pt, op->Prev->Pt, distSqrd))
- {
- op = ExcludeOp(op);
- size--;
- }
- else if (PointsAreClose(op->Prev->Pt, op->Next->Pt, distSqrd))
- {
- ExcludeOp(op->Next);
- op = ExcludeOp(op);
- size -= 2;
- }
- else if (SlopesNearCollinear(op->Prev->Pt, op->Pt, op->Next->Pt, distSqrd))
- {
- op = ExcludeOp(op);
- size--;
- }
- else
- {
- op->Idx = 1;
- op = op->Next;
- }
- }
-
- if (size < 3) size = 0;
- out_poly.resize(size);
- for (size_t i = 0; i < size; ++i)
- {
- out_poly[i] = op->Pt;
- op = op->Next;
- }
- delete [] outPts;
-}
-//------------------------------------------------------------------------------
-
-void CleanPolygon(Path& poly, double distance)
-{
- CleanPolygon(poly, poly, distance);
-}
-//------------------------------------------------------------------------------
-
-void CleanPolygons(const Paths& in_polys, Paths& out_polys, double distance)
-{
- out_polys.resize(in_polys.size());
- for (Paths::size_type i = 0; i < in_polys.size(); ++i)
- CleanPolygon(in_polys[i], out_polys[i], distance);
-}
-//------------------------------------------------------------------------------
-
-void CleanPolygons(Paths& polys, double distance)
-{
- CleanPolygons(polys, polys, distance);
-}
-//------------------------------------------------------------------------------
-
-void Minkowski(const Path& poly, const Path& path,
- Paths& solution, bool isSum, bool isClosed)
-{
- int delta = (isClosed ? 1 : 0);
- size_t polyCnt = poly.size();
- size_t pathCnt = path.size();
- Paths pp;
- pp.reserve(pathCnt);
- if (isSum)
- for (size_t i = 0; i < pathCnt; ++i)
- {
- Path p;
- p.reserve(polyCnt);
- for (size_t j = 0; j < poly.size(); ++j)
- p.push_back(IntPoint(path[i].X + poly[j].X, path[i].Y + poly[j].Y));
- pp.push_back(p);
- }
- else
- for (size_t i = 0; i < pathCnt; ++i)
- {
- Path p;
- p.reserve(polyCnt);
- for (size_t j = 0; j < poly.size(); ++j)
- p.push_back(IntPoint(path[i].X - poly[j].X, path[i].Y - poly[j].Y));
- pp.push_back(p);
- }
-
- solution.clear();
- solution.reserve((pathCnt + delta) * (polyCnt + 1));
- for (size_t i = 0; i < pathCnt - 1 + delta; ++i)
- for (size_t j = 0; j < polyCnt; ++j)
- {
- Path quad;
- quad.reserve(4);
- quad.push_back(pp[i % pathCnt][j % polyCnt]);
- quad.push_back(pp[(i + 1) % pathCnt][j % polyCnt]);
- quad.push_back(pp[(i + 1) % pathCnt][(j + 1) % polyCnt]);
- quad.push_back(pp[i % pathCnt][(j + 1) % polyCnt]);
- if (!Orientation(quad)) ReversePath(quad);
- solution.push_back(quad);
- }
-}
-//------------------------------------------------------------------------------
-
-void MinkowskiSum(const Path& pattern, const Path& path, Paths& solution, bool pathIsClosed)
-{
- Minkowski(pattern, path, solution, true, pathIsClosed);
- Clipper c;
- c.AddPaths(solution, ptSubject, true);
- c.Execute(ctUnion, solution, pftNonZero, pftNonZero);
-}
-//------------------------------------------------------------------------------
-
-void TranslatePath(const Path& input, Path& output, const IntPoint delta)
-{
- //precondition: input != output
- output.resize(input.size());
- for (size_t i = 0; i < input.size(); ++i)
- output[i] = IntPoint(input[i].X + delta.X, input[i].Y + delta.Y);
-}
-//------------------------------------------------------------------------------
-
-void MinkowskiSum(const Path& pattern, const Paths& paths, Paths& solution, bool pathIsClosed)
-{
- Clipper c;
- for (size_t i = 0; i < paths.size(); ++i)
- {
- Paths tmp;
- Minkowski(pattern, paths[i], tmp, true, pathIsClosed);
- c.AddPaths(tmp, ptSubject, true);
- if (pathIsClosed)
- {
- Path tmp2;
- TranslatePath(paths[i], tmp2, pattern[0]);
- c.AddPath(tmp2, ptClip, true);
- }
- }
- c.Execute(ctUnion, solution, pftNonZero, pftNonZero);
-}
-//------------------------------------------------------------------------------
-
-void MinkowskiDiff(const Path& poly1, const Path& poly2, Paths& solution)
-{
- Minkowski(poly1, poly2, solution, false, true);
- Clipper c;
- c.AddPaths(solution, ptSubject, true);
- c.Execute(ctUnion, solution, pftNonZero, pftNonZero);
-}
-//------------------------------------------------------------------------------
-
-enum NodeType {ntAny, ntOpen, ntClosed};
-
-void AddPolyNodeToPaths(const PolyNode& polynode, NodeType nodetype, Paths& paths)
-{
- bool match = true;
- if (nodetype == ntClosed) match = !polynode.IsOpen();
- else if (nodetype == ntOpen) return;
-
- if (!polynode.Contour.empty() && match)
- paths.push_back(polynode.Contour);
- for (int i = 0; i < polynode.ChildCount(); ++i)
- AddPolyNodeToPaths(*polynode.Childs[i], nodetype, paths);
-}
-//------------------------------------------------------------------------------
-
-void PolyTreeToPaths(const PolyTree& polytree, Paths& paths)
-{
- paths.resize(0);
- paths.reserve(polytree.Total());
- AddPolyNodeToPaths(polytree, ntAny, paths);
-}
-//------------------------------------------------------------------------------
-
-void ClosedPathsFromPolyTree(const PolyTree& polytree, Paths& paths)
-{
- paths.resize(0);
- paths.reserve(polytree.Total());
- AddPolyNodeToPaths(polytree, ntClosed, paths);
-}
-//------------------------------------------------------------------------------
-
-void OpenPathsFromPolyTree(PolyTree& polytree, Paths& paths)
-{
- paths.resize(0);
- paths.reserve(polytree.Total());
- //Open paths are top level only, so ...
- for (int i = 0; i < polytree.ChildCount(); ++i)
- if (polytree.Childs[i]->IsOpen())
- paths.push_back(polytree.Childs[i]->Contour);
-}
-//------------------------------------------------------------------------------
-
-std::ostream& operator <<(std::ostream &s, const IntPoint &p)
-{
- s << "(" << p.X << "," << p.Y << ")";
- return s;
-}
-//------------------------------------------------------------------------------
-
-std::ostream& operator <<(std::ostream &s, const Path &p)
-{
- if (p.empty()) return s;
- Path::size_type last = p.size() -1;
- for (Path::size_type i = 0; i < last; i++)
- s << "(" << p[i].X << "," << p[i].Y << "), ";
- s << "(" << p[last].X << "," << p[last].Y << ")\n";
- return s;
-}
-//------------------------------------------------------------------------------
-
-std::ostream& operator <<(std::ostream &s, const Paths &p)
-{
- for (Paths::size_type i = 0; i < p.size(); i++)
- s << p[i];
- s << "\n";
- return s;
-}
-//------------------------------------------------------------------------------
-
-} //ClipperLib namespace
diff --git a/libs/clipper/clipper.hpp b/libs/clipper/clipper.hpp
deleted file mode 100644
index df1f8137d..000000000
--- a/libs/clipper/clipper.hpp
+++ /dev/null
@@ -1,406 +0,0 @@
-/*******************************************************************************
-* *
-* Author : Angus Johnson *
-* Version : 6.4.2 *
-* Date : 27 February 2017 *
-* Website : http://www.angusj.com *
-* Copyright : Angus Johnson 2010-2017 *
-* *
-* License: *
-* Use, modification & distribution is subject to Boost Software License Ver 1. *
-* http://www.boost.org/LICENSE_1_0.txt *
-* *
-* Attributions: *
-* The code in this library is an extension of Bala Vatti's clipping algorithm: *
-* "A generic solution to polygon clipping" *
-* Communications of the ACM, Vol 35, Issue 7 (July 1992) pp 56-63. *
-* http://portal.acm.org/citation.cfm?id=129906 *
-* *
-* Computer graphics and geometric modeling: implementation and algorithms *
-* By Max K. Agoston *
-* Springer; 1 edition (January 4, 2005) *
-* http://books.google.com/books?q=vatti+clipping+agoston *
-* *
-* See also: *
-* "Polygon Offsetting by Computing Winding Numbers" *
-* Paper no. DETC2005-85513 pp. 565-575 *
-* ASME 2005 International Design Engineering Technical Conferences *
-* and Computers and Information in Engineering Conference (IDETC/CIE2005) *
-* September 24-28, 2005 , Long Beach, California, USA *
-* http://www.me.berkeley.edu/~mcmains/pubs/DAC05OffsetPolygon.pdf *
-* *
-*******************************************************************************/
-
-#ifndef clipper_hpp
-#define clipper_hpp
-
-#define CLIPPER_VERSION "6.4.2"
-
-//use_int32: When enabled 32bit ints are used instead of 64bit ints. This
-//improve performance but coordinate values are limited to the range +/- 46340
-//#define use_int32
-
-//use_xyz: adds a Z member to IntPoint. Adds a minor cost to perfomance.
-//#define use_xyz
-
-//use_lines: Enables line clipping. Adds a very minor cost to performance.
-#define use_lines
-
-//use_deprecated: Enables temporary support for the obsolete functions
-//#define use_deprecated
-
-#include <vector>
-#include <list>
-#include <set>
-#include <stdexcept>
-#include <cstring>
-#include <cstdlib>
-#include <ostream>
-#include <functional>
-#include <queue>
-
-namespace ClipperLib {
-
-enum ClipType { ctIntersection, ctUnion, ctDifference, ctXor };
-enum PolyType { ptSubject, ptClip };
-//By far the most widely used winding rules for polygon filling are
-//EvenOdd & NonZero (GDI, GDI+, XLib, OpenGL, Cairo, AGG, Quartz, SVG, Gr32)
-//Others rules include Positive, Negative and ABS_GTR_EQ_TWO (only in OpenGL)
-//see http://glprogramming.com/red/chapter11.html
-enum PolyFillType { pftEvenOdd, pftNonZero, pftPositive, pftNegative };
-
-#ifdef use_int32
- typedef int cInt;
- static cInt const loRange = 0x7FFF;
- static cInt const hiRange = 0x7FFF;
-#else
- typedef signed long long cInt;
- static cInt const loRange = 0x3FFFFFFF;
- static cInt const hiRange = 0x3FFFFFFFFFFFFFFFLL;
- typedef signed long long long64; //used by Int128 class
- typedef unsigned long long ulong64;
-
-#endif
-
-struct IntPoint {
- cInt X;
- cInt Y;
-#ifdef use_xyz
- cInt Z;
- IntPoint(cInt x = 0, cInt y = 0, cInt z = 0): X(x), Y(y), Z(z) {};
-#else
- IntPoint(cInt x = 0, cInt y = 0): X(x), Y(y) {};
-#endif
-
- friend inline bool operator== (const IntPoint& a, const IntPoint& b)
- {
- return a.X == b.X && a.Y == b.Y;
- }
- friend inline bool operator!= (const IntPoint& a, const IntPoint& b)
- {
- return a.X != b.X || a.Y != b.Y;
- }
-};
-//------------------------------------------------------------------------------
-
-typedef std::vector< IntPoint > Path;
-typedef std::vector< Path > Paths;
-
-inline Path& operator <<(Path& poly, const IntPoint& p) {poly.push_back(p); return poly;}
-inline Paths& operator <<(Paths& polys, const Path& p) {polys.push_back(p); return polys;}
-
-std::ostream& operator <<(std::ostream &s, const IntPoint &p);
-std::ostream& operator <<(std::ostream &s, const Path &p);
-std::ostream& operator <<(std::ostream &s, const Paths &p);
-
-struct DoublePoint
-{
- double X;
- double Y;
- DoublePoint(double x = 0, double y = 0) : X(x), Y(y) {}
- DoublePoint(IntPoint ip) : X((double)ip.X), Y((double)ip.Y) {}
-};
-//------------------------------------------------------------------------------
-
-#ifdef use_xyz
-typedef void (*ZFillCallback)(IntPoint& e1bot, IntPoint& e1top, IntPoint& e2bot, IntPoint& e2top, IntPoint& pt);
-#endif
-
-enum InitOptions {ioReverseSolution = 1, ioStrictlySimple = 2, ioPreserveCollinear = 4};
-enum JoinType {jtSquare, jtRound, jtMiter};
-enum EndType {etClosedPolygon, etClosedLine, etOpenButt, etOpenSquare, etOpenRound};
-
-class PolyNode;
-typedef std::vector< PolyNode* > PolyNodes;
-
-class PolyNode
-{
-public:
- PolyNode();
- virtual ~PolyNode(){};
- Path Contour;
- PolyNodes Childs;
- PolyNode* Parent;
- PolyNode* GetNext() const;
- bool IsHole() const;
- bool IsOpen() const;
- int ChildCount() const;
-private:
- //PolyNode& operator =(PolyNode& other);
- unsigned Index; //node index in Parent.Childs
- bool m_IsOpen;
- JoinType m_jointype;
- EndType m_endtype;
- PolyNode* GetNextSiblingUp() const;
- void AddChild(PolyNode& child);
- friend class Clipper; //to access Index
- friend class ClipperOffset;
-};
-
-class PolyTree: public PolyNode
-{
-public:
- ~PolyTree(){ Clear(); };
- PolyNode* GetFirst() const;
- void Clear();
- int Total() const;
-private:
- //PolyTree& operator =(PolyTree& other);
- PolyNodes AllNodes;
- friend class Clipper; //to access AllNodes
-};
-
-bool Orientation(const Path &poly);
-double Area(const Path &poly);
-int PointInPolygon(const IntPoint &pt, const Path &path);
-
-void SimplifyPolygon(const Path &in_poly, Paths &out_polys, PolyFillType fillType = pftEvenOdd);
-void SimplifyPolygons(const Paths &in_polys, Paths &out_polys, PolyFillType fillType = pftEvenOdd);
-void SimplifyPolygons(Paths &polys, PolyFillType fillType = pftEvenOdd);
-
-void CleanPolygon(const Path& in_poly, Path& out_poly, double distance = 1.415);
-void CleanPolygon(Path& poly, double distance = 1.415);
-void CleanPolygons(const Paths& in_polys, Paths& out_polys, double distance = 1.415);
-void CleanPolygons(Paths& polys, double distance = 1.415);
-
-void MinkowskiSum(const Path& pattern, const Path& path, Paths& solution, bool pathIsClosed);
-void MinkowskiSum(const Path& pattern, const Paths& paths, Paths& solution, bool pathIsClosed);
-void MinkowskiDiff(const Path& poly1, const Path& poly2, Paths& solution);
-
-void PolyTreeToPaths(const PolyTree& polytree, Paths& paths);
-void ClosedPathsFromPolyTree(const PolyTree& polytree, Paths& paths);
-void OpenPathsFromPolyTree(PolyTree& polytree, Paths& paths);
-
-void ReversePath(Path& p);
-void ReversePaths(Paths& p);
-
-struct IntRect { cInt left; cInt top; cInt right; cInt bottom; };
-
-//enums that are used internally ...
-enum EdgeSide { esLeft = 1, esRight = 2};
-
-//forward declarations (for stuff used internally) ...
-struct TEdge;
-struct IntersectNode;
-struct LocalMinimum;
-struct OutPt;
-struct OutRec;
-struct Join;
-
-typedef std::vector < OutRec* > PolyOutList;
-typedef std::vector < TEdge* > EdgeList;
-typedef std::vector < Join* > JoinList;
-typedef std::vector < IntersectNode* > IntersectList;
-
-//------------------------------------------------------------------------------
-
-//ClipperBase is the ancestor to the Clipper class. It should not be
-//instantiated directly. This class simply abstracts the conversion of sets of
-//polygon coordinates into edge objects that are stored in a LocalMinima list.
-class ClipperBase
-{
-public:
- ClipperBase();
- virtual ~ClipperBase();
- virtual bool AddPath(const Path &pg, PolyType PolyTyp, bool Closed);
- bool AddPaths(const Paths &ppg, PolyType PolyTyp, bool Closed);
- virtual void Clear();
- IntRect GetBounds();
- bool PreserveCollinear() {return m_PreserveCollinear;};
- void PreserveCollinear(bool value) {m_PreserveCollinear = value;};
-protected:
- void DisposeLocalMinimaList();
- TEdge* AddBoundsToLML(TEdge *e, bool IsClosed);
- virtual void Reset();
- TEdge* ProcessBound(TEdge* E, bool IsClockwise);
- void InsertScanbeam(const cInt Y);
- bool PopScanbeam(cInt &Y);
- bool LocalMinimaPending();
- bool PopLocalMinima(cInt Y, const LocalMinimum *&locMin);
- OutRec* CreateOutRec();
- void DisposeAllOutRecs();
- void DisposeOutRec(PolyOutList::size_type index);
- void SwapPositionsInAEL(TEdge *edge1, TEdge *edge2);
- void DeleteFromAEL(TEdge *e);
- void UpdateEdgeIntoAEL(TEdge *&e);
-
- typedef std::vector<LocalMinimum> MinimaList;
- MinimaList::iterator m_CurrentLM;
- MinimaList m_MinimaList;
-
- bool m_UseFullRange;
- EdgeList m_edges;
- bool m_PreserveCollinear;
- bool m_HasOpenPaths;
- PolyOutList m_PolyOuts;
- TEdge *m_ActiveEdges;
-
- typedef std::priority_queue<cInt> ScanbeamList;
- ScanbeamList m_Scanbeam;
-};
-//------------------------------------------------------------------------------
-
-class Clipper : public virtual ClipperBase
-{
-public:
- Clipper(int initOptions = 0);
- bool Execute(ClipType clipType,
- Paths &solution,
- PolyFillType fillType = pftEvenOdd);
- bool Execute(ClipType clipType,
- Paths &solution,
- PolyFillType subjFillType,
- PolyFillType clipFillType);
- bool Execute(ClipType clipType,
- PolyTree &polytree,
- PolyFillType fillType = pftEvenOdd);
- bool Execute(ClipType clipType,
- PolyTree &polytree,
- PolyFillType subjFillType,
- PolyFillType clipFillType);
- bool ReverseSolution() { return m_ReverseOutput; };
- void ReverseSolution(bool value) {m_ReverseOutput = value;};
- bool StrictlySimple() {return m_StrictSimple;};
- void StrictlySimple(bool value) {m_StrictSimple = value;};
- //set the callback function for z value filling on intersections (otherwise Z is 0)
-#ifdef use_xyz
- void ZFillFunction(ZFillCallback zFillFunc);
-#endif
-protected:
- virtual bool ExecuteInternal();
-private:
- JoinList m_Joins;
- JoinList m_GhostJoins;
- IntersectList m_IntersectList;
- ClipType m_ClipType;
- typedef std::list<cInt> MaximaList;
- MaximaList m_Maxima;
- TEdge *m_SortedEdges;
- bool m_ExecuteLocked;
- PolyFillType m_ClipFillType;
- PolyFillType m_SubjFillType;
- bool m_ReverseOutput;
- bool m_UsingPolyTree;
- bool m_StrictSimple;
-#ifdef use_xyz
- ZFillCallback m_ZFill; //custom callback
-#endif
- void SetWindingCount(TEdge& edge);
- bool IsEvenOddFillType(const TEdge& edge) const;
- bool IsEvenOddAltFillType(const TEdge& edge) const;
- void InsertLocalMinimaIntoAEL(const cInt botY);
- void InsertEdgeIntoAEL(TEdge *edge, TEdge* startEdge);
- void AddEdgeToSEL(TEdge *edge);
- bool PopEdgeFromSEL(TEdge *&edge);
- void CopyAELToSEL();
- void DeleteFromSEL(TEdge *e);
- void SwapPositionsInSEL(TEdge *edge1, TEdge *edge2);
- bool IsContributing(const TEdge& edge) const;
- bool IsTopHorz(const cInt XPos);
- void DoMaxima(TEdge *e);
- void ProcessHorizontals();
- void ProcessHorizontal(TEdge *horzEdge);
- void AddLocalMaxPoly(TEdge *e1, TEdge *e2, const IntPoint &pt);
- OutPt* AddLocalMinPoly(TEdge *e1, TEdge *e2, const IntPoint &pt);
- OutRec* GetOutRec(int idx);
- void AppendPolygon(TEdge *e1, TEdge *e2);
- void IntersectEdges(TEdge *e1, TEdge *e2, IntPoint &pt);
- OutPt* AddOutPt(TEdge *e, const IntPoint &pt);
- OutPt* GetLastOutPt(TEdge *e);
- bool ProcessIntersections(const cInt topY);
- void BuildIntersectList(const cInt topY);
- void ProcessIntersectList();
- void ProcessEdgesAtTopOfScanbeam(const cInt topY);
- void BuildResult(Paths& polys);
- void BuildResult2(PolyTree& polytree);
- void SetHoleState(TEdge *e, OutRec *outrec);
- void DisposeIntersectNodes();
- bool FixupIntersectionOrder();
- void FixupOutPolygon(OutRec &outrec);
- void FixupOutPolyline(OutRec &outrec);
- bool IsHole(TEdge *e);
- bool FindOwnerFromSplitRecs(OutRec &outRec, OutRec *&currOrfl);
- void FixHoleLinkage(OutRec &outrec);
- void AddJoin(OutPt *op1, OutPt *op2, const IntPoint offPt);
- void ClearJoins();
- void ClearGhostJoins();
- void AddGhostJoin(OutPt *op, const IntPoint offPt);
- bool JoinPoints(Join *j, OutRec* outRec1, OutRec* outRec2);
- void JoinCommonEdges();
- void DoSimplePolygons();
- void FixupFirstLefts1(OutRec* OldOutRec, OutRec* NewOutRec);
- void FixupFirstLefts2(OutRec* InnerOutRec, OutRec* OuterOutRec);
- void FixupFirstLefts3(OutRec* OldOutRec, OutRec* NewOutRec);
-#ifdef use_xyz
- void SetZ(IntPoint& pt, TEdge& e1, TEdge& e2);
-#endif
-};
-//------------------------------------------------------------------------------
-
-class ClipperOffset
-{
-public:
- ClipperOffset(double miterLimit = 2.0, double roundPrecision = 0.25);
- ~ClipperOffset();
- void AddPath(const Path& path, JoinType joinType, EndType endType);
- void AddPaths(const Paths& paths, JoinType joinType, EndType endType);
- void Execute(Paths& solution, double delta);
- void Execute(PolyTree& solution, double delta);
- void Clear();
- double MiterLimit;
- double ArcTolerance;
-private:
- Paths m_destPolys;
- Path m_srcPoly;
- Path m_destPoly;
- std::vector<DoublePoint> m_normals;
- double m_delta, m_sinA, m_sin, m_cos;
- double m_miterLim, m_StepsPerRad;
- IntPoint m_lowest;
- PolyNode m_polyNodes;
-
- void FixOrientations();
- void DoOffset(double delta);
- void OffsetPoint(int j, int& k, JoinType jointype);
- void DoSquare(int j, int k);
- void DoMiter(int j, int k, double r);
- void DoRound(int j, int k);
-};
-//------------------------------------------------------------------------------
-
-class clipperException : public std::exception
-{
- public:
- clipperException(const char* description): m_descr(description) {}
- virtual ~clipperException() throw() {}
- virtual const char* what() const throw() {return m_descr.c_str();}
- private:
- std::string m_descr;
-};
-//------------------------------------------------------------------------------
-
-} //ClipperLib namespace
-
-#endif //clipper_hpp
-
-
diff --git a/libs/rapidjson/allocators.h b/libs/rapidjson/allocators.h
deleted file mode 100644
index d68b74c11..000000000
--- a/libs/rapidjson/allocators.h
+++ /dev/null
@@ -1,249 +0,0 @@
-// Tencent is pleased to support the open source community by making RapidJSON available.
-//
-// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
-//
-// Licensed under the MIT License (the "License"); you may not use this file except
-// in compliance with the License. You may obtain a copy of the License at
-//
-// http://opensource.org/licenses/MIT
-//
-// Unless required by applicable law or agreed to in writing, software distributed
-// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
-// CONDITIONS OF ANY KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations under the License.
-
-#ifndef RAPIDJSON_ALLOCATORS_H_
-#define RAPIDJSON_ALLOCATORS_H_
-
-#include "rapidjson.h"
-
-RAPIDJSON_NAMESPACE_BEGIN
-
-///////////////////////////////////////////////////////////////////////////////
-// Allocator
-
-/*! \class rapidjson::Allocator
- \brief Concept for allocating, resizing and freeing memory block.
-
- Note that Malloc() and Realloc() are non-static but Free() is static.
-
- So if an allocator need to support Free(), it needs to put its pointer in
- the header of memory block.
-
-\code
-concept Allocator {
- static const bool kNeedFree; //!< Whether this allocator needs to call Free().
-
- // Allocate a memory block.
- // \param size of the memory block in bytes.
- // \returns pointer to the memory block.
- void* Malloc(size_t size);
-
- // Resize a memory block.
- // \param originalPtr The pointer to current memory block. Null pointer is permitted.
- // \param originalSize The current size in bytes. (Design issue: since some allocator may not book-keep this, explicitly pass to it can save memory.)
- // \param newSize the new size in bytes.
- void* Realloc(void* originalPtr, size_t originalSize, size_t newSize);
-
- // Free a memory block.
- // \param pointer to the memory block. Null pointer is permitted.
- static void Free(void *ptr);
-};
-\endcode
-*/
-
-///////////////////////////////////////////////////////////////////////////////
-// CrtAllocator
-
-//! C-runtime library allocator.
-/*! This class is just wrapper for standard C library memory routines.
- \note implements Allocator concept
-*/
-class CrtAllocator {
-public:
- static const bool kNeedFree = true;
- void* Malloc(size_t size) {
- if (size) // behavior of malloc(0) is implementation defined.
- return std::malloc(size);
- else
- return NULL; // standardize to returning NULL.
- }
- void* Realloc(void* originalPtr, size_t originalSize, size_t newSize) { (void)originalSize; return std::realloc(originalPtr, newSize); }
- static void Free(void *ptr) { std::free(ptr); }
-};
-
-///////////////////////////////////////////////////////////////////////////////
-// MemoryPoolAllocator
-
-//! Default memory allocator used by the parser and DOM.
-/*! This allocator allocate memory blocks from pre-allocated memory chunks.
-
- It does not free memory blocks. And Realloc() only allocate new memory.
-
- The memory chunks are allocated by BaseAllocator, which is CrtAllocator by default.
-
- User may also supply a buffer as the first chunk.
-
- If the user-buffer is full then additional chunks are allocated by BaseAllocator.
-
- The user-buffer is not deallocated by this allocator.
-
- \tparam BaseAllocator the allocator type for allocating memory chunks. Default is CrtAllocator.
- \note implements Allocator concept
-*/
-template <typename BaseAllocator = CrtAllocator>
-class MemoryPoolAllocator {
-public:
- static const bool kNeedFree = false; //!< Tell users that no need to call Free() with this allocator. (concept Allocator)
-
- //! Constructor with chunkSize.
- /*! \param chunkSize The size of memory chunk. The default is kDefaultChunkSize.
- \param baseAllocator The allocator for allocating memory chunks.
- */
- MemoryPoolAllocator(size_t chunkSize = kDefaultChunkCapacity, BaseAllocator* baseAllocator = 0) :
- chunkHead_(0), chunk_capacity_(chunkSize), userBuffer_(0), baseAllocator_(baseAllocator), ownBaseAllocator_(0)
- {
- }
-
- //! Constructor with user-supplied buffer.
- /*! The user buffer will be used firstly. When it is full, memory pool allocates new chunk with chunk size.
-
- The user buffer will not be deallocated when this allocator is destructed.
-
- \param buffer User supplied buffer.
- \param size Size of the buffer in bytes. It must at least larger than sizeof(ChunkHeader).
- \param chunkSize The size of memory chunk. The default is kDefaultChunkSize.
- \param baseAllocator The allocator for allocating memory chunks.
- */
- MemoryPoolAllocator(void *buffer, size_t size, size_t chunkSize = kDefaultChunkCapacity, BaseAllocator* baseAllocator = 0) :
- chunkHead_(0), chunk_capacity_(chunkSize), userBuffer_(buffer), baseAllocator_(baseAllocator), ownBaseAllocator_(0)
- {
- RAPIDJSON_ASSERT(buffer != 0);
- RAPIDJSON_ASSERT(size > sizeof(ChunkHeader));
- chunkHead_ = reinterpret_cast<ChunkHeader*>(buffer);
- chunkHead_->capacity = size - sizeof(ChunkHeader);
- chunkHead_->size = 0;
- chunkHead_->next = 0;
- }
-
- //! Destructor.
- /*! This deallocates all memory chunks, excluding the user-supplied buffer.
- */
- ~MemoryPoolAllocator() {
- Clear();
- RAPIDJSON_DELETE(ownBaseAllocator_);
- }
-
- //! Deallocates all memory chunks, excluding the user-supplied buffer.
- void Clear() {
- while(chunkHead_ != 0 && chunkHead_ != userBuffer_) {
- ChunkHeader* next = chunkHead_->next;
- baseAllocator_->Free(chunkHead_);
- chunkHead_ = next;
- }
- }
-
- //! Computes the total capacity of allocated memory chunks.
- /*! \return total capacity in bytes.
- */
- size_t Capacity() const {
- size_t capacity = 0;
- for (ChunkHeader* c = chunkHead_; c != 0; c = c->next)
- capacity += c->capacity;
- return capacity;
- }
-
- //! Computes the memory blocks allocated.
- /*! \return total used bytes.
- */
- size_t Size() const {
- size_t size = 0;
- for (ChunkHeader* c = chunkHead_; c != 0; c = c->next)
- size += c->size;
- return size;
- }
-
- //! Allocates a memory block. (concept Allocator)
- void* Malloc(size_t size) {
- if (!size)
- return NULL;
-
- size = RAPIDJSON_ALIGN(size);
- if (chunkHead_ == 0 || chunkHead_->size + size > chunkHead_->capacity)
- AddChunk(chunk_capacity_ > size ? chunk_capacity_ : size);
-
- void *buffer = reinterpret_cast<char *>(chunkHead_ + 1) + chunkHead_->size;
- chunkHead_->size += size;
- return buffer;
- }
-
- //! Resizes a memory block (concept Allocator)
- void* Realloc(void* originalPtr, size_t originalSize, size_t newSize) {
- if (originalPtr == 0)
- return Malloc(newSize);
-
- // Do not shrink if new size is smaller than original
- if (originalSize >= newSize)
- return originalPtr;
-
- // Simply expand it if it is the last allocation and there is sufficient space
- if (originalPtr == (char *)(chunkHead_ + 1) + chunkHead_->size - originalSize) {
- size_t increment = static_cast<size_t>(newSize - originalSize);
- increment = RAPIDJSON_ALIGN(increment);
- if (chunkHead_->size + increment <= chunkHead_->capacity) {
- chunkHead_->size += increment;
- return originalPtr;
- }
- }
-
- // Realloc process: allocate and copy memory, do not free original buffer.
- void* newBuffer = Malloc(newSize);
- RAPIDJSON_ASSERT(newBuffer != 0); // Do not handle out-of-memory explicitly.
- if (originalSize)
- std::memcpy(newBuffer, originalPtr, originalSize);
- return newBuffer;
- }
-
- //! Frees a memory block (concept Allocator)
- static void Free(void *ptr) { (void)ptr; } // Do nothing
-
-private:
- //! Copy constructor is not permitted.
- MemoryPoolAllocator(const MemoryPoolAllocator& rhs) /* = delete */;
- //! Copy assignment operator is not permitted.
- MemoryPoolAllocator& operator=(const MemoryPoolAllocator& rhs) /* = delete */;
-
- //! Creates a new chunk.
- /*! \param capacity Capacity of the chunk in bytes.
- */
- void AddChunk(size_t capacity) {
- if (!baseAllocator_)
- ownBaseAllocator_ = baseAllocator_ = RAPIDJSON_NEW(BaseAllocator());
- ChunkHeader* chunk = reinterpret_cast<ChunkHeader*>(baseAllocator_->Malloc(sizeof(ChunkHeader) + capacity));
- chunk->capacity = capacity;
- chunk->size = 0;
- chunk->next = chunkHead_;
- chunkHead_ = chunk;
- }
-
- static const int kDefaultChunkCapacity = 64 * 1024; //!< Default chunk capacity.
-
- //! Chunk header for perpending to each chunk.
- /*! Chunks are stored as a singly linked list.
- */
- struct ChunkHeader {
- size_t capacity; //!< Capacity of the chunk in bytes (excluding the header itself).
- size_t size; //!< Current size of allocated memory in bytes.
- ChunkHeader *next; //!< Next chunk in the linked list.
- };
-
- ChunkHeader *chunkHead_; //!< Head of the chunk linked-list. Only the head chunk serves allocation.
- size_t chunk_capacity_; //!< The minimum capacity of chunk when they are allocated.
- void *userBuffer_; //!< User supplied buffer.
- BaseAllocator* baseAllocator_; //!< base allocator for allocating memory chunks.
- BaseAllocator* ownBaseAllocator_; //!< base allocator created by this object.
-};
-
-RAPIDJSON_NAMESPACE_END
-
-#endif // RAPIDJSON_ENCODINGS_H_
diff --git a/libs/rapidjson/document.h b/libs/rapidjson/document.h
deleted file mode 100644
index 8573f6b21..000000000
--- a/libs/rapidjson/document.h
+++ /dev/null
@@ -1,1965 +0,0 @@
-// Tencent is pleased to support the open source community by making RapidJSON available.
-//
-// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
-//
-// Licensed under the MIT License (the "License"); you may not use this file except
-// in compliance with the License. You may obtain a copy of the License at
-//
-// http://opensource.org/licenses/MIT
-//
-// Unless required by applicable law or agreed to in writing, software distributed
-// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
-// CONDITIONS OF ANY KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations under the License.
-
-#ifndef RAPIDJSON_DOCUMENT_H_
-#define RAPIDJSON_DOCUMENT_H_
-
-/*! \file document.h */
-
-#include "reader.h"
-#include "internal/meta.h"
-#include "internal/strfunc.h"
-#include <new> // placement new
-
-#ifdef _MSC_VER
-RAPIDJSON_DIAG_PUSH
-RAPIDJSON_DIAG_OFF(4127) // conditional expression is constant
-#elif defined(__GNUC__)
-RAPIDJSON_DIAG_PUSH
-RAPIDJSON_DIAG_OFF(effc++)
-#endif
-
-///////////////////////////////////////////////////////////////////////////////
-// RAPIDJSON_HAS_STDSTRING
-
-#ifndef RAPIDJSON_HAS_STDSTRING
-#ifdef RAPIDJSON_DOXYGEN_RUNNING
-#define RAPIDJSON_HAS_STDSTRING 1 // force generation of documentation
-#else
-#define RAPIDJSON_HAS_STDSTRING 0 // no std::string support by default
-#endif
-/*! \def RAPIDJSON_HAS_STDSTRING
- \ingroup RAPIDJSON_CONFIG
- \brief Enable RapidJSON support for \c std::string
-
- By defining this preprocessor symbol to \c 1, several convenience functions for using
- \ref rapidjson::GenericValue with \c std::string are enabled, especially
- for construction and comparison.
-
- \hideinitializer
-*/
-#endif // !defined(RAPIDJSON_HAS_STDSTRING)
-
-#if RAPIDJSON_HAS_STDSTRING
-#include <string>
-#endif // RAPIDJSON_HAS_STDSTRING
-
-#ifndef RAPIDJSON_NOMEMBERITERATORCLASS
-#include <iterator> // std::iterator, std::random_access_iterator_tag
-#endif
-
-#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
-#include <utility> // std::move
-#endif
-
-RAPIDJSON_NAMESPACE_BEGIN
-
-// Forward declaration.
-template <typename Encoding, typename Allocator>
-class GenericValue;
-
-//! Name-value pair in a JSON object value.
-/*!
- This class was internal to GenericValue. It used to be a inner struct.
- But a compiler (IBM XL C/C++ for AIX) have reported to have problem with that so it moved as a namespace scope struct.
- https://code.google.com/p/rapidjson/issues/detail?id=64
-*/
-template <typename Encoding, typename Allocator>
-struct GenericMember {
- GenericValue<Encoding, Allocator> name; //!< name of member (must be a string)
- GenericValue<Encoding, Allocator> value; //!< value of member.
-};
-
-///////////////////////////////////////////////////////////////////////////////
-// GenericMemberIterator
-
-#ifndef RAPIDJSON_NOMEMBERITERATORCLASS
-
-//! (Constant) member iterator for a JSON object value
-/*!
- \tparam Const Is this a constant iterator?
- \tparam Encoding Encoding of the value. (Even non-string values need to have the same encoding in a document)
- \tparam Allocator Allocator type for allocating memory of object, array and string.
-
- This class implements a Random Access Iterator for GenericMember elements
- of a GenericValue, see ISO/IEC 14882:2003(E) C++ standard, 24.1 [lib.iterator.requirements].
-
- \note This iterator implementation is mainly intended to avoid implicit
- conversions from iterator values to \c NULL,
- e.g. from GenericValue::FindMember.
-
- \note Define \c RAPIDJSON_NOMEMBERITERATORCLASS to fall back to a
- pointer-based implementation, if your platform doesn't provide
- the C++ <iterator> header.
-
- \see GenericMember, GenericValue::MemberIterator, GenericValue::ConstMemberIterator
- */
-template <bool Const, typename Encoding, typename Allocator>
-class GenericMemberIterator
- : public std::iterator<std::random_access_iterator_tag
- , typename internal::MaybeAddConst<Const,GenericMember<Encoding,Allocator> >::Type> {
-
- friend class GenericValue<Encoding,Allocator>;
- template <bool, typename, typename> friend class GenericMemberIterator;
-
- typedef GenericMember<Encoding,Allocator> PlainType;
- typedef typename internal::MaybeAddConst<Const,PlainType>::Type ValueType;
- typedef std::iterator<std::random_access_iterator_tag,ValueType> BaseType;
-
-public:
- //! Iterator type itself
- typedef GenericMemberIterator Iterator;
- //! Constant iterator type
- typedef GenericMemberIterator<true,Encoding,Allocator> ConstIterator;
- //! Non-constant iterator type
- typedef GenericMemberIterator<false,Encoding,Allocator> NonConstIterator;
-
- //! Pointer to (const) GenericMember
- typedef typename BaseType::pointer Pointer;
- //! Reference to (const) GenericMember
- typedef typename BaseType::reference Reference;
- //! Signed integer type (e.g. \c ptrdiff_t)
- typedef typename BaseType::difference_type DifferenceType;
-
- //! Default constructor (singular value)
- /*! Creates an iterator pointing to no element.
- \note All operations, except for comparisons, are undefined on such values.
- */
- GenericMemberIterator() : ptr_() {}
-
- //! Iterator conversions to more const
- /*!
- \param it (Non-const) iterator to copy from
-
- Allows the creation of an iterator from another GenericMemberIterator
- that is "less const". Especially, creating a non-constant iterator
- from a constant iterator are disabled:
- \li const -> non-const (not ok)
- \li const -> const (ok)
- \li non-const -> const (ok)
- \li non-const -> non-const (ok)
-
- \note If the \c Const template parameter is already \c false, this
- constructor effectively defines a regular copy-constructor.
- Otherwise, the copy constructor is implicitly defined.
- */
- GenericMemberIterator(const NonConstIterator & it) : ptr_(it.ptr_) {}
-
- //! @name stepping
- //@{
- Iterator& operator++(){ ++ptr_; return *this; }
- Iterator& operator--(){ --ptr_; return *this; }
- Iterator operator++(int){ Iterator old(*this); ++ptr_; return old; }
- Iterator operator--(int){ Iterator old(*this); --ptr_; return old; }
- //@}
-
- //! @name increment/decrement
- //@{
- Iterator operator+(DifferenceType n) const { return Iterator(ptr_+n); }
- Iterator operator-(DifferenceType n) const { return Iterator(ptr_-n); }
-
- Iterator& operator+=(DifferenceType n) { ptr_+=n; return *this; }
- Iterator& operator-=(DifferenceType n) { ptr_-=n; return *this; }
- //@}
-
- //! @name relations
- //@{
- bool operator==(ConstIterator that) const { return ptr_ == that.ptr_; }
- bool operator!=(ConstIterator that) const { return ptr_ != that.ptr_; }
- bool operator<=(ConstIterator that) const { return ptr_ <= that.ptr_; }
- bool operator>=(ConstIterator that) const { return ptr_ >= that.ptr_; }
- bool operator< (ConstIterator that) const { return ptr_ < that.ptr_; }
- bool operator> (ConstIterator that) const { return ptr_ > that.ptr_; }
- //@}
-
- //! @name dereference
- //@{
- Reference operator*() const { return *ptr_; }
- Pointer operator->() const { return ptr_; }
- Reference operator[](DifferenceType n) const { return ptr_[n]; }
- //@}
-
- //! Distance
- DifferenceType operator-(ConstIterator that) const { return ptr_-that.ptr_; }
-
-private:
- //! Internal constructor from plain pointer
- explicit GenericMemberIterator(Pointer p) : ptr_(p) {}
-
- Pointer ptr_; //!< raw pointer
-};
-
-#else // RAPIDJSON_NOMEMBERITERATORCLASS
-
-// class-based member iterator implementation disabled, use plain pointers
-
-template <bool Const, typename Encoding, typename Allocator>
-struct GenericMemberIterator;
-
-//! non-const GenericMemberIterator
-template <typename Encoding, typename Allocator>
-struct GenericMemberIterator<false,Encoding,Allocator> {
- //! use plain pointer as iterator type
- typedef GenericMember<Encoding,Allocator>* Iterator;
-};
-//! const GenericMemberIterator
-template <typename Encoding, typename Allocator>
-struct GenericMemberIterator<true,Encoding,Allocator> {
- //! use plain const pointer as iterator type
- typedef const GenericMember<Encoding,Allocator>* Iterator;
-};
-
-#endif // RAPIDJSON_NOMEMBERITERATORCLASS
-
-///////////////////////////////////////////////////////////////////////////////
-// GenericStringRef
-
-//! Reference to a constant string (not taking a copy)
-/*!
- \tparam CharType character type of the string
-
- This helper class is used to automatically infer constant string
- references for string literals, especially from \c const \b (!)
- character arrays.
-
- The main use is for creating JSON string values without copying the
- source string via an \ref Allocator. This requires that the referenced
- string pointers have a sufficient lifetime, which exceeds the lifetime
- of the associated GenericValue.
-
- \b Example
- \code
- Value v("foo"); // ok, no need to copy & calculate length
- const char foo[] = "foo";
- v.SetString(foo); // ok
-
- const char* bar = foo;
- // Value x(bar); // not ok, can't rely on bar's lifetime
- Value x(StringRef(bar)); // lifetime explicitly guaranteed by user
- Value y(StringRef(bar, 3)); // ok, explicitly pass length
- \endcode
-
- \see StringRef, GenericValue::SetString
-*/
-template<typename CharType>
-struct GenericStringRef {
- typedef CharType Ch; //!< character type of the string
-
- //! Create string reference from \c const character array
- /*!
- This constructor implicitly creates a constant string reference from
- a \c const character array. It has better performance than
- \ref StringRef(const CharType*) by inferring the string \ref length
- from the array length, and also supports strings containing null
- characters.
-
- \tparam N length of the string, automatically inferred
-
- \param str Constant character array, lifetime assumed to be longer
- than the use of the string in e.g. a GenericValue
-
- \post \ref s == str
-
- \note Constant complexity.
- \note There is a hidden, private overload to disallow references to
- non-const character arrays to be created via this constructor.
- By this, e.g. function-scope arrays used to be filled via
- \c snprintf are excluded from consideration.
- In such cases, the referenced string should be \b copied to the
- GenericValue instead.
- */
- template<SizeType N>
- GenericStringRef(const CharType (&str)[N]) RAPIDJSON_NOEXCEPT
- : s(str), length(N-1) {}
-
- //! Explicitly create string reference from \c const character pointer
- /*!
- This constructor can be used to \b explicitly create a reference to
- a constant string pointer.
-
- \see StringRef(const CharType*)
-
- \param str Constant character pointer, lifetime assumed to be longer
- than the use of the string in e.g. a GenericValue
-
- \post \ref s == str
-
- \note There is a hidden, private overload to disallow references to
- non-const character arrays to be created via this constructor.
- By this, e.g. function-scope arrays used to be filled via
- \c snprintf are excluded from consideration.
- In such cases, the referenced string should be \b copied to the
- GenericValue instead.
- */
- explicit GenericStringRef(const CharType* str)
- : s(str), length(internal::StrLen(str)){ RAPIDJSON_ASSERT(s != NULL); }
-
- //! Create constant string reference from pointer and length
- /*! \param str constant string, lifetime assumed to be longer than the use of the string in e.g. a GenericValue
- \param len length of the string, excluding the trailing NULL terminator
-
- \post \ref s == str && \ref length == len
- \note Constant complexity.
- */
- GenericStringRef(const CharType* str, SizeType len)
- : s(str), length(len) { RAPIDJSON_ASSERT(s != NULL); }
-
- GenericStringRef(const GenericStringRef& original) = default;
-
- //! implicit conversion to plain CharType pointer
- operator const Ch *() const { return s; }
-
- const Ch* const s; //!< plain CharType pointer
- const SizeType length; //!< length of the string (excluding the trailing NULL terminator)
-
-private:
- //! Disallow copy-assignment
- GenericStringRef operator=(const GenericStringRef&);
- //! Disallow construction from non-const array
- template<SizeType N>
- GenericStringRef(CharType (&str)[N]) /* = delete */;
-};
-
-//! Mark a character pointer as constant string
-/*! Mark a plain character pointer as a "string literal". This function
- can be used to avoid copying a character string to be referenced as a
- value in a JSON GenericValue object, if the string's lifetime is known
- to be valid long enough.
- \tparam CharType Character type of the string
- \param str Constant string, lifetime assumed to be longer than the use of the string in e.g. a GenericValue
- \return GenericStringRef string reference object
- \relatesalso GenericStringRef
-
- \see GenericValue::GenericValue(StringRefType), GenericValue::operator=(StringRefType), GenericValue::SetString(StringRefType), GenericValue::PushBack(StringRefType, Allocator&), GenericValue::AddMember
-*/
-template<typename CharType>
-inline GenericStringRef<CharType> StringRef(const CharType* str) {
- return GenericStringRef<CharType>(str, internal::StrLen(str));
-}
-
-//! Mark a character pointer as constant string
-/*! Mark a plain character pointer as a "string literal". This function
- can be used to avoid copying a character string to be referenced as a
- value in a JSON GenericValue object, if the string's lifetime is known
- to be valid long enough.
-
- This version has better performance with supplied length, and also
- supports string containing null characters.
-
- \tparam CharType character type of the string
- \param str Constant string, lifetime assumed to be longer than the use of the string in e.g. a GenericValue
- \param length The length of source string.
- \return GenericStringRef string reference object
- \relatesalso GenericStringRef
-*/
-template<typename CharType>
-inline GenericStringRef<CharType> StringRef(const CharType* str, size_t length) {
- return GenericStringRef<CharType>(str, SizeType(length));
-}
-
-#if RAPIDJSON_HAS_STDSTRING
-//! Mark a string object as constant string
-/*! Mark a string object (e.g. \c std::string) as a "string literal".
- This function can be used to avoid copying a string to be referenced as a
- value in a JSON GenericValue object, if the string's lifetime is known
- to be valid long enough.
-
- \tparam CharType character type of the string
- \param str Constant string, lifetime assumed to be longer than the use of the string in e.g. a GenericValue
- \return GenericStringRef string reference object
- \relatesalso GenericStringRef
- \note Requires the definition of the preprocessor symbol \ref RAPIDJSON_HAS_STDSTRING.
-*/
-template<typename CharType>
-inline GenericStringRef<CharType> StringRef(const std::basic_string<CharType>& str) {
- return GenericStringRef<CharType>(str.data(), SizeType(str.size()));
-}
-#endif
-
-///////////////////////////////////////////////////////////////////////////////
-// GenericValue type traits
-namespace internal {
-
-template <typename T, typename Encoding = void, typename Allocator = void>
-struct IsGenericValueImpl : FalseType {};
-
-// select candidates according to nested encoding and allocator types
-template <typename T> struct IsGenericValueImpl<T, typename Void<typename T::EncodingType>::Type, typename Void<typename T::AllocatorType>::Type>
- : IsBaseOf<GenericValue<typename T::EncodingType, typename T::AllocatorType>, T>::Type {};
-
-// helper to match arbitrary GenericValue instantiations, including derived classes
-template <typename T> struct IsGenericValue : IsGenericValueImpl<T>::Type {};
-
-} // namespace internal
-
-///////////////////////////////////////////////////////////////////////////////
-// GenericValue
-
-//! Represents a JSON value. Use Value for UTF8 encoding and default allocator.
-/*!
- A JSON value can be one of 7 types. This class is a variant type supporting
- these types.
-
- Use the Value if UTF8 and default allocator
-
- \tparam Encoding Encoding of the value. (Even non-string values need to have the same encoding in a document)
- \tparam Allocator Allocator type for allocating memory of object, array and string.
-*/
-template <typename Encoding, typename Allocator = MemoryPoolAllocator<> >
-class GenericValue {
-public:
- //! Name-value pair in an object.
- typedef GenericMember<Encoding, Allocator> Member;
- typedef Encoding EncodingType; //!< Encoding type from template parameter.
- typedef Allocator AllocatorType; //!< Allocator type from template parameter.
- typedef typename Encoding::Ch Ch; //!< Character type derived from Encoding.
- typedef GenericStringRef<Ch> StringRefType; //!< Reference to a constant string
- typedef typename GenericMemberIterator<false,Encoding,Allocator>::Iterator MemberIterator; //!< Member iterator for iterating in object.
- typedef typename GenericMemberIterator<true,Encoding,Allocator>::Iterator ConstMemberIterator; //!< Constant member iterator for iterating in object.
- typedef GenericValue* ValueIterator; //!< Value iterator for iterating in array.
- typedef const GenericValue* ConstValueIterator; //!< Constant value iterator for iterating in array.
-
- //!@name Constructors and destructor.
- //@{
-
- //! Default constructor creates a null value.
- GenericValue() RAPIDJSON_NOEXCEPT : data_(), flags_(kNullFlag) {}
-
-#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
- //! Move constructor in C++11
- GenericValue(GenericValue&& rhs) RAPIDJSON_NOEXCEPT : data_(rhs.data_), flags_(rhs.flags_) {
- rhs.flags_ = kNullFlag; // give up contents
- }
-#endif
-
-private:
- //! Copy constructor is not permitted.
- GenericValue(const GenericValue& rhs);
-
-public:
-
- //! Constructor with JSON value type.
- /*! This creates a Value of specified type with default content.
- \param type Type of the value.
- \note Default content for number is zero.
- */
- explicit GenericValue(Type type) RAPIDJSON_NOEXCEPT : data_(), flags_() {
- static const unsigned defaultFlags[7] = {
- kNullFlag, kFalseFlag, kTrueFlag, kObjectFlag, kArrayFlag, kShortStringFlag,
- kNumberAnyFlag
- };
- RAPIDJSON_ASSERT(type <= kNumberType);
- flags_ = defaultFlags[type];
-
- // Use ShortString to store empty string.
- if (type == kStringType)
- data_.ss.SetLength(0);
- }
-
- //! Explicit copy constructor (with allocator)
- /*! Creates a copy of a Value by using the given Allocator
- \tparam SourceAllocator allocator of \c rhs
- \param rhs Value to copy from (read-only)
- \param allocator Allocator for allocating copied elements and buffers. Commonly use GenericDocument::GetAllocator().
- \see CopyFrom()
- */
- template< typename SourceAllocator >
- GenericValue(const GenericValue<Encoding, SourceAllocator>& rhs, Allocator & allocator);
-
- //! Constructor for boolean value.
- /*! \param b Boolean value
- \note This constructor is limited to \em real boolean values and rejects
- implicitly converted types like arbitrary pointers. Use an explicit cast
- to \c bool, if you want to construct a boolean JSON value in such cases.
- */
-#ifndef RAPIDJSON_DOXYGEN_RUNNING // hide SFINAE from Doxygen
- template <typename T>
- explicit GenericValue(T b, RAPIDJSON_ENABLEIF((internal::IsSame<T,bool>))) RAPIDJSON_NOEXCEPT
-#else
- explicit GenericValue(bool b) RAPIDJSON_NOEXCEPT
-#endif
- : data_(), flags_(b ? kTrueFlag : kFalseFlag) {
- // safe-guard against failing SFINAE
- RAPIDJSON_STATIC_ASSERT((internal::IsSame<bool,T>::Value));
- }
-
- //! Constructor for int value.
- explicit GenericValue(int i) RAPIDJSON_NOEXCEPT : data_(), flags_(kNumberIntFlag) {
- data_.n.i64 = i;
- if (i >= 0)
- flags_ |= kUintFlag | kUint64Flag;
- }
-
- //! Constructor for unsigned value.
- explicit GenericValue(unsigned u) RAPIDJSON_NOEXCEPT : data_(), flags_(kNumberUintFlag) {
- data_.n.u64 = u;
- if (!(u & 0x80000000))
- flags_ |= kIntFlag | kInt64Flag;
- }
-
- //! Constructor for int64_t value.
- explicit GenericValue(int64_t i64) RAPIDJSON_NOEXCEPT : data_(), flags_(kNumberInt64Flag) {
- data_.n.i64 = i64;
- if (i64 >= 0) {
- flags_ |= kNumberUint64Flag;
- if (!(static_cast<uint64_t>(i64) & RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0x00000000)))
- flags_ |= kUintFlag;
- if (!(static_cast<uint64_t>(i64) & RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0x80000000)))
- flags_ |= kIntFlag;
- }
- else if (i64 >= static_cast<int64_t>(RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0x80000000)))
- flags_ |= kIntFlag;
- }
-
- //! Constructor for uint64_t value.
- explicit GenericValue(uint64_t u64) RAPIDJSON_NOEXCEPT : data_(), flags_(kNumberUint64Flag) {
- data_.n.u64 = u64;
- if (!(u64 & RAPIDJSON_UINT64_C2(0x80000000, 0x00000000)))
- flags_ |= kInt64Flag;
- if (!(u64 & RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0x00000000)))
- flags_ |= kUintFlag;
- if (!(u64 & RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0x80000000)))
- flags_ |= kIntFlag;
- }
-
- //! Constructor for double value.
- explicit GenericValue(double d) RAPIDJSON_NOEXCEPT : data_(), flags_(kNumberDoubleFlag) { data_.n.d = d; }
-
- //! Constructor for constant string (i.e. do not make a copy of string)
- GenericValue(const Ch* s, SizeType length) RAPIDJSON_NOEXCEPT : data_(), flags_() { SetStringRaw(StringRef(s, length)); }
-
- //! Constructor for constant string (i.e. do not make a copy of string)
- explicit GenericValue(StringRefType s) RAPIDJSON_NOEXCEPT : data_(), flags_() { SetStringRaw(s); }
-
- //! Constructor for copy-string (i.e. do make a copy of string)
- GenericValue(const Ch* s, SizeType length, Allocator& allocator) : data_(), flags_() { SetStringRaw(StringRef(s, length), allocator); }
-
- //! Constructor for copy-string (i.e. do make a copy of string)
- GenericValue(const Ch*s, Allocator& allocator) : data_(), flags_() { SetStringRaw(StringRef(s), allocator); }
-
-#if RAPIDJSON_HAS_STDSTRING
- //! Constructor for copy-string from a string object (i.e. do make a copy of string)
- /*! \note Requires the definition of the preprocessor symbol \ref RAPIDJSON_HAS_STDSTRING.
- */
- GenericValue(const std::basic_string<Ch>& s, Allocator& allocator) : data_(), flags_() { SetStringRaw(StringRef(s), allocator); }
-#endif
-
- //! Destructor.
- /*! Need to destruct elements of array, members of object, or copy-string.
- */
- ~GenericValue() {
- if (Allocator::kNeedFree) { // Shortcut by Allocator's trait
- switch(flags_) {
- case kArrayFlag:
- for (GenericValue* v = data_.a.elements; v != data_.a.elements + data_.a.size; ++v)
- v->~GenericValue();
- Allocator::Free(data_.a.elements);
- break;
-
- case kObjectFlag:
- for (MemberIterator m = MemberBegin(); m != MemberEnd(); ++m)
- m->~Member();
- Allocator::Free(data_.o.members);
- break;
-
- case kCopyStringFlag:
- Allocator::Free(const_cast<Ch*>(data_.s.str));
- break;
-
- default:
- break; // Do nothing for other types.
- }
- }
- }
-
- //@}
-
- //!@name Assignment operators
- //@{
-
- //! Assignment with move semantics.
- /*! \param rhs Source of the assignment. It will become a null value after assignment.
- */
- GenericValue& operator=(GenericValue& rhs) RAPIDJSON_NOEXCEPT {
- RAPIDJSON_ASSERT(this != &rhs);
- this->~GenericValue();
- RawAssign(rhs);
- return *this;
- }
-
-#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
- //! Move assignment in C++11
- GenericValue& operator=(GenericValue&& rhs) RAPIDJSON_NOEXCEPT {
- return *this = rhs.Move();
- }
-#endif
-
- //! Assignment of constant string reference (no copy)
- /*! \param str Constant string reference to be assigned
- \note This overload is needed to avoid clashes with the generic primitive type assignment overload below.
- \see GenericStringRef, operator=(T)
- */
- GenericValue& operator=(StringRefType str) RAPIDJSON_NOEXCEPT {
- GenericValue s(str);
- return *this = s;
- }
-
- //! Assignment with primitive types.
- /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t
- \param value The value to be assigned.
-
- \note The source type \c T explicitly disallows all pointer types,
- especially (\c const) \ref Ch*. This helps avoiding implicitly
- referencing character strings with insufficient lifetime, use
- \ref SetString(const Ch*, Allocator&) (for copying) or
- \ref StringRef() (to explicitly mark the pointer as constant) instead.
- All other pointer types would implicitly convert to \c bool,
- use \ref SetBool() instead.
- */
- template <typename T>
- RAPIDJSON_DISABLEIF_RETURN((internal::IsPointer<T>), (GenericValue&))
- operator=(T value) {
- GenericValue v(value);
- return *this = v;
- }
-
- //! Deep-copy assignment from Value
- /*! Assigns a \b copy of the Value to the current Value object
- \tparam SourceAllocator Allocator type of \c rhs
- \param rhs Value to copy from (read-only)
- \param allocator Allocator to use for copying
- */
- template <typename SourceAllocator>
- GenericValue& CopyFrom(const GenericValue<Encoding, SourceAllocator>& rhs, Allocator& allocator) {
- RAPIDJSON_ASSERT((void*)this != (void const*)&rhs);
- this->~GenericValue();
- new (this) GenericValue(rhs, allocator);
- return *this;
- }
-
- //! Exchange the contents of this value with those of other.
- /*!
- \param other Another value.
- \note Constant complexity.
- */
- GenericValue& Swap(GenericValue& other) RAPIDJSON_NOEXCEPT {
- GenericValue temp;
- temp.RawAssign(*this);
- RawAssign(other);
- other.RawAssign(temp);
- return *this;
- }
-
- //! Prepare Value for move semantics
- /*! \return *this */
- GenericValue& Move() RAPIDJSON_NOEXCEPT { return *this; }
- //@}
-
- //!@name Equal-to and not-equal-to operators
- //@{
- //! Equal-to operator
- /*!
- \note If an object contains duplicated named member, comparing equality with any object is always \c false.
- \note Linear time complexity (number of all values in the subtree and total lengths of all strings).
- */
- template <typename SourceAllocator>
- bool operator==(const GenericValue<Encoding, SourceAllocator>& rhs) const {
- typedef GenericValue<Encoding, SourceAllocator> RhsType;
- if (GetType() != rhs.GetType())
- return false;
-
- switch (GetType()) {
- case kObjectType: // Warning: O(n^2) inner-loop
- if (data_.o.size != rhs.data_.o.size)
- return false;
- for (ConstMemberIterator lhsMemberItr = MemberBegin(); lhsMemberItr != MemberEnd(); ++lhsMemberItr) {
- typename RhsType::ConstMemberIterator rhsMemberItr = rhs.FindMember(lhsMemberItr->name);
- if (rhsMemberItr == rhs.MemberEnd() || lhsMemberItr->value != rhsMemberItr->value)
- return false;
- }
- return true;
-
- case kArrayType:
- if (data_.a.size != rhs.data_.a.size)
- return false;
- for (SizeType i = 0; i < data_.a.size; i++)
- if ((*this)[i] != rhs[i])
- return false;
- return true;
-
- case kStringType:
- return StringEqual(rhs);
-
- case kNumberType:
- if (IsDouble() || rhs.IsDouble()) {
- double a = GetDouble(); // May convert from integer to double.
- double b = rhs.GetDouble(); // Ditto
- return a >= b && a <= b; // Prevent -Wfloat-equal
- }
- else
- return data_.n.u64 == rhs.data_.n.u64;
-
- default: // kTrueType, kFalseType, kNullType
- return true;
- }
- }
-
- //! Equal-to operator with const C-string pointer
- bool operator==(const Ch* rhs) const { return *this == GenericValue(StringRef(rhs)); }
-
-#if RAPIDJSON_HAS_STDSTRING
- //! Equal-to operator with string object
- /*! \note Requires the definition of the preprocessor symbol \ref RAPIDJSON_HAS_STDSTRING.
- */
- bool operator==(const std::basic_string<Ch>& rhs) const { return *this == GenericValue(StringRef(rhs)); }
-#endif
-
- //! Equal-to operator with primitive types
- /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t, \c double, \c true, \c false
- */
- template <typename T> RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>,internal::IsGenericValue<T> >), (bool)) operator==(const T& rhs) const { return *this == GenericValue(rhs); }
-
- //! Not-equal-to operator
- /*! \return !(*this == rhs)
- */
- template <typename SourceAllocator>
- bool operator!=(const GenericValue<Encoding, SourceAllocator>& rhs) const { return !(*this == rhs); }
-
- //! Not-equal-to operator with const C-string pointer
- bool operator!=(const Ch* rhs) const { return !(*this == rhs); }
-
- //! Not-equal-to operator with arbitrary types
- /*! \return !(*this == rhs)
- */
- template <typename T> RAPIDJSON_DISABLEIF_RETURN((internal::IsGenericValue<T>), (bool)) operator!=(const T& rhs) const { return !(*this == rhs); }
-
- //! Equal-to operator with arbitrary types (symmetric version)
- /*! \return (rhs == lhs)
- */
- template <typename T> friend RAPIDJSON_DISABLEIF_RETURN((internal::IsGenericValue<T>), (bool)) operator==(const T& lhs, const GenericValue& rhs) { return rhs == lhs; }
-
- //! Not-Equal-to operator with arbitrary types (symmetric version)
- /*! \return !(rhs == lhs)
- */
- template <typename T> friend RAPIDJSON_DISABLEIF_RETURN((internal::IsGenericValue<T>), (bool)) operator!=(const T& lhs, const GenericValue& rhs) { return !(rhs == lhs); }
- //@}
-
- //!@name Type
- //@{
-
- Type GetType() const { return static_cast<Type>(flags_ & kTypeMask); }
- bool IsNull() const { return flags_ == kNullFlag; }
- bool IsFalse() const { return flags_ == kFalseFlag; }
- bool IsTrue() const { return flags_ == kTrueFlag; }
- bool IsBool() const { return (flags_ & kBoolFlag) != 0; }
- bool IsObject() const { return flags_ == kObjectFlag; }
- bool IsArray() const { return flags_ == kArrayFlag; }
- bool IsNumber() const { return (flags_ & kNumberFlag) != 0; }
- bool IsInt() const { return (flags_ & kIntFlag) != 0; }
- bool IsUint() const { return (flags_ & kUintFlag) != 0; }
- bool IsInt64() const { return (flags_ & kInt64Flag) != 0; }
- bool IsUint64() const { return (flags_ & kUint64Flag) != 0; }
- bool IsDouble() const { return (flags_ & kDoubleFlag) != 0; }
- bool IsString() const { return (flags_ & kStringFlag) != 0; }
-
- //@}
-
- //!@name Null
- //@{
-
- GenericValue& SetNull() { this->~GenericValue(); new (this) GenericValue(); return *this; }
-
- //@}
-
- //!@name Bool
- //@{
-
- bool GetBool() const { RAPIDJSON_ASSERT(IsBool()); return flags_ == kTrueFlag; }
- //!< Set boolean value
- /*! \post IsBool() == true */
- GenericValue& SetBool(bool b) { this->~GenericValue(); new (this) GenericValue(b); return *this; }
-
- //@}
-
- //!@name Object
- //@{
-
- //! Set this value as an empty object.
- /*! \post IsObject() == true */
- GenericValue& SetObject() { this->~GenericValue(); new (this) GenericValue(kObjectType); return *this; }
-
- //! Get the number of members in the object.
- SizeType MemberCount() const { RAPIDJSON_ASSERT(IsObject()); return data_.o.size; }
-
- //! Check whether the object is empty.
- bool ObjectEmpty() const { RAPIDJSON_ASSERT(IsObject()); return data_.o.size == 0; }
-
- //! Get a value from an object associated with the name.
- /*! \pre IsObject() == true
- \tparam T Either \c Ch or \c const \c Ch (template used for disambiguation with \ref operator[](SizeType))
- \note In version 0.1x, if the member is not found, this function returns a null value. This makes issue 7.
- Since 0.2, if the name is not correct, it will assert.
- If user is unsure whether a member exists, user should use HasMember() first.
- A better approach is to use FindMember().
- \note Linear time complexity.
- */
- template <typename T>
- RAPIDJSON_DISABLEIF_RETURN((internal::NotExpr<internal::IsSame<typename internal::RemoveConst<T>::Type, Ch> >),(GenericValue&)) operator[](T* name) {
- GenericValue n(StringRef(name));
- return (*this)[n];
- }
- template <typename T>
- RAPIDJSON_DISABLEIF_RETURN((internal::NotExpr<internal::IsSame<typename internal::RemoveConst<T>::Type, Ch> >),(const GenericValue&)) operator[](T* name) const { return const_cast<GenericValue&>(*this)[name]; }
-
- //! Get a value from an object associated with the name.
- /*! \pre IsObject() == true
- \tparam SourceAllocator Allocator of the \c name value
-
- \note Compared to \ref operator[](T*), this version is faster because it does not need a StrLen().
- And it can also handle strings with embedded null characters.
-
- \note Linear time complexity.
- */
- template <typename SourceAllocator>
- GenericValue& operator[](const GenericValue<Encoding, SourceAllocator>& name) {
- MemberIterator member = FindMember(name);
- if (member != MemberEnd())
- return member->value;
- else {
- RAPIDJSON_ASSERT(false); // see above note
- static GenericValue NullValue;
- return NullValue;
- }
- }
- template <typename SourceAllocator>
- const GenericValue& operator[](const GenericValue<Encoding, SourceAllocator>& name) const { return const_cast<GenericValue&>(*this)[name]; }
-
- //! Const member iterator
- /*! \pre IsObject() == true */
- ConstMemberIterator MemberBegin() const { RAPIDJSON_ASSERT(IsObject()); return ConstMemberIterator(data_.o.members); }
- //! Const \em past-the-end member iterator
- /*! \pre IsObject() == true */
- ConstMemberIterator MemberEnd() const { RAPIDJSON_ASSERT(IsObject()); return ConstMemberIterator(data_.o.members + data_.o.size); }
- //! Member iterator
- /*! \pre IsObject() == true */
- MemberIterator MemberBegin() { RAPIDJSON_ASSERT(IsObject()); return MemberIterator(data_.o.members); }
- //! \em Past-the-end member iterator
- /*! \pre IsObject() == true */
- MemberIterator MemberEnd() { RAPIDJSON_ASSERT(IsObject()); return MemberIterator(data_.o.members + data_.o.size); }
-
- //! Check whether a member exists in the object.
- /*!
- \param name Member name to be searched.
- \pre IsObject() == true
- \return Whether a member with that name exists.
- \note It is better to use FindMember() directly if you need the obtain the value as well.
- \note Linear time complexity.
- */
- bool HasMember(const Ch* name) const { return FindMember(name) != MemberEnd(); }
-
- //! Check whether a member exists in the object with GenericValue name.
- /*!
- This version is faster because it does not need a StrLen(). It can also handle string with null character.
- \param name Member name to be searched.
- \pre IsObject() == true
- \return Whether a member with that name exists.
- \note It is better to use FindMember() directly if you need the obtain the value as well.
- \note Linear time complexity.
- */
- template <typename SourceAllocator>
- bool HasMember(const GenericValue<Encoding, SourceAllocator>& name) const { return FindMember(name) != MemberEnd(); }
-
- //! Find member by name.
- /*!
- \param name Member name to be searched.
- \pre IsObject() == true
- \return Iterator to member, if it exists.
- Otherwise returns \ref MemberEnd().
-
- \note Earlier versions of Rapidjson returned a \c NULL pointer, in case
- the requested member doesn't exist. For consistency with e.g.
- \c std::map, this has been changed to MemberEnd() now.
- \note Linear time complexity.
- */
- MemberIterator FindMember(const Ch* name) {
- GenericValue n(StringRef(name));
- return FindMember(n);
- }
-
- ConstMemberIterator FindMember(const Ch* name) const { return const_cast<GenericValue&>(*this).FindMember(name); }
-
- //! Find member by name.
- /*!
- This version is faster because it does not need a StrLen(). It can also handle string with null character.
- \param name Member name to be searched.
- \pre IsObject() == true
- \return Iterator to member, if it exists.
- Otherwise returns \ref MemberEnd().
-
- \note Earlier versions of Rapidjson returned a \c NULL pointer, in case
- the requested member doesn't exist. For consistency with e.g.
- \c std::map, this has been changed to MemberEnd() now.
- \note Linear time complexity.
- */
- template <typename SourceAllocator>
- MemberIterator FindMember(const GenericValue<Encoding, SourceAllocator>& name) {
- RAPIDJSON_ASSERT(IsObject());
- RAPIDJSON_ASSERT(name.IsString());
- MemberIterator member = MemberBegin();
- for ( ; member != MemberEnd(); ++member)
- if (name.StringEqual(member->name))
- break;
- return member;
- }
- template <typename SourceAllocator> ConstMemberIterator FindMember(const GenericValue<Encoding, SourceAllocator>& name) const { return const_cast<GenericValue&>(*this).FindMember(name); }
-
- //! Add a member (name-value pair) to the object.
- /*! \param name A string value as name of member.
- \param value Value of any type.
- \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator().
- \return The value itself for fluent API.
- \note The ownership of \c name and \c value will be transferred to this object on success.
- \pre IsObject() && name.IsString()
- \post name.IsNull() && value.IsNull()
- \note Amortized Constant time complexity.
- */
- GenericValue& AddMember(GenericValue& name, GenericValue& value, Allocator& allocator) {
- RAPIDJSON_ASSERT(IsObject());
- RAPIDJSON_ASSERT(name.IsString());
-
- Object& o = data_.o;
- if (o.size >= o.capacity) {
- if (o.capacity == 0) {
- o.capacity = kDefaultObjectCapacity;
- o.members = reinterpret_cast<Member*>(allocator.Malloc(o.capacity * sizeof(Member)));
- }
- else {
- SizeType oldCapacity = o.capacity;
- o.capacity += (oldCapacity + 1) / 2; // grow by factor 1.5
- o.members = reinterpret_cast<Member*>(allocator.Realloc(o.members, oldCapacity * sizeof(Member), o.capacity * sizeof(Member)));
- }
- }
- o.members[o.size].name.RawAssign(name);
- o.members[o.size].value.RawAssign(value);
- o.size++;
- return *this;
- }
-
- //! Add a constant string value as member (name-value pair) to the object.
- /*! \param name A string value as name of member.
- \param value constant string reference as value of member.
- \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator().
- \return The value itself for fluent API.
- \pre IsObject()
- \note This overload is needed to avoid clashes with the generic primitive type AddMember(GenericValue&,T,Allocator&) overload below.
- \note Amortized Constant time complexity.
- */
- GenericValue& AddMember(GenericValue& name, StringRefType value, Allocator& allocator) {
- GenericValue v(value);
- return AddMember(name, v, allocator);
- }
-
- //! Add any primitive value as member (name-value pair) to the object.
- /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t
- \param name A string value as name of member.
- \param value Value of primitive type \c T as value of member
- \param allocator Allocator for reallocating memory. Commonly use GenericDocument::GetAllocator().
- \return The value itself for fluent API.
- \pre IsObject()
-
- \note The source type \c T explicitly disallows all pointer types,
- especially (\c const) \ref Ch*. This helps avoiding implicitly
- referencing character strings with insufficient lifetime, use
- \ref AddMember(StringRefType, GenericValue&, Allocator&) or \ref
- AddMember(StringRefType, StringRefType, Allocator&).
- All other pointer types would implicitly convert to \c bool,
- use an explicit cast instead, if needed.
- \note Amortized Constant time complexity.
- */
- template <typename T>
- RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (GenericValue&))
- AddMember(GenericValue& name, T value, Allocator& allocator) {
- GenericValue v(value);
- return AddMember(name, v, allocator);
- }
-
-#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
- GenericValue& AddMember(GenericValue&& name, GenericValue&& value, Allocator& allocator) {
- return AddMember(name, value, allocator);
- }
- GenericValue& AddMember(GenericValue&& name, GenericValue& value, Allocator& allocator) {
- return AddMember(name, value, allocator);
- }
- GenericValue& AddMember(GenericValue& name, GenericValue&& value, Allocator& allocator) {
- return AddMember(name, value, allocator);
- }
- GenericValue& AddMember(StringRefType name, GenericValue&& value, Allocator& allocator) {
- GenericValue n(name);
- return AddMember(n, value, allocator);
- }
-#endif // RAPIDJSON_HAS_CXX11_RVALUE_REFS
-
-
- //! Add a member (name-value pair) to the object.
- /*! \param name A constant string reference as name of member.
- \param value Value of any type.
- \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator().
- \return The value itself for fluent API.
- \note The ownership of \c value will be transferred to this object on success.
- \pre IsObject()
- \post value.IsNull()
- \note Amortized Constant time complexity.
- */
- GenericValue& AddMember(StringRefType name, GenericValue& value, Allocator& allocator) {
- GenericValue n(name);
- return AddMember(n, value, allocator);
- }
-
- //! Add a constant string value as member (name-value pair) to the object.
- /*! \param name A constant string reference as name of member.
- \param value constant string reference as value of member.
- \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator().
- \return The value itself for fluent API.
- \pre IsObject()
- \note This overload is needed to avoid clashes with the generic primitive type AddMember(StringRefType,T,Allocator&) overload below.
- \note Amortized Constant time complexity.
- */
- GenericValue& AddMember(StringRefType name, StringRefType value, Allocator& allocator) {
- GenericValue v(value);
- return AddMember(name, v, allocator);
- }
-
- //! Add any primitive value as member (name-value pair) to the object.
- /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t
- \param name A constant string reference as name of member.
- \param value Value of primitive type \c T as value of member
- \param allocator Allocator for reallocating memory. Commonly use GenericDocument::GetAllocator().
- \return The value itself for fluent API.
- \pre IsObject()
-
- \note The source type \c T explicitly disallows all pointer types,
- especially (\c const) \ref Ch*. This helps avoiding implicitly
- referencing character strings with insufficient lifetime, use
- \ref AddMember(StringRefType, GenericValue&, Allocator&) or \ref
- AddMember(StringRefType, StringRefType, Allocator&).
- All other pointer types would implicitly convert to \c bool,
- use an explicit cast instead, if needed.
- \note Amortized Constant time complexity.
- */
- template <typename T>
- RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (GenericValue&))
- AddMember(StringRefType name, T value, Allocator& allocator) {
- GenericValue n(name);
- return AddMember(n, value, allocator);
- }
-
- //! Remove all members in the object.
- /*! This function do not deallocate memory in the object, i.e. the capacity is unchanged.
- \note Linear time complexity.
- */
- void RemoveAllMembers() {
- RAPIDJSON_ASSERT(IsObject());
- for (MemberIterator m = MemberBegin(); m != MemberEnd(); ++m)
- m->~Member();
- data_.o.size = 0;
- }
-
- //! Remove a member in object by its name.
- /*! \param name Name of member to be removed.
- \return Whether the member existed.
- \note This function may reorder the object members. Use \ref
- EraseMember(ConstMemberIterator) if you need to preserve the
- relative order of the remaining members.
- \note Linear time complexity.
- */
- bool RemoveMember(const Ch* name) {
- GenericValue n(StringRef(name));
- return RemoveMember(n);
- }
-
- template <typename SourceAllocator>
- bool RemoveMember(const GenericValue<Encoding, SourceAllocator>& name) {
- MemberIterator m = FindMember(name);
- if (m != MemberEnd()) {
- RemoveMember(m);
- return true;
- }
- else
- return false;
- }
-
- //! Remove a member in object by iterator.
- /*! \param m member iterator (obtained by FindMember() or MemberBegin()).
- \return the new iterator after removal.
- \note This function may reorder the object members. Use \ref
- EraseMember(ConstMemberIterator) if you need to preserve the
- relative order of the remaining members.
- \note Constant time complexity.
- */
- MemberIterator RemoveMember(MemberIterator m) {
- RAPIDJSON_ASSERT(IsObject());
- RAPIDJSON_ASSERT(data_.o.size > 0);
- RAPIDJSON_ASSERT(data_.o.members != 0);
- RAPIDJSON_ASSERT(m >= MemberBegin() && m < MemberEnd());
-
- MemberIterator last(data_.o.members + (data_.o.size - 1));
- if (data_.o.size > 1 && m != last) {
- // Move the last one to this place
- *m = *last;
- }
- else {
- // Only one left, just destroy
- m->~Member();
- }
- --data_.o.size;
- return m;
- }
-
- //! Remove a member from an object by iterator.
- /*! \param pos iterator to the member to remove
- \pre IsObject() == true && \ref MemberBegin() <= \c pos < \ref MemberEnd()
- \return Iterator following the removed element.
- If the iterator \c pos refers to the last element, the \ref MemberEnd() iterator is returned.
- \note This function preserves the relative order of the remaining object
- members. If you do not need this, use the more efficient \ref RemoveMember(MemberIterator).
- \note Linear time complexity.
- */
- MemberIterator EraseMember(ConstMemberIterator pos) {
- return EraseMember(pos, pos +1);
- }
-
- //! Remove members in the range [first, last) from an object.
- /*! \param first iterator to the first member to remove
- \param last iterator following the last member to remove
- \pre IsObject() == true && \ref MemberBegin() <= \c first <= \c last <= \ref MemberEnd()
- \return Iterator following the last removed element.
- \note This function preserves the relative order of the remaining object
- members.
- \note Linear time complexity.
- */
- MemberIterator EraseMember(ConstMemberIterator first, ConstMemberIterator last) {
- RAPIDJSON_ASSERT(IsObject());
- RAPIDJSON_ASSERT(data_.o.size > 0);
- RAPIDJSON_ASSERT(data_.o.members != 0);
- RAPIDJSON_ASSERT(first >= MemberBegin());
- RAPIDJSON_ASSERT(first <= last);
- RAPIDJSON_ASSERT(last <= MemberEnd());
-
- MemberIterator pos = MemberBegin() + (first - MemberBegin());
- for (MemberIterator itr = pos; itr != last; ++itr)
- itr->~Member();
- std::memmove(&*pos, &*last, (MemberEnd() - last) * sizeof(Member));
- data_.o.size -= (last - first);
- return pos;
- }
-
- //@}
-
- //!@name Array
- //@{
-
- //! Set this value as an empty array.
- /*! \post IsArray == true */
- GenericValue& SetArray() { this->~GenericValue(); new (this) GenericValue(kArrayType); return *this; }
-
- //! Get the number of elements in array.
- SizeType Size() const { RAPIDJSON_ASSERT(IsArray()); return data_.a.size; }
-
- //! Get the capacity of array.
- SizeType Capacity() const { RAPIDJSON_ASSERT(IsArray()); return data_.a.capacity; }
-
- //! Check whether the array is empty.
- bool Empty() const { RAPIDJSON_ASSERT(IsArray()); return data_.a.size == 0; }
-
- //! Remove all elements in the array.
- /*! This function do not deallocate memory in the array, i.e. the capacity is unchanged.
- \note Linear time complexity.
- */
- void Clear() {
- RAPIDJSON_ASSERT(IsArray());
- for (SizeType i = 0; i < data_.a.size; ++i)
- data_.a.elements[i].~GenericValue();
- data_.a.size = 0;
- }
-
- //! Get an element from array by index.
- /*! \pre IsArray() == true
- \param index Zero-based index of element.
- \see operator[](T*)
- */
- GenericValue& operator[](SizeType index) {
- RAPIDJSON_ASSERT(IsArray());
- RAPIDJSON_ASSERT(index < data_.a.size);
- return data_.a.elements[index];
- }
- const GenericValue& operator[](SizeType index) const { return const_cast<GenericValue&>(*this)[index]; }
-
- //! Element iterator
- /*! \pre IsArray() == true */
- ValueIterator Begin() { RAPIDJSON_ASSERT(IsArray()); return data_.a.elements; }
- //! \em Past-the-end element iterator
- /*! \pre IsArray() == true */
- ValueIterator End() { RAPIDJSON_ASSERT(IsArray()); return data_.a.elements + data_.a.size; }
- //! Constant element iterator
- /*! \pre IsArray() == true */
- ConstValueIterator Begin() const { return const_cast<GenericValue&>(*this).Begin(); }
- //! Constant \em past-the-end element iterator
- /*! \pre IsArray() == true */
- ConstValueIterator End() const { return const_cast<GenericValue&>(*this).End(); }
-
- //! Request the array to have enough capacity to store elements.
- /*! \param newCapacity The capacity that the array at least need to have.
- \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator().
- \return The value itself for fluent API.
- \note Linear time complexity.
- */
- GenericValue& Reserve(SizeType newCapacity, Allocator &allocator) {
- RAPIDJSON_ASSERT(IsArray());
- if (newCapacity > data_.a.capacity) {
- data_.a.elements = (GenericValue*)allocator.Realloc(data_.a.elements, data_.a.capacity * sizeof(GenericValue), newCapacity * sizeof(GenericValue));
- data_.a.capacity = newCapacity;
- }
- return *this;
- }
-
- //! Append a GenericValue at the end of the array.
- /*! \param value Value to be appended.
- \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator().
- \pre IsArray() == true
- \post value.IsNull() == true
- \return The value itself for fluent API.
- \note The ownership of \c value will be transferred to this array on success.
- \note If the number of elements to be appended is known, calls Reserve() once first may be more efficient.
- \note Amortized constant time complexity.
- */
- GenericValue& PushBack(GenericValue& value, Allocator& allocator) {
- RAPIDJSON_ASSERT(IsArray());
- if (data_.a.size >= data_.a.capacity)
- Reserve(data_.a.capacity == 0 ? kDefaultArrayCapacity : (data_.a.capacity + (data_.a.capacity + 1) / 2), allocator);
- data_.a.elements[data_.a.size++].RawAssign(value);
- return *this;
- }
-
-#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
- GenericValue& PushBack(GenericValue&& value, Allocator& allocator) {
- return PushBack(value, allocator);
- }
-#endif // RAPIDJSON_HAS_CXX11_RVALUE_REFS
-
- //! Append a constant string reference at the end of the array.
- /*! \param value Constant string reference to be appended.
- \param allocator Allocator for reallocating memory. It must be the same one used previously. Commonly use GenericDocument::GetAllocator().
- \pre IsArray() == true
- \return The value itself for fluent API.
- \note If the number of elements to be appended is known, calls Reserve() once first may be more efficient.
- \note Amortized constant time complexity.
- \see GenericStringRef
- */
- GenericValue& PushBack(StringRefType value, Allocator& allocator) {
- return (*this).template PushBack<StringRefType>(value, allocator);
- }
-
- //! Append a primitive value at the end of the array.
- /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t
- \param value Value of primitive type T to be appended.
- \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator().
- \pre IsArray() == true
- \return The value itself for fluent API.
- \note If the number of elements to be appended is known, calls Reserve() once first may be more efficient.
-
- \note The source type \c T explicitly disallows all pointer types,
- especially (\c const) \ref Ch*. This helps avoiding implicitly
- referencing character strings with insufficient lifetime, use
- \ref PushBack(GenericValue&, Allocator&) or \ref
- PushBack(StringRefType, Allocator&).
- All other pointer types would implicitly convert to \c bool,
- use an explicit cast instead, if needed.
- \note Amortized constant time complexity.
- */
- template <typename T>
- RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (GenericValue&))
- PushBack(T value, Allocator& allocator) {
- GenericValue v(value);
- return PushBack(v, allocator);
- }
-
- //! Remove the last element in the array.
- /*!
- \note Constant time complexity.
- */
- GenericValue& PopBack() {
- RAPIDJSON_ASSERT(IsArray());
- RAPIDJSON_ASSERT(!Empty());
- data_.a.elements[--data_.a.size].~GenericValue();
- return *this;
- }
-
- //! Remove an element of array by iterator.
- /*!
- \param pos iterator to the element to remove
- \pre IsArray() == true && \ref Begin() <= \c pos < \ref End()
- \return Iterator following the removed element. If the iterator pos refers to the last element, the End() iterator is returned.
- \note Linear time complexity.
- */
- ValueIterator Erase(ConstValueIterator pos) {
- return Erase(pos, pos + 1);
- }
-
- //! Remove elements in the range [first, last) of the array.
- /*!
- \param first iterator to the first element to remove
- \param last iterator following the last element to remove
- \pre IsArray() == true && \ref Begin() <= \c first <= \c last <= \ref End()
- \return Iterator following the last removed element.
- \note Linear time complexity.
- */
- ValueIterator Erase(ConstValueIterator first, ConstValueIterator last) {
- RAPIDJSON_ASSERT(IsArray());
- RAPIDJSON_ASSERT(data_.a.size > 0);
- RAPIDJSON_ASSERT(data_.a.elements != 0);
- RAPIDJSON_ASSERT(first >= Begin());
- RAPIDJSON_ASSERT(first <= last);
- RAPIDJSON_ASSERT(last <= End());
- ValueIterator pos = Begin() + (first - Begin());
- for (ValueIterator itr = pos; itr != last; ++itr)
- itr->~GenericValue();
- std::memmove(pos, last, (End() - last) * sizeof(GenericValue));
- data_.a.size -= (last - first);
- return pos;
- }
-
- //@}
-
- //!@name Number
- //@{
-
- int GetInt() const { RAPIDJSON_ASSERT(flags_ & kIntFlag); return data_.n.i.i; }
- unsigned GetUint() const { RAPIDJSON_ASSERT(flags_ & kUintFlag); return data_.n.u.u; }
- int64_t GetInt64() const { RAPIDJSON_ASSERT(flags_ & kInt64Flag); return data_.n.i64; }
- uint64_t GetUint64() const { RAPIDJSON_ASSERT(flags_ & kUint64Flag); return data_.n.u64; }
-
- double GetDouble() const {
- RAPIDJSON_ASSERT(IsNumber());
- if ((flags_ & kDoubleFlag) != 0) return data_.n.d; // exact type, no conversion.
- if ((flags_ & kIntFlag) != 0) return data_.n.i.i; // int -> double
- if ((flags_ & kUintFlag) != 0) return data_.n.u.u; // unsigned -> double
- if ((flags_ & kInt64Flag) != 0) return (double)data_.n.i64; // int64_t -> double (may lose precision)
- RAPIDJSON_ASSERT((flags_ & kUint64Flag) != 0); return (double)data_.n.u64; // uint64_t -> double (may lose precision)
- }
-
- GenericValue& SetInt(int i) { this->~GenericValue(); new (this) GenericValue(i); return *this; }
- GenericValue& SetUint(unsigned u) { this->~GenericValue(); new (this) GenericValue(u); return *this; }
- GenericValue& SetInt64(int64_t i64) { this->~GenericValue(); new (this) GenericValue(i64); return *this; }
- GenericValue& SetUint64(uint64_t u64) { this->~GenericValue(); new (this) GenericValue(u64); return *this; }
- GenericValue& SetDouble(double d) { this->~GenericValue(); new (this) GenericValue(d); return *this; }
-
- //@}
-
- //!@name String
- //@{
-
- const Ch* GetString() const { RAPIDJSON_ASSERT(IsString()); return ((flags_ & kInlineStrFlag) ? data_.ss.str : data_.s.str); }
-
- //! Get the length of string.
- /*! Since rapidjson permits "\\u0000" in the json string, strlen(v.GetString()) may not equal to v.GetStringLength().
- */
- SizeType GetStringLength() const { RAPIDJSON_ASSERT(IsString()); return ((flags_ & kInlineStrFlag) ? (data_.ss.GetLength()) : data_.s.length); }
-
- //! Set this value as a string without copying source string.
- /*! This version has better performance with supplied length, and also support string containing null character.
- \param s source string pointer.
- \param length The length of source string, excluding the trailing null terminator.
- \return The value itself for fluent API.
- \post IsString() == true && GetString() == s && GetStringLength() == length
- \see SetString(StringRefType)
- */
- GenericValue& SetString(const Ch* s, SizeType length) { return SetString(StringRef(s, length)); }
-
- //! Set this value as a string without copying source string.
- /*! \param s source string reference
- \return The value itself for fluent API.
- \post IsString() == true && GetString() == s && GetStringLength() == s.length
- */
- GenericValue& SetString(StringRefType s) { this->~GenericValue(); SetStringRaw(s); return *this; }
-
- //! Set this value as a string by copying from source string.
- /*! This version has better performance with supplied length, and also support string containing null character.
- \param s source string.
- \param length The length of source string, excluding the trailing null terminator.
- \param allocator Allocator for allocating copied buffer. Commonly use GenericDocument::GetAllocator().
- \return The value itself for fluent API.
- \post IsString() == true && GetString() != s && strcmp(GetString(),s) == 0 && GetStringLength() == length
- */
- GenericValue& SetString(const Ch* s, SizeType length, Allocator& allocator) { this->~GenericValue(); SetStringRaw(StringRef(s, length), allocator); return *this; }
-
- //! Set this value as a string by copying from source string.
- /*! \param s source string.
- \param allocator Allocator for allocating copied buffer. Commonly use GenericDocument::GetAllocator().
- \return The value itself for fluent API.
- \post IsString() == true && GetString() != s && strcmp(GetString(),s) == 0 && GetStringLength() == length
- */
- GenericValue& SetString(const Ch* s, Allocator& allocator) { return SetString(s, internal::StrLen(s), allocator); }
-
-#if RAPIDJSON_HAS_STDSTRING
- //! Set this value as a string by copying from source string.
- /*! \param s source string.
- \param allocator Allocator for allocating copied buffer. Commonly use GenericDocument::GetAllocator().
- \return The value itself for fluent API.
- \post IsString() == true && GetString() != s.data() && strcmp(GetString(),s.data() == 0 && GetStringLength() == s.size()
- \note Requires the definition of the preprocessor symbol \ref RAPIDJSON_HAS_STDSTRING.
- */
- GenericValue& SetString(const std::basic_string<Ch>& s, Allocator& allocator) { return SetString(s.data(), s.size(), allocator); }
-#endif
-
- //@}
-
- //! Generate events of this value to a Handler.
- /*! This function adopts the GoF visitor pattern.
- Typical usage is to output this JSON value as JSON text via Writer, which is a Handler.
- It can also be used to deep clone this value via GenericDocument, which is also a Handler.
- \tparam Handler type of handler.
- \param handler An object implementing concept Handler.
- */
- template <typename Handler>
- bool Accept(Handler& handler) const {
- switch(GetType()) {
- case kNullType: return handler.Null();
- case kFalseType: return handler.Bool(false);
- case kTrueType: return handler.Bool(true);
-
- case kObjectType:
- if (!handler.StartObject())
- return false;
- for (ConstMemberIterator m = MemberBegin(); m != MemberEnd(); ++m) {
- RAPIDJSON_ASSERT(m->name.IsString()); // User may change the type of name by MemberIterator.
- if (!handler.Key(m->name.GetString(), m->name.GetStringLength(), (m->name.flags_ & kCopyFlag) != 0))
- return false;
- if (!m->value.Accept(handler))
- return false;
- }
- return handler.EndObject(data_.o.size);
-
- case kArrayType:
- if (!handler.StartArray())
- return false;
- for (GenericValue* v = data_.a.elements; v != data_.a.elements + data_.a.size; ++v)
- if (!v->Accept(handler))
- return false;
- return handler.EndArray(data_.a.size);
-
- case kStringType:
- return handler.String(GetString(), GetStringLength(), (flags_ & kCopyFlag) != 0);
-
- default:
- RAPIDJSON_ASSERT(GetType() == kNumberType);
- if (IsInt()) return handler.Int(data_.n.i.i);
- else if (IsUint()) return handler.Uint(data_.n.u.u);
- else if (IsInt64()) return handler.Int64(data_.n.i64);
- else if (IsUint64()) return handler.Uint64(data_.n.u64);
- else return handler.Double(data_.n.d);
- }
- }
-
-private:
- template <typename, typename> friend class GenericValue;
- template <typename, typename, typename> friend class GenericDocument;
-
- enum {
- kBoolFlag = 0x100,
- kNumberFlag = 0x200,
- kIntFlag = 0x400,
- kUintFlag = 0x800,
- kInt64Flag = 0x1000,
- kUint64Flag = 0x2000,
- kDoubleFlag = 0x4000,
- kStringFlag = 0x100000,
- kCopyFlag = 0x200000,
- kInlineStrFlag = 0x400000,
-
- // Initial flags of different types.
- kNullFlag = kNullType,
- kTrueFlag = kTrueType | kBoolFlag,
- kFalseFlag = kFalseType | kBoolFlag,
- kNumberIntFlag = kNumberType | kNumberFlag | kIntFlag | kInt64Flag,
- kNumberUintFlag = kNumberType | kNumberFlag | kUintFlag | kUint64Flag | kInt64Flag,
- kNumberInt64Flag = kNumberType | kNumberFlag | kInt64Flag,
- kNumberUint64Flag = kNumberType | kNumberFlag | kUint64Flag,
- kNumberDoubleFlag = kNumberType | kNumberFlag | kDoubleFlag,
- kNumberAnyFlag = kNumberType | kNumberFlag | kIntFlag | kInt64Flag | kUintFlag | kUint64Flag | kDoubleFlag,
- kConstStringFlag = kStringType | kStringFlag,
- kCopyStringFlag = kStringType | kStringFlag | kCopyFlag,
- kShortStringFlag = kStringType | kStringFlag | kCopyFlag | kInlineStrFlag,
- kObjectFlag = kObjectType,
- kArrayFlag = kArrayType,
-
- kTypeMask = 0xFF // bitwise-and with mask of 0xFF can be optimized by compiler
- };
-
- static const SizeType kDefaultArrayCapacity = 16;
- static const SizeType kDefaultObjectCapacity = 16;
-
- struct String {
- const Ch* str;
- SizeType length;
- unsigned hashcode; //!< reserved
- }; // 12 bytes in 32-bit mode, 16 bytes in 64-bit mode
-
- // implementation detail: ShortString can represent zero-terminated strings up to MaxSize chars
- // (excluding the terminating zero) and store a value to determine the length of the contained
- // string in the last character str[LenPos] by storing "MaxSize - length" there. If the string
- // to store has the maximal length of MaxSize then str[LenPos] will be 0 and therefore act as
- // the string terminator as well. For getting the string length back from that value just use
- // "MaxSize - str[LenPos]".
- // This allows to store 11-chars strings in 32-bit mode and 15-chars strings in 64-bit mode
- // inline (for `UTF8`-encoded strings).
- struct ShortString {
- enum { MaxChars = sizeof(String) / sizeof(Ch), MaxSize = MaxChars - 1, LenPos = MaxSize };
- Ch str[MaxChars];
-
- inline static bool Usable(SizeType len) { return (MaxSize >= len); }
- inline void SetLength(SizeType len) { str[LenPos] = (Ch)(MaxSize - len); }
- inline SizeType GetLength() const { return (SizeType)(MaxSize - str[LenPos]); }
- }; // at most as many bytes as "String" above => 12 bytes in 32-bit mode, 16 bytes in 64-bit mode
-
- // By using proper binary layout, retrieval of different integer types do not need conversions.
- union Number {
-#if RAPIDJSON_ENDIAN == RAPIDJSON_LITTLEENDIAN
- struct I {
- int i;
- char padding[4];
- }i;
- struct U {
- unsigned u;
- char padding2[4];
- }u;
-#else
- struct I {
- char padding[4];
- int i;
- }i;
- struct U {
- char padding2[4];
- unsigned u;
- }u;
-#endif
- int64_t i64;
- uint64_t u64;
- double d;
- }; // 8 bytes
-
- struct Object {
- Member* members;
- SizeType size;
- SizeType capacity;
- }; // 12 bytes in 32-bit mode, 16 bytes in 64-bit mode
-
- struct Array {
- GenericValue* elements;
- SizeType size;
- SizeType capacity;
- }; // 12 bytes in 32-bit mode, 16 bytes in 64-bit mode
-
- union Data {
- String s;
- ShortString ss;
- Number n;
- Object o;
- Array a;
- }; // 12 bytes in 32-bit mode, 16 bytes in 64-bit mode
-
- // Initialize this value as array with initial data, without calling destructor.
- void SetArrayRaw(GenericValue* values, SizeType count, Allocator& allocator) {
- flags_ = kArrayFlag;
- if (count) {
- data_.a.elements = (GenericValue*)allocator.Malloc(count * sizeof(GenericValue));
- std::memcpy(data_.a.elements, values, count * sizeof(GenericValue));
- }
- else
- data_.a.elements = NULL;
- data_.a.size = data_.a.capacity = count;
- }
-
- //! Initialize this value as object with initial data, without calling destructor.
- void SetObjectRaw(Member* members, SizeType count, Allocator& allocator) {
- flags_ = kObjectFlag;
- if (count) {
- data_.o.members = (Member*)allocator.Malloc(count * sizeof(Member));
- std::memcpy(data_.o.members, members, count * sizeof(Member));
- }
- else
- data_.o.members = NULL;
- data_.o.size = data_.o.capacity = count;
- }
-
- //! Initialize this value as constant string, without calling destructor.
- void SetStringRaw(StringRefType s) RAPIDJSON_NOEXCEPT {
- flags_ = kConstStringFlag;
- data_.s.str = s;
- data_.s.length = s.length;
- }
-
- //! Initialize this value as copy string with initial data, without calling destructor.
- void SetStringRaw(StringRefType s, Allocator& allocator) {
- Ch* str = NULL;
- if(ShortString::Usable(s.length)) {
- flags_ = kShortStringFlag;
- data_.ss.SetLength(s.length);
- str = data_.ss.str;
- } else {
- flags_ = kCopyStringFlag;
- data_.s.length = s.length;
- str = (Ch *)allocator.Malloc((s.length + 1) * sizeof(Ch));
- data_.s.str = str;
- }
- std::memcpy(str, s, s.length * sizeof(Ch));
- str[s.length] = '\0';
- }
-
- //! Assignment without calling destructor
- void RawAssign(GenericValue& rhs) RAPIDJSON_NOEXCEPT {
- data_ = rhs.data_;
- flags_ = rhs.flags_;
- rhs.flags_ = kNullFlag;
- }
-
- template <typename SourceAllocator>
- bool StringEqual(const GenericValue<Encoding, SourceAllocator>& rhs) const {
- RAPIDJSON_ASSERT(IsString());
- RAPIDJSON_ASSERT(rhs.IsString());
-
- const SizeType len1 = GetStringLength();
- const SizeType len2 = rhs.GetStringLength();
- if(len1 != len2) { return false; }
-
- const Ch* const str1 = GetString();
- const Ch* const str2 = rhs.GetString();
- if(str1 == str2) { return true; } // fast path for constant string
-
- return (std::memcmp(str1, str2, sizeof(Ch) * len1) == 0);
- }
-
- Data data_;
- unsigned flags_;
-};
-
-//! GenericValue with UTF8 encoding
-typedef GenericValue<UTF8<> > Value;
-
-///////////////////////////////////////////////////////////////////////////////
-// GenericDocument
-
-//! A document for parsing JSON text as DOM.
-/*!
- \note implements Handler concept
- \tparam Encoding Encoding for both parsing and string storage.
- \tparam Allocator Allocator for allocating memory for the DOM
- \tparam StackAllocator Allocator for allocating memory for stack during parsing.
- \warning Although GenericDocument inherits from GenericValue, the API does \b not provide any virtual functions, especially no virtual destructor. To avoid memory leaks, do not \c delete a GenericDocument object via a pointer to a GenericValue.
-*/
-template <typename Encoding, typename Allocator = MemoryPoolAllocator<>, typename StackAllocator = CrtAllocator>
-class GenericDocument : public GenericValue<Encoding, Allocator> {
-public:
- typedef typename Encoding::Ch Ch; //!< Character type derived from Encoding.
- typedef GenericValue<Encoding, Allocator> ValueType; //!< Value type of the document.
- typedef Allocator AllocatorType; //!< Allocator type from template parameter.
-
- //! Constructor
- /*! \param allocator Optional allocator for allocating memory.
- \param stackCapacity Optional initial capacity of stack in bytes.
- \param stackAllocator Optional allocator for allocating memory for stack.
- */
- GenericDocument(Allocator* allocator = 0, size_t stackCapacity = kDefaultStackCapacity, StackAllocator* stackAllocator = 0) :
- allocator_(allocator), ownAllocator_(0), stack_(stackAllocator, stackCapacity), parseResult_()
- {
- if (!allocator_)
- ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator());
- }
-
-#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
- //! Move constructor in C++11
- GenericDocument(GenericDocument&& rhs) RAPIDJSON_NOEXCEPT
- : ValueType(std::move(rhs)),
- allocator_(rhs.allocator_),
- ownAllocator_(rhs.ownAllocator_),
- stack_(std::move(rhs.stack_)),
- parseResult_(rhs.parseResult_)
- {
- rhs.allocator_ = 0;
- rhs.ownAllocator_ = 0;
- rhs.parseResult_ = ParseResult();
- }
-#endif
-
- ~GenericDocument() {
- Destroy();
- }
-
-#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
- //! Move assignment in C++11
- GenericDocument& operator=(GenericDocument&& rhs) RAPIDJSON_NOEXCEPT
- {
- // The cast to ValueType is necessary here, because otherwise it would
- // attempt to call GenericValue's templated assignment operator.
- ValueType::operator=(std::forward<ValueType>(rhs));
-
- // Calling the destructor here would prematurely call stack_'s destructor
- Destroy();
-
- allocator_ = rhs.allocator_;
- ownAllocator_ = rhs.ownAllocator_;
- stack_ = std::move(rhs.stack_);
- parseResult_ = rhs.parseResult_;
-
- rhs.allocator_ = 0;
- rhs.ownAllocator_ = 0;
- rhs.parseResult_ = ParseResult();
-
- return *this;
- }
-#endif
-
- //!@name Parse from stream
- //!@{
-
- //! Parse JSON text from an input stream (with Encoding conversion)
- /*! \tparam parseFlags Combination of \ref ParseFlag.
- \tparam SourceEncoding Encoding of input stream
- \tparam InputStream Type of input stream, implementing Stream concept
- \param is Input stream to be parsed.
- \return The document itself for fluent API.
- */
- template <unsigned parseFlags, typename SourceEncoding, typename InputStream>
- GenericDocument& ParseStream(InputStream& is) {
- ValueType::SetNull(); // Remove existing root if exist
- GenericReader<SourceEncoding, Encoding, Allocator> reader(&GetAllocator());
- ClearStackOnExit scope(*this);
- parseResult_ = reader.template Parse<parseFlags>(is, *this);
- if (parseResult_) {
- RAPIDJSON_ASSERT(stack_.GetSize() == sizeof(ValueType)); // Got one and only one root object
- this->RawAssign(*stack_.template Pop<ValueType>(1)); // Add this-> to prevent issue 13.
- }
- return *this;
- }
-
- //! Parse JSON text from an input stream
- /*! \tparam parseFlags Combination of \ref ParseFlag.
- \tparam InputStream Type of input stream, implementing Stream concept
- \param is Input stream to be parsed.
- \return The document itself for fluent API.
- */
- template <unsigned parseFlags, typename InputStream>
- GenericDocument& ParseStream(InputStream& is) {
- return ParseStream<parseFlags, Encoding, InputStream>(is);
- }
-
- //! Parse JSON text from an input stream (with \ref kParseDefaultFlags)
- /*! \tparam InputStream Type of input stream, implementing Stream concept
- \param is Input stream to be parsed.
- \return The document itself for fluent API.
- */
- template <typename InputStream>
- GenericDocument& ParseStream(InputStream& is) {
- return ParseStream<kParseDefaultFlags, Encoding, InputStream>(is);
- }
- //!@}
-
- //!@name Parse in-place from mutable string
- //!@{
-
- //! Parse JSON text from a mutable string
- /*! \tparam parseFlags Combination of \ref ParseFlag.
- \param str Mutable zero-terminated string to be parsed.
- \return The document itself for fluent API.
- */
- template <unsigned parseFlags>
- GenericDocument& ParseInsitu(Ch* str) {
- GenericInsituStringStream<Encoding> s(str);
- return ParseStream<parseFlags | kParseInsituFlag>(s);
- }
-
- //! Parse JSON text from a mutable string (with \ref kParseDefaultFlags)
- /*! \param str Mutable zero-terminated string to be parsed.
- \return The document itself for fluent API.
- */
- GenericDocument& ParseInsitu(Ch* str) {
- return ParseInsitu<kParseDefaultFlags>(str);
- }
- //!@}
-
- //!@name Parse from read-only string
- //!@{
-
- //! Parse JSON text from a read-only string (with Encoding conversion)
- /*! \tparam parseFlags Combination of \ref ParseFlag (must not contain \ref kParseInsituFlag).
- \tparam SourceEncoding Transcoding from input Encoding
- \param str Read-only zero-terminated string to be parsed.
- */
- template <unsigned parseFlags, typename SourceEncoding>
- GenericDocument& Parse(const Ch* str) {
- RAPIDJSON_ASSERT(!(parseFlags & kParseInsituFlag));
- GenericStringStream<SourceEncoding> s(str);
- return ParseStream<parseFlags, SourceEncoding>(s);
- }
-
- //! Parse JSON text from a read-only string
- /*! \tparam parseFlags Combination of \ref ParseFlag (must not contain \ref kParseInsituFlag).
- \param str Read-only zero-terminated string to be parsed.
- */
- template <unsigned parseFlags>
- GenericDocument& Parse(const Ch* str) {
- return Parse<parseFlags, Encoding>(str);
- }
-
- //! Parse JSON text from a read-only string (with \ref kParseDefaultFlags)
- /*! \param str Read-only zero-terminated string to be parsed.
- */
- GenericDocument& Parse(const Ch* str) {
- return Parse<kParseDefaultFlags>(str);
- }
- //!@}
-
- //!@name Handling parse errors
- //!@{
-
- //! Whether a parse error has occured in the last parsing.
- bool HasParseError() const { return parseResult_.IsError(); }
-
- //! Get the \ref ParseErrorCode of last parsing.
- ParseErrorCode GetParseError() const { return parseResult_.Code(); }
-
- //! Get the position of last parsing error in input, 0 otherwise.
- size_t GetErrorOffset() const { return parseResult_.Offset(); }
-
- //!@}
-
- //! Get the allocator of this document.
- Allocator& GetAllocator() { return *allocator_; }
-
- //! Get the capacity of stack in bytes.
- size_t GetStackCapacity() const { return stack_.GetCapacity(); }
-
-private:
- // clear stack on any exit from ParseStream, e.g. due to exception
- struct ClearStackOnExit {
- explicit ClearStackOnExit(GenericDocument& d) : d_(d) {}
- ~ClearStackOnExit() { d_.ClearStack(); }
- private:
- ClearStackOnExit(const ClearStackOnExit&);
- ClearStackOnExit& operator=(const ClearStackOnExit&);
- GenericDocument& d_;
- };
-
- // callers of the following private Handler functions
- template <typename,typename,typename> friend class GenericReader; // for parsing
- template <typename, typename> friend class GenericValue; // for deep copying
-
- // Implementation of Handler
- bool Null() { new (stack_.template Push<ValueType>()) ValueType(); return true; }
- bool Bool(bool b) { new (stack_.template Push<ValueType>()) ValueType(b); return true; }
- bool Int(int i) { new (stack_.template Push<ValueType>()) ValueType(i); return true; }
- bool Uint(unsigned i) { new (stack_.template Push<ValueType>()) ValueType(i); return true; }
- bool Int64(int64_t i) { new (stack_.template Push<ValueType>()) ValueType(i); return true; }
- bool Uint64(uint64_t i) { new (stack_.template Push<ValueType>()) ValueType(i); return true; }
- bool Double(double d) { new (stack_.template Push<ValueType>()) ValueType(d); return true; }
-
- bool String(const Ch* str, SizeType length, bool copy) {
- if (copy)
- new (stack_.template Push<ValueType>()) ValueType(str, length, GetAllocator());
- else
- new (stack_.template Push<ValueType>()) ValueType(str, length);
- return true;
- }
-
- bool StartObject() { new (stack_.template Push<ValueType>()) ValueType(kObjectType); return true; }
-
- bool Key(const Ch* str, SizeType length, bool copy) { return String(str, length, copy); }
-
- bool EndObject(SizeType memberCount) {
- typename ValueType::Member* members = stack_.template Pop<typename ValueType::Member>(memberCount);
- stack_.template Top<ValueType>()->SetObjectRaw(members, (SizeType)memberCount, GetAllocator());
- return true;
- }
-
- bool StartArray() { new (stack_.template Push<ValueType>()) ValueType(kArrayType); return true; }
-
- bool EndArray(SizeType elementCount) {
- ValueType* elements = stack_.template Pop<ValueType>(elementCount);
- stack_.template Top<ValueType>()->SetArrayRaw(elements, elementCount, GetAllocator());
- return true;
- }
-
-private:
- //! Prohibit copying
- GenericDocument(const GenericDocument&);
- //! Prohibit assignment
- GenericDocument& operator=(const GenericDocument&);
-
- void ClearStack() {
- if (Allocator::kNeedFree)
- while (stack_.GetSize() > 0) // Here assumes all elements in stack array are GenericValue (Member is actually 2 GenericValue objects)
- (stack_.template Pop<ValueType>(1))->~ValueType();
- else
- stack_.Clear();
- stack_.ShrinkToFit();
- }
-
- void Destroy() {
- RAPIDJSON_DELETE(ownAllocator_);
- }
-
- static const size_t kDefaultStackCapacity = 1024;
- Allocator* allocator_;
- Allocator* ownAllocator_;
- internal::Stack<StackAllocator> stack_;
- ParseResult parseResult_;
-};
-
-//! GenericDocument with UTF8 encoding
-typedef GenericDocument<UTF8<> > Document;
-
-// defined here due to the dependency on GenericDocument
-template <typename Encoding, typename Allocator>
-template <typename SourceAllocator>
-inline
-GenericValue<Encoding,Allocator>::GenericValue(const GenericValue<Encoding,SourceAllocator>& rhs, Allocator& allocator)
-{
- switch (rhs.GetType()) {
- case kObjectType:
- case kArrayType: { // perform deep copy via SAX Handler
- GenericDocument<Encoding,Allocator> d(&allocator);
- rhs.Accept(d);
- RawAssign(*d.stack_.template Pop<GenericValue>(1));
- }
- break;
- case kStringType:
- if (rhs.flags_ == kConstStringFlag) {
- flags_ = rhs.flags_;
- data_ = *reinterpret_cast<const Data*>(&rhs.data_);
- } else {
- SetStringRaw(StringRef(rhs.GetString(), rhs.GetStringLength()), allocator);
- }
- break;
- default: // kNumberType, kTrueType, kFalseType, kNullType
- flags_ = rhs.flags_;
- data_ = *reinterpret_cast<const Data*>(&rhs.data_);
- }
-}
-
-RAPIDJSON_NAMESPACE_END
-
-#if defined(_MSC_VER) || defined(__GNUC__)
-RAPIDJSON_DIAG_POP
-#endif
-
-#endif // RAPIDJSON_DOCUMENT_H_
diff --git a/libs/rapidjson/encodedstream.h b/libs/rapidjson/encodedstream.h
deleted file mode 100644
index 9a93b385f..000000000
--- a/libs/rapidjson/encodedstream.h
+++ /dev/null
@@ -1,261 +0,0 @@
-// Tencent is pleased to support the open source community by making RapidJSON available.
-//
-// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
-//
-// Licensed under the MIT License (the "License"); you may not use this file except
-// in compliance with the License. You may obtain a copy of the License at
-//
-// http://opensource.org/licenses/MIT
-//
-// Unless required by applicable law or agreed to in writing, software distributed
-// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
-// CONDITIONS OF ANY KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations under the License.
-
-#ifndef RAPIDJSON_ENCODEDSTREAM_H_
-#define RAPIDJSON_ENCODEDSTREAM_H_
-
-#include "rapidjson.h"
-
-#ifdef __GNUC__
-RAPIDJSON_DIAG_PUSH
-RAPIDJSON_DIAG_OFF(effc++)
-#endif
-
-RAPIDJSON_NAMESPACE_BEGIN
-
-//! Input byte stream wrapper with a statically bound encoding.
-/*!
- \tparam Encoding The interpretation of encoding of the stream. Either UTF8, UTF16LE, UTF16BE, UTF32LE, UTF32BE.
- \tparam InputByteStream Type of input byte stream. For example, FileReadStream.
-*/
-template <typename Encoding, typename InputByteStream>
-class EncodedInputStream {
- RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
-public:
- typedef typename Encoding::Ch Ch;
-
- EncodedInputStream(InputByteStream& is) : is_(is) {
- current_ = Encoding::TakeBOM(is_);
- }
-
- Ch Peek() const { return current_; }
- Ch Take() { Ch c = current_; current_ = Encoding::Take(is_); return c; }
- size_t Tell() const { return is_.Tell(); }
-
- // Not implemented
- void Put(Ch) { RAPIDJSON_ASSERT(false); }
- void Flush() { RAPIDJSON_ASSERT(false); }
- Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; }
- size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; }
-
-private:
- EncodedInputStream(const EncodedInputStream&);
- EncodedInputStream& operator=(const EncodedInputStream&);
-
- InputByteStream& is_;
- Ch current_;
-};
-
-//! Output byte stream wrapper with statically bound encoding.
-/*!
- \tparam Encoding The interpretation of encoding of the stream. Either UTF8, UTF16LE, UTF16BE, UTF32LE, UTF32BE.
- \tparam InputByteStream Type of input byte stream. For example, FileWriteStream.
-*/
-template <typename Encoding, typename OutputByteStream>
-class EncodedOutputStream {
- RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
-public:
- typedef typename Encoding::Ch Ch;
-
- EncodedOutputStream(OutputByteStream& os, bool putBOM = true) : os_(os) {
- if (putBOM)
- Encoding::PutBOM(os_);
- }
-
- void Put(Ch c) { Encoding::Put(os_, c); }
- void Flush() { os_.Flush(); }
-
- // Not implemented
- Ch Peek() const { RAPIDJSON_ASSERT(false); }
- Ch Take() { RAPIDJSON_ASSERT(false); }
- size_t Tell() const { RAPIDJSON_ASSERT(false); return 0; }
- Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; }
- size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; }
-
-private:
- EncodedOutputStream(const EncodedOutputStream&);
- EncodedOutputStream& operator=(const EncodedOutputStream&);
-
- OutputByteStream& os_;
-};
-
-#define RAPIDJSON_ENCODINGS_FUNC(x) UTF8<Ch>::x, UTF16LE<Ch>::x, UTF16BE<Ch>::x, UTF32LE<Ch>::x, UTF32BE<Ch>::x
-
-//! Input stream wrapper with dynamically bound encoding and automatic encoding detection.
-/*!
- \tparam CharType Type of character for reading.
- \tparam InputByteStream type of input byte stream to be wrapped.
-*/
-template <typename CharType, typename InputByteStream>
-class AutoUTFInputStream {
- RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
-public:
- typedef CharType Ch;
-
- //! Constructor.
- /*!
- \param is input stream to be wrapped.
- \param type UTF encoding type if it is not detected from the stream.
- */
- AutoUTFInputStream(InputByteStream& is, UTFType type = kUTF8) : is_(&is), type_(type), hasBOM_(false) {
- RAPIDJSON_ASSERT(type >= kUTF8 && type <= kUTF32BE);
- DetectType();
- static const TakeFunc f[] = { RAPIDJSON_ENCODINGS_FUNC(Take) };
- takeFunc_ = f[type_];
- current_ = takeFunc_(*is_);
- }
-
- UTFType GetType() const { return type_; }
- bool HasBOM() const { return hasBOM_; }
-
- Ch Peek() const { return current_; }
- Ch Take() { Ch c = current_; current_ = takeFunc_(*is_); return c; }
- size_t Tell() const { return is_->Tell(); }
-
- // Not implemented
- void Put(Ch) { RAPIDJSON_ASSERT(false); }
- void Flush() { RAPIDJSON_ASSERT(false); }
- Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; }
- size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; }
-
-private:
- AutoUTFInputStream(const AutoUTFInputStream&);
- AutoUTFInputStream& operator=(const AutoUTFInputStream&);
-
- // Detect encoding type with BOM or RFC 4627
- void DetectType() {
- // BOM (Byte Order Mark):
- // 00 00 FE FF UTF-32BE
- // FF FE 00 00 UTF-32LE
- // FE FF UTF-16BE
- // FF FE UTF-16LE
- // EF BB BF UTF-8
-
- const unsigned char* c = (const unsigned char *)is_->Peek4();
- if (!c)
- return;
-
- unsigned bom = c[0] | (c[1] << 8) | (c[2] << 16) | (c[3] << 24);
- hasBOM_ = false;
- if (bom == 0xFFFE0000) { type_ = kUTF32BE; hasBOM_ = true; is_->Take(); is_->Take(); is_->Take(); is_->Take(); }
- else if (bom == 0x0000FEFF) { type_ = kUTF32LE; hasBOM_ = true; is_->Take(); is_->Take(); is_->Take(); is_->Take(); }
- else if ((bom & 0xFFFF) == 0xFFFE) { type_ = kUTF16BE; hasBOM_ = true; is_->Take(); is_->Take(); }
- else if ((bom & 0xFFFF) == 0xFEFF) { type_ = kUTF16LE; hasBOM_ = true; is_->Take(); is_->Take(); }
- else if ((bom & 0xFFFFFF) == 0xBFBBEF) { type_ = kUTF8; hasBOM_ = true; is_->Take(); is_->Take(); is_->Take(); }
-
- // RFC 4627: Section 3
- // "Since the first two characters of a JSON text will always be ASCII
- // characters [RFC0020], it is possible to determine whether an octet
- // stream is UTF-8, UTF-16 (BE or LE), or UTF-32 (BE or LE) by looking
- // at the pattern of nulls in the first four octets."
- // 00 00 00 xx UTF-32BE
- // 00 xx 00 xx UTF-16BE
- // xx 00 00 00 UTF-32LE
- // xx 00 xx 00 UTF-16LE
- // xx xx xx xx UTF-8
-
- if (!hasBOM_) {
- unsigned pattern = (c[0] ? 1 : 0) | (c[1] ? 2 : 0) | (c[2] ? 4 : 0) | (c[3] ? 8 : 0);
- switch (pattern) {
- case 0x08: type_ = kUTF32BE; break;
- case 0x0A: type_ = kUTF16BE; break;
- case 0x01: type_ = kUTF32LE; break;
- case 0x05: type_ = kUTF16LE; break;
- case 0x0F: type_ = kUTF8; break;
- default: break; // Use type defined by user.
- }
- }
-
- // Runtime check whether the size of character type is sufficient. It only perform checks with assertion.
- if (type_ == kUTF16LE || type_ == kUTF16BE) RAPIDJSON_ASSERT(sizeof(Ch) >= 2);
- if (type_ == kUTF32LE || type_ == kUTF32BE) RAPIDJSON_ASSERT(sizeof(Ch) >= 4);
- }
-
- typedef Ch (*TakeFunc)(InputByteStream& is);
- InputByteStream* is_;
- UTFType type_;
- Ch current_;
- TakeFunc takeFunc_;
- bool hasBOM_;
-};
-
-//! Output stream wrapper with dynamically bound encoding and automatic encoding detection.
-/*!
- \tparam CharType Type of character for writing.
- \tparam InputByteStream type of output byte stream to be wrapped.
-*/
-template <typename CharType, typename OutputByteStream>
-class AutoUTFOutputStream {
- RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
-public:
- typedef CharType Ch;
-
- //! Constructor.
- /*!
- \param os output stream to be wrapped.
- \param type UTF encoding type.
- \param putBOM Whether to write BOM at the beginning of the stream.
- */
- AutoUTFOutputStream(OutputByteStream& os, UTFType type, bool putBOM) : os_(&os), type_(type) {
- RAPIDJSON_ASSERT(type >= kUTF8 && type <= kUTF32BE);
-
- // Runtime check whether the size of character type is sufficient. It only perform checks with assertion.
- if (type_ == kUTF16LE || type_ == kUTF16BE) RAPIDJSON_ASSERT(sizeof(Ch) >= 2);
- if (type_ == kUTF32LE || type_ == kUTF32BE) RAPIDJSON_ASSERT(sizeof(Ch) >= 4);
-
- static const PutFunc f[] = { RAPIDJSON_ENCODINGS_FUNC(Put) };
- putFunc_ = f[type_];
-
- if (putBOM)
- PutBOM();
- }
-
- UTFType GetType() const { return type_; }
-
- void Put(Ch c) { putFunc_(*os_, c); }
- void Flush() { os_->Flush(); }
-
- // Not implemented
- Ch Peek() const { RAPIDJSON_ASSERT(false); }
- Ch Take() { RAPIDJSON_ASSERT(false); }
- size_t Tell() const { RAPIDJSON_ASSERT(false); return 0; }
- Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; }
- size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; }
-
-private:
- AutoUTFOutputStream(const AutoUTFOutputStream&);
- AutoUTFOutputStream& operator=(const AutoUTFOutputStream&);
-
- void PutBOM() {
- typedef void (*PutBOMFunc)(OutputByteStream&);
- static const PutBOMFunc f[] = { RAPIDJSON_ENCODINGS_FUNC(PutBOM) };
- f[type_](*os_);
- }
-
- typedef void (*PutFunc)(OutputByteStream&, Ch);
-
- OutputByteStream* os_;
- UTFType type_;
- PutFunc putFunc_;
-};
-
-#undef RAPIDJSON_ENCODINGS_FUNC
-
-RAPIDJSON_NAMESPACE_END
-
-#ifdef __GNUC__
-RAPIDJSON_DIAG_POP
-#endif
-
-#endif // RAPIDJSON_FILESTREAM_H_
diff --git a/libs/rapidjson/encodings.h b/libs/rapidjson/encodings.h
deleted file mode 100644
index bc3cd8139..000000000
--- a/libs/rapidjson/encodings.h
+++ /dev/null
@@ -1,625 +0,0 @@
-// Tencent is pleased to support the open source community by making RapidJSON available.
-//
-// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
-//
-// Licensed under the MIT License (the "License"); you may not use this file except
-// in compliance with the License. You may obtain a copy of the License at
-//
-// http://opensource.org/licenses/MIT
-//
-// Unless required by applicable law or agreed to in writing, software distributed
-// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
-// CONDITIONS OF ANY KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations under the License.
-
-#ifndef RAPIDJSON_ENCODINGS_H_
-#define RAPIDJSON_ENCODINGS_H_
-
-#include "rapidjson.h"
-
-#ifdef _MSC_VER
-RAPIDJSON_DIAG_PUSH
-RAPIDJSON_DIAG_OFF(4244) // conversion from 'type1' to 'type2', possible loss of data
-RAPIDJSON_DIAG_OFF(4702) // unreachable code
-#elif defined(__GNUC__)
-RAPIDJSON_DIAG_PUSH
-RAPIDJSON_DIAG_OFF(effc++)
-RAPIDJSON_DIAG_OFF(overflow)
-#endif
-
-RAPIDJSON_NAMESPACE_BEGIN
-
-///////////////////////////////////////////////////////////////////////////////
-// Encoding
-
-/*! \class rapidjson::Encoding
- \brief Concept for encoding of Unicode characters.
-
-\code
-concept Encoding {
- typename Ch; //! Type of character. A "character" is actually a code unit in unicode's definition.
-
- enum { supportUnicode = 1 }; // or 0 if not supporting unicode
-
- //! \brief Encode a Unicode codepoint to an output stream.
- //! \param os Output stream.
- //! \param codepoint An unicode codepoint, ranging from 0x0 to 0x10FFFF inclusively.
- template<typename OutputStream>
- static void Encode(OutputStream& os, unsigned codepoint);
-
- //! \brief Decode a Unicode codepoint from an input stream.
- //! \param is Input stream.
- //! \param codepoint Output of the unicode codepoint.
- //! \return true if a valid codepoint can be decoded from the stream.
- template <typename InputStream>
- static bool Decode(InputStream& is, unsigned* codepoint);
-
- //! \brief Validate one Unicode codepoint from an encoded stream.
- //! \param is Input stream to obtain codepoint.
- //! \param os Output for copying one codepoint.
- //! \return true if it is valid.
- //! \note This function just validating and copying the codepoint without actually decode it.
- template <typename InputStream, typename OutputStream>
- static bool Validate(InputStream& is, OutputStream& os);
-
- // The following functions are deal with byte streams.
-
- //! Take a character from input byte stream, skip BOM if exist.
- template <typename InputByteStream>
- static CharType TakeBOM(InputByteStream& is);
-
- //! Take a character from input byte stream.
- template <typename InputByteStream>
- static Ch Take(InputByteStream& is);
-
- //! Put BOM to output byte stream.
- template <typename OutputByteStream>
- static void PutBOM(OutputByteStream& os);
-
- //! Put a character to output byte stream.
- template <typename OutputByteStream>
- static void Put(OutputByteStream& os, Ch c);
-};
-\endcode
-*/
-
-///////////////////////////////////////////////////////////////////////////////
-// UTF8
-
-//! UTF-8 encoding.
-/*! http://en.wikipedia.org/wiki/UTF-8
- http://tools.ietf.org/html/rfc3629
- \tparam CharType Code unit for storing 8-bit UTF-8 data. Default is char.
- \note implements Encoding concept
-*/
-template<typename CharType = char>
-struct UTF8 {
- typedef CharType Ch;
-
- enum { supportUnicode = 1 };
-
- template<typename OutputStream>
- static void Encode(OutputStream& os, unsigned codepoint) {
- if (codepoint <= 0x7F)
- os.Put(static_cast<Ch>(codepoint & 0xFF));
- else if (codepoint <= 0x7FF) {
- os.Put(static_cast<Ch>(0xC0 | ((codepoint >> 6) & 0xFF)));
- os.Put(static_cast<Ch>(0x80 | ((codepoint & 0x3F))));
- }
- else if (codepoint <= 0xFFFF) {
- os.Put(static_cast<Ch>(0xE0 | ((codepoint >> 12) & 0xFF)));
- os.Put(static_cast<Ch>(0x80 | ((codepoint >> 6) & 0x3F)));
- os.Put(static_cast<Ch>(0x80 | (codepoint & 0x3F)));
- }
- else {
- RAPIDJSON_ASSERT(codepoint <= 0x10FFFF);
- os.Put(static_cast<Ch>(0xF0 | ((codepoint >> 18) & 0xFF)));
- os.Put(static_cast<Ch>(0x80 | ((codepoint >> 12) & 0x3F)));
- os.Put(static_cast<Ch>(0x80 | ((codepoint >> 6) & 0x3F)));
- os.Put(static_cast<Ch>(0x80 | (codepoint & 0x3F)));
- }
- }
-
- template <typename InputStream>
- static bool Decode(InputStream& is, unsigned* codepoint) {
-#define COPY() c = is.Take(); *codepoint = (*codepoint << 6) | ((unsigned char)c & 0x3Fu)
-#define TRANS(mask) result &= ((GetRange((unsigned char)c) & mask) != 0)
-#define TAIL() COPY(); TRANS(0x70)
- Ch c = is.Take();
- if (!(c & 0x80)) {
- *codepoint = (unsigned char)c;
- return true;
- }
-
- unsigned char type = GetRange((unsigned char)c);
- *codepoint = (0xFF >> type) & (unsigned char)c;
- bool result = true;
- switch (type) {
- case 2: TAIL(); return result;
- case 3: TAIL(); TAIL(); return result;
- case 4: COPY(); TRANS(0x50); TAIL(); return result;
- case 5: COPY(); TRANS(0x10); TAIL(); TAIL(); return result;
- case 6: TAIL(); TAIL(); TAIL(); return result;
- case 10: COPY(); TRANS(0x20); TAIL(); return result;
- case 11: COPY(); TRANS(0x60); TAIL(); TAIL(); return result;
- default: return false;
- }
-#undef COPY
-#undef TRANS
-#undef TAIL
- }
-
- template <typename InputStream, typename OutputStream>
- static bool Validate(InputStream& is, OutputStream& os) {
-#define COPY() os.Put(c = is.Take())
-#define TRANS(mask) result &= ((GetRange((unsigned char)c) & mask) != 0)
-#define TAIL() COPY(); TRANS(0x70)
- Ch c;
- COPY();
- if (!(c & 0x80))
- return true;
-
- bool result = true;
- switch (GetRange((unsigned char)c)) {
- case 2: TAIL(); return result;
- case 3: TAIL(); TAIL(); return result;
- case 4: COPY(); TRANS(0x50); TAIL(); return result;
- case 5: COPY(); TRANS(0x10); TAIL(); TAIL(); return result;
- case 6: TAIL(); TAIL(); TAIL(); return result;
- case 10: COPY(); TRANS(0x20); TAIL(); return result;
- case 11: COPY(); TRANS(0x60); TAIL(); TAIL(); return result;
- default: return false;
- }
-#undef COPY
-#undef TRANS
-#undef TAIL
- }
-
- static unsigned char GetRange(unsigned char c) {
- // Referring to DFA of http://bjoern.hoehrmann.de/utf-8/decoder/dfa/
- // With new mapping 1 -> 0x10, 7 -> 0x20, 9 -> 0x40, such that AND operation can test multiple types.
- static const unsigned char type[] = {
- 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
- 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
- 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
- 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
- 0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,
- 0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,
- 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
- 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
- 8,8,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
- 10,3,3,3,3,3,3,3,3,3,3,3,3,4,3,3, 11,6,6,6,5,8,8,8,8,8,8,8,8,8,8,8,
- };
- return type[c];
- }
-
- template <typename InputByteStream>
- static CharType TakeBOM(InputByteStream& is) {
- RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
- Ch c = Take(is);
- if ((unsigned char)c != 0xEFu) return c;
- c = is.Take();
- if ((unsigned char)c != 0xBBu) return c;
- c = is.Take();
- if ((unsigned char)c != 0xBFu) return c;
- c = is.Take();
- return c;
- }
-
- template <typename InputByteStream>
- static Ch Take(InputByteStream& is) {
- RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
- return is.Take();
- }
-
- template <typename OutputByteStream>
- static void PutBOM(OutputByteStream& os) {
- RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
- os.Put(0xEFu); os.Put(0xBBu); os.Put(0xBFu);
- }
-
- template <typename OutputByteStream>
- static void Put(OutputByteStream& os, Ch c) {
- RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
- os.Put(static_cast<typename OutputByteStream::Ch>(c));
- }
-};
-
-///////////////////////////////////////////////////////////////////////////////
-// UTF16
-
-//! UTF-16 encoding.
-/*! http://en.wikipedia.org/wiki/UTF-16
- http://tools.ietf.org/html/rfc2781
- \tparam CharType Type for storing 16-bit UTF-16 data. Default is wchar_t. C++11 may use char16_t instead.
- \note implements Encoding concept
-
- \note For in-memory access, no need to concern endianness. The code units and code points are represented by CPU's endianness.
- For streaming, use UTF16LE and UTF16BE, which handle endianness.
-*/
-template<typename CharType = wchar_t>
-struct UTF16 {
- typedef CharType Ch;
- RAPIDJSON_STATIC_ASSERT(sizeof(Ch) >= 2);
-
- enum { supportUnicode = 1 };
-
- template<typename OutputStream>
- static void Encode(OutputStream& os, unsigned codepoint) {
- RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputStream::Ch) >= 2);
- if (codepoint <= 0xFFFF) {
- RAPIDJSON_ASSERT(codepoint < 0xD800 || codepoint > 0xDFFF); // Code point itself cannot be surrogate pair
- os.Put(static_cast<typename OutputStream::Ch>(codepoint));
- }
- else {
- RAPIDJSON_ASSERT(codepoint <= 0x10FFFF);
- unsigned v = codepoint - 0x10000;
- os.Put(static_cast<typename OutputStream::Ch>((v >> 10) | 0xD800));
- os.Put((v & 0x3FF) | 0xDC00);
- }
- }
-
- template <typename InputStream>
- static bool Decode(InputStream& is, unsigned* codepoint) {
- RAPIDJSON_STATIC_ASSERT(sizeof(typename InputStream::Ch) >= 2);
- Ch c = is.Take();
- if (c < 0xD800 || c > 0xDFFF) {
- *codepoint = c;
- return true;
- }
- else if (c <= 0xDBFF) {
- *codepoint = (c & 0x3FF) << 10;
- c = is.Take();
- *codepoint |= (c & 0x3FF);
- *codepoint += 0x10000;
- return c >= 0xDC00 && c <= 0xDFFF;
- }
- return false;
- }
-
- template <typename InputStream, typename OutputStream>
- static bool Validate(InputStream& is, OutputStream& os) {
- RAPIDJSON_STATIC_ASSERT(sizeof(typename InputStream::Ch) >= 2);
- RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputStream::Ch) >= 2);
- Ch c;
- os.Put(c = is.Take());
- if (c < 0xD800 || c > 0xDFFF)
- return true;
- else if (c <= 0xDBFF) {
- os.Put(c = is.Take());
- return c >= 0xDC00 && c <= 0xDFFF;
- }
- return false;
- }
-};
-
-//! UTF-16 little endian encoding.
-template<typename CharType = wchar_t>
-struct UTF16LE : UTF16<CharType> {
- template <typename InputByteStream>
- static CharType TakeBOM(InputByteStream& is) {
- RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
- CharType c = Take(is);
- return (unsigned short)c == 0xFEFFu ? Take(is) : c;
- }
-
- template <typename InputByteStream>
- static CharType Take(InputByteStream& is) {
- RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
- CharType c = (unsigned char)is.Take();
- c |= (unsigned char)is.Take() << 8;
- return c;
- }
-
- template <typename OutputByteStream>
- static void PutBOM(OutputByteStream& os) {
- RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
- os.Put(0xFFu); os.Put(0xFEu);
- }
-
- template <typename OutputByteStream>
- static void Put(OutputByteStream& os, CharType c) {
- RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
- os.Put(c & 0xFFu);
- os.Put((c >> 8) & 0xFFu);
- }
-};
-
-//! UTF-16 big endian encoding.
-template<typename CharType = wchar_t>
-struct UTF16BE : UTF16<CharType> {
- template <typename InputByteStream>
- static CharType TakeBOM(InputByteStream& is) {
- RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
- CharType c = Take(is);
- return (unsigned short)c == 0xFEFFu ? Take(is) : c;
- }
-
- template <typename InputByteStream>
- static CharType Take(InputByteStream& is) {
- RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
- CharType c = (unsigned char)is.Take() << 8;
- c |= (unsigned char)is.Take();
- return c;
- }
-
- template <typename OutputByteStream>
- static void PutBOM(OutputByteStream& os) {
- RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
- os.Put(0xFEu); os.Put(0xFFu);
- }
-
- template <typename OutputByteStream>
- static void Put(OutputByteStream& os, CharType c) {
- RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
- os.Put((c >> 8) & 0xFFu);
- os.Put(c & 0xFFu);
- }
-};
-
-///////////////////////////////////////////////////////////////////////////////
-// UTF32
-
-//! UTF-32 encoding.
-/*! http://en.wikipedia.org/wiki/UTF-32
- \tparam CharType Type for storing 32-bit UTF-32 data. Default is unsigned. C++11 may use char32_t instead.
- \note implements Encoding concept
-
- \note For in-memory access, no need to concern endianness. The code units and code points are represented by CPU's endianness.
- For streaming, use UTF32LE and UTF32BE, which handle endianness.
-*/
-template<typename CharType = unsigned>
-struct UTF32 {
- typedef CharType Ch;
- RAPIDJSON_STATIC_ASSERT(sizeof(Ch) >= 4);
-
- enum { supportUnicode = 1 };
-
- template<typename OutputStream>
- static void Encode(OutputStream& os, unsigned codepoint) {
- RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputStream::Ch) >= 4);
- RAPIDJSON_ASSERT(codepoint <= 0x10FFFF);
- os.Put(codepoint);
- }
-
- template <typename InputStream>
- static bool Decode(InputStream& is, unsigned* codepoint) {
- RAPIDJSON_STATIC_ASSERT(sizeof(typename InputStream::Ch) >= 4);
- Ch c = is.Take();
- *codepoint = c;
- return c <= 0x10FFFF;
- }
-
- template <typename InputStream, typename OutputStream>
- static bool Validate(InputStream& is, OutputStream& os) {
- RAPIDJSON_STATIC_ASSERT(sizeof(typename InputStream::Ch) >= 4);
- Ch c;
- os.Put(c = is.Take());
- return c <= 0x10FFFF;
- }
-};
-
-//! UTF-32 little endian enocoding.
-template<typename CharType = unsigned>
-struct UTF32LE : UTF32<CharType> {
- template <typename InputByteStream>
- static CharType TakeBOM(InputByteStream& is) {
- RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
- CharType c = Take(is);
- return (unsigned)c == 0x0000FEFFu ? Take(is) : c;
- }
-
- template <typename InputByteStream>
- static CharType Take(InputByteStream& is) {
- RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
- CharType c = (unsigned char)is.Take();
- c |= (unsigned char)is.Take() << 8;
- c |= (unsigned char)is.Take() << 16;
- c |= (unsigned char)is.Take() << 24;
- return c;
- }
-
- template <typename OutputByteStream>
- static void PutBOM(OutputByteStream& os) {
- RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
- os.Put(0xFFu); os.Put(0xFEu); os.Put(0x00u); os.Put(0x00u);
- }
-
- template <typename OutputByteStream>
- static void Put(OutputByteStream& os, CharType c) {
- RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
- os.Put(c & 0xFFu);
- os.Put((c >> 8) & 0xFFu);
- os.Put((c >> 16) & 0xFFu);
- os.Put((c >> 24) & 0xFFu);
- }
-};
-
-//! UTF-32 big endian encoding.
-template<typename CharType = unsigned>
-struct UTF32BE : UTF32<CharType> {
- template <typename InputByteStream>
- static CharType TakeBOM(InputByteStream& is) {
- RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
- CharType c = Take(is);
- return (unsigned)c == 0x0000FEFFu ? Take(is) : c;
- }
-
- template <typename InputByteStream>
- static CharType Take(InputByteStream& is) {
- RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
- CharType c = (unsigned char)is.Take() << 24;
- c |= (unsigned char)is.Take() << 16;
- c |= (unsigned char)is.Take() << 8;
- c |= (unsigned char)is.Take();
- return c;
- }
-
- template <typename OutputByteStream>
- static void PutBOM(OutputByteStream& os) {
- RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
- os.Put(0x00u); os.Put(0x00u); os.Put(0xFEu); os.Put(0xFFu);
- }
-
- template <typename OutputByteStream>
- static void Put(OutputByteStream& os, CharType c) {
- RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
- os.Put((c >> 24) & 0xFFu);
- os.Put((c >> 16) & 0xFFu);
- os.Put((c >> 8) & 0xFFu);
- os.Put(c & 0xFFu);
- }
-};
-
-///////////////////////////////////////////////////////////////////////////////
-// ASCII
-
-//! ASCII encoding.
-/*! http://en.wikipedia.org/wiki/ASCII
- \tparam CharType Code unit for storing 7-bit ASCII data. Default is char.
- \note implements Encoding concept
-*/
-template<typename CharType = char>
-struct ASCII {
- typedef CharType Ch;
-
- enum { supportUnicode = 0 };
-
- template<typename OutputStream>
- static void Encode(OutputStream& os, unsigned codepoint) {
- RAPIDJSON_ASSERT(codepoint <= 0x7F);
- os.Put(static_cast<Ch>(codepoint & 0xFF));
- }
-
- template <typename InputStream>
- static bool Decode(InputStream& is, unsigned* codepoint) {
- unsigned char c = static_cast<unsigned char>(is.Take());
- *codepoint = c;
- return c <= 0X7F;
- }
-
- template <typename InputStream, typename OutputStream>
- static bool Validate(InputStream& is, OutputStream& os) {
- unsigned char c = is.Take();
- os.Put(c);
- return c <= 0x7F;
- }
-
- template <typename InputByteStream>
- static CharType TakeBOM(InputByteStream& is) {
- RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
- Ch c = Take(is);
- return c;
- }
-
- template <typename InputByteStream>
- static Ch Take(InputByteStream& is) {
- RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
- return is.Take();
- }
-
- template <typename OutputByteStream>
- static void PutBOM(OutputByteStream& os) {
- RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
- (void)os;
- }
-
- template <typename OutputByteStream>
- static void Put(OutputByteStream& os, Ch c) {
- RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
- os.Put(static_cast<typename OutputByteStream::Ch>(c));
- }
-};
-
-///////////////////////////////////////////////////////////////////////////////
-// AutoUTF
-
-//! Runtime-specified UTF encoding type of a stream.
-enum UTFType {
- kUTF8 = 0, //!< UTF-8.
- kUTF16LE = 1, //!< UTF-16 little endian.
- kUTF16BE = 2, //!< UTF-16 big endian.
- kUTF32LE = 3, //!< UTF-32 little endian.
- kUTF32BE = 4 //!< UTF-32 big endian.
-};
-
-//! Dynamically select encoding according to stream's runtime-specified UTF encoding type.
-/*! \note This class can be used with AutoUTFInputtStream and AutoUTFOutputStream, which provides GetType().
-*/
-template<typename CharType>
-struct AutoUTF {
- typedef CharType Ch;
-
- enum { supportUnicode = 1 };
-
-#define RAPIDJSON_ENCODINGS_FUNC(x) UTF8<Ch>::x, UTF16LE<Ch>::x, UTF16BE<Ch>::x, UTF32LE<Ch>::x, UTF32BE<Ch>::x
-
- template<typename OutputStream>
- RAPIDJSON_FORCEINLINE static void Encode(OutputStream& os, unsigned codepoint) {
- typedef void (*EncodeFunc)(OutputStream&, unsigned);
- static const EncodeFunc f[] = { RAPIDJSON_ENCODINGS_FUNC(Encode) };
- (*f[os.GetType()])(os, codepoint);
- }
-
- template <typename InputStream>
- RAPIDJSON_FORCEINLINE static bool Decode(InputStream& is, unsigned* codepoint) {
- typedef bool (*DecodeFunc)(InputStream&, unsigned*);
- static const DecodeFunc f[] = { RAPIDJSON_ENCODINGS_FUNC(Decode) };
- return (*f[is.GetType()])(is, codepoint);
- }
-
- template <typename InputStream, typename OutputStream>
- RAPIDJSON_FORCEINLINE static bool Validate(InputStream& is, OutputStream& os) {
- typedef bool (*ValidateFunc)(InputStream&, OutputStream&);
- static const ValidateFunc f[] = { RAPIDJSON_ENCODINGS_FUNC(Validate) };
- return (*f[is.GetType()])(is, os);
- }
-
-#undef RAPIDJSON_ENCODINGS_FUNC
-};
-
-///////////////////////////////////////////////////////////////////////////////
-// Transcoder
-
-//! Encoding conversion.
-template<typename SourceEncoding, typename TargetEncoding>
-struct Transcoder {
- //! Take one Unicode codepoint from source encoding, convert it to target encoding and put it to the output stream.
- template<typename InputStream, typename OutputStream>
- RAPIDJSON_FORCEINLINE static bool Transcode(InputStream& is, OutputStream& os) {
- unsigned codepoint;
- if (!SourceEncoding::Decode(is, &codepoint))
- return false;
- TargetEncoding::Encode(os, codepoint);
- return true;
- }
-
- //! Validate one Unicode codepoint from an encoded stream.
- template<typename InputStream, typename OutputStream>
- RAPIDJSON_FORCEINLINE static bool Validate(InputStream& is, OutputStream& os) {
- return Transcode(is, os); // Since source/target encoding is different, must transcode.
- }
-};
-
-//! Specialization of Transcoder with same source and target encoding.
-template<typename Encoding>
-struct Transcoder<Encoding, Encoding> {
- template<typename InputStream, typename OutputStream>
- RAPIDJSON_FORCEINLINE static bool Transcode(InputStream& is, OutputStream& os) {
- os.Put(is.Take()); // Just copy one code unit. This semantic is different from primary template class.
- return true;
- }
-
- template<typename InputStream, typename OutputStream>
- RAPIDJSON_FORCEINLINE static bool Validate(InputStream& is, OutputStream& os) {
- return Encoding::Validate(is, os); // source/target encoding are the same
- }
-};
-
-RAPIDJSON_NAMESPACE_END
-
-#if defined(__GNUC__) || defined(_MSV_VER)
-RAPIDJSON_DIAG_POP
-#endif
-
-#endif // RAPIDJSON_ENCODINGS_H_
diff --git a/libs/rapidjson/error/en.h b/libs/rapidjson/error/en.h
deleted file mode 100644
index d5f9caab8..000000000
--- a/libs/rapidjson/error/en.h
+++ /dev/null
@@ -1,65 +0,0 @@
-// Tencent is pleased to support the open source community by making RapidJSON available.
-//
-// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
-//
-// Licensed under the MIT License (the "License"); you may not use this file except
-// in compliance with the License. You may obtain a copy of the License at
-//
-// http://opensource.org/licenses/MIT
-//
-// Unless required by applicable law or agreed to in writing, software distributed
-// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
-// CONDITIONS OF ANY KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations under the License.
-
-#ifndef RAPIDJSON_ERROR_EN_H__
-#define RAPIDJSON_ERROR_EN_H__
-
-#include "error.h"
-
-RAPIDJSON_NAMESPACE_BEGIN
-
-//! Maps error code of parsing into error message.
-/*!
- \ingroup RAPIDJSON_ERRORS
- \param parseErrorCode Error code obtained in parsing.
- \return the error message.
- \note User can make a copy of this function for localization.
- Using switch-case is safer for future modification of error codes.
-*/
-inline const RAPIDJSON_ERROR_CHARTYPE* GetParseError_En(ParseErrorCode parseErrorCode) {
- switch (parseErrorCode) {
- case kParseErrorNone: return RAPIDJSON_ERROR_STRING("No error.");
-
- case kParseErrorDocumentEmpty: return RAPIDJSON_ERROR_STRING("The document is empty.");
- case kParseErrorDocumentRootNotSingular: return RAPIDJSON_ERROR_STRING("The document root must not follow by other values.");
-
- case kParseErrorValueInvalid: return RAPIDJSON_ERROR_STRING("Invalid value.");
-
- case kParseErrorObjectMissName: return RAPIDJSON_ERROR_STRING("Missing a name for object member.");
- case kParseErrorObjectMissColon: return RAPIDJSON_ERROR_STRING("Missing a colon after a name of object member.");
- case kParseErrorObjectMissCommaOrCurlyBracket: return RAPIDJSON_ERROR_STRING("Missing a comma or '}' after an object member.");
-
- case kParseErrorArrayMissCommaOrSquareBracket: return RAPIDJSON_ERROR_STRING("Missing a comma or ']' after an array element.");
-
- case kParseErrorStringUnicodeEscapeInvalidHex: return RAPIDJSON_ERROR_STRING("Incorrect hex digit after \\u escape in string.");
- case kParseErrorStringUnicodeSurrogateInvalid: return RAPIDJSON_ERROR_STRING("The surrogate pair in string is invalid.");
- case kParseErrorStringEscapeInvalid: return RAPIDJSON_ERROR_STRING("Invalid escape character in string.");
- case kParseErrorStringMissQuotationMark: return RAPIDJSON_ERROR_STRING("Missing a closing quotation mark in string.");
- case kParseErrorStringInvalidEncoding: return RAPIDJSON_ERROR_STRING("Invalid encoding in string.");
-
- case kParseErrorNumberTooBig: return RAPIDJSON_ERROR_STRING("Number too big to be stored in double.");
- case kParseErrorNumberMissFraction: return RAPIDJSON_ERROR_STRING("Miss fraction part in number.");
- case kParseErrorNumberMissExponent: return RAPIDJSON_ERROR_STRING("Miss exponent in number.");
-
- case kParseErrorTermination: return RAPIDJSON_ERROR_STRING("Terminate parsing due to Handler error.");
- case kParseErrorUnspecificSyntaxError: return RAPIDJSON_ERROR_STRING("Unspecific syntax error.");
-
- default:
- return RAPIDJSON_ERROR_STRING("Unknown error.");
- }
-}
-
-RAPIDJSON_NAMESPACE_END
-
-#endif // RAPIDJSON_ERROR_EN_H__
diff --git a/libs/rapidjson/error/error.h b/libs/rapidjson/error/error.h
deleted file mode 100644
index aa5700ca8..000000000
--- a/libs/rapidjson/error/error.h
+++ /dev/null
@@ -1,144 +0,0 @@
-// Tencent is pleased to support the open source community by making RapidJSON available.
-//
-// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
-//
-// Licensed under the MIT License (the "License"); you may not use this file except
-// in compliance with the License. You may obtain a copy of the License at
-//
-// http://opensource.org/licenses/MIT
-//
-// Unless required by applicable law or agreed to in writing, software distributed
-// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
-// CONDITIONS OF ANY KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations under the License.
-
-#ifndef RAPIDJSON_ERROR_ERROR_H__
-#define RAPIDJSON_ERROR_ERROR_H__
-
-/*! \file error.h */
-
-/*! \defgroup RAPIDJSON_ERRORS RapidJSON error handling */
-
-///////////////////////////////////////////////////////////////////////////////
-// RAPIDJSON_ERROR_CHARTYPE
-
-//! Character type of error messages.
-/*! \ingroup RAPIDJSON_ERRORS
- The default character type is \c char.
- On Windows, user can define this macro as \c TCHAR for supporting both
- unicode/non-unicode settings.
-*/
-#ifndef RAPIDJSON_ERROR_CHARTYPE
-#define RAPIDJSON_ERROR_CHARTYPE char
-#endif
-
-///////////////////////////////////////////////////////////////////////////////
-// RAPIDJSON_ERROR_STRING
-
-//! Macro for converting string literial to \ref RAPIDJSON_ERROR_CHARTYPE[].
-/*! \ingroup RAPIDJSON_ERRORS
- By default this conversion macro does nothing.
- On Windows, user can define this macro as \c _T(x) for supporting both
- unicode/non-unicode settings.
-*/
-#ifndef RAPIDJSON_ERROR_STRING
-#define RAPIDJSON_ERROR_STRING(x) x
-#endif
-
-RAPIDJSON_NAMESPACE_BEGIN
-
-///////////////////////////////////////////////////////////////////////////////
-// ParseErrorCode
-
-//! Error code of parsing.
-/*! \ingroup RAPIDJSON_ERRORS
- \see GenericReader::Parse, GenericReader::GetParseErrorCode
-*/
-enum ParseErrorCode {
- kParseErrorNone = 0, //!< No error.
-
- kParseErrorDocumentEmpty, //!< The document is empty.
- kParseErrorDocumentRootNotSingular, //!< The document root must not follow by other values.
-
- kParseErrorValueInvalid, //!< Invalid value.
-
- kParseErrorObjectMissName, //!< Missing a name for object member.
- kParseErrorObjectMissColon, //!< Missing a colon after a name of object member.
- kParseErrorObjectMissCommaOrCurlyBracket, //!< Missing a comma or '}' after an object member.
-
- kParseErrorArrayMissCommaOrSquareBracket, //!< Missing a comma or ']' after an array element.
-
- kParseErrorStringUnicodeEscapeInvalidHex, //!< Incorrect hex digit after \\u escape in string.
- kParseErrorStringUnicodeSurrogateInvalid, //!< The surrogate pair in string is invalid.
- kParseErrorStringEscapeInvalid, //!< Invalid escape character in string.
- kParseErrorStringMissQuotationMark, //!< Missing a closing quotation mark in string.
- kParseErrorStringInvalidEncoding, //!< Invalid encoding in string.
-
- kParseErrorNumberTooBig, //!< Number too big to be stored in double.
- kParseErrorNumberMissFraction, //!< Miss fraction part in number.
- kParseErrorNumberMissExponent, //!< Miss exponent in number.
-
- kParseErrorTermination, //!< Parsing was terminated.
- kParseErrorUnspecificSyntaxError //!< Unspecific syntax error.
-};
-
-//! Result of parsing (wraps ParseErrorCode)
-/*!
- \ingroup RAPIDJSON_ERRORS
- \code
- Document doc;
- ParseResult ok = doc.Parse("[42]");
- if (!ok) {
- fprintf(stderr, "JSON parse error: %s (%u)",
- GetParseError_En(ok.Code()), ok.Offset());
- exit(EXIT_FAILURE);
- }
- \endcode
- \see GenericReader::Parse, GenericDocument::Parse
-*/
-struct ParseResult {
-
- //! Default constructor, no error.
- ParseResult() : code_(kParseErrorNone), offset_(0) {}
- //! Constructor to set an error.
- ParseResult(ParseErrorCode code, size_t offset) : code_(code), offset_(offset) {}
-
- //! Get the error code.
- ParseErrorCode Code() const { return code_; }
- //! Get the error offset, if \ref IsError(), 0 otherwise.
- size_t Offset() const { return offset_; }
-
- //! Conversion to \c bool, returns \c true, iff !\ref IsError().
- operator bool() const { return !IsError(); }
- //! Whether the result is an error.
- bool IsError() const { return code_ != kParseErrorNone; }
-
- bool operator==(const ParseResult& that) const { return code_ == that.code_; }
- bool operator==(ParseErrorCode code) const { return code_ == code; }
- friend bool operator==(ParseErrorCode code, const ParseResult & err) { return code == err.code_; }
-
- //! Reset error code.
- void Clear() { Set(kParseErrorNone); }
- //! Update error code and offset.
- void Set(ParseErrorCode code, size_t offset = 0) { code_ = code; offset_ = offset; }
-
-private:
- ParseErrorCode code_;
- size_t offset_;
-};
-
-//! Function pointer type of GetParseError().
-/*! \ingroup RAPIDJSON_ERRORS
-
- This is the prototype for \c GetParseError_X(), where \c X is a locale.
- User can dynamically change locale in runtime, e.g.:
-\code
- GetParseErrorFunc GetParseError = GetParseError_En; // or whatever
- const RAPIDJSON_ERROR_CHARTYPE* s = GetParseError(document.GetParseErrorCode());
-\endcode
-*/
-typedef const RAPIDJSON_ERROR_CHARTYPE* (*GetParseErrorFunc)(ParseErrorCode);
-
-RAPIDJSON_NAMESPACE_END
-
-#endif // RAPIDJSON_ERROR_ERROR_H__
diff --git a/libs/rapidjson/filereadstream.h b/libs/rapidjson/filereadstream.h
deleted file mode 100644
index 78ee403b6..000000000
--- a/libs/rapidjson/filereadstream.h
+++ /dev/null
@@ -1,88 +0,0 @@
-// Tencent is pleased to support the open source community by making RapidJSON available.
-//
-// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
-//
-// Licensed under the MIT License (the "License"); you may not use this file except
-// in compliance with the License. You may obtain a copy of the License at
-//
-// http://opensource.org/licenses/MIT
-//
-// Unless required by applicable law or agreed to in writing, software distributed
-// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
-// CONDITIONS OF ANY KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations under the License.
-
-#ifndef RAPIDJSON_FILEREADSTREAM_H_
-#define RAPIDJSON_FILEREADSTREAM_H_
-
-#include "rapidjson.h"
-#include <cstdio>
-
-RAPIDJSON_NAMESPACE_BEGIN
-
-//! File byte stream for input using fread().
-/*!
- \note implements Stream concept
-*/
-class FileReadStream {
-public:
- typedef char Ch; //!< Character type (byte).
-
- //! Constructor.
- /*!
- \param fp File pointer opened for read.
- \param buffer user-supplied buffer.
- \param bufferSize size of buffer in bytes. Must >=4 bytes.
- */
- FileReadStream(std::FILE* fp, char* buffer, size_t bufferSize) : fp_(fp), buffer_(buffer), bufferSize_(bufferSize), bufferLast_(0), current_(buffer_), readCount_(0), count_(0), eof_(false) {
- RAPIDJSON_ASSERT(fp_ != 0);
- RAPIDJSON_ASSERT(bufferSize >= 4);
- Read();
- }
-
- Ch Peek() const { return *current_; }
- Ch Take() { Ch c = *current_; Read(); return c; }
- size_t Tell() const { return count_ + static_cast<size_t>(current_ - buffer_); }
-
- // Not implemented
- void Put(Ch) { RAPIDJSON_ASSERT(false); }
- void Flush() { RAPIDJSON_ASSERT(false); }
- Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; }
- size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; }
-
- // For encoding detection only.
- const Ch* Peek4() const {
- return (current_ + 4 <= bufferLast_) ? current_ : 0;
- }
-
-private:
- void Read() {
- if (current_ < bufferLast_)
- ++current_;
- else if (!eof_) {
- count_ += readCount_;
- readCount_ = fread(buffer_, 1, bufferSize_, fp_);
- bufferLast_ = buffer_ + readCount_ - 1;
- current_ = buffer_;
-
- if (readCount_ < bufferSize_) {
- buffer_[readCount_] = '\0';
- ++bufferLast_;
- eof_ = true;
- }
- }
- }
-
- std::FILE* fp_;
- Ch *buffer_;
- size_t bufferSize_;
- Ch *bufferLast_;
- Ch *current_;
- size_t readCount_;
- size_t count_; //!< Number of characters read
- bool eof_;
-};
-
-RAPIDJSON_NAMESPACE_END
-
-#endif // RAPIDJSON_FILESTREAM_H_
diff --git a/libs/rapidjson/filewritestream.h b/libs/rapidjson/filewritestream.h
deleted file mode 100644
index 31223b8b3..000000000
--- a/libs/rapidjson/filewritestream.h
+++ /dev/null
@@ -1,91 +0,0 @@
-// Tencent is pleased to support the open source community by making RapidJSON available.
-//
-// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
-//
-// Licensed under the MIT License (the "License"); you may not use this file except
-// in compliance with the License. You may obtain a copy of the License at
-//
-// http://opensource.org/licenses/MIT
-//
-// Unless required by applicable law or agreed to in writing, software distributed
-// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
-// CONDITIONS OF ANY KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations under the License.
-
-#ifndef RAPIDJSON_FILEWRITESTREAM_H_
-#define RAPIDJSON_FILEWRITESTREAM_H_
-
-#include "rapidjson.h"
-#include <cstdio>
-
-RAPIDJSON_NAMESPACE_BEGIN
-
-//! Wrapper of C file stream for input using fread().
-/*!
- \note implements Stream concept
-*/
-class FileWriteStream {
-public:
- typedef char Ch; //!< Character type. Only support char.
-
- FileWriteStream(std::FILE* fp, char* buffer, size_t bufferSize) : fp_(fp), buffer_(buffer), bufferEnd_(buffer + bufferSize), current_(buffer_) {
- RAPIDJSON_ASSERT(fp_ != 0);
- }
-
- void Put(char c) {
- if (current_ >= bufferEnd_)
- Flush();
-
- *current_++ = c;
- }
-
- void PutN(char c, size_t n) {
- size_t avail = static_cast<size_t>(bufferEnd_ - current_);
- while (n > avail) {
- std::memset(current_, c, avail);
- current_ += avail;
- Flush();
- n -= avail;
- avail = static_cast<size_t>(bufferEnd_ - current_);
- }
-
- if (n > 0) {
- std::memset(current_, c, n);
- current_ += n;
- }
- }
-
- void Flush() {
- if (current_ != buffer_) {
- fwrite(buffer_, 1, static_cast<size_t>(current_ - buffer_), fp_);
- current_ = buffer_;
- }
- }
-
- // Not implemented
- char Peek() const { RAPIDJSON_ASSERT(false); return 0; }
- char Take() { RAPIDJSON_ASSERT(false); return 0; }
- size_t Tell() const { RAPIDJSON_ASSERT(false); return 0; }
- char* PutBegin() { RAPIDJSON_ASSERT(false); return 0; }
- size_t PutEnd(char*) { RAPIDJSON_ASSERT(false); return 0; }
-
-private:
- // Prohibit copy constructor & assignment operator.
- FileWriteStream(const FileWriteStream&);
- FileWriteStream& operator=(const FileWriteStream&);
-
- std::FILE* fp_;
- char *buffer_;
- char *bufferEnd_;
- char *current_;
-};
-
-//! Implement specialized version of PutN() with memset() for better performance.
-template<>
-inline void PutN(FileWriteStream& stream, char c, size_t n) {
- stream.PutN(c, n);
-}
-
-RAPIDJSON_NAMESPACE_END
-
-#endif // RAPIDJSON_FILESTREAM_H_
diff --git a/libs/rapidjson/internal/biginteger.h b/libs/rapidjson/internal/biginteger.h
deleted file mode 100644
index 5baba9bec..000000000
--- a/libs/rapidjson/internal/biginteger.h
+++ /dev/null
@@ -1,280 +0,0 @@
-// Tencent is pleased to support the open source community by making RapidJSON available.
-//
-// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
-//
-// Licensed under the MIT License (the "License"); you may not use this file except
-// in compliance with the License. You may obtain a copy of the License at
-//
-// http://opensource.org/licenses/MIT
-//
-// Unless required by applicable law or agreed to in writing, software distributed
-// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
-// CONDITIONS OF ANY KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations under the License.
-
-#ifndef RAPIDJSON_BIGINTEGER_H_
-#define RAPIDJSON_BIGINTEGER_H_
-
-#include "../rapidjson.h"
-
-#if defined(_MSC_VER) && defined(_M_AMD64)
-#include <intrin.h> // for _umul128
-#endif
-
-RAPIDJSON_NAMESPACE_BEGIN
-namespace internal {
-
-class BigInteger {
-public:
- typedef uint64_t Type;
-
- BigInteger(const BigInteger& rhs) : count_(rhs.count_) {
- std::memcpy(digits_, rhs.digits_, count_ * sizeof(Type));
- }
-
- explicit BigInteger(uint64_t u) : count_(1) {
- digits_[0] = u;
- }
-
- BigInteger(const char* decimals, size_t length) : count_(1) {
- RAPIDJSON_ASSERT(length > 0);
- digits_[0] = 0;
- size_t i = 0;
- const size_t kMaxDigitPerIteration = 19; // 2^64 = 18446744073709551616 > 10^19
- while (length >= kMaxDigitPerIteration) {
- AppendDecimal64(decimals + i, decimals + i + kMaxDigitPerIteration);
- length -= kMaxDigitPerIteration;
- i += kMaxDigitPerIteration;
- }
-
- if (length > 0)
- AppendDecimal64(decimals + i, decimals + i + length);
- }
-
- BigInteger& operator=(uint64_t u) {
- digits_[0] = u;
- count_ = 1;
- return *this;
- }
-
- BigInteger& operator+=(uint64_t u) {
- Type backup = digits_[0];
- digits_[0] += u;
- for (size_t i = 0; i < count_ - 1; i++) {
- if (digits_[i] >= backup)
- return *this; // no carry
- backup = digits_[i + 1];
- digits_[i + 1] += 1;
- }
-
- // Last carry
- if (digits_[count_ - 1] < backup)
- PushBack(1);
-
- return *this;
- }
-
- BigInteger& operator*=(uint64_t u) {
- if (u == 0) return *this = 0;
- if (u == 1) return *this;
- if (*this == 1) return *this = u;
-
- uint64_t k = 0;
- for (size_t i = 0; i < count_; i++) {
- uint64_t hi;
- digits_[i] = MulAdd64(digits_[i], u, k, &hi);
- k = hi;
- }
-
- if (k > 0)
- PushBack(k);
-
- return *this;
- }
-
- BigInteger& operator*=(uint32_t u) {
- if (u == 0) return *this = 0;
- if (u == 1) return *this;
- if (*this == 1) return *this = u;
-
- uint32_t k = 0;
- for (size_t i = 0; i < count_; i++) {
- const uint64_t c = digits_[i] >> 32;
- const uint64_t d = digits_[i] & 0xFFFFFFFF;
- const uint64_t uc = u * c;
- const uint64_t ud = u * d;
- const uint64_t p0 = ud + k;
- const uint64_t p1 = uc + (p0 >> 32);
- digits_[i] = (p0 & 0xFFFFFFFF) | (p1 << 32);
- k = p1 >> 32;
- }
-
- if (k > 0)
- PushBack(k);
-
- return *this;
- }
-
- BigInteger& operator<<=(size_t shift) {
- if (IsZero() || shift == 0) return *this;
-
- size_t offset = shift / kTypeBit;
- size_t interShift = shift % kTypeBit;
- RAPIDJSON_ASSERT(count_ + offset <= kCapacity);
-
- if (interShift == 0) {
- std::memmove(&digits_[count_ - 1 + offset], &digits_[count_ - 1], count_ * sizeof(Type));
- count_ += offset;
- }
- else {
- digits_[count_] = 0;
- for (size_t i = count_; i > 0; i--)
- digits_[i + offset] = (digits_[i] << interShift) | (digits_[i - 1] >> (kTypeBit - interShift));
- digits_[offset] = digits_[0] << interShift;
- count_ += offset;
- if (digits_[count_])
- count_++;
- }
-
- std::memset(digits_, 0, offset * sizeof(Type));
-
- return *this;
- }
-
- bool operator==(const BigInteger& rhs) const {
- return count_ == rhs.count_ && std::memcmp(digits_, rhs.digits_, count_ * sizeof(Type)) == 0;
- }
-
- bool operator==(const Type rhs) const {
- return count_ == 1 && digits_[0] == rhs;
- }
-
- BigInteger& MultiplyPow5(unsigned exp) {
- static const uint32_t kPow5[12] = {
- 5,
- 5 * 5,
- 5 * 5 * 5,
- 5 * 5 * 5 * 5,
- 5 * 5 * 5 * 5 * 5,
- 5 * 5 * 5 * 5 * 5 * 5,
- 5 * 5 * 5 * 5 * 5 * 5 * 5,
- 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
- 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
- 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
- 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
- 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5
- };
- if (exp == 0) return *this;
- for (; exp >= 27; exp -= 27) *this *= RAPIDJSON_UINT64_C2(0X6765C793, 0XFA10079D); // 5^27
- for (; exp >= 13; exp -= 13) *this *= static_cast<uint32_t>(1220703125u); // 5^13
- if (exp > 0) *this *= kPow5[exp - 1];
- return *this;
- }
-
- // Compute absolute difference of this and rhs.
- // Assume this != rhs
- bool Difference(const BigInteger& rhs, BigInteger* out) const {
- int cmp = Compare(rhs);
- RAPIDJSON_ASSERT(cmp != 0);
- const BigInteger *a, *b; // Makes a > b
- bool ret;
- if (cmp < 0) { a = &rhs; b = this; ret = true; }
- else { a = this; b = &rhs; ret = false; }
-
- Type borrow = 0;
- for (size_t i = 0; i < a->count_; i++) {
- Type d = a->digits_[i] - borrow;
- if (i < b->count_)
- d -= b->digits_[i];
- borrow = (d > a->digits_[i]) ? 1 : 0;
- out->digits_[i] = d;
- if (d != 0)
- out->count_ = i + 1;
- }
-
- return ret;
- }
-
- int Compare(const BigInteger& rhs) const {
- if (count_ != rhs.count_)
- return count_ < rhs.count_ ? -1 : 1;
-
- for (size_t i = count_; i-- > 0;)
- if (digits_[i] != rhs.digits_[i])
- return digits_[i] < rhs.digits_[i] ? -1 : 1;
-
- return 0;
- }
-
- size_t GetCount() const { return count_; }
- Type GetDigit(size_t index) const { RAPIDJSON_ASSERT(index < count_); return digits_[index]; }
- bool IsZero() const { return count_ == 1 && digits_[0] == 0; }
-
-private:
- void AppendDecimal64(const char* begin, const char* end) {
- uint64_t u = ParseUint64(begin, end);
- if (IsZero())
- *this = u;
- else {
- unsigned exp = static_cast<unsigned>(end - begin);
- (MultiplyPow5(exp) <<= exp) += u; // *this = *this * 10^exp + u
- }
- }
-
- void PushBack(Type digit) {
- RAPIDJSON_ASSERT(count_ < kCapacity);
- digits_[count_++] = digit;
- }
-
- static uint64_t ParseUint64(const char* begin, const char* end) {
- uint64_t r = 0;
- for (const char* p = begin; p != end; ++p) {
- RAPIDJSON_ASSERT(*p >= '0' && *p <= '9');
- r = r * 10 + (*p - '0');
- }
- return r;
- }
-
- // Assume a * b + k < 2^128
- static uint64_t MulAdd64(uint64_t a, uint64_t b, uint64_t k, uint64_t* outHigh) {
-#if defined(_MSC_VER) && defined(_M_AMD64)
- uint64_t low = _umul128(a, b, outHigh) + k;
- if (low < k)
- (*outHigh)++;
- return low;
-#elif (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) && defined(__x86_64__)
- __extension__ typedef unsigned __int128 uint128;
- uint128 p = static_cast<uint128>(a) * static_cast<uint128>(b);
- p += k;
- *outHigh = p >> 64;
- return static_cast<uint64_t>(p);
-#else
- const uint64_t a0 = a & 0xFFFFFFFF, a1 = a >> 32, b0 = b & 0xFFFFFFFF, b1 = b >> 32;
- uint64_t x0 = a0 * b0, x1 = a0 * b1, x2 = a1 * b0, x3 = a1 * b1;
- x1 += (x0 >> 32); // can't give carry
- x1 += x2;
- if (x1 < x2)
- x3 += (static_cast<uint64_t>(1) << 32);
- uint64_t lo = (x1 << 32) + (x0 & 0xFFFFFFFF);
- uint64_t hi = x3 + (x1 >> 32);
-
- lo += k;
- if (lo < k)
- hi++;
- *outHigh = hi;
- return lo;
-#endif
- }
-
- static const size_t kBitCount = 3328; // 64bit * 54 > 10^1000
- static const size_t kCapacity = kBitCount / sizeof(Type);
- static const size_t kTypeBit = sizeof(Type) * 8;
-
- Type digits_[kCapacity];
- size_t count_;
-};
-
-} // namespace internal
-RAPIDJSON_NAMESPACE_END
-
-#endif // RAPIDJSON_BIGINTEGER_H_
diff --git a/libs/rapidjson/internal/diyfp.h b/libs/rapidjson/internal/diyfp.h
deleted file mode 100644
index de3d1f01a..000000000
--- a/libs/rapidjson/internal/diyfp.h
+++ /dev/null
@@ -1,247 +0,0 @@
-// Tencent is pleased to support the open source community by making RapidJSON available.
-//
-// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
-//
-// Licensed under the MIT License (the "License"); you may not use this file except
-// in compliance with the License. You may obtain a copy of the License at
-//
-// http://opensource.org/licenses/MIT
-//
-// Unless required by applicable law or agreed to in writing, software distributed
-// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
-// CONDITIONS OF ANY KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations under the License.
-
-// This is a C++ header-only implementation of Grisu2 algorithm from the publication:
-// Loitsch, Florian. "Printing floating-point numbers quickly and accurately with
-// integers." ACM Sigplan Notices 45.6 (2010): 233-243.
-
-#ifndef RAPIDJSON_DIYFP_H_
-#define RAPIDJSON_DIYFP_H_
-
-#if defined(_MSC_VER)
-#include <intrin.h>
-#if defined(_M_AMD64)
-#pragma intrinsic(_BitScanReverse64)
-#endif
-#endif
-
-RAPIDJSON_NAMESPACE_BEGIN
-namespace internal {
-
-#ifdef __GNUC__
-RAPIDJSON_DIAG_PUSH
-RAPIDJSON_DIAG_OFF(effc++)
-#endif
-
-struct DiyFp {
- DiyFp() {}
-
- DiyFp(uint64_t fp, int exp) : f(fp), e(exp) {}
-
- explicit DiyFp(double d) {
- union {
- double d;
- uint64_t u64;
- } u = { d };
-
- int biased_e = (u.u64 & kDpExponentMask) >> kDpSignificandSize;
- uint64_t significand = (u.u64 & kDpSignificandMask);
- if (biased_e != 0) {
- f = significand + kDpHiddenBit;
- e = biased_e - kDpExponentBias;
- }
- else {
- f = significand;
- e = kDpMinExponent + 1;
- }
- }
-
- DiyFp operator-(const DiyFp& rhs) const {
- return DiyFp(f - rhs.f, e);
- }
-
- DiyFp operator*(const DiyFp& rhs) const {
-#if defined(_MSC_VER) && defined(_M_AMD64)
- uint64_t h;
- uint64_t l = _umul128(f, rhs.f, &h);
- if (l & (uint64_t(1) << 63)) // rounding
- h++;
- return DiyFp(h, e + rhs.e + 64);
-#elif (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) && defined(__x86_64__)
- __extension__ typedef unsigned __int128 uint128;
- uint128 p = static_cast<uint128>(f) * static_cast<uint128>(rhs.f);
- uint64_t h = p >> 64;
- uint64_t l = static_cast<uint64_t>(p);
- if (l & (uint64_t(1) << 63)) // rounding
- h++;
- return DiyFp(h, e + rhs.e + 64);
-#else
- const uint64_t M32 = 0xFFFFFFFF;
- const uint64_t a = f >> 32;
- const uint64_t b = f & M32;
- const uint64_t c = rhs.f >> 32;
- const uint64_t d = rhs.f & M32;
- const uint64_t ac = a * c;
- const uint64_t bc = b * c;
- const uint64_t ad = a * d;
- const uint64_t bd = b * d;
- uint64_t tmp = (bd >> 32) + (ad & M32) + (bc & M32);
- tmp += 1U << 31; /// mult_round
- return DiyFp(ac + (ad >> 32) + (bc >> 32) + (tmp >> 32), e + rhs.e + 64);
-#endif
- }
-
- DiyFp Normalize() const {
-#if defined(_MSC_VER) && defined(_M_AMD64)
- unsigned long index;
- _BitScanReverse64(&index, f);
- return DiyFp(f << (63 - index), e - (63 - index));
-#elif defined(__GNUC__) && __GNUC__ >= 4
- int s = __builtin_clzll(f);
- return DiyFp(f << s, e - s);
-#else
- DiyFp res = *this;
- while (!(res.f & (static_cast<uint64_t>(1) << 63))) {
- res.f <<= 1;
- res.e--;
- }
- return res;
-#endif
- }
-
- DiyFp NormalizeBoundary() const {
- DiyFp res = *this;
- while (!(res.f & (kDpHiddenBit << 1))) {
- res.f <<= 1;
- res.e--;
- }
- res.f <<= (kDiySignificandSize - kDpSignificandSize - 2);
- res.e = res.e - (kDiySignificandSize - kDpSignificandSize - 2);
- return res;
- }
-
- void NormalizedBoundaries(DiyFp* minus, DiyFp* plus) const {
- DiyFp pl = DiyFp((f << 1) + 1, e - 1).NormalizeBoundary();
- DiyFp mi = (f == kDpHiddenBit) ? DiyFp((f << 2) - 1, e - 2) : DiyFp((f << 1) - 1, e - 1);
- mi.f <<= mi.e - pl.e;
- mi.e = pl.e;
- *plus = pl;
- *minus = mi;
- }
-
- double ToDouble() const {
- union {
- double d;
- uint64_t u64;
- }u;
- const uint64_t be = (e == kDpDenormalExponent && (f & kDpHiddenBit) == 0) ? 0 :
- static_cast<uint64_t>(e + kDpExponentBias);
- u.u64 = (f & kDpSignificandMask) | (be << kDpSignificandSize);
- return u.d;
- }
-
- static const int kDiySignificandSize = 64;
- static const int kDpSignificandSize = 52;
- static const int kDpExponentBias = 0x3FF + kDpSignificandSize;
- static const int kDpMaxExponent = 0x7FF - kDpExponentBias;
- static const int kDpMinExponent = -kDpExponentBias;
- static const int kDpDenormalExponent = -kDpExponentBias + 1;
- static const uint64_t kDpExponentMask = RAPIDJSON_UINT64_C2(0x7FF00000, 0x00000000);
- static const uint64_t kDpSignificandMask = RAPIDJSON_UINT64_C2(0x000FFFFF, 0xFFFFFFFF);
- static const uint64_t kDpHiddenBit = RAPIDJSON_UINT64_C2(0x00100000, 0x00000000);
-
- uint64_t f;
- int e;
-};
-
-inline DiyFp GetCachedPowerByIndex(size_t index) {
- // 10^-348, 10^-340, ..., 10^340
- static const uint64_t kCachedPowers_F[] = {
- RAPIDJSON_UINT64_C2(0xfa8fd5a0, 0x081c0288), RAPIDJSON_UINT64_C2(0xbaaee17f, 0xa23ebf76),
- RAPIDJSON_UINT64_C2(0x8b16fb20, 0x3055ac76), RAPIDJSON_UINT64_C2(0xcf42894a, 0x5dce35ea),
- RAPIDJSON_UINT64_C2(0x9a6bb0aa, 0x55653b2d), RAPIDJSON_UINT64_C2(0xe61acf03, 0x3d1a45df),
- RAPIDJSON_UINT64_C2(0xab70fe17, 0xc79ac6ca), RAPIDJSON_UINT64_C2(0xff77b1fc, 0xbebcdc4f),
- RAPIDJSON_UINT64_C2(0xbe5691ef, 0x416bd60c), RAPIDJSON_UINT64_C2(0x8dd01fad, 0x907ffc3c),
- RAPIDJSON_UINT64_C2(0xd3515c28, 0x31559a83), RAPIDJSON_UINT64_C2(0x9d71ac8f, 0xada6c9b5),
- RAPIDJSON_UINT64_C2(0xea9c2277, 0x23ee8bcb), RAPIDJSON_UINT64_C2(0xaecc4991, 0x4078536d),
- RAPIDJSON_UINT64_C2(0x823c1279, 0x5db6ce57), RAPIDJSON_UINT64_C2(0xc2109436, 0x4dfb5637),
- RAPIDJSON_UINT64_C2(0x9096ea6f, 0x3848984f), RAPIDJSON_UINT64_C2(0xd77485cb, 0x25823ac7),
- RAPIDJSON_UINT64_C2(0xa086cfcd, 0x97bf97f4), RAPIDJSON_UINT64_C2(0xef340a98, 0x172aace5),
- RAPIDJSON_UINT64_C2(0xb23867fb, 0x2a35b28e), RAPIDJSON_UINT64_C2(0x84c8d4df, 0xd2c63f3b),
- RAPIDJSON_UINT64_C2(0xc5dd4427, 0x1ad3cdba), RAPIDJSON_UINT64_C2(0x936b9fce, 0xbb25c996),
- RAPIDJSON_UINT64_C2(0xdbac6c24, 0x7d62a584), RAPIDJSON_UINT64_C2(0xa3ab6658, 0x0d5fdaf6),
- RAPIDJSON_UINT64_C2(0xf3e2f893, 0xdec3f126), RAPIDJSON_UINT64_C2(0xb5b5ada8, 0xaaff80b8),
- RAPIDJSON_UINT64_C2(0x87625f05, 0x6c7c4a8b), RAPIDJSON_UINT64_C2(0xc9bcff60, 0x34c13053),
- RAPIDJSON_UINT64_C2(0x964e858c, 0x91ba2655), RAPIDJSON_UINT64_C2(0xdff97724, 0x70297ebd),
- RAPIDJSON_UINT64_C2(0xa6dfbd9f, 0xb8e5b88f), RAPIDJSON_UINT64_C2(0xf8a95fcf, 0x88747d94),
- RAPIDJSON_UINT64_C2(0xb9447093, 0x8fa89bcf), RAPIDJSON_UINT64_C2(0x8a08f0f8, 0xbf0f156b),
- RAPIDJSON_UINT64_C2(0xcdb02555, 0x653131b6), RAPIDJSON_UINT64_C2(0x993fe2c6, 0xd07b7fac),
- RAPIDJSON_UINT64_C2(0xe45c10c4, 0x2a2b3b06), RAPIDJSON_UINT64_C2(0xaa242499, 0x697392d3),
- RAPIDJSON_UINT64_C2(0xfd87b5f2, 0x8300ca0e), RAPIDJSON_UINT64_C2(0xbce50864, 0x92111aeb),
- RAPIDJSON_UINT64_C2(0x8cbccc09, 0x6f5088cc), RAPIDJSON_UINT64_C2(0xd1b71758, 0xe219652c),
- RAPIDJSON_UINT64_C2(0x9c400000, 0x00000000), RAPIDJSON_UINT64_C2(0xe8d4a510, 0x00000000),
- RAPIDJSON_UINT64_C2(0xad78ebc5, 0xac620000), RAPIDJSON_UINT64_C2(0x813f3978, 0xf8940984),
- RAPIDJSON_UINT64_C2(0xc097ce7b, 0xc90715b3), RAPIDJSON_UINT64_C2(0x8f7e32ce, 0x7bea5c70),
- RAPIDJSON_UINT64_C2(0xd5d238a4, 0xabe98068), RAPIDJSON_UINT64_C2(0x9f4f2726, 0x179a2245),
- RAPIDJSON_UINT64_C2(0xed63a231, 0xd4c4fb27), RAPIDJSON_UINT64_C2(0xb0de6538, 0x8cc8ada8),
- RAPIDJSON_UINT64_C2(0x83c7088e, 0x1aab65db), RAPIDJSON_UINT64_C2(0xc45d1df9, 0x42711d9a),
- RAPIDJSON_UINT64_C2(0x924d692c, 0xa61be758), RAPIDJSON_UINT64_C2(0xda01ee64, 0x1a708dea),
- RAPIDJSON_UINT64_C2(0xa26da399, 0x9aef774a), RAPIDJSON_UINT64_C2(0xf209787b, 0xb47d6b85),
- RAPIDJSON_UINT64_C2(0xb454e4a1, 0x79dd1877), RAPIDJSON_UINT64_C2(0x865b8692, 0x5b9bc5c2),
- RAPIDJSON_UINT64_C2(0xc83553c5, 0xc8965d3d), RAPIDJSON_UINT64_C2(0x952ab45c, 0xfa97a0b3),
- RAPIDJSON_UINT64_C2(0xde469fbd, 0x99a05fe3), RAPIDJSON_UINT64_C2(0xa59bc234, 0xdb398c25),
- RAPIDJSON_UINT64_C2(0xf6c69a72, 0xa3989f5c), RAPIDJSON_UINT64_C2(0xb7dcbf53, 0x54e9bece),
- RAPIDJSON_UINT64_C2(0x88fcf317, 0xf22241e2), RAPIDJSON_UINT64_C2(0xcc20ce9b, 0xd35c78a5),
- RAPIDJSON_UINT64_C2(0x98165af3, 0x7b2153df), RAPIDJSON_UINT64_C2(0xe2a0b5dc, 0x971f303a),
- RAPIDJSON_UINT64_C2(0xa8d9d153, 0x5ce3b396), RAPIDJSON_UINT64_C2(0xfb9b7cd9, 0xa4a7443c),
- RAPIDJSON_UINT64_C2(0xbb764c4c, 0xa7a44410), RAPIDJSON_UINT64_C2(0x8bab8eef, 0xb6409c1a),
- RAPIDJSON_UINT64_C2(0xd01fef10, 0xa657842c), RAPIDJSON_UINT64_C2(0x9b10a4e5, 0xe9913129),
- RAPIDJSON_UINT64_C2(0xe7109bfb, 0xa19c0c9d), RAPIDJSON_UINT64_C2(0xac2820d9, 0x623bf429),
- RAPIDJSON_UINT64_C2(0x80444b5e, 0x7aa7cf85), RAPIDJSON_UINT64_C2(0xbf21e440, 0x03acdd2d),
- RAPIDJSON_UINT64_C2(0x8e679c2f, 0x5e44ff8f), RAPIDJSON_UINT64_C2(0xd433179d, 0x9c8cb841),
- RAPIDJSON_UINT64_C2(0x9e19db92, 0xb4e31ba9), RAPIDJSON_UINT64_C2(0xeb96bf6e, 0xbadf77d9),
- RAPIDJSON_UINT64_C2(0xaf87023b, 0x9bf0ee6b)
- };
- static const int16_t kCachedPowers_E[] = {
- -1220, -1193, -1166, -1140, -1113, -1087, -1060, -1034, -1007, -980,
- -954, -927, -901, -874, -847, -821, -794, -768, -741, -715,
- -688, -661, -635, -608, -582, -555, -529, -502, -475, -449,
- -422, -396, -369, -343, -316, -289, -263, -236, -210, -183,
- -157, -130, -103, -77, -50, -24, 3, 30, 56, 83,
- 109, 136, 162, 189, 216, 242, 269, 295, 322, 348,
- 375, 402, 428, 455, 481, 508, 534, 561, 588, 614,
- 641, 667, 694, 720, 747, 774, 800, 827, 853, 880,
- 907, 933, 960, 986, 1013, 1039, 1066
- };
- return DiyFp(kCachedPowers_F[index], kCachedPowers_E[index]);
-}
-
-inline DiyFp GetCachedPower(int e, int* K) {
-
- //int k = static_cast<int>(ceil((-61 - e) * 0.30102999566398114)) + 374;
- double dk = (-61 - e) * 0.30102999566398114 + 347; // dk must be positive, so can do ceiling in positive
- int k = static_cast<int>(dk);
- if (dk - k > 0.0)
- k++;
-
- unsigned index = static_cast<unsigned>((k >> 3) + 1);
- *K = -(-348 + static_cast<int>(index << 3)); // decimal exponent no need lookup table
-
- return GetCachedPowerByIndex(index);
-}
-
-inline DiyFp GetCachedPower10(int exp, int *outExp) {
- unsigned index = (exp + 348) / 8;
- *outExp = -348 + index * 8;
- return GetCachedPowerByIndex(index);
- }
-
-#ifdef __GNUC__
-RAPIDJSON_DIAG_POP
-#endif
-
-} // namespace internal
-RAPIDJSON_NAMESPACE_END
-
-#endif // RAPIDJSON_DIYFP_H_
diff --git a/libs/rapidjson/internal/dtoa.h b/libs/rapidjson/internal/dtoa.h
deleted file mode 100644
index 2d8d2e46a..000000000
--- a/libs/rapidjson/internal/dtoa.h
+++ /dev/null
@@ -1,217 +0,0 @@
-// Tencent is pleased to support the open source community by making RapidJSON available.
-//
-// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
-//
-// Licensed under the MIT License (the "License"); you may not use this file except
-// in compliance with the License. You may obtain a copy of the License at
-//
-// http://opensource.org/licenses/MIT
-//
-// Unless required by applicable law or agreed to in writing, software distributed
-// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
-// CONDITIONS OF ANY KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations under the License.
-
-// This is a C++ header-only implementation of Grisu2 algorithm from the publication:
-// Loitsch, Florian. "Printing floating-point numbers quickly and accurately with
-// integers." ACM Sigplan Notices 45.6 (2010): 233-243.
-
-#ifndef RAPIDJSON_DTOA_
-#define RAPIDJSON_DTOA_
-
-#include "itoa.h" // GetDigitsLut()
-#include "diyfp.h"
-#include "ieee754.h"
-
-RAPIDJSON_NAMESPACE_BEGIN
-namespace internal {
-
-#ifdef __GNUC__
-RAPIDJSON_DIAG_PUSH
-RAPIDJSON_DIAG_OFF(effc++)
-#endif
-
-inline void GrisuRound(char* buffer, int len, uint64_t delta, uint64_t rest, uint64_t ten_kappa, uint64_t wp_w) {
- while (rest < wp_w && delta - rest >= ten_kappa &&
- (rest + ten_kappa < wp_w || /// closer
- wp_w - rest > rest + ten_kappa - wp_w)) {
- buffer[len - 1]--;
- rest += ten_kappa;
- }
-}
-
-inline unsigned CountDecimalDigit32(uint32_t n) {
- // Simple pure C++ implementation was faster than __builtin_clz version in this situation.
- if (n < 10) return 1;
- if (n < 100) return 2;
- if (n < 1000) return 3;
- if (n < 10000) return 4;
- if (n < 100000) return 5;
- if (n < 1000000) return 6;
- if (n < 10000000) return 7;
- if (n < 100000000) return 8;
- // Will not reach 10 digits in DigitGen()
- //if (n < 1000000000) return 9;
- //return 10;
- return 9;
-}
-
-inline void DigitGen(const DiyFp& W, const DiyFp& Mp, uint64_t delta, char* buffer, int* len, int* K) {
- static const uint32_t kPow10[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 };
- const DiyFp one(uint64_t(1) << -Mp.e, Mp.e);
- const DiyFp wp_w = Mp - W;
- uint32_t p1 = static_cast<uint32_t>(Mp.f >> -one.e);
- uint64_t p2 = Mp.f & (one.f - 1);
- int kappa = CountDecimalDigit32(p1); // kappa in [0, 9]
- *len = 0;
-
- while (kappa > 0) {
- uint32_t d = 0;
- switch (kappa) {
- case 9: d = p1 / 100000000; p1 %= 100000000; break;
- case 8: d = p1 / 10000000; p1 %= 10000000; break;
- case 7: d = p1 / 1000000; p1 %= 1000000; break;
- case 6: d = p1 / 100000; p1 %= 100000; break;
- case 5: d = p1 / 10000; p1 %= 10000; break;
- case 4: d = p1 / 1000; p1 %= 1000; break;
- case 3: d = p1 / 100; p1 %= 100; break;
- case 2: d = p1 / 10; p1 %= 10; break;
- case 1: d = p1; p1 = 0; break;
- default:;
- }
- if (d || *len)
- buffer[(*len)++] = static_cast<char>('0' + static_cast<char>(d));
- kappa--;
- uint64_t tmp = (static_cast<uint64_t>(p1) << -one.e) + p2;
- if (tmp <= delta) {
- *K += kappa;
- GrisuRound(buffer, *len, delta, tmp, static_cast<uint64_t>(kPow10[kappa]) << -one.e, wp_w.f);
- return;
- }
- }
-
- // kappa = 0
- for (;;) {
- p2 *= 10;
- delta *= 10;
- char d = static_cast<char>(p2 >> -one.e);
- if (d || *len)
- buffer[(*len)++] = static_cast<char>('0' + d);
- p2 &= one.f - 1;
- kappa--;
- if (p2 < delta) {
- *K += kappa;
- GrisuRound(buffer, *len, delta, p2, one.f, wp_w.f * kPow10[-kappa]);
- return;
- }
- }
-}
-
-inline void Grisu2(double value, char* buffer, int* length, int* K) {
- const DiyFp v(value);
- DiyFp w_m, w_p;
- v.NormalizedBoundaries(&w_m, &w_p);
-
- const DiyFp c_mk = GetCachedPower(w_p.e, K);
- const DiyFp W = v.Normalize() * c_mk;
- DiyFp Wp = w_p * c_mk;
- DiyFp Wm = w_m * c_mk;
- Wm.f++;
- Wp.f--;
- DigitGen(W, Wp, Wp.f - Wm.f, buffer, length, K);
-}
-
-inline char* WriteExponent(int K, char* buffer) {
- if (K < 0) {
- *buffer++ = '-';
- K = -K;
- }
-
- if (K >= 100) {
- *buffer++ = static_cast<char>('0' + static_cast<char>(K / 100));
- K %= 100;
- const char* d = GetDigitsLut() + K * 2;
- *buffer++ = d[0];
- *buffer++ = d[1];
- }
- else if (K >= 10) {
- const char* d = GetDigitsLut() + K * 2;
- *buffer++ = d[0];
- *buffer++ = d[1];
- }
- else
- *buffer++ = static_cast<char>('0' + static_cast<char>(K));
-
- return buffer;
-}
-
-inline char* Prettify(char* buffer, int length, int k) {
- const int kk = length + k; // 10^(kk-1) <= v < 10^kk
-
- if (length <= kk && kk <= 21) {
- // 1234e7 -> 12340000000
- for (int i = length; i < kk; i++)
- buffer[i] = '0';
- buffer[kk] = '.';
- buffer[kk + 1] = '0';
- return &buffer[kk + 2];
- }
- else if (0 < kk && kk <= 21) {
- // 1234e-2 -> 12.34
- std::memmove(&buffer[kk + 1], &buffer[kk], length - kk);
- buffer[kk] = '.';
- return &buffer[length + 1];
- }
- else if (-6 < kk && kk <= 0) {
- // 1234e-6 -> 0.001234
- const int offset = 2 - kk;
- std::memmove(&buffer[offset], &buffer[0], length);
- buffer[0] = '0';
- buffer[1] = '.';
- for (int i = 2; i < offset; i++)
- buffer[i] = '0';
- return &buffer[length + offset];
- }
- else if (length == 1) {
- // 1e30
- buffer[1] = 'e';
- return WriteExponent(kk - 1, &buffer[2]);
- }
- else {
- // 1234e30 -> 1.234e33
- std::memmove(&buffer[2], &buffer[1], length - 1);
- buffer[1] = '.';
- buffer[length + 1] = 'e';
- return WriteExponent(kk - 1, &buffer[0 + length + 2]);
- }
-}
-
-inline char* dtoa(double value, char* buffer) {
- Double d(value);
- if (d.IsZero()) {
- if (d.Sign())
- *buffer++ = '-'; // -0.0, Issue #289
- buffer[0] = '0';
- buffer[1] = '.';
- buffer[2] = '0';
- return &buffer[3];
- }
- else {
- if (value < 0) {
- *buffer++ = '-';
- value = -value;
- }
- int length, K;
- Grisu2(value, buffer, &length, &K);
- return Prettify(buffer, length, K);
- }
-}
-
-#ifdef __GNUC__
-RAPIDJSON_DIAG_POP
-#endif
-
-} // namespace internal
-RAPIDJSON_NAMESPACE_END
-
-#endif // RAPIDJSON_DTOA_
diff --git a/libs/rapidjson/internal/ieee754.h b/libs/rapidjson/internal/ieee754.h
deleted file mode 100644
index 9a82880e4..000000000
--- a/libs/rapidjson/internal/ieee754.h
+++ /dev/null
@@ -1,77 +0,0 @@
-// Tencent is pleased to support the open source community by making RapidJSON available.
-//
-// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
-//
-// Licensed under the MIT License (the "License"); you may not use this file except
-// in compliance with the License. You may obtain a copy of the License at
-//
-// http://opensource.org/licenses/MIT
-//
-// Unless required by applicable law or agreed to in writing, software distributed
-// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
-// CONDITIONS OF ANY KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations under the License.
-
-#ifndef RAPIDJSON_IEEE754_
-#define RAPIDJSON_IEEE754_
-
-#include "../rapidjson.h"
-
-RAPIDJSON_NAMESPACE_BEGIN
-namespace internal {
-
-class Double {
-public:
- Double() {}
- Double(double d) : d(d) {}
- Double(uint64_t u) : u(u) {}
-
- double Value() const { return d; }
- uint64_t Uint64Value() const { return u; }
-
- double NextPositiveDouble() const {
- RAPIDJSON_ASSERT(!Sign());
- return Double(u + 1).Value();
- }
-
- bool Sign() const { return (u & kSignMask) != 0; }
- uint64_t Significand() const { return u & kSignificandMask; }
- int Exponent() const { return ((u & kExponentMask) >> kSignificandSize) - kExponentBias; }
-
- bool IsNan() const { return (u & kExponentMask) == kExponentMask && Significand() != 0; }
- bool IsInf() const { return (u & kExponentMask) == kExponentMask && Significand() == 0; }
- bool IsNormal() const { return (u & kExponentMask) != 0 || Significand() == 0; }
- bool IsZero() const { return (u & (kExponentMask | kSignificandMask)) == 0; }
-
- uint64_t IntegerSignificand() const { return IsNormal() ? Significand() | kHiddenBit : Significand(); }
- int IntegerExponent() const { return (IsNormal() ? Exponent() : kDenormalExponent) - kSignificandSize; }
- uint64_t ToBias() const { return (u & kSignMask) ? ~u + 1 : u | kSignMask; }
-
- static unsigned EffectiveSignificandSize(int order) {
- if (order >= -1021)
- return 53;
- else if (order <= -1074)
- return 0;
- else
- return order + 1074;
- }
-
-private:
- static const int kSignificandSize = 52;
- static const int kExponentBias = 0x3FF;
- static const int kDenormalExponent = 1 - kExponentBias;
- static const uint64_t kSignMask = RAPIDJSON_UINT64_C2(0x80000000, 0x00000000);
- static const uint64_t kExponentMask = RAPIDJSON_UINT64_C2(0x7FF00000, 0x00000000);
- static const uint64_t kSignificandMask = RAPIDJSON_UINT64_C2(0x000FFFFF, 0xFFFFFFFF);
- static const uint64_t kHiddenBit = RAPIDJSON_UINT64_C2(0x00100000, 0x00000000);
-
- union {
- double d;
- uint64_t u;
- };
-};
-
-} // namespace internal
-RAPIDJSON_NAMESPACE_END
-
-#endif // RAPIDJSON_IEEE754_
diff --git a/libs/rapidjson/internal/itoa.h b/libs/rapidjson/internal/itoa.h
deleted file mode 100644
index 01a4e7e72..000000000
--- a/libs/rapidjson/internal/itoa.h
+++ /dev/null
@@ -1,304 +0,0 @@
-// Tencent is pleased to support the open source community by making RapidJSON available.
-//
-// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
-//
-// Licensed under the MIT License (the "License"); you may not use this file except
-// in compliance with the License. You may obtain a copy of the License at
-//
-// http://opensource.org/licenses/MIT
-//
-// Unless required by applicable law or agreed to in writing, software distributed
-// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
-// CONDITIONS OF ANY KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations under the License.
-
-#ifndef RAPIDJSON_ITOA_
-#define RAPIDJSON_ITOA_
-
-#include "../rapidjson.h"
-
-RAPIDJSON_NAMESPACE_BEGIN
-namespace internal {
-
-inline const char* GetDigitsLut() {
- static const char cDigitsLut[200] = {
- '0','0','0','1','0','2','0','3','0','4','0','5','0','6','0','7','0','8','0','9',
- '1','0','1','1','1','2','1','3','1','4','1','5','1','6','1','7','1','8','1','9',
- '2','0','2','1','2','2','2','3','2','4','2','5','2','6','2','7','2','8','2','9',
- '3','0','3','1','3','2','3','3','3','4','3','5','3','6','3','7','3','8','3','9',
- '4','0','4','1','4','2','4','3','4','4','4','5','4','6','4','7','4','8','4','9',
- '5','0','5','1','5','2','5','3','5','4','5','5','5','6','5','7','5','8','5','9',
- '6','0','6','1','6','2','6','3','6','4','6','5','6','6','6','7','6','8','6','9',
- '7','0','7','1','7','2','7','3','7','4','7','5','7','6','7','7','7','8','7','9',
- '8','0','8','1','8','2','8','3','8','4','8','5','8','6','8','7','8','8','8','9',
- '9','0','9','1','9','2','9','3','9','4','9','5','9','6','9','7','9','8','9','9'
- };
- return cDigitsLut;
-}
-
-inline char* u32toa(uint32_t value, char* buffer) {
- const char* cDigitsLut = GetDigitsLut();
-
- if (value < 10000) {
- const uint32_t d1 = (value / 100) << 1;
- const uint32_t d2 = (value % 100) << 1;
-
- if (value >= 1000)
- *buffer++ = cDigitsLut[d1];
- if (value >= 100)
- *buffer++ = cDigitsLut[d1 + 1];
- if (value >= 10)
- *buffer++ = cDigitsLut[d2];
- *buffer++ = cDigitsLut[d2 + 1];
- }
- else if (value < 100000000) {
- // value = bbbbcccc
- const uint32_t b = value / 10000;
- const uint32_t c = value % 10000;
-
- const uint32_t d1 = (b / 100) << 1;
- const uint32_t d2 = (b % 100) << 1;
-
- const uint32_t d3 = (c / 100) << 1;
- const uint32_t d4 = (c % 100) << 1;
-
- if (value >= 10000000)
- *buffer++ = cDigitsLut[d1];
- if (value >= 1000000)
- *buffer++ = cDigitsLut[d1 + 1];
- if (value >= 100000)
- *buffer++ = cDigitsLut[d2];
- *buffer++ = cDigitsLut[d2 + 1];
-
- *buffer++ = cDigitsLut[d3];
- *buffer++ = cDigitsLut[d3 + 1];
- *buffer++ = cDigitsLut[d4];
- *buffer++ = cDigitsLut[d4 + 1];
- }
- else {
- // value = aabbbbcccc in decimal
-
- const uint32_t a = value / 100000000; // 1 to 42
- value %= 100000000;
-
- if (a >= 10) {
- const unsigned i = a << 1;
- *buffer++ = cDigitsLut[i];
- *buffer++ = cDigitsLut[i + 1];
- }
- else
- *buffer++ = static_cast<char>('0' + static_cast<char>(a));
-
- const uint32_t b = value / 10000; // 0 to 9999
- const uint32_t c = value % 10000; // 0 to 9999
-
- const uint32_t d1 = (b / 100) << 1;
- const uint32_t d2 = (b % 100) << 1;
-
- const uint32_t d3 = (c / 100) << 1;
- const uint32_t d4 = (c % 100) << 1;
-
- *buffer++ = cDigitsLut[d1];
- *buffer++ = cDigitsLut[d1 + 1];
- *buffer++ = cDigitsLut[d2];
- *buffer++ = cDigitsLut[d2 + 1];
- *buffer++ = cDigitsLut[d3];
- *buffer++ = cDigitsLut[d3 + 1];
- *buffer++ = cDigitsLut[d4];
- *buffer++ = cDigitsLut[d4 + 1];
- }
- return buffer;
-}
-
-inline char* i32toa(int32_t value, char* buffer) {
- uint32_t u = static_cast<uint32_t>(value);
- if (value < 0) {
- *buffer++ = '-';
- u = ~u + 1;
- }
-
- return u32toa(u, buffer);
-}
-
-inline char* u64toa(uint64_t value, char* buffer) {
- const char* cDigitsLut = GetDigitsLut();
- const uint64_t kTen8 = 100000000;
- const uint64_t kTen9 = kTen8 * 10;
- const uint64_t kTen10 = kTen8 * 100;
- const uint64_t kTen11 = kTen8 * 1000;
- const uint64_t kTen12 = kTen8 * 10000;
- const uint64_t kTen13 = kTen8 * 100000;
- const uint64_t kTen14 = kTen8 * 1000000;
- const uint64_t kTen15 = kTen8 * 10000000;
- const uint64_t kTen16 = kTen8 * kTen8;
-
- if (value < kTen8) {
- uint32_t v = static_cast<uint32_t>(value);
- if (v < 10000) {
- const uint32_t d1 = (v / 100) << 1;
- const uint32_t d2 = (v % 100) << 1;
-
- if (v >= 1000)
- *buffer++ = cDigitsLut[d1];
- if (v >= 100)
- *buffer++ = cDigitsLut[d1 + 1];
- if (v >= 10)
- *buffer++ = cDigitsLut[d2];
- *buffer++ = cDigitsLut[d2 + 1];
- }
- else {
- // value = bbbbcccc
- const uint32_t b = v / 10000;
- const uint32_t c = v % 10000;
-
- const uint32_t d1 = (b / 100) << 1;
- const uint32_t d2 = (b % 100) << 1;
-
- const uint32_t d3 = (c / 100) << 1;
- const uint32_t d4 = (c % 100) << 1;
-
- if (value >= 10000000)
- *buffer++ = cDigitsLut[d1];
- if (value >= 1000000)
- *buffer++ = cDigitsLut[d1 + 1];
- if (value >= 100000)
- *buffer++ = cDigitsLut[d2];
- *buffer++ = cDigitsLut[d2 + 1];
-
- *buffer++ = cDigitsLut[d3];
- *buffer++ = cDigitsLut[d3 + 1];
- *buffer++ = cDigitsLut[d4];
- *buffer++ = cDigitsLut[d4 + 1];
- }
- }
- else if (value < kTen16) {
- const uint32_t v0 = static_cast<uint32_t>(value / kTen8);
- const uint32_t v1 = static_cast<uint32_t>(value % kTen8);
-
- const uint32_t b0 = v0 / 10000;
- const uint32_t c0 = v0 % 10000;
-
- const uint32_t d1 = (b0 / 100) << 1;
- const uint32_t d2 = (b0 % 100) << 1;
-
- const uint32_t d3 = (c0 / 100) << 1;
- const uint32_t d4 = (c0 % 100) << 1;
-
- const uint32_t b1 = v1 / 10000;
- const uint32_t c1 = v1 % 10000;
-
- const uint32_t d5 = (b1 / 100) << 1;
- const uint32_t d6 = (b1 % 100) << 1;
-
- const uint32_t d7 = (c1 / 100) << 1;
- const uint32_t d8 = (c1 % 100) << 1;
-
- if (value >= kTen15)
- *buffer++ = cDigitsLut[d1];
- if (value >= kTen14)
- *buffer++ = cDigitsLut[d1 + 1];
- if (value >= kTen13)
- *buffer++ = cDigitsLut[d2];
- if (value >= kTen12)
- *buffer++ = cDigitsLut[d2 + 1];
- if (value >= kTen11)
- *buffer++ = cDigitsLut[d3];
- if (value >= kTen10)
- *buffer++ = cDigitsLut[d3 + 1];
- if (value >= kTen9)
- *buffer++ = cDigitsLut[d4];
- if (value >= kTen8)
- *buffer++ = cDigitsLut[d4 + 1];
-
- *buffer++ = cDigitsLut[d5];
- *buffer++ = cDigitsLut[d5 + 1];
- *buffer++ = cDigitsLut[d6];
- *buffer++ = cDigitsLut[d6 + 1];
- *buffer++ = cDigitsLut[d7];
- *buffer++ = cDigitsLut[d7 + 1];
- *buffer++ = cDigitsLut[d8];
- *buffer++ = cDigitsLut[d8 + 1];
- }
- else {
- const uint32_t a = static_cast<uint32_t>(value / kTen16); // 1 to 1844
- value %= kTen16;
-
- if (a < 10)
- *buffer++ = static_cast<char>('0' + static_cast<char>(a));
- else if (a < 100) {
- const uint32_t i = a << 1;
- *buffer++ = cDigitsLut[i];
- *buffer++ = cDigitsLut[i + 1];
- }
- else if (a < 1000) {
- *buffer++ = static_cast<char>('0' + static_cast<char>(a / 100));
-
- const uint32_t i = (a % 100) << 1;
- *buffer++ = cDigitsLut[i];
- *buffer++ = cDigitsLut[i + 1];
- }
- else {
- const uint32_t i = (a / 100) << 1;
- const uint32_t j = (a % 100) << 1;
- *buffer++ = cDigitsLut[i];
- *buffer++ = cDigitsLut[i + 1];
- *buffer++ = cDigitsLut[j];
- *buffer++ = cDigitsLut[j + 1];
- }
-
- const uint32_t v0 = static_cast<uint32_t>(value / kTen8);
- const uint32_t v1 = static_cast<uint32_t>(value % kTen8);
-
- const uint32_t b0 = v0 / 10000;
- const uint32_t c0 = v0 % 10000;
-
- const uint32_t d1 = (b0 / 100) << 1;
- const uint32_t d2 = (b0 % 100) << 1;
-
- const uint32_t d3 = (c0 / 100) << 1;
- const uint32_t d4 = (c0 % 100) << 1;
-
- const uint32_t b1 = v1 / 10000;
- const uint32_t c1 = v1 % 10000;
-
- const uint32_t d5 = (b1 / 100) << 1;
- const uint32_t d6 = (b1 % 100) << 1;
-
- const uint32_t d7 = (c1 / 100) << 1;
- const uint32_t d8 = (c1 % 100) << 1;
-
- *buffer++ = cDigitsLut[d1];
- *buffer++ = cDigitsLut[d1 + 1];
- *buffer++ = cDigitsLut[d2];
- *buffer++ = cDigitsLut[d2 + 1];
- *buffer++ = cDigitsLut[d3];
- *buffer++ = cDigitsLut[d3 + 1];
- *buffer++ = cDigitsLut[d4];
- *buffer++ = cDigitsLut[d4 + 1];
- *buffer++ = cDigitsLut[d5];
- *buffer++ = cDigitsLut[d5 + 1];
- *buffer++ = cDigitsLut[d6];
- *buffer++ = cDigitsLut[d6 + 1];
- *buffer++ = cDigitsLut[d7];
- *buffer++ = cDigitsLut[d7 + 1];
- *buffer++ = cDigitsLut[d8];
- *buffer++ = cDigitsLut[d8 + 1];
- }
-
- return buffer;
-}
-
-inline char* i64toa(int64_t value, char* buffer) {
- uint64_t u = static_cast<uint64_t>(value);
- if (value < 0) {
- *buffer++ = '-';
- u = ~u + 1;
- }
-
- return u64toa(u, buffer);
-}
-
-} // namespace internal
-RAPIDJSON_NAMESPACE_END
-
-#endif // RAPIDJSON_ITOA_
diff --git a/libs/rapidjson/internal/meta.h b/libs/rapidjson/internal/meta.h
deleted file mode 100644
index 594e2597b..000000000
--- a/libs/rapidjson/internal/meta.h
+++ /dev/null
@@ -1,183 +0,0 @@
-// Tencent is pleased to support the open source community by making RapidJSON available.
-//
-// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
-//
-// Licensed under the MIT License (the "License"); you may not use this file except
-// in compliance with the License. You may obtain a copy of the License at
-//
-// http://opensource.org/licenses/MIT
-//
-// Unless required by applicable law or agreed to in writing, software distributed
-// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
-// CONDITIONS OF ANY KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations under the License.
-
-#ifndef RAPIDJSON_INTERNAL_META_H_
-#define RAPIDJSON_INTERNAL_META_H_
-
-#ifndef RAPIDJSON_RAPIDJSON_H_
-#error <rapidjson.h> not yet included. Do not include this file directly.
-#endif
-
-#ifdef __GNUC__
-RAPIDJSON_DIAG_PUSH
-RAPIDJSON_DIAG_OFF(effc++)
-#endif
-#if defined(_MSC_VER)
-RAPIDJSON_DIAG_PUSH
-RAPIDJSON_DIAG_OFF(6334)
-#endif
-
-#if RAPIDJSON_HAS_CXX11_TYPETRAITS
-#include <type_traits>
-#endif
-
-//@cond RAPIDJSON_INTERNAL
-RAPIDJSON_NAMESPACE_BEGIN
-namespace internal {
-
-// Helper to wrap/convert arbitrary types to void, useful for arbitrary type matching
-template <typename T> struct Void { typedef void Type; };
-
-///////////////////////////////////////////////////////////////////////////////
-// BoolType, TrueType, FalseType
-//
-template <bool Cond> struct BoolType {
- static const bool Value = Cond;
- typedef BoolType Type;
-};
-typedef BoolType<true> TrueType;
-typedef BoolType<false> FalseType;
-
-
-///////////////////////////////////////////////////////////////////////////////
-// SelectIf, BoolExpr, NotExpr, AndExpr, OrExpr
-//
-
-template <bool C> struct SelectIfImpl { template <typename T1, typename T2> struct Apply { typedef T1 Type; }; };
-template <> struct SelectIfImpl<false> { template <typename T1, typename T2> struct Apply { typedef T2 Type; }; };
-template <bool C, typename T1, typename T2> struct SelectIfCond : SelectIfImpl<C>::template Apply<T1,T2> {};
-template <typename C, typename T1, typename T2> struct SelectIf : SelectIfCond<C::Value, T1, T2> {};
-
-template <bool Cond1, bool Cond2> struct AndExprCond : FalseType {};
-template <> struct AndExprCond<true, true> : TrueType {};
-template <bool Cond1, bool Cond2> struct OrExprCond : TrueType {};
-template <> struct OrExprCond<false, false> : FalseType {};
-
-template <typename C> struct BoolExpr : SelectIf<C,TrueType,FalseType>::Type {};
-template <typename C> struct NotExpr : SelectIf<C,FalseType,TrueType>::Type {};
-template <typename C1, typename C2> struct AndExpr : AndExprCond<C1::Value, C2::Value>::Type {};
-template <typename C1, typename C2> struct OrExpr : OrExprCond<C1::Value, C2::Value>::Type {};
-
-
-///////////////////////////////////////////////////////////////////////////////
-// AddConst, MaybeAddConst, RemoveConst
-template <typename T> struct AddConst { typedef const T Type; };
-template <bool Constify, typename T> struct MaybeAddConst : SelectIfCond<Constify, const T, T> {};
-template <typename T> struct RemoveConst { typedef T Type; };
-template <typename T> struct RemoveConst<const T> { typedef T Type; };
-
-
-///////////////////////////////////////////////////////////////////////////////
-// IsSame, IsConst, IsMoreConst, IsPointer
-//
-template <typename T, typename U> struct IsSame : FalseType {};
-template <typename T> struct IsSame<T, T> : TrueType {};
-
-template <typename T> struct IsConst : FalseType {};
-template <typename T> struct IsConst<const T> : TrueType {};
-
-template <typename CT, typename T>
-struct IsMoreConst
- : AndExpr<IsSame<typename RemoveConst<CT>::Type, typename RemoveConst<T>::Type>,
- BoolType<IsConst<CT>::Value >= IsConst<T>::Value> >::Type {};
-
-template <typename T> struct IsPointer : FalseType {};
-template <typename T> struct IsPointer<T*> : TrueType {};
-
-///////////////////////////////////////////////////////////////////////////////
-// IsBaseOf
-//
-#if RAPIDJSON_HAS_CXX11_TYPETRAITS
-
-template <typename B, typename D> struct IsBaseOf
- : BoolType< ::std::is_base_of<B,D>::value> {};
-
-#else // simplified version adopted from Boost
-
-template<typename B, typename D> struct IsBaseOfImpl {
- RAPIDJSON_STATIC_ASSERT(sizeof(B) != 0);
- RAPIDJSON_STATIC_ASSERT(sizeof(D) != 0);
-
- typedef char (&Yes)[1];
- typedef char (&No) [2];
-
- template <typename T>
- static Yes Check(const D*, T);
- static No Check(const B*, int);
-
- struct Host {
- operator const B*() const;
- operator const D*();
- };
-
- enum { Value = (sizeof(Check(Host(), 0)) == sizeof(Yes)) };
-};
-
-template <typename B, typename D> struct IsBaseOf
- : OrExpr<IsSame<B, D>, BoolExpr<IsBaseOfImpl<B, D> > >::Type {};
-
-#endif // RAPIDJSON_HAS_CXX11_TYPETRAITS
-
-
-//////////////////////////////////////////////////////////////////////////
-// EnableIf / DisableIf
-//
-template <bool Condition, typename T = void> struct EnableIfCond { typedef T Type; };
-template <typename T> struct EnableIfCond<false, T> { /* empty */ };
-
-template <bool Condition, typename T = void> struct DisableIfCond { typedef T Type; };
-template <typename T> struct DisableIfCond<true, T> { /* empty */ };
-
-template <typename Condition, typename T = void>
-struct EnableIf : EnableIfCond<Condition::Value, T> {};
-
-template <typename Condition, typename T = void>
-struct DisableIf : DisableIfCond<Condition::Value, T> {};
-
-// SFINAE helpers
-struct SfinaeTag {};
-template <typename T> struct RemoveSfinaeTag;
-template <typename T> struct RemoveSfinaeTag<SfinaeTag&(*)(T)> { typedef T Type; };
-
-#define RAPIDJSON_REMOVEFPTR_(type) \
- typename ::RAPIDJSON_NAMESPACE::internal::RemoveSfinaeTag \
- < ::RAPIDJSON_NAMESPACE::internal::SfinaeTag&(*) type>::Type
-
-#define RAPIDJSON_ENABLEIF(cond) \
- typename ::RAPIDJSON_NAMESPACE::internal::EnableIf \
- <RAPIDJSON_REMOVEFPTR_(cond)>::Type * = NULL
-
-#define RAPIDJSON_DISABLEIF(cond) \
- typename ::RAPIDJSON_NAMESPACE::internal::DisableIf \
- <RAPIDJSON_REMOVEFPTR_(cond)>::Type * = NULL
-
-#define RAPIDJSON_ENABLEIF_RETURN(cond,returntype) \
- typename ::RAPIDJSON_NAMESPACE::internal::EnableIf \
- <RAPIDJSON_REMOVEFPTR_(cond), \
- RAPIDJSON_REMOVEFPTR_(returntype)>::Type
-
-#define RAPIDJSON_DISABLEIF_RETURN(cond,returntype) \
- typename ::RAPIDJSON_NAMESPACE::internal::DisableIf \
- <RAPIDJSON_REMOVEFPTR_(cond), \
- RAPIDJSON_REMOVEFPTR_(returntype)>::Type
-
-} // namespace internal
-RAPIDJSON_NAMESPACE_END
-//@endcond
-
-#if defined(__GNUC__) || defined(_MSC_VER)
-RAPIDJSON_DIAG_POP
-#endif
-
-#endif // RAPIDJSON_INTERNAL_META_H_
diff --git a/libs/rapidjson/internal/pow10.h b/libs/rapidjson/internal/pow10.h
deleted file mode 100644
index c552d9f8d..000000000
--- a/libs/rapidjson/internal/pow10.h
+++ /dev/null
@@ -1,53 +0,0 @@
-// Tencent is pleased to support the open source community by making RapidJSON available.
-//
-// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
-//
-// Licensed under the MIT License (the "License"); you may not use this file except
-// in compliance with the License. You may obtain a copy of the License at
-//
-// http://opensource.org/licenses/MIT
-//
-// Unless required by applicable law or agreed to in writing, software distributed
-// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
-// CONDITIONS OF ANY KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations under the License.
-
-#ifndef RAPIDJSON_POW10_
-#define RAPIDJSON_POW10_
-
-RAPIDJSON_NAMESPACE_BEGIN
-namespace internal {
-
-//! Computes integer powers of 10 in double (10.0^n).
-/*! This function uses lookup table for fast and accurate results.
- \param n non-negative exponent. Must <= 308.
- \return 10.0^n
-*/
-inline double Pow10(int n) {
- static const double e[] = { // 1e-0...1e308: 309 * 8 bytes = 2472 bytes
- 1e+0,
- 1e+1, 1e+2, 1e+3, 1e+4, 1e+5, 1e+6, 1e+7, 1e+8, 1e+9, 1e+10, 1e+11, 1e+12, 1e+13, 1e+14, 1e+15, 1e+16, 1e+17, 1e+18, 1e+19, 1e+20,
- 1e+21, 1e+22, 1e+23, 1e+24, 1e+25, 1e+26, 1e+27, 1e+28, 1e+29, 1e+30, 1e+31, 1e+32, 1e+33, 1e+34, 1e+35, 1e+36, 1e+37, 1e+38, 1e+39, 1e+40,
- 1e+41, 1e+42, 1e+43, 1e+44, 1e+45, 1e+46, 1e+47, 1e+48, 1e+49, 1e+50, 1e+51, 1e+52, 1e+53, 1e+54, 1e+55, 1e+56, 1e+57, 1e+58, 1e+59, 1e+60,
- 1e+61, 1e+62, 1e+63, 1e+64, 1e+65, 1e+66, 1e+67, 1e+68, 1e+69, 1e+70, 1e+71, 1e+72, 1e+73, 1e+74, 1e+75, 1e+76, 1e+77, 1e+78, 1e+79, 1e+80,
- 1e+81, 1e+82, 1e+83, 1e+84, 1e+85, 1e+86, 1e+87, 1e+88, 1e+89, 1e+90, 1e+91, 1e+92, 1e+93, 1e+94, 1e+95, 1e+96, 1e+97, 1e+98, 1e+99, 1e+100,
- 1e+101,1e+102,1e+103,1e+104,1e+105,1e+106,1e+107,1e+108,1e+109,1e+110,1e+111,1e+112,1e+113,1e+114,1e+115,1e+116,1e+117,1e+118,1e+119,1e+120,
- 1e+121,1e+122,1e+123,1e+124,1e+125,1e+126,1e+127,1e+128,1e+129,1e+130,1e+131,1e+132,1e+133,1e+134,1e+135,1e+136,1e+137,1e+138,1e+139,1e+140,
- 1e+141,1e+142,1e+143,1e+144,1e+145,1e+146,1e+147,1e+148,1e+149,1e+150,1e+151,1e+152,1e+153,1e+154,1e+155,1e+156,1e+157,1e+158,1e+159,1e+160,
- 1e+161,1e+162,1e+163,1e+164,1e+165,1e+166,1e+167,1e+168,1e+169,1e+170,1e+171,1e+172,1e+173,1e+174,1e+175,1e+176,1e+177,1e+178,1e+179,1e+180,
- 1e+181,1e+182,1e+183,1e+184,1e+185,1e+186,1e+187,1e+188,1e+189,1e+190,1e+191,1e+192,1e+193,1e+194,1e+195,1e+196,1e+197,1e+198,1e+199,1e+200,
- 1e+201,1e+202,1e+203,1e+204,1e+205,1e+206,1e+207,1e+208,1e+209,1e+210,1e+211,1e+212,1e+213,1e+214,1e+215,1e+216,1e+217,1e+218,1e+219,1e+220,
- 1e+221,1e+222,1e+223,1e+224,1e+225,1e+226,1e+227,1e+228,1e+229,1e+230,1e+231,1e+232,1e+233,1e+234,1e+235,1e+236,1e+237,1e+238,1e+239,1e+240,
- 1e+241,1e+242,1e+243,1e+244,1e+245,1e+246,1e+247,1e+248,1e+249,1e+250,1e+251,1e+252,1e+253,1e+254,1e+255,1e+256,1e+257,1e+258,1e+259,1e+260,
- 1e+261,1e+262,1e+263,1e+264,1e+265,1e+266,1e+267,1e+268,1e+269,1e+270,1e+271,1e+272,1e+273,1e+274,1e+275,1e+276,1e+277,1e+278,1e+279,1e+280,
- 1e+281,1e+282,1e+283,1e+284,1e+285,1e+286,1e+287,1e+288,1e+289,1e+290,1e+291,1e+292,1e+293,1e+294,1e+295,1e+296,1e+297,1e+298,1e+299,1e+300,
- 1e+301,1e+302,1e+303,1e+304,1e+305,1e+306,1e+307,1e+308
- };
- RAPIDJSON_ASSERT(n >= 0 && n <= 308);
- return e[n];
-}
-
-} // namespace internal
-RAPIDJSON_NAMESPACE_END
-
-#endif // RAPIDJSON_POW10_
diff --git a/libs/rapidjson/internal/stack.h b/libs/rapidjson/internal/stack.h
deleted file mode 100644
index 2f2c76a36..000000000
--- a/libs/rapidjson/internal/stack.h
+++ /dev/null
@@ -1,177 +0,0 @@
-// Tencent is pleased to support the open source community by making RapidJSON available.
-//
-// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
-//
-// Licensed under the MIT License (the "License"); you may not use this file except
-// in compliance with the License. You may obtain a copy of the License at
-//
-// http://opensource.org/licenses/MIT
-//
-// Unless required by applicable law or agreed to in writing, software distributed
-// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
-// CONDITIONS OF ANY KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations under the License.
-
-#ifndef RAPIDJSON_INTERNAL_STACK_H_
-#define RAPIDJSON_INTERNAL_STACK_H_
-
-RAPIDJSON_NAMESPACE_BEGIN
-namespace internal {
-
-///////////////////////////////////////////////////////////////////////////////
-// Stack
-
-//! A type-unsafe stack for storing different types of data.
-/*! \tparam Allocator Allocator for allocating stack memory.
-*/
-template <typename Allocator>
-class Stack {
-public:
- // Optimization note: Do not allocate memory for stack_ in constructor.
- // Do it lazily when first Push() -> Expand() -> Resize().
- Stack(Allocator* allocator, size_t stackCapacity) : allocator_(allocator), ownAllocator_(0), stack_(0), stackTop_(0), stackEnd_(0), initialCapacity_(stackCapacity) {
- RAPIDJSON_ASSERT(stackCapacity > 0);
- }
-
-#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
- Stack(Stack&& rhs)
- : allocator_(rhs.allocator_),
- ownAllocator_(rhs.ownAllocator_),
- stack_(rhs.stack_),
- stackTop_(rhs.stackTop_),
- stackEnd_(rhs.stackEnd_),
- initialCapacity_(rhs.initialCapacity_)
- {
- rhs.allocator_ = 0;
- rhs.ownAllocator_ = 0;
- rhs.stack_ = 0;
- rhs.stackTop_ = 0;
- rhs.stackEnd_ = 0;
- rhs.initialCapacity_ = 0;
- }
-#endif
-
- ~Stack() {
- Destroy();
- }
-
-#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
- Stack& operator=(Stack&& rhs) {
- if (&rhs != this)
- {
- Destroy();
-
- allocator_ = rhs.allocator_;
- ownAllocator_ = rhs.ownAllocator_;
- stack_ = rhs.stack_;
- stackTop_ = rhs.stackTop_;
- stackEnd_ = rhs.stackEnd_;
- initialCapacity_ = rhs.initialCapacity_;
-
- rhs.allocator_ = 0;
- rhs.ownAllocator_ = 0;
- rhs.stack_ = 0;
- rhs.stackTop_ = 0;
- rhs.stackEnd_ = 0;
- rhs.initialCapacity_ = 0;
- }
- return *this;
- }
-#endif
-
- void Clear() { stackTop_ = stack_; }
-
- void ShrinkToFit() {
- if (Empty()) {
- // If the stack is empty, completely deallocate the memory.
- Allocator::Free(stack_);
- stack_ = 0;
- stackTop_ = 0;
- stackEnd_ = 0;
- }
- else
- Resize(GetSize());
- }
-
- // Optimization note: try to minimize the size of this function for force inline.
- // Expansion is run very infrequently, so it is moved to another (probably non-inline) function.
- template<typename T>
- RAPIDJSON_FORCEINLINE T* Push(size_t count = 1) {
- // Expand the stack if needed
- if (stackTop_ + sizeof(T) * count >= stackEnd_)
- Expand<T>(count);
-
- T* ret = reinterpret_cast<T*>(stackTop_);
- stackTop_ += sizeof(T) * count;
- return ret;
- }
-
- template<typename T>
- T* Pop(size_t count) {
- RAPIDJSON_ASSERT(GetSize() >= count * sizeof(T));
- stackTop_ -= count * sizeof(T);
- return reinterpret_cast<T*>(stackTop_);
- }
-
- template<typename T>
- T* Top() {
- RAPIDJSON_ASSERT(GetSize() >= sizeof(T));
- return reinterpret_cast<T*>(stackTop_ - sizeof(T));
- }
-
- template<typename T>
- T* Bottom() { return (T*)stack_; }
-
- Allocator& GetAllocator() { return *allocator_; }
- bool Empty() const { return stackTop_ == stack_; }
- size_t GetSize() const { return static_cast<size_t>(stackTop_ - stack_); }
- size_t GetCapacity() const { return static_cast<size_t>(stackEnd_ - stack_); }
-
-private:
- template<typename T>
- void Expand(size_t count) {
- // Only expand the capacity if the current stack exists. Otherwise just create a stack with initial capacity.
- size_t newCapacity;
- if (stack_ == 0) {
- if (!allocator_)
- ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator());
- newCapacity = initialCapacity_;
- } else {
- newCapacity = GetCapacity();
- newCapacity += (newCapacity + 1) / 2;
- }
- size_t newSize = GetSize() + sizeof(T) * count;
- if (newCapacity < newSize)
- newCapacity = newSize;
-
- Resize(newCapacity);
- }
-
- void Resize(size_t newCapacity) {
- const size_t size = GetSize(); // Backup the current size
- stack_ = (char*)allocator_->Realloc(stack_, GetCapacity(), newCapacity);
- stackTop_ = stack_ + size;
- stackEnd_ = stack_ + newCapacity;
- }
-
- void Destroy() {
- Allocator::Free(stack_);
- RAPIDJSON_DELETE(ownAllocator_); // Only delete if it is owned by the stack
- }
-
- // Prohibit copy constructor & assignment operator.
- Stack(const Stack&);
- Stack& operator=(const Stack&);
-
- Allocator* allocator_;
- Allocator* ownAllocator_;
- char *stack_;
- char *stackTop_;
- char *stackEnd_;
- size_t initialCapacity_;
-};
-
-} // namespace internal
-RAPIDJSON_NAMESPACE_END
-
-#endif // RAPIDJSON_STACK_H_
diff --git a/libs/rapidjson/internal/strfunc.h b/libs/rapidjson/internal/strfunc.h
deleted file mode 100644
index e6d1c2122..000000000
--- a/libs/rapidjson/internal/strfunc.h
+++ /dev/null
@@ -1,37 +0,0 @@
-// Tencent is pleased to support the open source community by making RapidJSON available.
-//
-// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
-//
-// Licensed under the MIT License (the "License"); you may not use this file except
-// in compliance with the License. You may obtain a copy of the License at
-//
-// http://opensource.org/licenses/MIT
-//
-// Unless required by applicable law or agreed to in writing, software distributed
-// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
-// CONDITIONS OF ANY KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations under the License.
-
-#ifndef RAPIDJSON_INTERNAL_STRFUNC_H_
-#define RAPIDJSON_INTERNAL_STRFUNC_H_
-
-RAPIDJSON_NAMESPACE_BEGIN
-namespace internal {
-
-//! Custom strlen() which works on different character types.
-/*! \tparam Ch Character type (e.g. char, wchar_t, short)
- \param s Null-terminated input string.
- \return Number of characters in the string.
- \note This has the same semantics as strlen(), the return value is not number of Unicode codepoints.
-*/
-template <typename Ch>
-inline SizeType StrLen(const Ch* s) {
- const Ch* p = s;
- while (*p) ++p;
- return SizeType(p - s);
-}
-
-} // namespace internal
-RAPIDJSON_NAMESPACE_END
-
-#endif // RAPIDJSON_INTERNAL_STRFUNC_H_
diff --git a/libs/rapidjson/internal/strtod.h b/libs/rapidjson/internal/strtod.h
deleted file mode 100644
index fa85286d4..000000000
--- a/libs/rapidjson/internal/strtod.h
+++ /dev/null
@@ -1,265 +0,0 @@
-// Tencent is pleased to support the open source community by making RapidJSON available.
-//
-// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
-//
-// Licensed under the MIT License (the "License"); you may not use this file except
-// in compliance with the License. You may obtain a copy of the License at
-//
-// http://opensource.org/licenses/MIT
-//
-// Unless required by applicable law or agreed to in writing, software distributed
-// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
-// CONDITIONS OF ANY KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations under the License.
-
-#ifndef RAPIDJSON_STRTOD_
-#define RAPIDJSON_STRTOD_
-
-#include "../rapidjson.h"
-#include "ieee754.h"
-#include "biginteger.h"
-#include "diyfp.h"
-#include "pow10.h"
-
-RAPIDJSON_NAMESPACE_BEGIN
-namespace internal {
-
-inline double FastPath(double significand, int exp) {
- if (exp < -308)
- return 0.0;
- else if (exp >= 0)
- return significand * internal::Pow10(exp);
- else
- return significand / internal::Pow10(-exp);
-}
-
-inline double StrtodNormalPrecision(double d, int p) {
- if (p < -308) {
- // Prevent expSum < -308, making Pow10(p) = 0
- d = FastPath(d, -308);
- d = FastPath(d, p + 308);
- }
- else
- d = FastPath(d, p);
- return d;
-}
-
-template <typename T>
-inline T Min3(T a, T b, T c) {
- T m = a;
- if (m > b) m = b;
- if (m > c) m = c;
- return m;
-}
-
-inline int CheckWithinHalfULP(double b, const BigInteger& d, int dExp) {
- const Double db(b);
- const uint64_t bInt = db.IntegerSignificand();
- const int bExp = db.IntegerExponent();
- const int hExp = bExp - 1;
-
- int dS_Exp2 = 0, dS_Exp5 = 0, bS_Exp2 = 0, bS_Exp5 = 0, hS_Exp2 = 0, hS_Exp5 = 0;
-
- // Adjust for decimal exponent
- if (dExp >= 0) {
- dS_Exp2 += dExp;
- dS_Exp5 += dExp;
- }
- else {
- bS_Exp2 -= dExp;
- bS_Exp5 -= dExp;
- hS_Exp2 -= dExp;
- hS_Exp5 -= dExp;
- }
-
- // Adjust for binary exponent
- if (bExp >= 0)
- bS_Exp2 += bExp;
- else {
- dS_Exp2 -= bExp;
- hS_Exp2 -= bExp;
- }
-
- // Adjust for half ulp exponent
- if (hExp >= 0)
- hS_Exp2 += hExp;
- else {
- dS_Exp2 -= hExp;
- bS_Exp2 -= hExp;
- }
-
- // Remove common power of two factor from all three scaled values
- int common_Exp2 = Min3(dS_Exp2, bS_Exp2, hS_Exp2);
- dS_Exp2 -= common_Exp2;
- bS_Exp2 -= common_Exp2;
- hS_Exp2 -= common_Exp2;
-
- BigInteger dS = d;
- dS.MultiplyPow5(dS_Exp5) <<= dS_Exp2;
-
- BigInteger bS(bInt);
- bS.MultiplyPow5(bS_Exp5) <<= bS_Exp2;
-
- BigInteger hS(1);
- hS.MultiplyPow5(hS_Exp5) <<= hS_Exp2;
-
- BigInteger delta(0);
- dS.Difference(bS, &delta);
-
- return delta.Compare(hS);
-}
-
-inline bool StrtodFast(double d, int p, double* result) {
- // Use fast path for string-to-double conversion if possible
- // see http://www.exploringbinary.com/fast-path-decimal-to-floating-point-conversion/
- if (p > 22 && p < 22 + 16) {
- // Fast Path Cases In Disguise
- d *= internal::Pow10(p - 22);
- p = 22;
- }
-
- if (p >= -22 && p <= 22 && d <= 9007199254740991.0) { // 2^53 - 1
- *result = FastPath(d, p);
- return true;
- }
- else
- return false;
-}
-
-// Compute an approximation and see if it is within 1/2 ULP
-inline bool StrtodDiyFp(const char* decimals, size_t length, size_t decimalPosition, int exp, double* result) {
- uint64_t significand = 0;
- size_t i = 0; // 2^64 - 1 = 18446744073709551615, 1844674407370955161 = 0x1999999999999999
- for (; i < length; i++) {
- if (significand > RAPIDJSON_UINT64_C2(0x19999999, 0x99999999) ||
- (significand == RAPIDJSON_UINT64_C2(0x19999999, 0x99999999) && decimals[i] > '5'))
- break;
- significand = significand * 10 + (decimals[i] - '0');
- }
-
- if (i < length && decimals[i] >= '5') // Rounding
- significand++;
-
- size_t remaining = length - i;
- const unsigned kUlpShift = 3;
- const unsigned kUlp = 1 << kUlpShift;
- int error = (remaining == 0) ? 0 : kUlp / 2;
-
- DiyFp v(significand, 0);
- v = v.Normalize();
- error <<= -v.e;
-
- const int dExp = (int)decimalPosition - (int)i + exp;
-
- int actualExp;
- DiyFp cachedPower = GetCachedPower10(dExp, &actualExp);
- if (actualExp != dExp) {
- static const DiyFp kPow10[] = {
- DiyFp(RAPIDJSON_UINT64_C2(0xa0000000, 00000000), -60), // 10^1
- DiyFp(RAPIDJSON_UINT64_C2(0xc8000000, 00000000), -57), // 10^2
- DiyFp(RAPIDJSON_UINT64_C2(0xfa000000, 00000000), -54), // 10^3
- DiyFp(RAPIDJSON_UINT64_C2(0x9c400000, 00000000), -50), // 10^4
- DiyFp(RAPIDJSON_UINT64_C2(0xc3500000, 00000000), -47), // 10^5
- DiyFp(RAPIDJSON_UINT64_C2(0xf4240000, 00000000), -44), // 10^6
- DiyFp(RAPIDJSON_UINT64_C2(0x98968000, 00000000), -40) // 10^7
- };
- int adjustment = dExp - actualExp - 1;
- RAPIDJSON_ASSERT(adjustment >= 0 && adjustment < 7);
- v = v * kPow10[adjustment];
- if (length + adjustment > 19) // has more digits than decimal digits in 64-bit
- error += kUlp / 2;
- }
-
- v = v * cachedPower;
-
- error += kUlp + (error == 0 ? 0 : 1);
-
- const int oldExp = v.e;
- v = v.Normalize();
- error <<= oldExp - v.e;
-
- const unsigned effectiveSignificandSize = Double::EffectiveSignificandSize(64 + v.e);
- unsigned precisionSize = 64 - effectiveSignificandSize;
- if (precisionSize + kUlpShift >= 64) {
- unsigned scaleExp = (precisionSize + kUlpShift) - 63;
- v.f >>= scaleExp;
- v.e += scaleExp;
- error = (error >> scaleExp) + 1 + kUlp;
- precisionSize -= scaleExp;
- }
-
- DiyFp rounded(v.f >> precisionSize, v.e + precisionSize);
- const uint64_t precisionBits = (v.f & ((uint64_t(1) << precisionSize) - 1)) * kUlp;
- const uint64_t halfWay = (uint64_t(1) << (precisionSize - 1)) * kUlp;
- if (precisionBits >= halfWay + error)
- rounded.f++;
-
- *result = rounded.ToDouble();
-
- return halfWay - error >= precisionBits || precisionBits >= halfWay + error;
-}
-
-inline double StrtodBigInteger(double approx, const char* decimals, size_t length, size_t decimalPosition, int exp) {
- const BigInteger dInt(decimals, length);
- const int dExp = (int)decimalPosition - (int)length + exp;
- Double a(approx);
- int cmp = CheckWithinHalfULP(a.Value(), dInt, dExp);
- if (cmp < 0)
- return a.Value(); // within half ULP
- else if (cmp == 0) {
- // Round towards even
- if (a.Significand() & 1)
- return a.NextPositiveDouble();
- else
- return a.Value();
- }
- else // adjustment
- return a.NextPositiveDouble();
-}
-
-inline double StrtodFullPrecision(double d, int p, const char* decimals, size_t length, size_t decimalPosition, int exp) {
- RAPIDJSON_ASSERT(d >= 0.0);
- RAPIDJSON_ASSERT(length >= 1);
-
- double result;
- if (StrtodFast(d, p, &result))
- return result;
-
- // Trim leading zeros
- while (*decimals == '0' && length > 1) {
- length--;
- decimals++;
- decimalPosition--;
- }
-
- // Trim trailing zeros
- while (decimals[length - 1] == '0' && length > 1) {
- length--;
- decimalPosition--;
- exp++;
- }
-
- // Trim right-most digits
- const int kMaxDecimalDigit = 780;
- if ((int)length > kMaxDecimalDigit) {
- int delta = (int(length) - kMaxDecimalDigit);
- exp += delta;
- decimalPosition -= delta;
- length = kMaxDecimalDigit;
- }
-
- // If too small, underflow to zero
- if (int(length) + exp < -324)
- return 0.0;
-
- if (StrtodDiyFp(decimals, length, decimalPosition, exp, &result))
- return result;
-
- // Use approximation from StrtodDiyFp and make adjustment with BigInteger comparison
- return StrtodBigInteger(result, decimals, length, decimalPosition, exp);
-}
-
-} // namespace internal
-RAPIDJSON_NAMESPACE_END
-
-#endif // RAPIDJSON_STRTOD_
diff --git a/libs/rapidjson/license.txt b/libs/rapidjson/license.txt
deleted file mode 100644
index 9145f6fa1..000000000
--- a/libs/rapidjson/license.txt
+++ /dev/null
@@ -1,57 +0,0 @@
-Tencent is pleased to support the open source community by making RapidJSON available.
-
-Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
-
-If you have downloaded a copy of the RapidJSON binary from Tencent, please note that the RapidJSON binary is licensed under the MIT License.
-If you have downloaded a copy of the RapidJSON source code from Tencent, please note that RapidJSON source code is licensed under the MIT License, except for the third-party components listed below which are subject to different license terms. Your integration of RapidJSON into your own projects may require compliance with the MIT License, as well as the other licenses applicable to the third-party components included within RapidJSON.
-A copy of the MIT License is included in this file.
-
-Other dependencies and licenses:
-
-Open Source Software Licensed Under the BSD License:
---------------------------------------------------------------------
-
-The msinttypes r29
-Copyright (c) 2006-2013 Alexander Chemeris
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
-
-* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
-* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
-* Neither the name of copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-Open Source Software Licensed Under the JSON License:
---------------------------------------------------------------------
-
-json.org
-Copyright (c) 2002 JSON.org
-All Rights Reserved.
-
-JSON_checker
-Copyright (c) 2002 JSON.org
-All Rights Reserved.
-
-
-Terms of the JSON License:
----------------------------------------------------
-
-Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
-
-The Software shall be used for Good, not Evil.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-
-Terms of the MIT License:
---------------------------------------------------------------------
-
-Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file
diff --git a/libs/rapidjson/memorybuffer.h b/libs/rapidjson/memorybuffer.h
deleted file mode 100644
index 2484b2185..000000000
--- a/libs/rapidjson/memorybuffer.h
+++ /dev/null
@@ -1,70 +0,0 @@
-// Tencent is pleased to support the open source community by making RapidJSON available.
-//
-// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
-//
-// Licensed under the MIT License (the "License"); you may not use this file except
-// in compliance with the License. You may obtain a copy of the License at
-//
-// http://opensource.org/licenses/MIT
-//
-// Unless required by applicable law or agreed to in writing, software distributed
-// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
-// CONDITIONS OF ANY KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations under the License.
-
-#ifndef RAPIDJSON_MEMORYBUFFER_H_
-#define RAPIDJSON_MEMORYBUFFER_H_
-
-#include "rapidjson.h"
-#include "internal/stack.h"
-
-RAPIDJSON_NAMESPACE_BEGIN
-
-//! Represents an in-memory output byte stream.
-/*!
- This class is mainly for being wrapped by EncodedOutputStream or AutoUTFOutputStream.
-
- It is similar to FileWriteBuffer but the destination is an in-memory buffer instead of a file.
-
- Differences between MemoryBuffer and StringBuffer:
- 1. StringBuffer has Encoding but MemoryBuffer is only a byte buffer.
- 2. StringBuffer::GetString() returns a null-terminated string. MemoryBuffer::GetBuffer() returns a buffer without terminator.
-
- \tparam Allocator type for allocating memory buffer.
- \note implements Stream concept
-*/
-template <typename Allocator = CrtAllocator>
-struct GenericMemoryBuffer {
- typedef char Ch; // byte
-
- GenericMemoryBuffer(Allocator* allocator = 0, size_t capacity = kDefaultCapacity) : stack_(allocator, capacity) {}
-
- void Put(Ch c) { *stack_.template Push<Ch>() = c; }
- void Flush() {}
-
- void Clear() { stack_.Clear(); }
- void ShrinkToFit() { stack_.ShrinkToFit(); }
- Ch* Push(size_t count) { return stack_.template Push<Ch>(count); }
- void Pop(size_t count) { stack_.template Pop<Ch>(count); }
-
- const Ch* GetBuffer() const {
- return stack_.template Bottom<Ch>();
- }
-
- size_t GetSize() const { return stack_.GetSize(); }
-
- static const size_t kDefaultCapacity = 256;
- mutable internal::Stack<Allocator> stack_;
-};
-
-typedef GenericMemoryBuffer<> MemoryBuffer;
-
-//! Implement specialized version of PutN() with memset() for better performance.
-template<>
-inline void PutN(MemoryBuffer& memoryBuffer, char c, size_t n) {
- std::memset(memoryBuffer.stack_.Push<char>(n), c, n * sizeof(c));
-}
-
-RAPIDJSON_NAMESPACE_END
-
-#endif // RAPIDJSON_MEMORYBUFFER_H_
diff --git a/libs/rapidjson/memorystream.h b/libs/rapidjson/memorystream.h
deleted file mode 100644
index 99feae5d7..000000000
--- a/libs/rapidjson/memorystream.h
+++ /dev/null
@@ -1,61 +0,0 @@
-// Tencent is pleased to support the open source community by making RapidJSON available.
-//
-// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
-//
-// Licensed under the MIT License (the "License"); you may not use this file except
-// in compliance with the License. You may obtain a copy of the License at
-//
-// http://opensource.org/licenses/MIT
-//
-// Unless required by applicable law or agreed to in writing, software distributed
-// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
-// CONDITIONS OF ANY KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations under the License.
-
-#ifndef RAPIDJSON_MEMORYSTREAM_H_
-#define RAPIDJSON_MEMORYSTREAM_H_
-
-#include "rapidjson.h"
-
-RAPIDJSON_NAMESPACE_BEGIN
-
-//! Represents an in-memory input byte stream.
-/*!
- This class is mainly for being wrapped by EncodedInputStream or AutoUTFInputStream.
-
- It is similar to FileReadBuffer but the source is an in-memory buffer instead of a file.
-
- Differences between MemoryStream and StringStream:
- 1. StringStream has encoding but MemoryStream is a byte stream.
- 2. MemoryStream needs size of the source buffer and the buffer don't need to be null terminated. StringStream assume null-terminated string as source.
- 3. MemoryStream supports Peek4() for encoding detection. StringStream is specified with an encoding so it should not have Peek4().
- \note implements Stream concept
-*/
-struct MemoryStream {
- typedef char Ch; // byte
-
- MemoryStream(const Ch *src, size_t size) : src_(src), begin_(src), end_(src + size), size_(size) {}
-
- Ch Peek() const { return (src_ == end_) ? '\0' : *src_; }
- Ch Take() { return (src_ == end_) ? '\0' : *src_++; }
- size_t Tell() const { return static_cast<size_t>(src_ - begin_); }
-
- Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; }
- void Put(Ch) { RAPIDJSON_ASSERT(false); }
- void Flush() { RAPIDJSON_ASSERT(false); }
- size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; }
-
- // For encoding detection only.
- const Ch* Peek4() const {
- return Tell() + 4 <= size_ ? src_ : 0;
- }
-
- const Ch* src_; //!< Current read position.
- const Ch* begin_; //!< Original head of the string.
- const Ch* end_; //!< End of stream.
- size_t size_; //!< Size of the stream.
-};
-
-RAPIDJSON_NAMESPACE_END
-
-#endif // RAPIDJSON_MEMORYBUFFER_H_
diff --git a/libs/rapidjson/msinttypes/inttypes.h b/libs/rapidjson/msinttypes/inttypes.h
deleted file mode 100644
index 18111286b..000000000
--- a/libs/rapidjson/msinttypes/inttypes.h
+++ /dev/null
@@ -1,316 +0,0 @@
-// ISO C9x compliant inttypes.h for Microsoft Visual Studio
-// Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124
-//
-// Copyright (c) 2006-2013 Alexander Chemeris
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-// 1. Redistributions of source code must retain the above copyright notice,
-// this list of conditions and the following disclaimer.
-//
-// 2. Redistributions in binary form must reproduce the above copyright
-// notice, this list of conditions and the following disclaimer in the
-// documentation and/or other materials provided with the distribution.
-//
-// 3. Neither the name of the product nor the names of its contributors may
-// be used to endorse or promote products derived from this software
-// without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
-// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
-// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
-// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
-// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
-// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
-// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
-// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-///////////////////////////////////////////////////////////////////////////////
-
-// The above software in this distribution may have been modified by
-// THL A29 Limited ("Tencent Modifications").
-// All Tencent Modifications are Copyright (C) 2015 THL A29 Limited.
-
-#ifndef _MSC_VER // [
-#error "Use this header only with Microsoft Visual C++ compilers!"
-#endif // _MSC_VER ]
-
-#ifndef _MSC_INTTYPES_H_ // [
-#define _MSC_INTTYPES_H_
-
-#if _MSC_VER > 1000
-#pragma once
-#endif
-
-#include "stdint.h"
-
-// miloyip: VC supports inttypes.h since VC2013
-#if _MSC_VER >= 1800
-#include <inttypes.h>
-#else
-
-// 7.8 Format conversion of integer types
-
-typedef struct {
- intmax_t quot;
- intmax_t rem;
-} imaxdiv_t;
-
-// 7.8.1 Macros for format specifiers
-
-#if !defined(__cplusplus) || defined(__STDC_FORMAT_MACROS) // [ See footnote 185 at page 198
-
-// The fprintf macros for signed integers are:
-#define PRId8 "d"
-#define PRIi8 "i"
-#define PRIdLEAST8 "d"
-#define PRIiLEAST8 "i"
-#define PRIdFAST8 "d"
-#define PRIiFAST8 "i"
-
-#define PRId16 "hd"
-#define PRIi16 "hi"
-#define PRIdLEAST16 "hd"
-#define PRIiLEAST16 "hi"
-#define PRIdFAST16 "hd"
-#define PRIiFAST16 "hi"
-
-#define PRId32 "I32d"
-#define PRIi32 "I32i"
-#define PRIdLEAST32 "I32d"
-#define PRIiLEAST32 "I32i"
-#define PRIdFAST32 "I32d"
-#define PRIiFAST32 "I32i"
-
-#define PRId64 "I64d"
-#define PRIi64 "I64i"
-#define PRIdLEAST64 "I64d"
-#define PRIiLEAST64 "I64i"
-#define PRIdFAST64 "I64d"
-#define PRIiFAST64 "I64i"
-
-#define PRIdMAX "I64d"
-#define PRIiMAX "I64i"
-
-#define PRIdPTR "Id"
-#define PRIiPTR "Ii"
-
-// The fprintf macros for unsigned integers are:
-#define PRIo8 "o"
-#define PRIu8 "u"
-#define PRIx8 "x"
-#define PRIX8 "X"
-#define PRIoLEAST8 "o"
-#define PRIuLEAST8 "u"
-#define PRIxLEAST8 "x"
-#define PRIXLEAST8 "X"
-#define PRIoFAST8 "o"
-#define PRIuFAST8 "u"
-#define PRIxFAST8 "x"
-#define PRIXFAST8 "X"
-
-#define PRIo16 "ho"
-#define PRIu16 "hu"
-#define PRIx16 "hx"
-#define PRIX16 "hX"
-#define PRIoLEAST16 "ho"
-#define PRIuLEAST16 "hu"
-#define PRIxLEAST16 "hx"
-#define PRIXLEAST16 "hX"
-#define PRIoFAST16 "ho"
-#define PRIuFAST16 "hu"
-#define PRIxFAST16 "hx"
-#define PRIXFAST16 "hX"
-
-#define PRIo32 "I32o"
-#define PRIu32 "I32u"
-#define PRIx32 "I32x"
-#define PRIX32 "I32X"
-#define PRIoLEAST32 "I32o"
-#define PRIuLEAST32 "I32u"
-#define PRIxLEAST32 "I32x"
-#define PRIXLEAST32 "I32X"
-#define PRIoFAST32 "I32o"
-#define PRIuFAST32 "I32u"
-#define PRIxFAST32 "I32x"
-#define PRIXFAST32 "I32X"
-
-#define PRIo64 "I64o"
-#define PRIu64 "I64u"
-#define PRIx64 "I64x"
-#define PRIX64 "I64X"
-#define PRIoLEAST64 "I64o"
-#define PRIuLEAST64 "I64u"
-#define PRIxLEAST64 "I64x"
-#define PRIXLEAST64 "I64X"
-#define PRIoFAST64 "I64o"
-#define PRIuFAST64 "I64u"
-#define PRIxFAST64 "I64x"
-#define PRIXFAST64 "I64X"
-
-#define PRIoMAX "I64o"
-#define PRIuMAX "I64u"
-#define PRIxMAX "I64x"
-#define PRIXMAX "I64X"
-
-#define PRIoPTR "Io"
-#define PRIuPTR "Iu"
-#define PRIxPTR "Ix"
-#define PRIXPTR "IX"
-
-// The fscanf macros for signed integers are:
-#define SCNd8 "d"
-#define SCNi8 "i"
-#define SCNdLEAST8 "d"
-#define SCNiLEAST8 "i"
-#define SCNdFAST8 "d"
-#define SCNiFAST8 "i"
-
-#define SCNd16 "hd"
-#define SCNi16 "hi"
-#define SCNdLEAST16 "hd"
-#define SCNiLEAST16 "hi"
-#define SCNdFAST16 "hd"
-#define SCNiFAST16 "hi"
-
-#define SCNd32 "ld"
-#define SCNi32 "li"
-#define SCNdLEAST32 "ld"
-#define SCNiLEAST32 "li"
-#define SCNdFAST32 "ld"
-#define SCNiFAST32 "li"
-
-#define SCNd64 "I64d"
-#define SCNi64 "I64i"
-#define SCNdLEAST64 "I64d"
-#define SCNiLEAST64 "I64i"
-#define SCNdFAST64 "I64d"
-#define SCNiFAST64 "I64i"
-
-#define SCNdMAX "I64d"
-#define SCNiMAX "I64i"
-
-#ifdef _WIN64 // [
-# define SCNdPTR "I64d"
-# define SCNiPTR "I64i"
-#else // _WIN64 ][
-# define SCNdPTR "ld"
-# define SCNiPTR "li"
-#endif // _WIN64 ]
-
-// The fscanf macros for unsigned integers are:
-#define SCNo8 "o"
-#define SCNu8 "u"
-#define SCNx8 "x"
-#define SCNX8 "X"
-#define SCNoLEAST8 "o"
-#define SCNuLEAST8 "u"
-#define SCNxLEAST8 "x"
-#define SCNXLEAST8 "X"
-#define SCNoFAST8 "o"
-#define SCNuFAST8 "u"
-#define SCNxFAST8 "x"
-#define SCNXFAST8 "X"
-
-#define SCNo16 "ho"
-#define SCNu16 "hu"
-#define SCNx16 "hx"
-#define SCNX16 "hX"
-#define SCNoLEAST16 "ho"
-#define SCNuLEAST16 "hu"
-#define SCNxLEAST16 "hx"
-#define SCNXLEAST16 "hX"
-#define SCNoFAST16 "ho"
-#define SCNuFAST16 "hu"
-#define SCNxFAST16 "hx"
-#define SCNXFAST16 "hX"
-
-#define SCNo32 "lo"
-#define SCNu32 "lu"
-#define SCNx32 "lx"
-#define SCNX32 "lX"
-#define SCNoLEAST32 "lo"
-#define SCNuLEAST32 "lu"
-#define SCNxLEAST32 "lx"
-#define SCNXLEAST32 "lX"
-#define SCNoFAST32 "lo"
-#define SCNuFAST32 "lu"
-#define SCNxFAST32 "lx"
-#define SCNXFAST32 "lX"
-
-#define SCNo64 "I64o"
-#define SCNu64 "I64u"
-#define SCNx64 "I64x"
-#define SCNX64 "I64X"
-#define SCNoLEAST64 "I64o"
-#define SCNuLEAST64 "I64u"
-#define SCNxLEAST64 "I64x"
-#define SCNXLEAST64 "I64X"
-#define SCNoFAST64 "I64o"
-#define SCNuFAST64 "I64u"
-#define SCNxFAST64 "I64x"
-#define SCNXFAST64 "I64X"
-
-#define SCNoMAX "I64o"
-#define SCNuMAX "I64u"
-#define SCNxMAX "I64x"
-#define SCNXMAX "I64X"
-
-#ifdef _WIN64 // [
-# define SCNoPTR "I64o"
-# define SCNuPTR "I64u"
-# define SCNxPTR "I64x"
-# define SCNXPTR "I64X"
-#else // _WIN64 ][
-# define SCNoPTR "lo"
-# define SCNuPTR "lu"
-# define SCNxPTR "lx"
-# define SCNXPTR "lX"
-#endif // _WIN64 ]
-
-#endif // __STDC_FORMAT_MACROS ]
-
-// 7.8.2 Functions for greatest-width integer types
-
-// 7.8.2.1 The imaxabs function
-#define imaxabs _abs64
-
-// 7.8.2.2 The imaxdiv function
-
-// This is modified version of div() function from Microsoft's div.c found
-// in %MSVC.NET%\crt\src\div.c
-#ifdef STATIC_IMAXDIV // [
-static
-#else // STATIC_IMAXDIV ][
-_inline
-#endif // STATIC_IMAXDIV ]
-imaxdiv_t __cdecl imaxdiv(intmax_t numer, intmax_t denom)
-{
- imaxdiv_t result;
-
- result.quot = numer / denom;
- result.rem = numer % denom;
-
- if (numer < 0 && result.rem > 0) {
- // did division wrong; must fix up
- ++result.quot;
- result.rem -= denom;
- }
-
- return result;
-}
-
-// 7.8.2.3 The strtoimax and strtoumax functions
-#define strtoimax _strtoi64
-#define strtoumax _strtoui64
-
-// 7.8.2.4 The wcstoimax and wcstoumax functions
-#define wcstoimax _wcstoi64
-#define wcstoumax _wcstoui64
-
-#endif // _MSC_VER >= 1800
-
-#endif // _MSC_INTTYPES_H_ ]
diff --git a/libs/rapidjson/msinttypes/stdint.h b/libs/rapidjson/msinttypes/stdint.h
deleted file mode 100644
index a26fff4bf..000000000
--- a/libs/rapidjson/msinttypes/stdint.h
+++ /dev/null
@@ -1,300 +0,0 @@
-// ISO C9x compliant stdint.h for Microsoft Visual Studio
-// Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124
-//
-// Copyright (c) 2006-2013 Alexander Chemeris
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-// 1. Redistributions of source code must retain the above copyright notice,
-// this list of conditions and the following disclaimer.
-//
-// 2. Redistributions in binary form must reproduce the above copyright
-// notice, this list of conditions and the following disclaimer in the
-// documentation and/or other materials provided with the distribution.
-//
-// 3. Neither the name of the product nor the names of its contributors may
-// be used to endorse or promote products derived from this software
-// without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
-// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
-// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
-// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
-// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
-// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
-// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
-// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-//
-///////////////////////////////////////////////////////////////////////////////
-
-// The above software in this distribution may have been modified by
-// THL A29 Limited ("Tencent Modifications").
-// All Tencent Modifications are Copyright (C) 2015 THL A29 Limited.
-
-#ifndef _MSC_VER // [
-#error "Use this header only with Microsoft Visual C++ compilers!"
-#endif // _MSC_VER ]
-
-#ifndef _MSC_STDINT_H_ // [
-#define _MSC_STDINT_H_
-
-#if _MSC_VER > 1000
-#pragma once
-#endif
-
-// miloyip: Originally Visual Studio 2010 uses its own stdint.h. However it generates warning with INT64_C(), so change to use this file for vs2010.
-#if _MSC_VER >= 1600 // [
-#include <stdint.h>
-
-#if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260
-
-#undef INT8_C
-#undef INT16_C
-#undef INT32_C
-#undef INT64_C
-#undef UINT8_C
-#undef UINT16_C
-#undef UINT32_C
-#undef UINT64_C
-
-// 7.18.4.1 Macros for minimum-width integer constants
-
-#define INT8_C(val) val##i8
-#define INT16_C(val) val##i16
-#define INT32_C(val) val##i32
-#define INT64_C(val) val##i64
-
-#define UINT8_C(val) val##ui8
-#define UINT16_C(val) val##ui16
-#define UINT32_C(val) val##ui32
-#define UINT64_C(val) val##ui64
-
-// 7.18.4.2 Macros for greatest-width integer constants
-// These #ifndef's are needed to prevent collisions with <boost/cstdint.hpp>.
-// Check out Issue 9 for the details.
-#ifndef INTMAX_C // [
-# define INTMAX_C INT64_C
-#endif // INTMAX_C ]
-#ifndef UINTMAX_C // [
-# define UINTMAX_C UINT64_C
-#endif // UINTMAX_C ]
-
-#endif // __STDC_CONSTANT_MACROS ]
-
-#else // ] _MSC_VER >= 1700 [
-
-#include <limits.h>
-
-// For Visual Studio 6 in C++ mode and for many Visual Studio versions when
-// compiling for ARM we should wrap <wchar.h> include with 'extern "C++" {}'
-// or compiler give many errors like this:
-// error C2733: second C linkage of overloaded function 'wmemchr' not allowed
-#ifdef __cplusplus
-extern "C" {
-#endif
-# include <wchar.h>
-#ifdef __cplusplus
-}
-#endif
-
-// Define _W64 macros to mark types changing their size, like intptr_t.
-#ifndef _W64
-# if !defined(__midl) && (defined(_X86_) || defined(_M_IX86)) && _MSC_VER >= 1300
-# define _W64 __w64
-# else
-# define _W64
-# endif
-#endif
-
-
-// 7.18.1 Integer types
-
-// 7.18.1.1 Exact-width integer types
-
-// Visual Studio 6 and Embedded Visual C++ 4 doesn't
-// realize that, e.g. char has the same size as __int8
-// so we give up on __intX for them.
-#if (_MSC_VER < 1300)
- typedef signed char int8_t;
- typedef signed short int16_t;
- typedef signed int int32_t;
- typedef unsigned char uint8_t;
- typedef unsigned short uint16_t;
- typedef unsigned int uint32_t;
-#else
- typedef signed __int8 int8_t;
- typedef signed __int16 int16_t;
- typedef signed __int32 int32_t;
- typedef unsigned __int8 uint8_t;
- typedef unsigned __int16 uint16_t;
- typedef unsigned __int32 uint32_t;
-#endif
-typedef signed __int64 int64_t;
-typedef unsigned __int64 uint64_t;
-
-
-// 7.18.1.2 Minimum-width integer types
-typedef int8_t int_least8_t;
-typedef int16_t int_least16_t;
-typedef int32_t int_least32_t;
-typedef int64_t int_least64_t;
-typedef uint8_t uint_least8_t;
-typedef uint16_t uint_least16_t;
-typedef uint32_t uint_least32_t;
-typedef uint64_t uint_least64_t;
-
-// 7.18.1.3 Fastest minimum-width integer types
-typedef int8_t int_fast8_t;
-typedef int16_t int_fast16_t;
-typedef int32_t int_fast32_t;
-typedef int64_t int_fast64_t;
-typedef uint8_t uint_fast8_t;
-typedef uint16_t uint_fast16_t;
-typedef uint32_t uint_fast32_t;
-typedef uint64_t uint_fast64_t;
-
-// 7.18.1.4 Integer types capable of holding object pointers
-#ifdef _WIN64 // [
- typedef signed __int64 intptr_t;
- typedef unsigned __int64 uintptr_t;
-#else // _WIN64 ][
- typedef _W64 signed int intptr_t;
- typedef _W64 unsigned int uintptr_t;
-#endif // _WIN64 ]
-
-// 7.18.1.5 Greatest-width integer types
-typedef int64_t intmax_t;
-typedef uint64_t uintmax_t;
-
-
-// 7.18.2 Limits of specified-width integer types
-
-#if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS) // [ See footnote 220 at page 257 and footnote 221 at page 259
-
-// 7.18.2.1 Limits of exact-width integer types
-#define INT8_MIN ((int8_t)_I8_MIN)
-#define INT8_MAX _I8_MAX
-#define INT16_MIN ((int16_t)_I16_MIN)
-#define INT16_MAX _I16_MAX
-#define INT32_MIN ((int32_t)_I32_MIN)
-#define INT32_MAX _I32_MAX
-#define INT64_MIN ((int64_t)_I64_MIN)
-#define INT64_MAX _I64_MAX
-#define UINT8_MAX _UI8_MAX
-#define UINT16_MAX _UI16_MAX
-#define UINT32_MAX _UI32_MAX
-#define UINT64_MAX _UI64_MAX
-
-// 7.18.2.2 Limits of minimum-width integer types
-#define INT_LEAST8_MIN INT8_MIN
-#define INT_LEAST8_MAX INT8_MAX
-#define INT_LEAST16_MIN INT16_MIN
-#define INT_LEAST16_MAX INT16_MAX
-#define INT_LEAST32_MIN INT32_MIN
-#define INT_LEAST32_MAX INT32_MAX
-#define INT_LEAST64_MIN INT64_MIN
-#define INT_LEAST64_MAX INT64_MAX
-#define UINT_LEAST8_MAX UINT8_MAX
-#define UINT_LEAST16_MAX UINT16_MAX
-#define UINT_LEAST32_MAX UINT32_MAX
-#define UINT_LEAST64_MAX UINT64_MAX
-
-// 7.18.2.3 Limits of fastest minimum-width integer types
-#define INT_FAST8_MIN INT8_MIN
-#define INT_FAST8_MAX INT8_MAX
-#define INT_FAST16_MIN INT16_MIN
-#define INT_FAST16_MAX INT16_MAX
-#define INT_FAST32_MIN INT32_MIN
-#define INT_FAST32_MAX INT32_MAX
-#define INT_FAST64_MIN INT64_MIN
-#define INT_FAST64_MAX INT64_MAX
-#define UINT_FAST8_MAX UINT8_MAX
-#define UINT_FAST16_MAX UINT16_MAX
-#define UINT_FAST32_MAX UINT32_MAX
-#define UINT_FAST64_MAX UINT64_MAX
-
-// 7.18.2.4 Limits of integer types capable of holding object pointers
-#ifdef _WIN64 // [
-# define INTPTR_MIN INT64_MIN
-# define INTPTR_MAX INT64_MAX
-# define UINTPTR_MAX UINT64_MAX
-#else // _WIN64 ][
-# define INTPTR_MIN INT32_MIN
-# define INTPTR_MAX INT32_MAX
-# define UINTPTR_MAX UINT32_MAX
-#endif // _WIN64 ]
-
-// 7.18.2.5 Limits of greatest-width integer types
-#define INTMAX_MIN INT64_MIN
-#define INTMAX_MAX INT64_MAX
-#define UINTMAX_MAX UINT64_MAX
-
-// 7.18.3 Limits of other integer types
-
-#ifdef _WIN64 // [
-# define PTRDIFF_MIN _I64_MIN
-# define PTRDIFF_MAX _I64_MAX
-#else // _WIN64 ][
-# define PTRDIFF_MIN _I32_MIN
-# define PTRDIFF_MAX _I32_MAX
-#endif // _WIN64 ]
-
-#define SIG_ATOMIC_MIN INT_MIN
-#define SIG_ATOMIC_MAX INT_MAX
-
-#ifndef SIZE_MAX // [
-# ifdef _WIN64 // [
-# define SIZE_MAX _UI64_MAX
-# else // _WIN64 ][
-# define SIZE_MAX _UI32_MAX
-# endif // _WIN64 ]
-#endif // SIZE_MAX ]
-
-// WCHAR_MIN and WCHAR_MAX are also defined in <wchar.h>
-#ifndef WCHAR_MIN // [
-# define WCHAR_MIN 0
-#endif // WCHAR_MIN ]
-#ifndef WCHAR_MAX // [
-# define WCHAR_MAX _UI16_MAX
-#endif // WCHAR_MAX ]
-
-#define WINT_MIN 0
-#define WINT_MAX _UI16_MAX
-
-#endif // __STDC_LIMIT_MACROS ]
-
-
-// 7.18.4 Limits of other integer types
-
-#if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260
-
-// 7.18.4.1 Macros for minimum-width integer constants
-
-#define INT8_C(val) val##i8
-#define INT16_C(val) val##i16
-#define INT32_C(val) val##i32
-#define INT64_C(val) val##i64
-
-#define UINT8_C(val) val##ui8
-#define UINT16_C(val) val##ui16
-#define UINT32_C(val) val##ui32
-#define UINT64_C(val) val##ui64
-
-// 7.18.4.2 Macros for greatest-width integer constants
-// These #ifndef's are needed to prevent collisions with <boost/cstdint.hpp>.
-// Check out Issue 9 for the details.
-#ifndef INTMAX_C // [
-# define INTMAX_C INT64_C
-#endif // INTMAX_C ]
-#ifndef UINTMAX_C // [
-# define UINTMAX_C UINT64_C
-#endif // UINTMAX_C ]
-
-#endif // __STDC_CONSTANT_MACROS ]
-
-#endif // _MSC_VER >= 1600 ]
-
-#endif // _MSC_STDINT_H_ ]
diff --git a/libs/rapidjson/prettywriter.h b/libs/rapidjson/prettywriter.h
deleted file mode 100644
index fff888621..000000000
--- a/libs/rapidjson/prettywriter.h
+++ /dev/null
@@ -1,207 +0,0 @@
-// Tencent is pleased to support the open source community by making RapidJSON available.
-//
-// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
-//
-// Licensed under the MIT License (the "License"); you may not use this file except
-// in compliance with the License. You may obtain a copy of the License at
-//
-// http://opensource.org/licenses/MIT
-//
-// Unless required by applicable law or agreed to in writing, software distributed
-// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
-// CONDITIONS OF ANY KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations under the License.
-
-#ifndef RAPIDJSON_PRETTYWRITER_H_
-#define RAPIDJSON_PRETTYWRITER_H_
-
-#include "writer.h"
-
-#ifdef __GNUC__
-RAPIDJSON_DIAG_PUSH
-RAPIDJSON_DIAG_OFF(effc++)
-#endif
-
-RAPIDJSON_NAMESPACE_BEGIN
-
-//! Writer with indentation and spacing.
-/*!
- \tparam OutputStream Type of ouptut os.
- \tparam SourceEncoding Encoding of source string.
- \tparam TargetEncoding Encoding of output stream.
- \tparam StackAllocator Type of allocator for allocating memory of stack.
-*/
-template<typename OutputStream, typename SourceEncoding = UTF8<>, typename TargetEncoding = UTF8<>, typename StackAllocator = CrtAllocator>
-class PrettyWriter : public Writer<OutputStream, SourceEncoding, TargetEncoding, StackAllocator> {
-public:
- typedef Writer<OutputStream, SourceEncoding, TargetEncoding, StackAllocator> Base;
- typedef typename Base::Ch Ch;
-
- //! Constructor
- /*! \param os Output stream.
- \param allocator User supplied allocator. If it is null, it will create a private one.
- \param levelDepth Initial capacity of stack.
- */
- PrettyWriter(OutputStream& os, StackAllocator* allocator = 0, size_t levelDepth = Base::kDefaultLevelDepth) :
- Base(os, allocator, levelDepth), indentChar_(' '), indentCharCount_(4) {}
-
- //! Set custom indentation.
- /*! \param indentChar Character for indentation. Must be whitespace character (' ', '\\t', '\\n', '\\r').
- \param indentCharCount Number of indent characters for each indentation level.
- \note The default indentation is 4 spaces.
- */
- PrettyWriter& SetIndent(Ch indentChar, unsigned indentCharCount) {
- RAPIDJSON_ASSERT(indentChar == ' ' || indentChar == '\t' || indentChar == '\n' || indentChar == '\r');
- indentChar_ = indentChar;
- indentCharCount_ = indentCharCount;
- return *this;
- }
-
- /*! @name Implementation of Handler
- \see Handler
- */
- //@{
-
- bool Null() { PrettyPrefix(kNullType); return Base::WriteNull(); }
- bool Bool(bool b) { PrettyPrefix(b ? kTrueType : kFalseType); return Base::WriteBool(b); }
- bool Int(int i) { PrettyPrefix(kNumberType); return Base::WriteInt(i); }
- bool Uint(unsigned u) { PrettyPrefix(kNumberType); return Base::WriteUint(u); }
- bool Int64(int64_t i64) { PrettyPrefix(kNumberType); return Base::WriteInt64(i64); }
- bool Uint64(uint64_t u64) { PrettyPrefix(kNumberType); return Base::WriteUint64(u64); }
- bool Double(double d) { PrettyPrefix(kNumberType); return Base::WriteDouble(d); }
-
- bool String(const Ch* str, SizeType length, bool copy = false) {
- (void)copy;
- PrettyPrefix(kStringType);
- return Base::WriteString(str, length);
- }
-
-#if RAPIDJSON_HAS_STDSTRING
- bool String(const std::basic_string<Ch>& str) {
- return String(str.data(), SizeType(str.size()));
- }
-#endif
-
- bool StartObject() {
- PrettyPrefix(kObjectType);
- new (Base::level_stack_.template Push<typename Base::Level>()) typename Base::Level(false);
- return Base::WriteStartObject();
- }
-
- bool Key(const Ch* str, SizeType length, bool copy = false) { return String(str, length, copy); }
-
- bool EndObject(SizeType memberCount = 0) {
- (void)memberCount;
- RAPIDJSON_ASSERT(Base::level_stack_.GetSize() >= sizeof(typename Base::Level));
- RAPIDJSON_ASSERT(!Base::level_stack_.template Top<typename Base::Level>()->inArray);
- bool empty = Base::level_stack_.template Pop<typename Base::Level>(1)->valueCount == 0;
-
- if (!empty) {
- Base::os_->Put('\n');
- WriteIndent();
- }
- bool ret = Base::WriteEndObject();
- (void)ret;
- RAPIDJSON_ASSERT(ret == true);
- if (Base::level_stack_.Empty()) // end of json text
- Base::os_->Flush();
- return true;
- }
-
- bool StartArray() {
- PrettyPrefix(kArrayType);
- new (Base::level_stack_.template Push<typename Base::Level>()) typename Base::Level(true);
- return Base::WriteStartArray();
- }
-
- bool EndArray(SizeType memberCount = 0) {
- (void)memberCount;
- RAPIDJSON_ASSERT(Base::level_stack_.GetSize() >= sizeof(typename Base::Level));
- RAPIDJSON_ASSERT(Base::level_stack_.template Top<typename Base::Level>()->inArray);
- bool empty = Base::level_stack_.template Pop<typename Base::Level>(1)->valueCount == 0;
-
- if (!empty) {
- Base::os_->Put('\n');
- WriteIndent();
- }
- bool ret = Base::WriteEndArray();
- (void)ret;
- RAPIDJSON_ASSERT(ret == true);
- if (Base::level_stack_.Empty()) // end of json text
- Base::os_->Flush();
- return true;
- }
-
- //@}
-
- /*! @name Convenience extensions */
- //@{
-
- //! Simpler but slower overload.
- bool String(const Ch* str) { return String(str, internal::StrLen(str)); }
- bool Key(const Ch* str) { return Key(str, internal::StrLen(str)); }
-
- //@}
-protected:
- void PrettyPrefix(Type type) {
- (void)type;
- if (Base::level_stack_.GetSize() != 0) { // this value is not at root
- typename Base::Level* level = Base::level_stack_.template Top<typename Base::Level>();
-
- if (level->inArray) {
- if (level->valueCount > 0) {
- Base::os_->Put(','); // add comma if it is not the first element in array
- Base::os_->Put('\n');
- }
- else
- Base::os_->Put('\n');
- WriteIndent();
- }
- else { // in object
- if (level->valueCount > 0) {
- if (level->valueCount % 2 == 0) {
- Base::os_->Put(',');
- Base::os_->Put('\n');
- }
- else {
- Base::os_->Put(':');
- Base::os_->Put(' ');
- }
- }
- else
- Base::os_->Put('\n');
-
- if (level->valueCount % 2 == 0)
- WriteIndent();
- }
- if (!level->inArray && level->valueCount % 2 == 0)
- RAPIDJSON_ASSERT(type == kStringType); // if it's in object, then even number should be a name
- level->valueCount++;
- }
- else {
- RAPIDJSON_ASSERT(!Base::hasRoot_); // Should only has one and only one root.
- Base::hasRoot_ = true;
- }
- }
-
- void WriteIndent() {
- size_t count = (Base::level_stack_.GetSize() / sizeof(typename Base::Level)) * indentCharCount_;
- PutN(*Base::os_, indentChar_, count);
- }
-
- Ch indentChar_;
- unsigned indentCharCount_;
-
-private:
- // Prohibit copy constructor & assignment operator.
- PrettyWriter(const PrettyWriter&);
- PrettyWriter& operator=(const PrettyWriter&);
-};
-
-RAPIDJSON_NAMESPACE_END
-
-#ifdef __GNUC__
-RAPIDJSON_DIAG_POP
-#endif
-
-#endif // RAPIDJSON_RAPIDJSON_H_
diff --git a/libs/rapidjson/rapidjson.h b/libs/rapidjson/rapidjson.h
deleted file mode 100644
index 4351aeae9..000000000
--- a/libs/rapidjson/rapidjson.h
+++ /dev/null
@@ -1,620 +0,0 @@
-// Tencent is pleased to support the open source community by making RapidJSON available.
-//
-// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
-//
-// Licensed under the MIT License (the "License"); you may not use this file except
-// in compliance with the License. You may obtain a copy of the License at
-//
-// http://opensource.org/licenses/MIT
-//
-// Unless required by applicable law or agreed to in writing, software distributed
-// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
-// CONDITIONS OF ANY KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations under the License.
-
-#ifndef RAPIDJSON_RAPIDJSON_H_
-#define RAPIDJSON_RAPIDJSON_H_
-
-/*!\file rapidjson.h
- \brief common definitions and configuration
-
- \see RAPIDJSON_CONFIG
- */
-
-/*! \defgroup RAPIDJSON_CONFIG RapidJSON configuration
- \brief Configuration macros for library features
-
- Some RapidJSON features are configurable to adapt the library to a wide
- variety of platforms, environments and usage scenarios. Most of the
- features can be configured in terms of overriden or predefined
- preprocessor macros at compile-time.
-
- Some additional customization is available in the \ref RAPIDJSON_ERRORS APIs.
-
- \note These macros should be given on the compiler command-line
- (where applicable) to avoid inconsistent values when compiling
- different translation units of a single application.
- */
-
-#include <cstdlib> // malloc(), realloc(), free(), size_t
-#include <cstring> // memset(), memcpy(), memmove(), memcmp()
-
-///////////////////////////////////////////////////////////////////////////////
-// RAPIDJSON_NAMESPACE_(BEGIN|END)
-/*! \def RAPIDJSON_NAMESPACE
- \ingroup RAPIDJSON_CONFIG
- \brief provide custom rapidjson namespace
-
- In order to avoid symbol clashes and/or "One Definition Rule" errors
- between multiple inclusions of (different versions of) RapidJSON in
- a single binary, users can customize the name of the main RapidJSON
- namespace.
-
- In case of a single nesting level, defining \c RAPIDJSON_NAMESPACE
- to a custom name (e.g. \c MyRapidJSON) is sufficient. If multiple
- levels are needed, both \ref RAPIDJSON_NAMESPACE_BEGIN and \ref
- RAPIDJSON_NAMESPACE_END need to be defined as well:
-
- \code
- // in some .cpp file
- #define RAPIDJSON_NAMESPACE my::rapidjson
- #define RAPIDJSON_NAMESPACE_BEGIN namespace my { namespace rapidjson {
- #define RAPIDJSON_NAMESPACE_END } }
- #include "rapidjson/..."
- \endcode
-
- \see rapidjson
- */
-/*! \def RAPIDJSON_NAMESPACE_BEGIN
- \ingroup RAPIDJSON_CONFIG
- \brief provide custom rapidjson namespace (opening expression)
- \see RAPIDJSON_NAMESPACE
-*/
-/*! \def RAPIDJSON_NAMESPACE_END
- \ingroup RAPIDJSON_CONFIG
- \brief provide custom rapidjson namespace (closing expression)
- \see RAPIDJSON_NAMESPACE
-*/
-#ifndef RAPIDJSON_NAMESPACE
-#define RAPIDJSON_NAMESPACE rapidjson
-#endif
-#ifndef RAPIDJSON_NAMESPACE_BEGIN
-#define RAPIDJSON_NAMESPACE_BEGIN namespace RAPIDJSON_NAMESPACE {
-#endif
-#ifndef RAPIDJSON_NAMESPACE_END
-#define RAPIDJSON_NAMESPACE_END }
-#endif
-
-///////////////////////////////////////////////////////////////////////////////
-// RAPIDJSON_NO_INT64DEFINE
-
-/*! \def RAPIDJSON_NO_INT64DEFINE
- \ingroup RAPIDJSON_CONFIG
- \brief Use external 64-bit integer types.
-
- RapidJSON requires the 64-bit integer types \c int64_t and \c uint64_t types
- to be available at global scope.
-
- If users have their own definition, define RAPIDJSON_NO_INT64DEFINE to
- prevent RapidJSON from defining its own types.
-*/
-#ifndef RAPIDJSON_NO_INT64DEFINE
-//!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN
-#ifdef _MSC_VER
-#include "msinttypes/stdint.h"
-#include "msinttypes/inttypes.h"
-#else
-// Other compilers should have this.
-#include <stdint.h>
-#include <inttypes.h>
-#endif
-//!@endcond
-#ifdef RAPIDJSON_DOXYGEN_RUNNING
-#define RAPIDJSON_NO_INT64DEFINE
-#endif
-#endif // RAPIDJSON_NO_INT64TYPEDEF
-
-///////////////////////////////////////////////////////////////////////////////
-// RAPIDJSON_FORCEINLINE
-
-#ifndef RAPIDJSON_FORCEINLINE
-//!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN
-#if defined(_MSC_VER) && !defined(NDEBUG)
-#define RAPIDJSON_FORCEINLINE __forceinline
-#elif defined(__GNUC__) && __GNUC__ >= 4 && !defined(NDEBUG)
-#define RAPIDJSON_FORCEINLINE __attribute__((always_inline))
-#else
-#define RAPIDJSON_FORCEINLINE
-#endif
-//!@endcond
-#endif // RAPIDJSON_FORCEINLINE
-
-///////////////////////////////////////////////////////////////////////////////
-// RAPIDJSON_ENDIAN
-#define RAPIDJSON_LITTLEENDIAN 0 //!< Little endian machine
-#define RAPIDJSON_BIGENDIAN 1 //!< Big endian machine
-
-//! Endianness of the machine.
-/*!
- \def RAPIDJSON_ENDIAN
- \ingroup RAPIDJSON_CONFIG
-
- GCC 4.6 provided macro for detecting endianness of the target machine. But other
- compilers may not have this. User can define RAPIDJSON_ENDIAN to either
- \ref RAPIDJSON_LITTLEENDIAN or \ref RAPIDJSON_BIGENDIAN.
-
- Default detection implemented with reference to
- \li https://gcc.gnu.org/onlinedocs/gcc-4.6.0/cpp/Common-Predefined-Macros.html
- \li http://www.boost.org/doc/libs/1_42_0/boost/detail/endian.hpp
-*/
-#ifndef RAPIDJSON_ENDIAN
-// Detect with GCC 4.6's macro
-# ifdef __BYTE_ORDER__
-# if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
-# define RAPIDJSON_ENDIAN RAPIDJSON_LITTLEENDIAN
-# elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
-# define RAPIDJSON_ENDIAN RAPIDJSON_BIGENDIAN
-# else
-# error Unknown machine endianess detected. User needs to define RAPIDJSON_ENDIAN.
-# endif // __BYTE_ORDER__
-// Detect with GLIBC's endian.h
-# elif defined(__GLIBC__)
-# include <endian.h>
-# if (__BYTE_ORDER == __LITTLE_ENDIAN)
-# define RAPIDJSON_ENDIAN RAPIDJSON_LITTLEENDIAN
-# elif (__BYTE_ORDER == __BIG_ENDIAN)
-# define RAPIDJSON_ENDIAN RAPIDJSON_BIGENDIAN
-# else
-# error Unknown machine endianess detected. User needs to define RAPIDJSON_ENDIAN.
-# endif // __GLIBC__
-// Detect with _LITTLE_ENDIAN and _BIG_ENDIAN macro
-# elif defined(_LITTLE_ENDIAN) && !defined(_BIG_ENDIAN)
-# define RAPIDJSON_ENDIAN RAPIDJSON_LITTLEENDIAN
-# elif defined(_BIG_ENDIAN) && !defined(_LITTLE_ENDIAN)
-# define RAPIDJSON_ENDIAN RAPIDJSON_BIGENDIAN
-// Detect with architecture macros
-# elif defined(__sparc) || defined(__sparc__) || defined(_POWER) || defined(__powerpc__) || defined(__ppc__) || defined(__hpux) || defined(__hppa) || defined(_MIPSEB) || defined(_POWER) || defined(__s390__)
-# define RAPIDJSON_ENDIAN RAPIDJSON_BIGENDIAN
-# elif defined(__i386__) || defined(__alpha__) || defined(__ia64) || defined(__ia64__) || defined(_M_IX86) || defined(_M_IA64) || defined(_M_ALPHA) || defined(__amd64) || defined(__amd64__) || defined(_M_AMD64) || defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || defined(__bfin__)
-# define RAPIDJSON_ENDIAN RAPIDJSON_LITTLEENDIAN
-# elif defined(RAPIDJSON_DOXYGEN_RUNNING)
-# define RAPIDJSON_ENDIAN
-# else
-# error Unknown machine endianess detected. User needs to define RAPIDJSON_ENDIAN.
-# endif
-#endif // RAPIDJSON_ENDIAN
-
-///////////////////////////////////////////////////////////////////////////////
-// RAPIDJSON_64BIT
-
-//! Whether using 64-bit architecture
-#ifndef RAPIDJSON_64BIT
-#if defined(__LP64__) || defined(_WIN64)
-#define RAPIDJSON_64BIT 1
-#else
-#define RAPIDJSON_64BIT 0
-#endif
-#endif // RAPIDJSON_64BIT
-
-///////////////////////////////////////////////////////////////////////////////
-// RAPIDJSON_ALIGN
-
-//! Data alignment of the machine.
-/*! \ingroup RAPIDJSON_CONFIG
- \param x pointer to align
-
- Some machines require strict data alignment. Currently the default uses 4 bytes
- alignment. User can customize by defining the RAPIDJSON_ALIGN function macro.,
-*/
-#ifndef RAPIDJSON_ALIGN
-#define RAPIDJSON_ALIGN(x) ((x + 3u) & ~3u)
-#endif
-
-///////////////////////////////////////////////////////////////////////////////
-// RAPIDJSON_UINT64_C2
-
-//! Construct a 64-bit literal by a pair of 32-bit integer.
-/*!
- 64-bit literal with or without ULL suffix is prone to compiler warnings.
- UINT64_C() is C macro which cause compilation problems.
- Use this macro to define 64-bit constants by a pair of 32-bit integer.
-*/
-#ifndef RAPIDJSON_UINT64_C2
-#define RAPIDJSON_UINT64_C2(high32, low32) ((static_cast<uint64_t>(high32) << 32) | static_cast<uint64_t>(low32))
-#endif
-
-///////////////////////////////////////////////////////////////////////////////
-// RAPIDJSON_SSE2/RAPIDJSON_SSE42/RAPIDJSON_SIMD
-
-/*! \def RAPIDJSON_SIMD
- \ingroup RAPIDJSON_CONFIG
- \brief Enable SSE2/SSE4.2 optimization.
-
- RapidJSON supports optimized implementations for some parsing operations
- based on the SSE2 or SSE4.2 SIMD extensions on modern Intel-compatible
- processors.
-
- To enable these optimizations, two different symbols can be defined;
- \code
- // Enable SSE2 optimization.
- #define RAPIDJSON_SSE2
-
- // Enable SSE4.2 optimization.
- #define RAPIDJSON_SSE42
- \endcode
-
- \c RAPIDJSON_SSE42 takes precedence, if both are defined.
-
- If any of these symbols is defined, RapidJSON defines the macro
- \c RAPIDJSON_SIMD to indicate the availability of the optimized code.
-*/
-#if defined(RAPIDJSON_SSE2) || defined(RAPIDJSON_SSE42) \
- || defined(RAPIDJSON_DOXYGEN_RUNNING)
-#define RAPIDJSON_SIMD
-#endif
-
-///////////////////////////////////////////////////////////////////////////////
-// RAPIDJSON_NO_SIZETYPEDEFINE
-
-#ifndef RAPIDJSON_NO_SIZETYPEDEFINE
-/*! \def RAPIDJSON_NO_SIZETYPEDEFINE
- \ingroup RAPIDJSON_CONFIG
- \brief User-provided \c SizeType definition.
-
- In order to avoid using 32-bit size types for indexing strings and arrays,
- define this preprocessor symbol and provide the type rapidjson::SizeType
- before including RapidJSON:
- \code
- #define RAPIDJSON_NO_SIZETYPEDEFINE
- namespace rapidjson { typedef ::std::size_t SizeType; }
- #include "rapidjson/..."
- \endcode
-
- \see rapidjson::SizeType
-*/
-#ifdef RAPIDJSON_DOXYGEN_RUNNING
-#define RAPIDJSON_NO_SIZETYPEDEFINE
-#endif
-RAPIDJSON_NAMESPACE_BEGIN
-//! Size type (for string lengths, array sizes, etc.)
-/*! RapidJSON uses 32-bit array/string indices even on 64-bit platforms,
- instead of using \c size_t. Users may override the SizeType by defining
- \ref RAPIDJSON_NO_SIZETYPEDEFINE.
-*/
-typedef unsigned SizeType;
-RAPIDJSON_NAMESPACE_END
-#endif
-
-// always import std::size_t to rapidjson namespace
-RAPIDJSON_NAMESPACE_BEGIN
-using std::size_t;
-RAPIDJSON_NAMESPACE_END
-
-///////////////////////////////////////////////////////////////////////////////
-// RAPIDJSON_ASSERT
-
-//! Assertion.
-/*! \ingroup RAPIDJSON_CONFIG
- By default, rapidjson uses C \c assert() for internal assertions.
- User can override it by defining RAPIDJSON_ASSERT(x) macro.
-
- \note Parsing errors are handled and can be customized by the
- \ref RAPIDJSON_ERRORS APIs.
-*/
-#ifndef RAPIDJSON_ASSERT
-#include <cassert>
-#define RAPIDJSON_ASSERT(x) assert(x)
-#endif // RAPIDJSON_ASSERT
-
-///////////////////////////////////////////////////////////////////////////////
-// RAPIDJSON_STATIC_ASSERT
-
-// Adopt from boost
-#ifndef RAPIDJSON_STATIC_ASSERT
-//!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN
-RAPIDJSON_NAMESPACE_BEGIN
-template <bool x> struct STATIC_ASSERTION_FAILURE;
-template <> struct STATIC_ASSERTION_FAILURE<true> { enum { value = 1 }; };
-template<int x> struct StaticAssertTest {};
-RAPIDJSON_NAMESPACE_END
-
-#define RAPIDJSON_JOIN(X, Y) RAPIDJSON_DO_JOIN(X, Y)
-#define RAPIDJSON_DO_JOIN(X, Y) RAPIDJSON_DO_JOIN2(X, Y)
-#define RAPIDJSON_DO_JOIN2(X, Y) X##Y
-
-#if defined(__GNUC__)
-#define RAPIDJSON_STATIC_ASSERT_UNUSED_ATTRIBUTE __attribute__((unused))
-#else
-#define RAPIDJSON_STATIC_ASSERT_UNUSED_ATTRIBUTE
-#endif
-//!@endcond
-
-/*! \def RAPIDJSON_STATIC_ASSERT
- \brief (Internal) macro to check for conditions at compile-time
- \param x compile-time condition
- \hideinitializer
- */
-#define RAPIDJSON_STATIC_ASSERT(x) \
- typedef ::RAPIDJSON_NAMESPACE::StaticAssertTest< \
- sizeof(::RAPIDJSON_NAMESPACE::STATIC_ASSERTION_FAILURE<bool(x) >)> \
- RAPIDJSON_JOIN(StaticAssertTypedef, __LINE__) RAPIDJSON_STATIC_ASSERT_UNUSED_ATTRIBUTE
-#endif
-
-///////////////////////////////////////////////////////////////////////////////
-// Helpers
-
-//!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN
-
-#define RAPIDJSON_MULTILINEMACRO_BEGIN do {
-#define RAPIDJSON_MULTILINEMACRO_END \
-} while((void)0, 0)
-
-// adopted from Boost
-#define RAPIDJSON_VERSION_CODE(x,y,z) \
- (((x)*100000) + ((y)*100) + (z))
-
-// token stringification
-#define RAPIDJSON_STRINGIFY(x) RAPIDJSON_DO_STRINGIFY(x)
-#define RAPIDJSON_DO_STRINGIFY(x) #x
-
-///////////////////////////////////////////////////////////////////////////////
-// RAPIDJSON_DIAG_PUSH/POP, RAPIDJSON_DIAG_OFF
-
-#if defined(__GNUC__)
-#define RAPIDJSON_GNUC \
- RAPIDJSON_VERSION_CODE(__GNUC__,__GNUC_MINOR__,__GNUC_PATCHLEVEL__)
-#endif
-
-#if defined(__clang__) || (defined(RAPIDJSON_GNUC) && RAPIDJSON_GNUC >= RAPIDJSON_VERSION_CODE(4,2,0))
-
-#define RAPIDJSON_PRAGMA(x) _Pragma(RAPIDJSON_STRINGIFY(x))
-#define RAPIDJSON_DIAG_PRAGMA(x) RAPIDJSON_PRAGMA(GCC diagnostic x)
-#define RAPIDJSON_DIAG_OFF(x) \
- RAPIDJSON_DIAG_PRAGMA(ignored RAPIDJSON_STRINGIFY(RAPIDJSON_JOIN(-W,x)))
-
-// push/pop support in Clang and GCC>=4.6
-#if defined(__clang__) || (defined(RAPIDJSON_GNUC) && RAPIDJSON_GNUC >= RAPIDJSON_VERSION_CODE(4,6,0))
-#define RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_PRAGMA(push)
-#define RAPIDJSON_DIAG_POP RAPIDJSON_DIAG_PRAGMA(pop)
-#else // GCC >= 4.2, < 4.6
-#define RAPIDJSON_DIAG_PUSH /* ignored */
-#define RAPIDJSON_DIAG_POP /* ignored */
-#endif
-
-#elif defined(_MSC_VER)
-
-// pragma (MSVC specific)
-#define RAPIDJSON_PRAGMA(x) __pragma(x)
-#define RAPIDJSON_DIAG_PRAGMA(x) RAPIDJSON_PRAGMA(warning(x))
-
-#define RAPIDJSON_DIAG_OFF(x) RAPIDJSON_DIAG_PRAGMA(disable: x)
-#define RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_PRAGMA(push)
-#define RAPIDJSON_DIAG_POP RAPIDJSON_DIAG_PRAGMA(pop)
-
-#else
-
-#define RAPIDJSON_DIAG_OFF(x) /* ignored */
-#define RAPIDJSON_DIAG_PUSH /* ignored */
-#define RAPIDJSON_DIAG_POP /* ignored */
-
-#endif // RAPIDJSON_DIAG_*
-
-///////////////////////////////////////////////////////////////////////////////
-// C++11 features
-
-#ifndef RAPIDJSON_HAS_CXX11_RVALUE_REFS
-#if defined(__clang__)
-#define RAPIDJSON_HAS_CXX11_RVALUE_REFS __has_feature(cxx_rvalue_references) && \
- (defined(_LIBCPP_VERSION) || defined(__GLIBCXX__) && __GLIBCXX__ >= 20080306)
-#elif (defined(RAPIDJSON_GNUC) && (RAPIDJSON_GNUC >= RAPIDJSON_VERSION_CODE(4,3,0)) && defined(__GXX_EXPERIMENTAL_CXX0X__)) || \
- (defined(_MSC_VER) && _MSC_VER >= 1600)
-
-#define RAPIDJSON_HAS_CXX11_RVALUE_REFS 1
-#else
-#define RAPIDJSON_HAS_CXX11_RVALUE_REFS 0
-#endif
-#endif // RAPIDJSON_HAS_CXX11_RVALUE_REFS
-
-#ifndef RAPIDJSON_HAS_CXX11_NOEXCEPT
-#if defined(__clang__)
-#define RAPIDJSON_HAS_CXX11_NOEXCEPT __has_feature(cxx_noexcept)
-#elif (defined(RAPIDJSON_GNUC) && (RAPIDJSON_GNUC >= RAPIDJSON_VERSION_CODE(4,6,0)) && defined(__GXX_EXPERIMENTAL_CXX0X__))
-// (defined(_MSC_VER) && _MSC_VER >= ????) // not yet supported
-#define RAPIDJSON_HAS_CXX11_NOEXCEPT 1
-#else
-#define RAPIDJSON_HAS_CXX11_NOEXCEPT 0
-#endif
-#endif
-#if RAPIDJSON_HAS_CXX11_NOEXCEPT
-#define RAPIDJSON_NOEXCEPT noexcept
-#else
-#define RAPIDJSON_NOEXCEPT /* noexcept */
-#endif // RAPIDJSON_HAS_CXX11_NOEXCEPT
-
-// no automatic detection, yet
-#ifndef RAPIDJSON_HAS_CXX11_TYPETRAITS
-#define RAPIDJSON_HAS_CXX11_TYPETRAITS 0
-#endif
-
-//!@endcond
-
-///////////////////////////////////////////////////////////////////////////////
-// new/delete
-
-#ifndef RAPIDJSON_NEW
-///! customization point for global \c new
-#define RAPIDJSON_NEW(x) new x
-#endif
-#ifndef RAPIDJSON_DELETE
-///! customization point for global \c delete
-#define RAPIDJSON_DELETE(x) delete x
-#endif
-
-///////////////////////////////////////////////////////////////////////////////
-// Allocators and Encodings
-
-#include "allocators.h"
-#include "encodings.h"
-
-/*! \namespace rapidjson
- \brief main RapidJSON namespace
- \see RAPIDJSON_NAMESPACE
-*/
-RAPIDJSON_NAMESPACE_BEGIN
-
-///////////////////////////////////////////////////////////////////////////////
-// Stream
-
-/*! \class rapidjson::Stream
- \brief Concept for reading and writing characters.
-
- For read-only stream, no need to implement PutBegin(), Put(), Flush() and PutEnd().
-
- For write-only stream, only need to implement Put() and Flush().
-
-\code
-concept Stream {
- typename Ch; //!< Character type of the stream.
-
- //! Read the current character from stream without moving the read cursor.
- Ch Peek() const;
-
- //! Read the current character from stream and moving the read cursor to next character.
- Ch Take();
-
- //! Get the current read cursor.
- //! \return Number of characters read from start.
- size_t Tell();
-
- //! Begin writing operation at the current read pointer.
- //! \return The begin writer pointer.
- Ch* PutBegin();
-
- //! Write a character.
- void Put(Ch c);
-
- //! Flush the buffer.
- void Flush();
-
- //! End the writing operation.
- //! \param begin The begin write pointer returned by PutBegin().
- //! \return Number of characters written.
- size_t PutEnd(Ch* begin);
-}
-\endcode
-*/
-
-//! Provides additional information for stream.
-/*!
- By using traits pattern, this type provides a default configuration for stream.
- For custom stream, this type can be specialized for other configuration.
- See TEST(Reader, CustomStringStream) in readertest.cpp for example.
-*/
-template<typename Stream>
-struct StreamTraits {
- //! Whether to make local copy of stream for optimization during parsing.
- /*!
- By default, for safety, streams do not use local copy optimization.
- Stream that can be copied fast should specialize this, like StreamTraits<StringStream>.
- */
- enum { copyOptimization = 0 };
-};
-
-//! Put N copies of a character to a stream.
-template<typename Stream, typename Ch>
-inline void PutN(Stream& stream, Ch c, size_t n) {
- for (size_t i = 0; i < n; i++)
- stream.Put(c);
-}
-
-///////////////////////////////////////////////////////////////////////////////
-// StringStream
-
-//! Read-only string stream.
-/*! \note implements Stream concept
-*/
-template <typename Encoding>
-struct GenericStringStream {
- typedef typename Encoding::Ch Ch;
-
- GenericStringStream(const Ch *src) : src_(src), head_(src) {}
-
- Ch Peek() const { return *src_; }
- Ch Take() { return *src_++; }
- size_t Tell() const { return static_cast<size_t>(src_ - head_); }
-
- Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; }
- void Put(Ch) { RAPIDJSON_ASSERT(false); }
- void Flush() { RAPIDJSON_ASSERT(false); }
- size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; }
-
- const Ch* src_; //!< Current read position.
- const Ch* head_; //!< Original head of the string.
-};
-
-template <typename Encoding>
-struct StreamTraits<GenericStringStream<Encoding> > {
- enum { copyOptimization = 1 };
-};
-
-//! String stream with UTF8 encoding.
-typedef GenericStringStream<UTF8<> > StringStream;
-
-///////////////////////////////////////////////////////////////////////////////
-// InsituStringStream
-
-//! A read-write string stream.
-/*! This string stream is particularly designed for in-situ parsing.
- \note implements Stream concept
-*/
-template <typename Encoding>
-struct GenericInsituStringStream {
- typedef typename Encoding::Ch Ch;
-
- GenericInsituStringStream(Ch *src) : src_(src), dst_(0), head_(src) {}
-
- // Read
- Ch Peek() { return *src_; }
- Ch Take() { return *src_++; }
- size_t Tell() { return static_cast<size_t>(src_ - head_); }
-
- // Write
- void Put(Ch c) { RAPIDJSON_ASSERT(dst_ != 0); *dst_++ = c; }
-
- Ch* PutBegin() { return dst_ = src_; }
- size_t PutEnd(Ch* begin) { return static_cast<size_t>(dst_ - begin); }
- void Flush() {}
-
- Ch* Push(size_t count) { Ch* begin = dst_; dst_ += count; return begin; }
- void Pop(size_t count) { dst_ -= count; }
-
- Ch* src_;
- Ch* dst_;
- Ch* head_;
-};
-
-template <typename Encoding>
-struct StreamTraits<GenericInsituStringStream<Encoding> > {
- enum { copyOptimization = 1 };
-};
-
-//! Insitu string stream with UTF8 encoding.
-typedef GenericInsituStringStream<UTF8<> > InsituStringStream;
-
-///////////////////////////////////////////////////////////////////////////////
-// Type
-
-//! Type of JSON value
-enum Type {
- kNullType = 0, //!< null
- kFalseType = 1, //!< false
- kTrueType = 2, //!< true
- kObjectType = 3, //!< object
- kArrayType = 4, //!< array
- kStringType = 5, //!< string
- kNumberType = 6 //!< number
-};
-
-RAPIDJSON_NAMESPACE_END
-
-#endif // RAPIDJSON_RAPIDJSON_H_
diff --git a/libs/rapidjson/reader.h b/libs/rapidjson/reader.h
deleted file mode 100644
index 08297a08b..000000000
--- a/libs/rapidjson/reader.h
+++ /dev/null
@@ -1,1440 +0,0 @@
-// Tencent is pleased to support the open source community by making RapidJSON available.
-//
-// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
-//
-// Licensed under the MIT License (the "License"); you may not use this file except
-// in compliance with the License. You may obtain a copy of the License at
-//
-// http://opensource.org/licenses/MIT
-//
-// Unless required by applicable law or agreed to in writing, software distributed
-// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
-// CONDITIONS OF ANY KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations under the License.
-
-#ifndef RAPIDJSON_READER_H_
-#define RAPIDJSON_READER_H_
-
-/*! \file reader.h */
-
-#include "rapidjson.h"
-#include "encodings.h"
-#include "internal/meta.h"
-#include "internal/stack.h"
-#include "internal/strtod.h"
-
-#if defined(RAPIDJSON_SIMD) && defined(_MSC_VER)
-#include <intrin.h>
-#pragma intrinsic(_BitScanForward)
-#endif
-#ifdef RAPIDJSON_SSE42
-#include <nmmintrin.h>
-#elif defined(RAPIDJSON_SSE2)
-#include <emmintrin.h>
-#endif
-
-#ifdef _MSC_VER
-RAPIDJSON_DIAG_PUSH
-RAPIDJSON_DIAG_OFF(4127) // conditional expression is constant
-RAPIDJSON_DIAG_OFF(4702) // unreachable code
-#endif
-
-#ifdef __GNUC__
-RAPIDJSON_DIAG_PUSH
-RAPIDJSON_DIAG_OFF(effc++)
-#endif
-
-//!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN
-#define RAPIDJSON_NOTHING /* deliberately empty */
-#ifndef RAPIDJSON_PARSE_ERROR_EARLY_RETURN
-#define RAPIDJSON_PARSE_ERROR_EARLY_RETURN(value) \
- RAPIDJSON_MULTILINEMACRO_BEGIN \
- if (HasParseError()) { return value; } \
- RAPIDJSON_MULTILINEMACRO_END
-#endif
-#define RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID \
- RAPIDJSON_PARSE_ERROR_EARLY_RETURN(RAPIDJSON_NOTHING)
-//!@endcond
-
-/*! \def RAPIDJSON_PARSE_ERROR_NORETURN
- \ingroup RAPIDJSON_ERRORS
- \brief Macro to indicate a parse error.
- \param parseErrorCode \ref rapidjson::ParseErrorCode of the error
- \param offset position of the error in JSON input (\c size_t)
-
- This macros can be used as a customization point for the internal
- error handling mechanism of RapidJSON.
-
- A common usage model is to throw an exception instead of requiring the
- caller to explicitly check the \ref rapidjson::GenericReader::Parse's
- return value:
-
- \code
- #define RAPIDJSON_PARSE_ERROR_NORETURN(parseErrorCode,offset) \
- throw ParseException(parseErrorCode, #parseErrorCode, offset)
-
- #include <stdexcept> // std::runtime_error
- #include "rapidjson/error/error.h" // rapidjson::ParseResult
-
- struct ParseException : std::runtime_error, rapidjson::ParseResult {
- ParseException(rapidjson::ParseErrorCode code, const char* msg, size_t offset)
- : std::runtime_error(msg), ParseResult(code, offset) {}
- };
-
- #include "rapidjson/reader.h"
- \endcode
-
- \see RAPIDJSON_PARSE_ERROR, rapidjson::GenericReader::Parse
- */
-#ifndef RAPIDJSON_PARSE_ERROR_NORETURN
-#define RAPIDJSON_PARSE_ERROR_NORETURN(parseErrorCode, offset) \
- RAPIDJSON_MULTILINEMACRO_BEGIN \
- RAPIDJSON_ASSERT(!HasParseError()); /* Error can only be assigned once */ \
- SetParseError(parseErrorCode, offset); \
- RAPIDJSON_MULTILINEMACRO_END
-#endif
-
-/*! \def RAPIDJSON_PARSE_ERROR
- \ingroup RAPIDJSON_ERRORS
- \brief (Internal) macro to indicate and handle a parse error.
- \param parseErrorCode \ref rapidjson::ParseErrorCode of the error
- \param offset position of the error in JSON input (\c size_t)
-
- Invokes RAPIDJSON_PARSE_ERROR_NORETURN and stops the parsing.
-
- \see RAPIDJSON_PARSE_ERROR_NORETURN
- \hideinitializer
- */
-#ifndef RAPIDJSON_PARSE_ERROR
-#define RAPIDJSON_PARSE_ERROR(parseErrorCode, offset) \
- RAPIDJSON_MULTILINEMACRO_BEGIN \
- RAPIDJSON_PARSE_ERROR_NORETURN(parseErrorCode, offset); \
- RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; \
- RAPIDJSON_MULTILINEMACRO_END
-#endif
-
-#include "error/error.h" // ParseErrorCode, ParseResult
-
-RAPIDJSON_NAMESPACE_BEGIN
-
-///////////////////////////////////////////////////////////////////////////////
-// ParseFlag
-
-/*! \def RAPIDJSON_PARSE_DEFAULT_FLAGS
- \ingroup RAPIDJSON_CONFIG
- \brief User-defined kParseDefaultFlags definition.
-
- User can define this as any \c ParseFlag combinations.
-*/
-#ifndef RAPIDJSON_PARSE_DEFAULT_FLAGS
-#define RAPIDJSON_PARSE_DEFAULT_FLAGS kParseNoFlags
-#endif
-
-//! Combination of parseFlags
-/*! \see Reader::Parse, Document::Parse, Document::ParseInsitu, Document::ParseStream
- */
-enum ParseFlag {
- kParseNoFlags = 0, //!< No flags are set.
- kParseInsituFlag = 1, //!< In-situ(destructive) parsing.
- kParseValidateEncodingFlag = 2, //!< Validate encoding of JSON strings.
- kParseIterativeFlag = 4, //!< Iterative(constant complexity in terms of function call stack size) parsing.
- kParseStopWhenDoneFlag = 8, //!< After parsing a complete JSON root from stream, stop further processing the rest of stream. When this flag is used, parser will not generate kParseErrorDocumentRootNotSingular error.
- kParseFullPrecisionFlag = 16, //!< Parse number in full precision (but slower).
- kParseDefaultFlags = RAPIDJSON_PARSE_DEFAULT_FLAGS //!< Default parse flags. Can be customized by defining RAPIDJSON_PARSE_DEFAULT_FLAGS
-};
-
-///////////////////////////////////////////////////////////////////////////////
-// Handler
-
-/*! \class rapidjson::Handler
- \brief Concept for receiving events from GenericReader upon parsing.
- The functions return true if no error occurs. If they return false,
- the event publisher should terminate the process.
-\code
-concept Handler {
- typename Ch;
-
- bool Null();
- bool Bool(bool b);
- bool Int(int i);
- bool Uint(unsigned i);
- bool Int64(int64_t i);
- bool Uint64(uint64_t i);
- bool Double(double d);
- bool String(const Ch* str, SizeType length, bool copy);
- bool StartObject();
- bool Key(const Ch* str, SizeType length, bool copy);
- bool EndObject(SizeType memberCount);
- bool StartArray();
- bool EndArray(SizeType elementCount);
-};
-\endcode
-*/
-///////////////////////////////////////////////////////////////////////////////
-// BaseReaderHandler
-
-//! Default implementation of Handler.
-/*! This can be used as base class of any reader handler.
- \note implements Handler concept
-*/
-template<typename Encoding = UTF8<>, typename Derived = void>
-struct BaseReaderHandler {
- typedef typename Encoding::Ch Ch;
-
- typedef typename internal::SelectIf<internal::IsSame<Derived, void>, BaseReaderHandler, Derived>::Type Override;
-
- bool Default() { return true; }
- bool Null() { return static_cast<Override&>(*this).Default(); }
- bool Bool(bool) { return static_cast<Override&>(*this).Default(); }
- bool Int(int) { return static_cast<Override&>(*this).Default(); }
- bool Uint(unsigned) { return static_cast<Override&>(*this).Default(); }
- bool Int64(int64_t) { return static_cast<Override&>(*this).Default(); }
- bool Uint64(uint64_t) { return static_cast<Override&>(*this).Default(); }
- bool Double(double) { return static_cast<Override&>(*this).Default(); }
- bool String(const Ch*, SizeType, bool) { return static_cast<Override&>(*this).Default(); }
- bool StartObject() { return static_cast<Override&>(*this).Default(); }
- bool Key(const Ch* str, SizeType len, bool copy) { return static_cast<Override&>(*this).String(str, len, copy); }
- bool EndObject(SizeType) { return static_cast<Override&>(*this).Default(); }
- bool StartArray() { return static_cast<Override&>(*this).Default(); }
- bool EndArray(SizeType) { return static_cast<Override&>(*this).Default(); }
-};
-
-///////////////////////////////////////////////////////////////////////////////
-// StreamLocalCopy
-
-namespace internal {
-
-template<typename Stream, int = StreamTraits<Stream>::copyOptimization>
-class StreamLocalCopy;
-
-//! Do copy optimization.
-template<typename Stream>
-class StreamLocalCopy<Stream, 1> {
-public:
- StreamLocalCopy(Stream& original) : s(original), original_(original) {}
- ~StreamLocalCopy() { original_ = s; }
-
- Stream s;
-
-private:
- StreamLocalCopy& operator=(const StreamLocalCopy&) /* = delete */;
-
- Stream& original_;
-};
-
-//! Keep reference.
-template<typename Stream>
-class StreamLocalCopy<Stream, 0> {
-public:
- StreamLocalCopy(Stream& original) : s(original) {}
-
- Stream& s;
-
-private:
- StreamLocalCopy& operator=(const StreamLocalCopy&) /* = delete */;
-};
-
-} // namespace internal
-
-///////////////////////////////////////////////////////////////////////////////
-// SkipWhitespace
-
-//! Skip the JSON white spaces in a stream.
-/*! \param is A input stream for skipping white spaces.
- \note This function has SSE2/SSE4.2 specialization.
-*/
-template<typename InputStream>
-void SkipWhitespace(InputStream& is) {
- internal::StreamLocalCopy<InputStream> copy(is);
- InputStream& s(copy.s);
-
- while (s.Peek() == ' ' || s.Peek() == '\n' || s.Peek() == '\r' || s.Peek() == '\t')
- s.Take();
-}
-
-#ifdef RAPIDJSON_SSE42
-//! Skip whitespace with SSE 4.2 pcmpistrm instruction, testing 16 8-byte characters at once.
-inline const char *SkipWhitespace_SIMD(const char* p) {
- // Fast return for single non-whitespace
- if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t')
- ++p;
- else
- return p;
-
- // 16-byte align to the next boundary
- const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & ~15);
- while (p != nextAligned)
- if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t')
- ++p;
- else
- return p;
-
- // The rest of string using SIMD
- static const char whitespace[16] = " \n\r\t";
- const __m128i w = _mm_load_si128((const __m128i *)&whitespace[0]);
-
- for (;; p += 16) {
- const __m128i s = _mm_load_si128((const __m128i *)p);
- const unsigned r = _mm_cvtsi128_si32(_mm_cmpistrm(w, s, _SIDD_UBYTE_OPS | _SIDD_CMP_EQUAL_ANY | _SIDD_BIT_MASK | _SIDD_NEGATIVE_POLARITY));
- if (r != 0) { // some of characters is non-whitespace
-#ifdef _MSC_VER // Find the index of first non-whitespace
- unsigned long offset;
- _BitScanForward(&offset, r);
- return p + offset;
-#else
- return p + __builtin_ffs(r) - 1;
-#endif
- }
- }
-}
-
-#elif defined(RAPIDJSON_SSE2)
-
-//! Skip whitespace with SSE2 instructions, testing 16 8-byte characters at once.
-inline const char *SkipWhitespace_SIMD(const char* p) {
- // Fast return for single non-whitespace
- if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t')
- ++p;
- else
- return p;
-
- // 16-byte align to the next boundary
- const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & ~15);
- while (p != nextAligned)
- if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t')
- ++p;
- else
- return p;
-
- // The rest of string
- static const char whitespaces[4][17] = {
- " ",
- "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
- "\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r",
- "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t"};
-
- const __m128i w0 = _mm_loadu_si128((const __m128i *)&whitespaces[0][0]);
- const __m128i w1 = _mm_loadu_si128((const __m128i *)&whitespaces[1][0]);
- const __m128i w2 = _mm_loadu_si128((const __m128i *)&whitespaces[2][0]);
- const __m128i w3 = _mm_loadu_si128((const __m128i *)&whitespaces[3][0]);
-
- for (;; p += 16) {
- const __m128i s = _mm_load_si128((const __m128i *)p);
- __m128i x = _mm_cmpeq_epi8(s, w0);
- x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w1));
- x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w2));
- x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w3));
- unsigned short r = (unsigned short)~_mm_movemask_epi8(x);
- if (r != 0) { // some of characters may be non-whitespace
-#ifdef _MSC_VER // Find the index of first non-whitespace
- unsigned long offset;
- _BitScanForward(&offset, r);
- return p + offset;
-#else
- return p + __builtin_ffs(r) - 1;
-#endif
- }
- }
-}
-
-#endif // RAPIDJSON_SSE2
-
-#ifdef RAPIDJSON_SIMD
-//! Template function specialization for InsituStringStream
-template<> inline void SkipWhitespace(InsituStringStream& is) {
- is.src_ = const_cast<char*>(SkipWhitespace_SIMD(is.src_));
-}
-
-//! Template function specialization for StringStream
-template<> inline void SkipWhitespace(StringStream& is) {
- is.src_ = SkipWhitespace_SIMD(is.src_);
-}
-#endif // RAPIDJSON_SIMD
-
-///////////////////////////////////////////////////////////////////////////////
-// GenericReader
-
-//! SAX-style JSON parser. Use \ref Reader for UTF8 encoding and default allocator.
-/*! GenericReader parses JSON text from a stream, and send events synchronously to an
- object implementing Handler concept.
-
- It needs to allocate a stack for storing a single decoded string during
- non-destructive parsing.
-
- For in-situ parsing, the decoded string is directly written to the source
- text string, no temporary buffer is required.
-
- A GenericReader object can be reused for parsing multiple JSON text.
-
- \tparam SourceEncoding Encoding of the input stream.
- \tparam TargetEncoding Encoding of the parse output.
- \tparam StackAllocator Allocator type for stack.
-*/
-template <typename SourceEncoding, typename TargetEncoding, typename StackAllocator = CrtAllocator>
-class GenericReader {
-public:
- typedef typename SourceEncoding::Ch Ch; //!< SourceEncoding character type
-
- //! Constructor.
- /*! \param stackAllocator Optional allocator for allocating stack memory. (Only use for non-destructive parsing)
- \param stackCapacity stack capacity in bytes for storing a single decoded string. (Only use for non-destructive parsing)
- */
- GenericReader(StackAllocator* stackAllocator = 0, size_t stackCapacity = kDefaultStackCapacity) : stack_(stackAllocator, stackCapacity), parseResult_() {}
-
- //! Parse JSON text.
- /*! \tparam parseFlags Combination of \ref ParseFlag.
- \tparam InputStream Type of input stream, implementing Stream concept.
- \tparam Handler Type of handler, implementing Handler concept.
- \param is Input stream to be parsed.
- \param handler The handler to receive events.
- \return Whether the parsing is successful.
- */
- template <unsigned parseFlags, typename InputStream, typename Handler>
- ParseResult Parse(InputStream& is, Handler& handler) {
- if (parseFlags & kParseIterativeFlag)
- return IterativeParse<parseFlags>(is, handler);
-
- parseResult_.Clear();
-
- ClearStackOnExit scope(*this);
-
- SkipWhitespace(is);
-
- if (is.Peek() == '\0') {
- RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorDocumentEmpty, is.Tell());
- RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_);
- }
- else {
- ParseValue<parseFlags>(is, handler);
- RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_);
-
- if (!(parseFlags & kParseStopWhenDoneFlag)) {
- SkipWhitespace(is);
-
- if (is.Peek() != '\0') {
- RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorDocumentRootNotSingular, is.Tell());
- RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_);
- }
- }
- }
-
- return parseResult_;
- }
-
- //! Parse JSON text (with \ref kParseDefaultFlags)
- /*! \tparam InputStream Type of input stream, implementing Stream concept
- \tparam Handler Type of handler, implementing Handler concept.
- \param is Input stream to be parsed.
- \param handler The handler to receive events.
- \return Whether the parsing is successful.
- */
- template <typename InputStream, typename Handler>
- ParseResult Parse(InputStream& is, Handler& handler) {
- return Parse<kParseDefaultFlags>(is, handler);
- }
-
- //! Whether a parse error has occured in the last parsing.
- bool HasParseError() const { return parseResult_.IsError(); }
-
- //! Get the \ref ParseErrorCode of last parsing.
- ParseErrorCode GetParseErrorCode() const { return parseResult_.Code(); }
-
- //! Get the position of last parsing error in input, 0 otherwise.
- size_t GetErrorOffset() const { return parseResult_.Offset(); }
-
-protected:
- void SetParseError(ParseErrorCode code, size_t offset) { parseResult_.Set(code, offset); }
-
-private:
- // Prohibit copy constructor & assignment operator.
- GenericReader(const GenericReader&);
- GenericReader& operator=(const GenericReader&);
-
- void ClearStack() { stack_.Clear(); }
-
- // clear stack on any exit from ParseStream, e.g. due to exception
- struct ClearStackOnExit {
- explicit ClearStackOnExit(GenericReader& r) : r_(r) {}
- ~ClearStackOnExit() { r_.ClearStack(); }
- private:
- GenericReader& r_;
- ClearStackOnExit(const ClearStackOnExit&);
- ClearStackOnExit& operator=(const ClearStackOnExit&);
- };
-
- // Parse object: { string : value, ... }
- template<unsigned parseFlags, typename InputStream, typename Handler>
- void ParseObject(InputStream& is, Handler& handler) {
- RAPIDJSON_ASSERT(is.Peek() == '{');
- is.Take(); // Skip '{'
-
- if (!handler.StartObject())
- RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell());
-
- SkipWhitespace(is);
-
- if (is.Peek() == '}') {
- is.Take();
- if (!handler.EndObject(0)) // empty object
- RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell());
- return;
- }
-
- for (SizeType memberCount = 0;;) {
- if (is.Peek() != '"')
- RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissName, is.Tell());
-
- ParseString<parseFlags>(is, handler, true);
- RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
-
- SkipWhitespace(is);
-
- if (is.Take() != ':')
- RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissColon, is.Tell());
-
- SkipWhitespace(is);
-
- ParseValue<parseFlags>(is, handler);
- RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
-
- SkipWhitespace(is);
-
- ++memberCount;
-
- switch (is.Take()) {
- case ',': SkipWhitespace(is); break;
- case '}':
- if (!handler.EndObject(memberCount))
- RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell());
- return;
- default: RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissCommaOrCurlyBracket, is.Tell());
- }
- }
- }
-
- // Parse array: [ value, ... ]
- template<unsigned parseFlags, typename InputStream, typename Handler>
- void ParseArray(InputStream& is, Handler& handler) {
- RAPIDJSON_ASSERT(is.Peek() == '[');
- is.Take(); // Skip '['
-
- if (!handler.StartArray())
- RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell());
-
- SkipWhitespace(is);
-
- if (is.Peek() == ']') {
- is.Take();
- if (!handler.EndArray(0)) // empty array
- RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell());
- return;
- }
-
- for (SizeType elementCount = 0;;) {
- ParseValue<parseFlags>(is, handler);
- RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
-
- ++elementCount;
- SkipWhitespace(is);
-
- switch (is.Take()) {
- case ',': SkipWhitespace(is); break;
- case ']':
- if (!handler.EndArray(elementCount))
- RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell());
- return;
- default: RAPIDJSON_PARSE_ERROR(kParseErrorArrayMissCommaOrSquareBracket, is.Tell());
- }
- }
- }
-
- template<unsigned parseFlags, typename InputStream, typename Handler>
- void ParseNull(InputStream& is, Handler& handler) {
- RAPIDJSON_ASSERT(is.Peek() == 'n');
- is.Take();
-
- if (is.Take() == 'u' && is.Take() == 'l' && is.Take() == 'l') {
- if (!handler.Null())
- RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell());
- }
- else
- RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, is.Tell() - 1);
- }
-
- template<unsigned parseFlags, typename InputStream, typename Handler>
- void ParseTrue(InputStream& is, Handler& handler) {
- RAPIDJSON_ASSERT(is.Peek() == 't');
- is.Take();
-
- if (is.Take() == 'r' && is.Take() == 'u' && is.Take() == 'e') {
- if (!handler.Bool(true))
- RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell());
- }
- else
- RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, is.Tell() - 1);
- }
-
- template<unsigned parseFlags, typename InputStream, typename Handler>
- void ParseFalse(InputStream& is, Handler& handler) {
- RAPIDJSON_ASSERT(is.Peek() == 'f');
- is.Take();
-
- if (is.Take() == 'a' && is.Take() == 'l' && is.Take() == 's' && is.Take() == 'e') {
- if (!handler.Bool(false))
- RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell());
- }
- else
- RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, is.Tell() - 1);
- }
-
- // Helper function to parse four hexidecimal digits in \uXXXX in ParseString().
- template<typename InputStream>
- unsigned ParseHex4(InputStream& is) {
- unsigned codepoint = 0;
- for (int i = 0; i < 4; i++) {
- Ch c = is.Take();
- codepoint <<= 4;
- codepoint += static_cast<unsigned>(c);
- if (c >= '0' && c <= '9')
- codepoint -= '0';
- else if (c >= 'A' && c <= 'F')
- codepoint -= 'A' - 10;
- else if (c >= 'a' && c <= 'f')
- codepoint -= 'a' - 10;
- else {
- RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorStringUnicodeEscapeInvalidHex, is.Tell() - 1);
- RAPIDJSON_PARSE_ERROR_EARLY_RETURN(0);
- }
- }
- return codepoint;
- }
-
- template <typename CharType>
- class StackStream {
- public:
- typedef CharType Ch;
-
- StackStream(internal::Stack<StackAllocator>& stack) : stack_(stack), length_(0) {}
- RAPIDJSON_FORCEINLINE void Put(Ch c) {
- *stack_.template Push<Ch>() = c;
- ++length_;
- }
- size_t Length() const { return length_; }
- Ch* Pop() {
- return stack_.template Pop<Ch>(length_);
- }
-
- private:
- StackStream(const StackStream&);
- StackStream& operator=(const StackStream&);
-
- internal::Stack<StackAllocator>& stack_;
- SizeType length_;
- };
-
- // Parse string and generate String event. Different code paths for kParseInsituFlag.
- template<unsigned parseFlags, typename InputStream, typename Handler>
- void ParseString(InputStream& is, Handler& handler, bool isKey = false) {
- internal::StreamLocalCopy<InputStream> copy(is);
- InputStream& s(copy.s);
-
- bool success = false;
- if (parseFlags & kParseInsituFlag) {
- typename InputStream::Ch *head = s.PutBegin();
- ParseStringToStream<parseFlags, SourceEncoding, SourceEncoding>(s, s);
- RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
- size_t length = s.PutEnd(head) - 1;
- RAPIDJSON_ASSERT(length <= 0xFFFFFFFF);
- const typename TargetEncoding::Ch* const str = (typename TargetEncoding::Ch*)head;
- success = (isKey ? handler.Key(str, SizeType(length), false) : handler.String(str, SizeType(length), false));
- }
- else {
- StackStream<typename TargetEncoding::Ch> stackStream(stack_);
- ParseStringToStream<parseFlags, SourceEncoding, TargetEncoding>(s, stackStream);
- RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
- SizeType length = static_cast<SizeType>(stackStream.Length()) - 1;
- const typename TargetEncoding::Ch* const str = stackStream.Pop();
- success = (isKey ? handler.Key(str, length, true) : handler.String(str, length, true));
- }
- if (!success)
- RAPIDJSON_PARSE_ERROR(kParseErrorTermination, s.Tell());
- }
-
- // Parse string to an output is
- // This function handles the prefix/suffix double quotes, escaping, and optional encoding validation.
- template<unsigned parseFlags, typename SEncoding, typename TEncoding, typename InputStream, typename OutputStream>
- RAPIDJSON_FORCEINLINE void ParseStringToStream(InputStream& is, OutputStream& os) {
-//!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN
-#define Z16 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
- static const char escape[256] = {
- Z16, Z16, 0, 0,'\"', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,'/',
- Z16, Z16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,'\\', 0, 0, 0,
- 0, 0,'\b', 0, 0, 0,'\f', 0, 0, 0, 0, 0, 0, 0,'\n', 0,
- 0, 0,'\r', 0,'\t', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16
- };
-#undef Z16
-//!@endcond
-
- RAPIDJSON_ASSERT(is.Peek() == '\"');
- is.Take(); // Skip '\"'
-
- for (;;) {
- Ch c = is.Peek();
- if (c == '\\') { // Escape
- is.Take();
- Ch e = is.Take();
- if ((sizeof(Ch) == 1 || unsigned(e) < 256) && escape[(unsigned char)e]) {
- os.Put(escape[(unsigned char)e]);
- }
- else if (e == 'u') { // Unicode
- unsigned codepoint = ParseHex4(is);
- RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
- if (codepoint >= 0xD800 && codepoint <= 0xDBFF) {
- // Handle UTF-16 surrogate pair
- if (is.Take() != '\\' || is.Take() != 'u')
- RAPIDJSON_PARSE_ERROR(kParseErrorStringUnicodeSurrogateInvalid, is.Tell() - 2);
- unsigned codepoint2 = ParseHex4(is);
- RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
- if (codepoint2 < 0xDC00 || codepoint2 > 0xDFFF)
- RAPIDJSON_PARSE_ERROR(kParseErrorStringUnicodeSurrogateInvalid, is.Tell() - 2);
- codepoint = (((codepoint - 0xD800) << 10) | (codepoint2 - 0xDC00)) + 0x10000;
- }
- TEncoding::Encode(os, codepoint);
- }
- else
- RAPIDJSON_PARSE_ERROR(kParseErrorStringEscapeInvalid, is.Tell() - 1);
- }
- else if (c == '"') { // Closing double quote
- is.Take();
- os.Put('\0'); // null-terminate the string
- return;
- }
- else if (c == '\0')
- RAPIDJSON_PARSE_ERROR(kParseErrorStringMissQuotationMark, is.Tell() - 1);
- else if ((unsigned)c < 0x20) // RFC 4627: unescaped = %x20-21 / %x23-5B / %x5D-10FFFF
- RAPIDJSON_PARSE_ERROR(kParseErrorStringEscapeInvalid, is.Tell() - 1);
- else {
- if (parseFlags & kParseValidateEncodingFlag ?
- !Transcoder<SEncoding, TEncoding>::Validate(is, os) :
- !Transcoder<SEncoding, TEncoding>::Transcode(is, os))
- RAPIDJSON_PARSE_ERROR(kParseErrorStringInvalidEncoding, is.Tell());
- }
- }
- }
-
- template<typename InputStream, bool backup>
- class NumberStream;
-
- template<typename InputStream>
- class NumberStream<InputStream, false> {
- public:
- NumberStream(GenericReader& reader, InputStream& s) : is(s) { (void)reader; }
- ~NumberStream() {}
-
- RAPIDJSON_FORCEINLINE Ch Peek() const { return is.Peek(); }
- RAPIDJSON_FORCEINLINE Ch TakePush() { return is.Take(); }
- RAPIDJSON_FORCEINLINE Ch Take() { return is.Take(); }
- size_t Tell() { return is.Tell(); }
- size_t Length() { return 0; }
- const char* Pop() { return 0; }
-
- protected:
- NumberStream& operator=(const NumberStream&);
-
- InputStream& is;
- };
-
- template<typename InputStream>
- class NumberStream<InputStream, true> : public NumberStream<InputStream, false> {
- typedef NumberStream<InputStream, false> Base;
- public:
- NumberStream(GenericReader& reader, InputStream& is) : NumberStream<InputStream, false>(reader, is), stackStream(reader.stack_) {}
- ~NumberStream() {}
-
- RAPIDJSON_FORCEINLINE Ch TakePush() {
- stackStream.Put((char)Base::is.Peek());
- return Base::is.Take();
- }
-
- size_t Length() { return stackStream.Length(); }
-
- const char* Pop() {
- stackStream.Put('\0');
- return stackStream.Pop();
- }
-
- private:
- StackStream<char> stackStream;
- };
-
- template<unsigned parseFlags, typename InputStream, typename Handler>
- void ParseNumber(InputStream& is, Handler& handler) {
- internal::StreamLocalCopy<InputStream> copy(is);
- NumberStream<InputStream, (parseFlags & kParseFullPrecisionFlag) != 0> s(*this, copy.s);
-
- // Parse minus
- bool minus = false;
- if (s.Peek() == '-') {
- minus = true;
- s.Take();
- }
-
- // Parse int: zero / ( digit1-9 *DIGIT )
- unsigned i = 0;
- uint64_t i64 = 0;
- bool use64bit = false;
- int significandDigit = 0;
- if (s.Peek() == '0') {
- i = 0;
- s.TakePush();
- }
- else if (s.Peek() >= '1' && s.Peek() <= '9') {
- i = static_cast<unsigned>(s.TakePush() - '0');
-
- if (minus)
- while (s.Peek() >= '0' && s.Peek() <= '9') {
- if (i >= 214748364) { // 2^31 = 2147483648
- if (i != 214748364 || s.Peek() > '8') {
- i64 = i;
- use64bit = true;
- break;
- }
- }
- i = i * 10 + static_cast<unsigned>(s.TakePush() - '0');
- significandDigit++;
- }
- else
- while (s.Peek() >= '0' && s.Peek() <= '9') {
- if (i >= 429496729) { // 2^32 - 1 = 4294967295
- if (i != 429496729 || s.Peek() > '5') {
- i64 = i;
- use64bit = true;
- break;
- }
- }
- i = i * 10 + static_cast<unsigned>(s.TakePush() - '0');
- significandDigit++;
- }
- }
- else
- RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, s.Tell());
-
- // Parse 64bit int
- bool useDouble = false;
- double d = 0.0;
- if (use64bit) {
- if (minus)
- while (s.Peek() >= '0' && s.Peek() <= '9') {
- if (i64 >= RAPIDJSON_UINT64_C2(0x0CCCCCCC, 0xCCCCCCCC)) // 2^63 = 9223372036854775808
- if (i64 != RAPIDJSON_UINT64_C2(0x0CCCCCCC, 0xCCCCCCCC) || s.Peek() > '8') {
- d = i64;
- useDouble = true;
- break;
- }
- i64 = i64 * 10 + static_cast<unsigned>(s.TakePush() - '0');
- significandDigit++;
- }
- else
- while (s.Peek() >= '0' && s.Peek() <= '9') {
- if (i64 >= RAPIDJSON_UINT64_C2(0x19999999, 0x99999999)) // 2^64 - 1 = 18446744073709551615
- if (i64 != RAPIDJSON_UINT64_C2(0x19999999, 0x99999999) || s.Peek() > '5') {
- d = i64;
- useDouble = true;
- break;
- }
- i64 = i64 * 10 + static_cast<unsigned>(s.TakePush() - '0');
- significandDigit++;
- }
- }
-
- // Force double for big integer
- if (useDouble) {
- while (s.Peek() >= '0' && s.Peek() <= '9') {
- if (d >= 1.7976931348623157e307) // DBL_MAX / 10.0
- RAPIDJSON_PARSE_ERROR(kParseErrorNumberTooBig, s.Tell());
- d = d * 10 + (s.TakePush() - '0');
- }
- }
-
- // Parse frac = decimal-point 1*DIGIT
- int expFrac = 0;
- size_t decimalPosition;
- if (s.Peek() == '.') {
- s.Take();
- decimalPosition = s.Length();
-
- if (!(s.Peek() >= '0' && s.Peek() <= '9'))
- RAPIDJSON_PARSE_ERROR(kParseErrorNumberMissFraction, s.Tell());
-
- if (!useDouble) {
-#if RAPIDJSON_64BIT
- // Use i64 to store significand in 64-bit architecture
- if (!use64bit)
- i64 = i;
-
- while (s.Peek() >= '0' && s.Peek() <= '9') {
- if (i64 > RAPIDJSON_UINT64_C2(0x1FFFFF, 0xFFFFFFFF)) // 2^53 - 1 for fast path
- break;
- else {
- i64 = i64 * 10 + static_cast<unsigned>(s.TakePush() - '0');
- --expFrac;
- if (i64 != 0)
- significandDigit++;
- }
- }
-
- d = (double)i64;
-#else
- // Use double to store significand in 32-bit architecture
- d = use64bit ? (double)i64 : (double)i;
-#endif
- useDouble = true;
- }
-
- while (s.Peek() >= '0' && s.Peek() <= '9') {
- if (significandDigit < 17) {
- d = d * 10.0 + (s.TakePush() - '0');
- --expFrac;
- if (d > 0.0)
- significandDigit++;
- }
- else
- s.TakePush();
- }
- }
- else
- decimalPosition = s.Length(); // decimal position at the end of integer.
-
- // Parse exp = e [ minus / plus ] 1*DIGIT
- int exp = 0;
- if (s.Peek() == 'e' || s.Peek() == 'E') {
- if (!useDouble) {
- d = use64bit ? i64 : i;
- useDouble = true;
- }
- s.Take();
-
- bool expMinus = false;
- if (s.Peek() == '+')
- s.Take();
- else if (s.Peek() == '-') {
- s.Take();
- expMinus = true;
- }
-
- if (s.Peek() >= '0' && s.Peek() <= '9') {
- exp = s.Take() - '0';
- while (s.Peek() >= '0' && s.Peek() <= '9') {
- exp = exp * 10 + (s.Take() - '0');
- if (exp > 308 && !expMinus) // exp > 308 should be rare, so it should be checked first.
- RAPIDJSON_PARSE_ERROR(kParseErrorNumberTooBig, s.Tell());
- }
- }
- else
- RAPIDJSON_PARSE_ERROR(kParseErrorNumberMissExponent, s.Tell());
-
- if (expMinus)
- exp = -exp;
- }
-
- // Finish parsing, call event according to the type of number.
- bool cont = true;
- size_t length = s.Length();
- const char* decimal = s.Pop(); // Pop stack no matter if it will be used or not.
-
- if (useDouble) {
- int p = exp + expFrac;
- if (parseFlags & kParseFullPrecisionFlag)
- d = internal::StrtodFullPrecision(d, p, decimal, length, decimalPosition, exp);
- else
- d = internal::StrtodNormalPrecision(d, p);
-
- cont = handler.Double(minus ? -d : d);
- }
- else {
- if (use64bit) {
- if (minus)
- cont = handler.Int64(-(int64_t)i64);
- else
- cont = handler.Uint64(i64);
- }
- else {
- if (minus)
- cont = handler.Int(-(int)i);
- else
- cont = handler.Uint(i);
- }
- }
- if (!cont)
- RAPIDJSON_PARSE_ERROR(kParseErrorTermination, s.Tell());
- }
-
- // Parse any JSON value
- template<unsigned parseFlags, typename InputStream, typename Handler>
- void ParseValue(InputStream& is, Handler& handler) {
- switch (is.Peek()) {
- case 'n': ParseNull <parseFlags>(is, handler); break;
- case 't': ParseTrue <parseFlags>(is, handler); break;
- case 'f': ParseFalse <parseFlags>(is, handler); break;
- case '"': ParseString<parseFlags>(is, handler); break;
- case '{': ParseObject<parseFlags>(is, handler); break;
- case '[': ParseArray <parseFlags>(is, handler); break;
- default : ParseNumber<parseFlags>(is, handler);
- }
- }
-
- // Iterative Parsing
-
- // States
- enum IterativeParsingState {
- IterativeParsingStartState = 0,
- IterativeParsingFinishState,
- IterativeParsingErrorState,
-
- // Object states
- IterativeParsingObjectInitialState,
- IterativeParsingMemberKeyState,
- IterativeParsingKeyValueDelimiterState,
- IterativeParsingMemberValueState,
- IterativeParsingMemberDelimiterState,
- IterativeParsingObjectFinishState,
-
- // Array states
- IterativeParsingArrayInitialState,
- IterativeParsingElementState,
- IterativeParsingElementDelimiterState,
- IterativeParsingArrayFinishState,
-
- // Single value state
- IterativeParsingValueState,
-
- cIterativeParsingStateCount
- };
-
- // Tokens
- enum Token {
- LeftBracketToken = 0,
- RightBracketToken,
-
- LeftCurlyBracketToken,
- RightCurlyBracketToken,
-
- CommaToken,
- ColonToken,
-
- StringToken,
- FalseToken,
- TrueToken,
- NullToken,
- NumberToken,
-
- kTokenCount
- };
-
- RAPIDJSON_FORCEINLINE Token Tokenize(Ch c) {
-
-//!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN
-#define N NumberToken
-#define N16 N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N
- // Maps from ASCII to Token
- static const unsigned char tokenMap[256] = {
- N16, // 00~0F
- N16, // 10~1F
- N, N, StringToken, N, N, N, N, N, N, N, N, N, CommaToken, N, N, N, // 20~2F
- N, N, N, N, N, N, N, N, N, N, ColonToken, N, N, N, N, N, // 30~3F
- N16, // 40~4F
- N, N, N, N, N, N, N, N, N, N, N, LeftBracketToken, N, RightBracketToken, N, N, // 50~5F
- N, N, N, N, N, N, FalseToken, N, N, N, N, N, N, N, NullToken, N, // 60~6F
- N, N, N, N, TrueToken, N, N, N, N, N, N, LeftCurlyBracketToken, N, RightCurlyBracketToken, N, N, // 70~7F
- N16, N16, N16, N16, N16, N16, N16, N16 // 80~FF
- };
-#undef N
-#undef N16
-//!@endcond
-
- if (sizeof(Ch) == 1 || unsigned(c) < 256)
- return (Token)tokenMap[(unsigned char)c];
- else
- return NumberToken;
- }
-
- RAPIDJSON_FORCEINLINE IterativeParsingState Predict(IterativeParsingState state, Token token) {
- // current state x one lookahead token -> new state
- static const char G[cIterativeParsingStateCount][kTokenCount] = {
- // Start
- {
- IterativeParsingArrayInitialState, // Left bracket
- IterativeParsingErrorState, // Right bracket
- IterativeParsingObjectInitialState, // Left curly bracket
- IterativeParsingErrorState, // Right curly bracket
- IterativeParsingErrorState, // Comma
- IterativeParsingErrorState, // Colon
- IterativeParsingValueState, // String
- IterativeParsingValueState, // False
- IterativeParsingValueState, // True
- IterativeParsingValueState, // Null
- IterativeParsingValueState // Number
- },
- // Finish(sink state)
- {
- IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState,
- IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState,
- IterativeParsingErrorState
- },
- // Error(sink state)
- {
- IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState,
- IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState,
- IterativeParsingErrorState
- },
- // ObjectInitial
- {
- IterativeParsingErrorState, // Left bracket
- IterativeParsingErrorState, // Right bracket
- IterativeParsingErrorState, // Left curly bracket
- IterativeParsingObjectFinishState, // Right curly bracket
- IterativeParsingErrorState, // Comma
- IterativeParsingErrorState, // Colon
- IterativeParsingMemberKeyState, // String
- IterativeParsingErrorState, // False
- IterativeParsingErrorState, // True
- IterativeParsingErrorState, // Null
- IterativeParsingErrorState // Number
- },
- // MemberKey
- {
- IterativeParsingErrorState, // Left bracket
- IterativeParsingErrorState, // Right bracket
- IterativeParsingErrorState, // Left curly bracket
- IterativeParsingErrorState, // Right curly bracket
- IterativeParsingErrorState, // Comma
- IterativeParsingKeyValueDelimiterState, // Colon
- IterativeParsingErrorState, // String
- IterativeParsingErrorState, // False
- IterativeParsingErrorState, // True
- IterativeParsingErrorState, // Null
- IterativeParsingErrorState // Number
- },
- // KeyValueDelimiter
- {
- IterativeParsingArrayInitialState, // Left bracket(push MemberValue state)
- IterativeParsingErrorState, // Right bracket
- IterativeParsingObjectInitialState, // Left curly bracket(push MemberValue state)
- IterativeParsingErrorState, // Right curly bracket
- IterativeParsingErrorState, // Comma
- IterativeParsingErrorState, // Colon
- IterativeParsingMemberValueState, // String
- IterativeParsingMemberValueState, // False
- IterativeParsingMemberValueState, // True
- IterativeParsingMemberValueState, // Null
- IterativeParsingMemberValueState // Number
- },
- // MemberValue
- {
- IterativeParsingErrorState, // Left bracket
- IterativeParsingErrorState, // Right bracket
- IterativeParsingErrorState, // Left curly bracket
- IterativeParsingObjectFinishState, // Right curly bracket
- IterativeParsingMemberDelimiterState, // Comma
- IterativeParsingErrorState, // Colon
- IterativeParsingErrorState, // String
- IterativeParsingErrorState, // False
- IterativeParsingErrorState, // True
- IterativeParsingErrorState, // Null
- IterativeParsingErrorState // Number
- },
- // MemberDelimiter
- {
- IterativeParsingErrorState, // Left bracket
- IterativeParsingErrorState, // Right bracket
- IterativeParsingErrorState, // Left curly bracket
- IterativeParsingErrorState, // Right curly bracket
- IterativeParsingErrorState, // Comma
- IterativeParsingErrorState, // Colon
- IterativeParsingMemberKeyState, // String
- IterativeParsingErrorState, // False
- IterativeParsingErrorState, // True
- IterativeParsingErrorState, // Null
- IterativeParsingErrorState // Number
- },
- // ObjectFinish(sink state)
- {
- IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState,
- IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState,
- IterativeParsingErrorState
- },
- // ArrayInitial
- {
- IterativeParsingArrayInitialState, // Left bracket(push Element state)
- IterativeParsingArrayFinishState, // Right bracket
- IterativeParsingObjectInitialState, // Left curly bracket(push Element state)
- IterativeParsingErrorState, // Right curly bracket
- IterativeParsingErrorState, // Comma
- IterativeParsingErrorState, // Colon
- IterativeParsingElementState, // String
- IterativeParsingElementState, // False
- IterativeParsingElementState, // True
- IterativeParsingElementState, // Null
- IterativeParsingElementState // Number
- },
- // Element
- {
- IterativeParsingErrorState, // Left bracket
- IterativeParsingArrayFinishState, // Right bracket
- IterativeParsingErrorState, // Left curly bracket
- IterativeParsingErrorState, // Right curly bracket
- IterativeParsingElementDelimiterState, // Comma
- IterativeParsingErrorState, // Colon
- IterativeParsingErrorState, // String
- IterativeParsingErrorState, // False
- IterativeParsingErrorState, // True
- IterativeParsingErrorState, // Null
- IterativeParsingErrorState // Number
- },
- // ElementDelimiter
- {
- IterativeParsingArrayInitialState, // Left bracket(push Element state)
- IterativeParsingErrorState, // Right bracket
- IterativeParsingObjectInitialState, // Left curly bracket(push Element state)
- IterativeParsingErrorState, // Right curly bracket
- IterativeParsingErrorState, // Comma
- IterativeParsingErrorState, // Colon
- IterativeParsingElementState, // String
- IterativeParsingElementState, // False
- IterativeParsingElementState, // True
- IterativeParsingElementState, // Null
- IterativeParsingElementState // Number
- },
- // ArrayFinish(sink state)
- {
- IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState,
- IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState,
- IterativeParsingErrorState
- },
- // Single Value (sink state)
- {
- IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState,
- IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState,
- IterativeParsingErrorState
- }
- }; // End of G
-
- return (IterativeParsingState)G[state][token];
- }
-
- // Make an advance in the token stream and state based on the candidate destination state which was returned by Transit().
- // May return a new state on state pop.
- template <unsigned parseFlags, typename InputStream, typename Handler>
- RAPIDJSON_FORCEINLINE IterativeParsingState Transit(IterativeParsingState src, Token token, IterativeParsingState dst, InputStream& is, Handler& handler) {
- (void)token;
-
- switch (dst) {
- case IterativeParsingErrorState:
- return dst;
-
- case IterativeParsingObjectInitialState:
- case IterativeParsingArrayInitialState:
- {
- // Push the state(Element or MemeberValue) if we are nested in another array or value of member.
- // In this way we can get the correct state on ObjectFinish or ArrayFinish by frame pop.
- IterativeParsingState n = src;
- if (src == IterativeParsingArrayInitialState || src == IterativeParsingElementDelimiterState)
- n = IterativeParsingElementState;
- else if (src == IterativeParsingKeyValueDelimiterState)
- n = IterativeParsingMemberValueState;
- // Push current state.
- *stack_.template Push<SizeType>(1) = n;
- // Initialize and push the member/element count.
- *stack_.template Push<SizeType>(1) = 0;
- // Call handler
- bool hr = (dst == IterativeParsingObjectInitialState) ? handler.StartObject() : handler.StartArray();
- // On handler short circuits the parsing.
- if (!hr) {
- RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorTermination, is.Tell());
- return IterativeParsingErrorState;
- }
- else {
- is.Take();
- return dst;
- }
- }
-
- case IterativeParsingMemberKeyState:
- ParseString<parseFlags>(is, handler, true);
- if (HasParseError())
- return IterativeParsingErrorState;
- else
- return dst;
-
- case IterativeParsingKeyValueDelimiterState:
- RAPIDJSON_ASSERT(token == ColonToken);
- is.Take();
- return dst;
-
- case IterativeParsingMemberValueState:
- // Must be non-compound value. Or it would be ObjectInitial or ArrayInitial state.
- ParseValue<parseFlags>(is, handler);
- if (HasParseError()) {
- return IterativeParsingErrorState;
- }
- return dst;
-
- case IterativeParsingElementState:
- // Must be non-compound value. Or it would be ObjectInitial or ArrayInitial state.
- ParseValue<parseFlags>(is, handler);
- if (HasParseError()) {
- return IterativeParsingErrorState;
- }
- return dst;
-
- case IterativeParsingMemberDelimiterState:
- case IterativeParsingElementDelimiterState:
- is.Take();
- // Update member/element count.
- *stack_.template Top<SizeType>() = *stack_.template Top<SizeType>() + 1;
- return dst;
-
- case IterativeParsingObjectFinishState:
- {
- // Get member count.
- SizeType c = *stack_.template Pop<SizeType>(1);
- // If the object is not empty, count the last member.
- if (src == IterativeParsingMemberValueState)
- ++c;
- // Restore the state.
- IterativeParsingState n = static_cast<IterativeParsingState>(*stack_.template Pop<SizeType>(1));
- // Transit to Finish state if this is the topmost scope.
- if (n == IterativeParsingStartState)
- n = IterativeParsingFinishState;
- // Call handler
- bool hr = handler.EndObject(c);
- // On handler short circuits the parsing.
- if (!hr) {
- RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorTermination, is.Tell());
- return IterativeParsingErrorState;
- }
- else {
- is.Take();
- return n;
- }
- }
-
- case IterativeParsingArrayFinishState:
- {
- // Get element count.
- SizeType c = *stack_.template Pop<SizeType>(1);
- // If the array is not empty, count the last element.
- if (src == IterativeParsingElementState)
- ++c;
- // Restore the state.
- IterativeParsingState n = static_cast<IterativeParsingState>(*stack_.template Pop<SizeType>(1));
- // Transit to Finish state if this is the topmost scope.
- if (n == IterativeParsingStartState)
- n = IterativeParsingFinishState;
- // Call handler
- bool hr = handler.EndArray(c);
- // On handler short circuits the parsing.
- if (!hr) {
- RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorTermination, is.Tell());
- return IterativeParsingErrorState;
- }
- else {
- is.Take();
- return n;
- }
- }
-
- default:
- // This branch is for IterativeParsingValueState actually.
- // Use `default:` rather than
- // `case IterativeParsingValueState:` is for code coverage.
-
- // The IterativeParsingStartState is not enumerated in this switch-case.
- // It is impossible for that case. And it can be caught by following assertion.
-
- // The IterativeParsingFinishState is not enumerated in this switch-case either.
- // It is a "derivative" state which cannot triggered from Predict() directly.
- // Therefore it cannot happen here. And it can be caught by following assertion.
- RAPIDJSON_ASSERT(dst == IterativeParsingValueState);
-
- // Must be non-compound value. Or it would be ObjectInitial or ArrayInitial state.
- ParseValue<parseFlags>(is, handler);
- if (HasParseError()) {
- return IterativeParsingErrorState;
- }
- return IterativeParsingFinishState;
- }
- }
-
- template <typename InputStream>
- void HandleError(IterativeParsingState src, InputStream& is) {
- if (HasParseError()) {
- // Error flag has been set.
- return;
- }
-
- switch (src) {
- case IterativeParsingStartState: RAPIDJSON_PARSE_ERROR(kParseErrorDocumentEmpty, is.Tell());
- case IterativeParsingFinishState: RAPIDJSON_PARSE_ERROR(kParseErrorDocumentRootNotSingular, is.Tell());
- case IterativeParsingObjectInitialState:
- case IterativeParsingMemberDelimiterState: RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissName, is.Tell());
- case IterativeParsingMemberKeyState: RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissColon, is.Tell());
- case IterativeParsingMemberValueState: RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissCommaOrCurlyBracket, is.Tell());
- case IterativeParsingElementState: RAPIDJSON_PARSE_ERROR(kParseErrorArrayMissCommaOrSquareBracket, is.Tell());
- default: RAPIDJSON_PARSE_ERROR(kParseErrorUnspecificSyntaxError, is.Tell());
- }
- }
-
- template <unsigned parseFlags, typename InputStream, typename Handler>
- ParseResult IterativeParse(InputStream& is, Handler& handler) {
- parseResult_.Clear();
- ClearStackOnExit scope(*this);
- IterativeParsingState state = IterativeParsingStartState;
-
- SkipWhitespace(is);
- while (is.Peek() != '\0') {
- Token t = Tokenize(is.Peek());
- IterativeParsingState n = Predict(state, t);
- IterativeParsingState d = Transit<parseFlags>(state, t, n, is, handler);
-
- if (d == IterativeParsingErrorState) {
- HandleError(state, is);
- break;
- }
-
- state = d;
-
- // Do not further consume streams if a root JSON has been parsed.
- if ((parseFlags & kParseStopWhenDoneFlag) && state == IterativeParsingFinishState)
- break;
-
- SkipWhitespace(is);
- }
-
- // Handle the end of file.
- if (state != IterativeParsingFinishState)
- HandleError(state, is);
-
- return parseResult_;
- }
-
- static const size_t kDefaultStackCapacity = 256; //!< Default stack capacity in bytes for storing a single decoded string.
- internal::Stack<StackAllocator> stack_; //!< A stack for storing decoded string temporarily during non-destructive parsing.
- ParseResult parseResult_;
-}; // class GenericReader
-
-//! Reader with UTF8 encoding and default allocator.
-typedef GenericReader<UTF8<>, UTF8<> > Reader;
-
-RAPIDJSON_NAMESPACE_END
-
-#ifdef __GNUC__
-RAPIDJSON_DIAG_POP
-#endif
-
-#ifdef _MSC_VER
-RAPIDJSON_DIAG_POP
-#endif
-
-#endif // RAPIDJSON_READER_H_
diff --git a/libs/rapidjson/stringbuffer.h b/libs/rapidjson/stringbuffer.h
deleted file mode 100644
index e9be84909..000000000
--- a/libs/rapidjson/stringbuffer.h
+++ /dev/null
@@ -1,93 +0,0 @@
-// Tencent is pleased to support the open source community by making RapidJSON available.
-//
-// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
-//
-// Licensed under the MIT License (the "License"); you may not use this file except
-// in compliance with the License. You may obtain a copy of the License at
-//
-// http://opensource.org/licenses/MIT
-//
-// Unless required by applicable law or agreed to in writing, software distributed
-// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
-// CONDITIONS OF ANY KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations under the License.
-
-#ifndef RAPIDJSON_STRINGBUFFER_H_
-#define RAPIDJSON_STRINGBUFFER_H_
-
-#include "rapidjson.h"
-
-#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
-#include <utility> // std::move
-#endif
-
-#include "internal/stack.h"
-
-RAPIDJSON_NAMESPACE_BEGIN
-
-//! Represents an in-memory output stream.
-/*!
- \tparam Encoding Encoding of the stream.
- \tparam Allocator type for allocating memory buffer.
- \note implements Stream concept
-*/
-template <typename Encoding, typename Allocator = CrtAllocator>
-class GenericStringBuffer {
-public:
- typedef typename Encoding::Ch Ch;
-
- GenericStringBuffer(Allocator* allocator = 0, size_t capacity = kDefaultCapacity) : stack_(allocator, capacity) {}
-
-#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
- GenericStringBuffer(GenericStringBuffer&& rhs) : stack_(std::move(rhs.stack_)) {}
- GenericStringBuffer& operator=(GenericStringBuffer&& rhs) {
- if (&rhs != this)
- stack_ = std::move(rhs.stack_);
- return *this;
- }
-#endif
-
- void Put(Ch c) { *stack_.template Push<Ch>() = c; }
- void Flush() {}
-
- void Clear() { stack_.Clear(); }
- void ShrinkToFit() {
- // Push and pop a null terminator. This is safe.
- *stack_.template Push<Ch>() = '\0';
- stack_.ShrinkToFit();
- stack_.template Pop<Ch>(1);
- }
- Ch* Push(size_t count) { return stack_.template Push<Ch>(count); }
- void Pop(size_t count) { stack_.template Pop<Ch>(count); }
-
- const Ch* GetString() const {
- // Push and pop a null terminator. This is safe.
- *stack_.template Push<Ch>() = '\0';
- stack_.template Pop<Ch>(1);
-
- return stack_.template Bottom<Ch>();
- }
-
- size_t GetSize() const { return stack_.GetSize(); }
-
- static const size_t kDefaultCapacity = 256;
- mutable internal::Stack<Allocator> stack_;
-
-private:
- // Prohibit copy constructor & assignment operator.
- GenericStringBuffer(const GenericStringBuffer&);
- GenericStringBuffer& operator=(const GenericStringBuffer&);
-};
-
-//! String buffer with UTF8 encoding
-typedef GenericStringBuffer<UTF8<> > StringBuffer;
-
-//! Implement specialized version of PutN() with memset() for better performance.
-template<>
-inline void PutN(GenericStringBuffer<UTF8<> >& stream, char c, size_t n) {
- std::memset(stream.stack_.Push<char>(n), c, n * sizeof(c));
-}
-
-RAPIDJSON_NAMESPACE_END
-
-#endif // RAPIDJSON_STRINGBUFFER_H_
diff --git a/libs/rapidjson/writer.h b/libs/rapidjson/writer.h
deleted file mode 100644
index 40cdb359f..000000000
--- a/libs/rapidjson/writer.h
+++ /dev/null
@@ -1,395 +0,0 @@
-// Tencent is pleased to support the open source community by making RapidJSON available.
-//
-// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
-//
-// Licensed under the MIT License (the "License"); you may not use this file except
-// in compliance with the License. You may obtain a copy of the License at
-//
-// http://opensource.org/licenses/MIT
-//
-// Unless required by applicable law or agreed to in writing, software distributed
-// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
-// CONDITIONS OF ANY KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations under the License.
-
-#ifndef RAPIDJSON_WRITER_H_
-#define RAPIDJSON_WRITER_H_
-
-#include "rapidjson.h"
-#include "internal/stack.h"
-#include "internal/strfunc.h"
-#include "internal/dtoa.h"
-#include "internal/itoa.h"
-#include "stringbuffer.h"
-#include <new> // placement new
-
-#if RAPIDJSON_HAS_STDSTRING
-#include <string>
-#endif
-
-#ifdef _MSC_VER
-RAPIDJSON_DIAG_PUSH
-RAPIDJSON_DIAG_OFF(4127) // conditional expression is constant
-#endif
-
-RAPIDJSON_NAMESPACE_BEGIN
-
-//! JSON writer
-/*! Writer implements the concept Handler.
- It generates JSON text by events to an output os.
-
- User may programmatically calls the functions of a writer to generate JSON text.
-
- On the other side, a writer can also be passed to objects that generates events,
-
- for example Reader::Parse() and Document::Accept().
-
- \tparam OutputStream Type of output stream.
- \tparam SourceEncoding Encoding of source string.
- \tparam TargetEncoding Encoding of output stream.
- \tparam StackAllocator Type of allocator for allocating memory of stack.
- \note implements Handler concept
-*/
-template<typename OutputStream, typename SourceEncoding = UTF8<>, typename TargetEncoding = UTF8<>, typename StackAllocator = CrtAllocator>
-class Writer {
-public:
- typedef typename SourceEncoding::Ch Ch;
-
- //! Constructor
- /*! \param os Output stream.
- \param stackAllocator User supplied allocator. If it is null, it will create a private one.
- \param levelDepth Initial capacity of stack.
- */
- explicit
- Writer(OutputStream& os, StackAllocator* stackAllocator = 0, size_t levelDepth = kDefaultLevelDepth) :
- os_(&os), level_stack_(stackAllocator, levelDepth * sizeof(Level)), hasRoot_(false) {}
-
- explicit
- Writer(StackAllocator* allocator = 0, size_t levelDepth = kDefaultLevelDepth) :
- os_(0), level_stack_(allocator, levelDepth * sizeof(Level)), hasRoot_(false) {}
-
- //! Reset the writer with a new stream.
- /*!
- This function reset the writer with a new stream and default settings,
- in order to make a Writer object reusable for output multiple JSONs.
-
- \param os New output stream.
- \code
- Writer<OutputStream> writer(os1);
- writer.StartObject();
- // ...
- writer.EndObject();
-
- writer.Reset(os2);
- writer.StartObject();
- // ...
- writer.EndObject();
- \endcode
- */
- void Reset(OutputStream& os) {
- os_ = &os;
- hasRoot_ = false;
- level_stack_.Clear();
- }
-
- //! Checks whether the output is a complete JSON.
- /*!
- A complete JSON has a complete root object or array.
- */
- bool IsComplete() const {
- return hasRoot_ && level_stack_.Empty();
- }
-
- /*!@name Implementation of Handler
- \see Handler
- */
- //@{
-
- bool Null() { Prefix(kNullType); return WriteNull(); }
- bool Bool(bool b) { Prefix(b ? kTrueType : kFalseType); return WriteBool(b); }
- bool Int(int i) { Prefix(kNumberType); return WriteInt(i); }
- bool Uint(unsigned u) { Prefix(kNumberType); return WriteUint(u); }
- bool Int64(int64_t i64) { Prefix(kNumberType); return WriteInt64(i64); }
- bool Uint64(uint64_t u64) { Prefix(kNumberType); return WriteUint64(u64); }
-
- //! Writes the given \c double value to the stream
- /*!
- \param d The value to be written.
- \return Whether it is succeed.
- */
- bool Double(double d) { Prefix(kNumberType); return WriteDouble(d); }
-
- bool String(const Ch* str, SizeType length, bool copy = false) {
- (void)copy;
- Prefix(kStringType);
- return WriteString(str, length);
- }
-
-#if RAPIDJSON_HAS_STDSTRING
- bool String(const std::basic_string<Ch>& str) {
- return String(str.data(), SizeType(str.size()));
- }
-#endif
-
- bool StartObject() {
- Prefix(kObjectType);
- new (level_stack_.template Push<Level>()) Level(false);
- return WriteStartObject();
- }
-
- bool Key(const Ch* str, SizeType length, bool copy = false) { return String(str, length, copy); }
-
- bool EndObject(SizeType memberCount = 0) {
- (void)memberCount;
- RAPIDJSON_ASSERT(level_stack_.GetSize() >= sizeof(Level));
- RAPIDJSON_ASSERT(!level_stack_.template Top<Level>()->inArray);
- level_stack_.template Pop<Level>(1);
- bool ret = WriteEndObject();
- if (level_stack_.Empty()) // end of json text
- os_->Flush();
- return ret;
- }
-
- bool StartArray() {
- Prefix(kArrayType);
- new (level_stack_.template Push<Level>()) Level(true);
- return WriteStartArray();
- }
-
- bool EndArray(SizeType elementCount = 0) {
- (void)elementCount;
- RAPIDJSON_ASSERT(level_stack_.GetSize() >= sizeof(Level));
- RAPIDJSON_ASSERT(level_stack_.template Top<Level>()->inArray);
- level_stack_.template Pop<Level>(1);
- bool ret = WriteEndArray();
- if (level_stack_.Empty()) // end of json text
- os_->Flush();
- return ret;
- }
- //@}
-
- /*! @name Convenience extensions */
- //@{
-
- //! Simpler but slower overload.
- bool String(const Ch* str) { return String(str, internal::StrLen(str)); }
- bool Key(const Ch* str) { return Key(str, internal::StrLen(str)); }
-
- //@}
-
-protected:
- //! Information for each nested level
- struct Level {
- Level(bool inArray_) : valueCount(0), inArray(inArray_) {}
- size_t valueCount; //!< number of values in this level
- bool inArray; //!< true if in array, otherwise in object
- };
-
- static const size_t kDefaultLevelDepth = 32;
-
- bool WriteNull() {
- os_->Put('n'); os_->Put('u'); os_->Put('l'); os_->Put('l'); return true;
- }
-
- bool WriteBool(bool b) {
- if (b) {
- os_->Put('t'); os_->Put('r'); os_->Put('u'); os_->Put('e');
- }
- else {
- os_->Put('f'); os_->Put('a'); os_->Put('l'); os_->Put('s'); os_->Put('e');
- }
- return true;
- }
-
- bool WriteInt(int i) {
- char buffer[11];
- const char* end = internal::i32toa(i, buffer);
- for (const char* p = buffer; p != end; ++p)
- os_->Put(*p);
- return true;
- }
-
- bool WriteUint(unsigned u) {
- char buffer[10];
- const char* end = internal::u32toa(u, buffer);
- for (const char* p = buffer; p != end; ++p)
- os_->Put(*p);
- return true;
- }
-
- bool WriteInt64(int64_t i64) {
- char buffer[21];
- const char* end = internal::i64toa(i64, buffer);
- for (const char* p = buffer; p != end; ++p)
- os_->Put(*p);
- return true;
- }
-
- bool WriteUint64(uint64_t u64) {
- char buffer[20];
- char* end = internal::u64toa(u64, buffer);
- for (char* p = buffer; p != end; ++p)
- os_->Put(*p);
- return true;
- }
-
- bool WriteDouble(double d) {
- char buffer[25];
- char* end = internal::dtoa(d, buffer);
- for (char* p = buffer; p != end; ++p)
- os_->Put(*p);
- return true;
- }
-
- bool WriteString(const Ch* str, SizeType length) {
- static const char hexDigits[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
- static const char escape[256] = {
-#define Z16 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
- //0 1 2 3 4 5 6 7 8 9 A B C D E F
- 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'b', 't', 'n', 'u', 'f', 'r', 'u', 'u', // 00
- 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', // 10
- 0, 0, '"', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20
- Z16, Z16, // 30~4F
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,'\\', 0, 0, 0, // 50
- Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16 // 60~FF
-#undef Z16
- };
-
- os_->Put('\"');
- GenericStringStream<SourceEncoding> is(str);
- while (is.Tell() < length) {
- const Ch c = is.Peek();
- if (!TargetEncoding::supportUnicode && (unsigned)c >= 0x80) {
- // Unicode escaping
- unsigned codepoint;
- if (!SourceEncoding::Decode(is, &codepoint))
- return false;
- os_->Put('\\');
- os_->Put('u');
- if (codepoint <= 0xD7FF || (codepoint >= 0xE000 && codepoint <= 0xFFFF)) {
- os_->Put(hexDigits[(codepoint >> 12) & 15]);
- os_->Put(hexDigits[(codepoint >> 8) & 15]);
- os_->Put(hexDigits[(codepoint >> 4) & 15]);
- os_->Put(hexDigits[(codepoint ) & 15]);
- }
- else {
- RAPIDJSON_ASSERT(codepoint >= 0x010000 && codepoint <= 0x10FFFF);
- // Surrogate pair
- unsigned s = codepoint - 0x010000;
- unsigned lead = (s >> 10) + 0xD800;
- unsigned trail = (s & 0x3FF) + 0xDC00;
- os_->Put(hexDigits[(lead >> 12) & 15]);
- os_->Put(hexDigits[(lead >> 8) & 15]);
- os_->Put(hexDigits[(lead >> 4) & 15]);
- os_->Put(hexDigits[(lead ) & 15]);
- os_->Put('\\');
- os_->Put('u');
- os_->Put(hexDigits[(trail >> 12) & 15]);
- os_->Put(hexDigits[(trail >> 8) & 15]);
- os_->Put(hexDigits[(trail >> 4) & 15]);
- os_->Put(hexDigits[(trail ) & 15]);
- }
- }
- else if ((sizeof(Ch) == 1 || (unsigned)c < 256) && escape[(unsigned char)c]) {
- is.Take();
- os_->Put('\\');
- os_->Put(escape[(unsigned char)c]);
- if (escape[(unsigned char)c] == 'u') {
- os_->Put('0');
- os_->Put('0');
- os_->Put(hexDigits[(unsigned char)c >> 4]);
- os_->Put(hexDigits[(unsigned char)c & 0xF]);
- }
- }
- else
- if (!Transcoder<SourceEncoding, TargetEncoding>::Transcode(is, *os_))
- return false;
- }
- os_->Put('\"');
- return true;
- }
-
- bool WriteStartObject() { os_->Put('{'); return true; }
- bool WriteEndObject() { os_->Put('}'); return true; }
- bool WriteStartArray() { os_->Put('['); return true; }
- bool WriteEndArray() { os_->Put(']'); return true; }
-
- void Prefix(Type type) {
- (void)type;
- if (level_stack_.GetSize() != 0) { // this value is not at root
- Level* level = level_stack_.template Top<Level>();
- if (level->valueCount > 0) {
- if (level->inArray)
- os_->Put(','); // add comma if it is not the first element in array
- else // in object
- os_->Put((level->valueCount % 2 == 0) ? ',' : ':');
- }
- if (!level->inArray && level->valueCount % 2 == 0)
- RAPIDJSON_ASSERT(type == kStringType); // if it's in object, then even number should be a name
- level->valueCount++;
- }
- else {
- RAPIDJSON_ASSERT(!hasRoot_); // Should only has one and only one root.
- hasRoot_ = true;
- }
- }
-
- OutputStream* os_;
- internal::Stack<StackAllocator> level_stack_;
- bool hasRoot_;
-
-private:
- // Prohibit copy constructor & assignment operator.
- Writer(const Writer&);
- Writer& operator=(const Writer&);
-};
-
-// Full specialization for StringStream to prevent memory copying
-
-template<>
-inline bool Writer<StringBuffer>::WriteInt(int i) {
- char *buffer = os_->Push(11);
- const char* end = internal::i32toa(i, buffer);
- os_->Pop(11 - (end - buffer));
- return true;
-}
-
-template<>
-inline bool Writer<StringBuffer>::WriteUint(unsigned u) {
- char *buffer = os_->Push(10);
- const char* end = internal::u32toa(u, buffer);
- os_->Pop(10 - (end - buffer));
- return true;
-}
-
-template<>
-inline bool Writer<StringBuffer>::WriteInt64(int64_t i64) {
- char *buffer = os_->Push(21);
- const char* end = internal::i64toa(i64, buffer);
- os_->Pop(21 - (end - buffer));
- return true;
-}
-
-template<>
-inline bool Writer<StringBuffer>::WriteUint64(uint64_t u) {
- char *buffer = os_->Push(20);
- const char* end = internal::u64toa(u, buffer);
- os_->Pop(20 - (end - buffer));
- return true;
-}
-
-template<>
-inline bool Writer<StringBuffer>::WriteDouble(double d) {
- char *buffer = os_->Push(25);
- char* end = internal::dtoa(d, buffer);
- os_->Pop(25 - (end - buffer));
- return true;
-}
-
-RAPIDJSON_NAMESPACE_END
-
-#ifdef _MSC_VER
-RAPIDJSON_DIAG_POP
-#endif
-
-#endif // RAPIDJSON_RAPIDJSON_H_
diff --git a/src/infill/ImageBasedDensityProvider.cpp b/src/infill/ImageBasedDensityProvider.cpp
index 0917e9148..dcc13a9f4 100644
--- a/src/infill/ImageBasedDensityProvider.cpp
+++ b/src/infill/ImageBasedDensityProvider.cpp
@@ -4,7 +4,7 @@
#define STBI_FAILURE_USERMSG // enable user friendly bug messages for STB lib
#define STB_IMAGE_IMPLEMENTATION // needed in order to enable the implementation of libs/std_image.h
-#include <stb/stb_image.h>
+#include <stb_image.h>
#include "ImageBasedDensityProvider.h"
#include "SierpinskiFill.h"
diff --git a/src/raft.cpp b/src/raft.cpp
index 7ab5ac9cb..2b1c92980 100644
--- a/src/raft.cpp
+++ b/src/raft.cpp
@@ -1,7 +1,7 @@
//Copyright (c) 2018 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
-#include "clipper.hpp"
+#include <polyclipping/clipper.hpp>
#include "Application.h" //To get settings.
#include "ExtruderTrain.h"
diff --git a/src/utils/Coord_t.h b/src/utils/Coord_t.h
index 4b0847d23..ddddb2d8c 100644
--- a/src/utils/Coord_t.h
+++ b/src/utils/Coord_t.h
@@ -6,7 +6,7 @@
//Include Clipper to get the ClipperLib::IntPoint definition, which we reuse as Point definition.
-#include "clipper.hpp"
+#include <polyclipping/clipper.hpp>
namespace cura
{
diff --git a/src/utils/IntPoint.h b/src/utils/IntPoint.h
index ab66e3a8c..ebf8d0ef9 100644
--- a/src/utils/IntPoint.h
+++ b/src/utils/IntPoint.h
@@ -11,7 +11,7 @@ Integer points are used to avoid floating point rounding errors, and because Cli
#define INLINE static inline
//Include Clipper to get the ClipperLib::IntPoint definition, which we reuse as Point definition.
-#include "clipper.hpp"
+#include <polyclipping/clipper.hpp>
#include <cmath>
#include <functional> // for hash function object
#include <iostream> // auto-serialization / auto-toString()
diff --git a/src/utils/polygon.h b/src/utils/polygon.h
index f69515038..1644c2d57 100644
--- a/src/utils/polygon.h
+++ b/src/utils/polygon.h
@@ -9,7 +9,7 @@
#include <assert.h>
#include <float.h>
#include <algorithm>
-#include "clipper.hpp"
+#include <polyclipping/clipper.hpp>
#include <algorithm> // std::reverse, fill_n array
#include <cmath> // fabs
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
new file mode 100644
index 000000000..44ef8e1b3
--- /dev/null
+++ b/tests/CMakeLists.txt
@@ -0,0 +1,103 @@
+include(CTest)
+message(STATUS "Building tests...")
+find_package(GTest CONFIG REQUIRED)
+
+# List of tests. For each test there must be a file tests/${NAME}.cpp.
+set(engine_TEST
+ ExtruderPlanTest
+ GCodeExportTest
+ InfillTest
+ LayerPlanTest
+ PathOrderOptimizerTest
+ PathOrderMonotonicTest
+ TimeEstimateCalculatorTest
+ WallsComputationTest
+ )
+set(engine_TEST_ARCUS
+ ArcusCommunicationTest
+ ArcusCommunicationPrivateTest
+ )
+set(engine_TEST_BEADING_STRATEGY
+ CenterDeviationBeadingStrategyTest
+ )
+set(engine_TEST_INFILL
+ )
+set(engine_TEST_INTEGRATION
+ SlicePhaseTest
+ )
+set(engine_TEST_SETTINGS
+ SettingsTest
+ )
+set(engine_TEST_UTILS
+ AABBTest
+ AABB3DTest
+ ExtrusionLineTest
+ IntPointTest
+ LinearAlg2DTest
+ MinimumSpanningTreeTest
+ PolygonConnectorTest
+ PolygonTest
+ PolygonUtilsTest
+ SparseGridTest
+ StringTest
+ UnionFindTest
+ )
+
+# Helper classes for some tests.
+set(engine_TEST_ARCUS_HELPERS
+ arcus/MockSocket.cpp
+ )
+set(engine_TEST_HELPERS
+ ReadTestPolygons.cpp
+ )
+
+target_link_libraries(_CuraEngine PUBLIC GTest::gtest GTest::gmock)
+
+#To make sure that the tests are built before running them, add the building of these tests as an additional test.
+add_custom_target(build_all_tests)
+add_test(BuildTests "${CMAKE_COMMAND}" --build "${CMAKE_CURRENT_BINARY_DIR}" --target build_all_tests)
+
+foreach (test ${engine_TEST})
+ add_executable(${test} main.cpp ${engine_TEST_HELPERS} ${test}.cpp)
+ target_link_libraries(${test} PRIVATE _CuraEngine GTest::gtest GTest::gmock polyclipping::polyclipping)
+ add_test(NAME ${test} COMMAND "${test}" WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}/tests")
+ add_dependencies(build_all_tests ${test}) #Make sure that this gets built as part of the build_all_tests target.
+ message(STATUS "Added test: ${test}")
+endforeach()
+foreach (test ${engine_TEST_INFILL})
+ add_executable(${test} main.cpp infill/${test}.cpp)
+ target_link_libraries(${test} PRIVATE _CuraEngine GTest::gtest GTest::gmock)
+ add_test(NAME ${test} COMMAND "${test}" WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}/tests/")
+ add_dependencies(build_all_tests ${test}) #Make sure that this gets built as part of the build_all_tests target.
+ message(STATUS "Added test: ${test}")
+endforeach()
+foreach (test ${engine_TEST_INTEGRATION})
+ add_executable(${test} main.cpp integration/${test}.cpp)
+ target_link_libraries(${test} PRIVATE _CuraEngine GTest::gtest GTest::gmock)
+ add_test(NAME ${test} COMMAND "${test}" WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}/tests/")
+ add_dependencies(build_all_tests ${test}) #Make sure that this gets built as part of the build_all_tests target.
+ message(STATUS "Added test: ${test}")
+endforeach()
+foreach (test ${engine_TEST_SETTINGS})
+ add_executable(${test} main.cpp settings/${test}.cpp)
+ target_link_libraries(${test} PRIVATE _CuraEngine GTest::gtest GTest::gmock polyclipping::polyclipping)
+ add_test(NAME ${test} COMMAND "${test}" WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}/tests/")
+ add_dependencies(build_all_tests ${test}) #Make sure that this gets built as part of the build_all_tests target.
+ message(STATUS "Added test: ${test}")
+endforeach()
+if (ENABLE_ARCUS)
+ foreach (test ${engine_TEST_ARCUS})
+ add_executable(${test} main.cpp ${engine_TEST_ARCUS_HELPERS} arcus/${test}.cpp)
+ target_link_libraries(${test} PRIVATE _CuraEngine GTest::gtest GTest::gmock Arcus::Arcus)
+ add_test(NAME ${test} COMMAND "${test}" WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}/tests/")
+ add_dependencies(build_all_tests ${test}) #Make sure that this gets built as part of the build_all_tests target.
+ message(STATUS "Added test: ${test}")
+ endforeach()
+endif ()
+foreach (test ${engine_TEST_UTILS})
+ add_executable(${test} main.cpp utils/${test}.cpp)
+ target_link_libraries(${test} PUBLIC _CuraEngine GTest::gtest GTest::gmock polyclipping::polyclipping)
+ add_test(NAME ${test} COMMAND "${test}" WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}/tests/")
+ add_dependencies(build_all_tests ${test}) #Make sure that this gets built as part of the build_all_tests target.
+ message(STATUS "Added test: ${test}")
+endforeach() \ No newline at end of file
diff --git a/tests/PathOrderMonotonicTest.cpp b/tests/PathOrderMonotonicTest.cpp
index 3e066c611..a1dca462b 100644
--- a/tests/PathOrderMonotonicTest.cpp
+++ b/tests/PathOrderMonotonicTest.cpp
@@ -4,7 +4,7 @@
#include <string>
#include <gtest/gtest.h>
-#include <clipper.hpp>
+#include <polyclipping/clipper.hpp>
#include "../src/infill.h"
#include "../src/utils/linearAlg2D.h"
diff --git a/tests/utils/AABB3DTest.cpp b/tests/utils/AABB3DTest.cpp
index bb1b2d0d1..5e8291398 100644
--- a/tests/utils/AABB3DTest.cpp
+++ b/tests/utils/AABB3DTest.cpp
@@ -2,7 +2,7 @@
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include <gtest/gtest.h>
-#include <clipper.hpp>
+#include <polyclipping/clipper.hpp>
#include "../src/utils/AABB.h"
#include "../src/utils/AABB3D.h"
diff --git a/tests/utils/AABBTest.cpp b/tests/utils/AABBTest.cpp
index ad87b3923..4b809bf31 100644
--- a/tests/utils/AABBTest.cpp
+++ b/tests/utils/AABBTest.cpp
@@ -2,7 +2,7 @@
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include <gtest/gtest.h>
-#include <clipper.hpp>
+#include <polyclipping/clipper.hpp>
#include <../src/utils/AABB.h>
#include <../src/utils/polygon.h>