Sign Up
Log In
Log In
or
Sign Up
Places
All Projects
Status Monitor
Collapse sidebar
games:WorldForge
wfmath
_service:obs_scm:wfmath-1701611135.403a8bd.obscpio
Overview
Repositories
Revisions
Requests
Users
Attributes
Meta
File _service:obs_scm:wfmath-1701611135.403a8bd.obscpio of Package wfmath
07070100000000000041ED000000000000000000000003656C867F00000000000000000000000000000000000000000000002200000000wfmath-1701611135.403a8bd/.github07070100000001000041ED000000000000000000000002656C867F00000000000000000000000000000000000000000000002C00000000wfmath-1701611135.403a8bd/.github/workflows07070100000002000081A4000000000000000000000001656C867F000008E7000000000000000000000000000000000000003600000000wfmath-1701611135.403a8bd/.github/workflows/cmake.ymlname: Build all on: workflow_dispatch: push: branches: - master env: CONAN_REVISIONS_ENABLED: 1 CONAN_SCM_TO_CONANDATA: 1 CONAN_PASSWORD: ${{ secrets.CONAN_PASSWORD }} CONAN_LOGIN_USERNAME: ${{ secrets.CONAN_LOGIN_USERNAME }} PROFILE_CONAN: conan-release jobs: build: runs-on: ${{ matrix.os }} strategy: matrix: # os: [ ubuntu-20.04, ubuntu-22.04, windows-2019, windows-2022, macos-11, macos-12 ] os: [ ubuntu-20.04, ubuntu-22.04, macos-11, macos-12 ] steps: - name: Workaround preset name difference if: runner.os == 'Windows' shell: bash run: echo "PROFILE_CONAN=conan-default" >> $GITHUB_ENV - uses: actions/checkout@v3 - uses: actions/setup-python@v4 with: python-version: '3.9' cache: 'pip' - name: Install Conan shell: bash run: | pip install -r .github/workflows/requirements.txt conan profile detect #Set the default profile to use g++ 17 it it's not detected sed -i.backup 's/compiler.cppstd=gnu14/compiler.cppstd=gnu17/g' ~/.conan2/profiles/default conan remote add worldforge https://artifactory.ogenvik.org/artifactory/api/conan/conan - name: Have Conan install packages shell: bash run: | conan install tools/conan -pr default --build=missing --update - name: Configure CMake # Use a bash shell so we can use the same syntax for environment variable # access regardless of the host operating system shell: bash run: cmake --preset $PROFILE_CONAN . -DBUILD_TESTING=ON - name: Build shell: bash run: cmake --build --preset $PROFILE_CONAN --parallel - name: Test shell: bash run: ctest --preset $PROFILE_CONAN --output-on-failure --parallel - name: Upload artifacts shell: bash run: | if [[ x"$CONAN_PASSWORD" != "x" && x"$CONAN_LOGIN_USERNAME" != "x" ]]; then echo "Creating and uploading Conan artifacts" conan remote login worldforge $CONAN_LOGIN_USERNAME -p $CONAN_PASSWORD conan create tools/conan -pr default conan upload "*" -r worldforge -c fi 07070100000003000081A4000000000000000000000001656C867F00000005000000000000000000000000000000000000003D00000000wfmath-1701611135.403a8bd/.github/workflows/requirements.txtconan07070100000004000081A4000000000000000000000001656C867F000001E3000000000000000000000000000000000000002500000000wfmath-1701611135.403a8bd/.gitignoreconfig.guess config.h config.h.in config.h.in~ config.log config.status config.sub configure depcomp doc/Doxyfile mingw32-wfmath.spec missing stamp-h1 wfmath-1.0.pc wfmath.spec .deps .libs *.lo *.la *.o *_test *_test.log .*.swp test-suite.log # Ignore temporary files *~ # ignore Eclipse project files .project .cproject .settings .cdtconfig* .autotools *.orig *.log *.kdevelop #The report generated by the ABI checker tool abi_report .idea cmake-build-* build CMakeUserPresets.json 07070100000005000081A4000000000000000000000001656C867F000001D4000000000000000000000000000000000000002300000000wfmath-1701611135.403a8bd/.mailmapErik Ogenvik <erik@ogenvik.org> Erik Hjortsberg <erik.hjortsberg@iteam.se> Erik Ogenvik <erik@ogenvik.org> Erik Hjortsberg <erik.hjortsberg@gmail.com> Erik Ogenvik <erik@ogenvik.org> Erik Hjortsberg <erik.hjortsberg@jayway.se> Alistair Riddoch <alriddoch@googlemail.com> Al Riddoch <alriddoch@googlemail.com> Alistair Riddoch <alriddoch@googlemail.com> Al Riddoch <alriddoch@localhost> Peter Szücs <peter.szucs.dev@gmail.com> Peter Szucs <peter.szucs.dev@gmail.com> 07070100000006000081A4000000000000000000000001656C867F000006FA000000000000000000000000000000000000002600000000wfmath-1701611135.403a8bd/.travis.ymllanguage: cpp jobs: include: - os: linux dist: bionic compiler: clang - os: linux dist: bionic compiler: gcc - os: linux dist: focal compiler: clang - os: linux dist: focal compiler: gcc - os: osx osx_image: xcode10.2 compiler: clang addons: apt: packages: - ccache - python3-pip - doxygen - graphviz homebrew: packages: - xz - ccache - python3 env: global: - CONAN_V2_MODE=1 - CONAN_REVISIONS_ENABLED=1 - CONAN_SCM_TO_CONANDATA=1 cache: - pip - ccache - directories: - $HOME/Library/Caches/Homebrew before_install: - sudo pip3 install --upgrade pip wheel setuptools jinja2 - sudo pip3 install --upgrade conan - conan --version - conan user - conan remote add worldforge https://artifactory.ogenvik.org/artifactory/api/conan/conan script: - mkdir build && cd build - conan profile new default --detect - | if [[ "$TRAVIS_OS_NAME" != "osx" && "$CXX" == "clang++" ]]; then echo "Setting libc to use C++11 features" conan profile update settings.compiler.libcxx=libstdc++11 default fi - conan install ../tools/conan -pr default --build=missing --update - cmake -DBUILD_SHARED_LIBS=OFF .. || travis_terminate 1 - make || travis_terminate 1 - make check || travis_terminate 1 # - if [ "$TRAVIS_OS_NAME" != "osx" -a "$CC" == "gcc" ]; then make dox; fi - | if [[ x"$CONAN_PASSWORD" != "x" && x"$CONAN_LOGIN_USERNAME" != "x" ]]; then echo "Creating and uploading Conan artifacts" conan user -p $CONAN_PASSWORD -r worldforge $CONAN_LOGIN_USERNAME conan create ../tools/conan worldforge/testing -pr default conan upload "*" -r worldforge -c --all fi 07070100000007000081A4000000000000000000000001656C867F00000204000000000000000000000000000000000000002200000000wfmath-1701611135.403a8bd/AUTHORSMaintainer: Erik Ogenvik <erik@ogenvik.org> Original author: Ron Steinke <rsteinke@w-link.net> Other contributors: James Turner <james@worldforge.org> Michael Koch <konqueror@gmx.de> Dan Tomalesky <grim@xynesis.com> Al Riddoch <alriddoch@googlemail.com> The Miniball code of Bernd Gaertner <http://www.inf.ethz.ch/personal/gaertner> is used for finding bounding spheres for collections of points. The Mersenne Twister code of Richard J. Wagner <rjwagner@writeme.com> is used for random number generation. 07070100000008000081A4000000000000000000000001656C867F000019C7000000000000000000000000000000000000002900000000wfmath-1701611135.403a8bd/CMakeLists.txtcmake_minimum_required(VERSION 3.12) project(wfmath) set(CMAKE_CXX_STANDARD 14) set(CMAKE_CXX_STANDARD_REQUIRED on) include(GNUInstallDirs) include(FindPkgConfig) # Version setup set(VERSION_MAJOR 1) set(VERSION_MINOR 0) set(VERSION_PATCH 3) set(VERSION ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}) set(ABI_CURRENT 1) set(ABI_REVISION 0) set(ABI_AGE 0) math(EXPR SOVERSION ${ABI_CURRENT}-${ABI_AGE}) set(ABI_VERSION ${SOVERSION}.${ABI_AGE}.${ABI_REVISION}) option(BUILD_TESTING "Should tests always be built; otherwise they will be built when the 'check' target is executed." OFF) option(BUILD_SHARED_LIBS "Build libraries as shared as opposed to static." ON) # Set compiler flags if (CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") set(WF_WARNING_FLAGS /W3) add_definitions(-D_WIN32_WINNT=0x0601) #target Windows 7 else () set(WF_WARNING_FLAGS -Wall -Winit-self -Wcast-qual -Wwrite-strings -Wextra -Wundef -Wmissing-declarations -Wno-unused-parameter -Wshadow -Wno-missing-field-initializers -Wno-long-long) endif () include_directories("${PROJECT_SOURCE_DIR}/src") # Meta data set(DESCRIPTION "A math library for the Worldforge system.") # This macro defines a library macro(wf_add_library _LIB_NAME _SOURCE_FILES_VAR _HEADER_FILES_VAR) add_library(${_LIB_NAME} ${${_SOURCE_FILES_VAR}}) set_target_properties(${_LIB_NAME} PROPERTIES VERSION ${ABI_VERSION} SOVERSION ${SOVERSION} ) target_compile_options(${_LIB_NAME} PUBLIC ${WF_WARNING_FLAGS}) target_include_directories(${_LIB_NAME} PUBLIC "$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>" "$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>" ) install(TARGETS ${_LIB_NAME} EXPORT "${PROJECT_NAME}Targets" LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} ) #We would want to use the FILE_SET feature, but that requires CMake 3.23, which prevents us from currently building # Snap packages (as of 2023-02-12). Instead we'll copy each include file. #When distros catch up to more recent CMake versions we can use FILE_SET instead. foreach (file ${${_HEADER_FILES_VAR}}) get_filename_component(dir ${file} DIRECTORY) install(FILES ${file} DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${dir}) endforeach () endmacro() enable_testing() # Add a "check" target, which builds and runs the tests. add_custom_target(check COMMAND ${CMAKE_CTEST_COMMAND}) #Macro for adding a test. The test name will be extracted from the name of the first submitted file. #Additional files can be submitted as varargs. macro(wf_add_test TEST_FILE) get_filename_component(TEST_NAME ${TEST_FILE} NAME_WE) # If BUILD_TESTING is defined we'll build the test no matter what. This makes it work better on Windows. if (BUILD_TESTING) add_executable(${TEST_NAME} ${TEST_FILE} ${ARGN}) else (BUILD_TESTING) add_executable(${TEST_NAME} EXCLUDE_FROM_ALL ${TEST_FILE} ${ARGN}) endif (BUILD_TESTING) target_link_libraries(${TEST_NAME} "${PROJECT_NAME}") target_compile_options(${TEST_NAME} PUBLIC "-w") add_test(NAME ${TEST_NAME} COMMAND $<TARGET_FILE:${TEST_NAME}>) #We need to tell adjust the path so tests on windows can find the .dll files. SET_TESTS_PROPERTIES(${TEST_NAME} PROPERTIES ENVIRONMENT "PATH=${CMAKE_BINARY_DIR}/bin;$ENV{PATH}") add_dependencies(check ${TEST_NAME}) endmacro() # We only need Atlas for tests find_package(Atlas 0.7.0) add_subdirectory(src) add_subdirectory(tests) # pkg-config files configure_file(tools/${PROJECT_NAME}.pc.in ${PROJECT_NAME}.pc @ONLY) install(FILES ${PROJECT_BINARY_DIR}/${PROJECT_NAME}.pc DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig) # Doxygen support, exports a "dox" target. find_package(Doxygen) configure_file(docs/Doxyfile.in Doxyfile @ONLY) if (DOXYGEN_FOUND) set(DOXYGEN_INPUT ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile) set(DOXYGEN_OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/docs) add_custom_command( OUTPUT ${DOXYGEN_OUTPUT} COMMAND ${CMAKE_COMMAND} -E echo_append "Building API Documentation..." COMMAND ${DOXYGEN_EXECUTABLE} ${DOXYGEN_INPUT} COMMAND ${CMAKE_COMMAND} -E echo "Done." WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} DEPENDS ${DOXYGEN_INPUT} ) add_custom_target(dox DEPENDS ${DOXYGEN_OUTPUT}) endif (DOXYGEN_FOUND) add_custom_command( OUTPUT ChangeLog COMMAND ${CMAKE_SOURCE_DIR}/support/generate-ChangeLog.sh ${CMAKE_SOURCE_DIR} ${CMAKE_SOURCE_DIR} 8bd480b053190ffde2afe33af66f484953036f5a ) add_custom_target(changelog DEPENDS ChangeLog) # CMake config files include(CMakePackageConfigHelpers) install(EXPORT "${PROJECT_NAME}Targets" FILE "${PROJECT_NAME}Targets.cmake" NAMESPACE "${PROJECT_NAME}::" DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}" ) configure_package_config_file(tools/Config.cmake.in ${PROJECT_BINARY_DIR}/cmake/${PROJECT_NAME}Config.cmake INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME} PATH_VARS CMAKE_INSTALL_INCLUDEDIR CMAKE_INSTALL_LIBDIR) write_basic_package_version_file( ${PROJECT_BINARY_DIR}/cmake/${PROJECT_NAME}ConfigVersion.cmake VERSION ${VERSION} COMPATIBILITY ExactVersion) install(FILES ${PROJECT_BINARY_DIR}/cmake/${PROJECT_NAME}Config.cmake ${PROJECT_BINARY_DIR}/cmake/${PROJECT_NAME}ConfigVersion.cmake DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}) # Packaging (for source tarballs set(CPACK_PACKAGE_DESCRIPTION_SUMMARY ${DESCRIPTION}) set(CPACK_PACKAGE_VENDOR "Worldforge") set(CPACK_PACKAGE_DESCRIPTION_FILE "${PROJECT_SOURCE_DIR}/README.md") set(CPACK_RESOURCE_FILE_LICENSE "${PROJECT_SOURCE_DIR}/COPYING") set(CPACK_PACKAGE_VERSION_MAJOR "${VERSION_MAJOR}") set(CPACK_PACKAGE_VERSION_MINOR "${VERSION_MINOR}") set(CPACK_PACKAGE_VERSION_PATCH "${VERSION_PATCH}") #set(CPACK_INSTALL_SCRIPT "sh ${CMAKE_SOURCE_DIR}/support/generate-ChangeLog.sh ${CMAKE_SOURCE_DIR} ${CPACK_PACKAGE_INSTALL_DIRECTORY} 8bd480b053190ffde2afe33af66f484953036f5a") set(CPACK_SOURCE_GENERATOR TBZ2 ZIP) set(CPACK_SOURCE_PACKAGE_FILE_NAME "${PROJECT_NAME}-${VERSION}" CACHE INTERNAL "tarball basename") set(CPACK_SOURCE_IGNORE_FILES # no hidden files "/\\\\..+$" "~$" ) include(CPack) 07070100000009000081A4000000000000000000000001656C867F000046AC000000000000000000000000000000000000002200000000wfmath-1701611135.403a8bd/COPYING GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. <signature of Ty Coon>, 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. 0707010000000A000081A4000000000000000000000001656C867F00000123000000000000000000000000000000000000002400000000wfmath-1701611135.403a8bd/ChangeLogThis file is autogenerated from the Git history when a the "dist" make target is invoked. If you find this file in an official release something has gone wrong and you should contact erik@ogenvik.org. It needs to be exactly one line long in order for the ChangeLog generating script to work.0707010000000B000081A4000000000000000000000001656C867F000003F4000000000000000000000000000000000000001F00000000wfmath-1701611135.403a8bd/NEWS2013-08-31 Erik Ogenvik <erik@ogenvik.org> * wfmath 1.0.2 released. 2012-10-24 Al Riddoch <alriddoch@googlemail.com> * wfmath 1.0.1 released. 2012-03-21 Al Riddoch <alriddoch@googlemail.com> * wfmath 1.0.0 released. 2012-01-18 Al Riddoch <alriddoch@googlemail.com> * wfmath 0.3.12 released. 2011-02-12 Al Riddoch <alriddoch@googlemail.com> * wfmath 0.3.11 released. 2009-12-29 Al Riddoch <alriddoch@googlemail.com> * wfmath 0.3.10 released. 2009-01-26 Al Riddoch <alriddoch@googlemail.com> * wfmath 0.3.9 released. 2008-11-15 Al Riddoch <alriddoch@googlemail.com> * wfmath 0.3.8 released. 2007-07-25 Al Riddoch <alriddoch@googlemail.com> * wfmath 0.3.7 released. 2007-07-20 Al Riddoch <alriddoch@zepler.org> * wfmath 0.3.6 released. 2006-08-18 Al Riddoch <alriddoch@zepler.org> * wfmath 0.3.5 released. 2005-06-11 Al Riddoch <alriddoch@zepler.org> * wfmath 0.3.4 released. 2003-04-24 Al Riddoch <alriddoch@zepler.org> * wfmath 0.2.11 released. 0707010000000C000081A4000000000000000000000001656C867F000012F3000000000000000000000000000000000000002400000000wfmath-1701611135.403a8bd/README.md# DEPRECATED This code has been moved to [the Worldforge repository](https://github.com/worldforge/worldforge). # WFMath [![Join us on Gitter!](https://badges.gitter.im/Worldforge.svg)](https://gitter.im/Worldforge/Lobby) [![Appveyor build status](https://ci.appveyor.com/api/projects/status/github/worldforge/wfmath?branch=master&svg=true)](https://ci.appveyor.com/project/erikogenvik/wfmath) [![Travis build Status](https://travis-ci.com/worldforge/wfmath.svg?branch=master)](https://travis-ci.com/worldforge/wfmath) [![Github build status](https://github.com/worldforge/wfmath/actions/workflows/cmake.yml/badge.svg)](https://github.com/worldforge/wfmath/actions/workflows/cmake.yml) This is the [WorldForge](http://worldforge.org/ "The main Worldforge site") math library. It's licensed under the GPL (see file COPYING). The primary focus of WFMath is geometric objects. Thus, it includes several shapes (boxes, balls, lines), in addition to the basic math objects that are used to build these shapes (points, vectors, matricies). ## Installation If you intend to build this as a prerequisite for the Ember client or the Cyphesis server we strongly suggest that you use the [Hammer](http://wiki.worldforge.org/wiki/Hammer_Script "The Hammer script") tool to compile it. This is script provided by the Worldforge project which will download and install all of the required libraries and components used by Worldforge. Alternatively you can use [Conan](https://www.conan.io) to install all dependencies. ```bash conan remote add worldforge https://artifactory.ogenvik.org/artifactory/api/conan/conan conan install tools/conan --build missing cmake --preset conan-release cmake --build --preset conan-release ``` Otherwise the library can most easily be built through the following commands. ```bash mkdir build && cd build cmake .. make -j all install ``` ### Tests The test suite can be built and run using the ```check``` target. For example: ```bash make check ``` or ```bash cmake --build --preset conan-release --target check ``` ### API documentation If Doxygen is available API documentation can be generated using the ```dox``` target. For example: ```bash make dox ``` or ```bash cmake --build --preset conan-release --target dox ``` ## Dependencies The only library that WFMath checks for is Atlas, and it only does this for the sake of some test functions. The only dependency on Atlas is in the file atlasconv.h. This header file contains some inline functions which can be used to convert the various objects in WFMath to Atlas::Message::Object and back. This header file will be installed whether Atlas is present or not, but to use it you must of course have the Atlas headers installed. ## Design Most of the library classes can be divided into two sorts. The first kind are basic mathematical objects, whose members are all fundamental types. The second kind are shapes, which implement the shape class interface described in doc/shape.h. There are four classes of the first kind: * Vector<> A basic mathematical vector * RotMatrix<> An orthogonal matrix of determinant 1, useful for describing rotations. * Point<> A point in space. This basic class also implements the shape interface in doc/shape.h. * Quaternion A quaternion The shape classes are: * AxisBox<> A box oriented parallel to the coordinate axes * Ball<> Ball<2> is a circle, Ball<3> is a sphere, etc. * Segment<> A line segment, defined by its endpoints * RotBox<> Like AxisBox<>, but it can be rotated to arbitrary angles * Polygon<> A 2 dimensional polygon contained in a (possibly) larger dimensional space The library also contains some probability-related functions, as well as wrappers for system time and random number functions. # Contributing Anyone interested in contributing to this project shouldl ook at the file doc/CLASS_LAYOUT, which specifies which member functions all classes should have, and what order they should appear in. This only applies to significant classes, not things like ColinearVectors in error.h, which is only there to be thrown as as exception. The documentation is at this point confined to the doc/CLASS_LAYOUT file and comments in the code. There's also a sample shape class definition in the file shape.h in the doc directory. This has comments about what member functions all shape classes are supposed to have, and what they do. ## How to help If you're interested in helping out with development you should check out these resources: * [The main Worldforge site](http://worldforge.org/ "The main Worldforge site") * [Bugs and feature planning on Launchpad](https://launchpad.net/wfmath "WFMath Launchpad entry") * [Gitter conversation](https://gitter.im/Worldforge/Lobby "Gitter conversation") * [Mailing lists](http://mail.worldforge.org/lists/listinfo/ "Mailing lists") 0707010000000D000081A4000000000000000000000001656C867F000007C7000000000000000000000000000000000000001F00000000wfmath-1701611135.403a8bd/TODOInline in the foo.h any method in foo_funcs.h that does not require another header, and has no loop Re-write operators so that for a given operator O, operatorO is implemented using operatorO= rather than the other way around which is inefficient. Add throw(ColinearVectors) to the appropriate vector and matrix rotation functions Get rid of templates as template args, use ValueType for standard containers instead Intersect functions unimplemented for dim != 2,3 (extremely low priority): Intersect(Polygon<>, AxisBox<>, bool) Intersect(Polygon<>, RotBox<>, bool) Intersect(RotBox<>, AxisBox<>, bool) Intersect(RotBox<>, RotBox<>, bool) These will be postponed until I can think of a way to write them, or someone needs them, whichever comes first Add shape tests from COAL Write rotateInverse() functions Look into whether miniball code can handle using float instead of double; if so, replace Wrapped_array with Point Requests from Jesse: NAN, INFINITY, RADIANS_TO_DEGREES, DEGREES_TO_RADIANS Write an API reference for the library. Find some inline documentation tool? Deal with difficulties in making certain functions friends of the appropriate classes Rearrange the functions in foo_funcs.h to match the order in the class in foo.h Schedule: 0.3.0 will come out once I get around to testing the Polygon intersect functions and make sure they work. At that point the old Intersect()/IntersectProper() interface will be removed, as will support for deprecated network formats in atlas_conv.h. This is also an appropriate time to make changes that break binary compatibility. alriddoch's TODO 2008-11-10 Clean up const.h removing all includes that it itself does not use. <cmath>, <cassert> and <iosfwd> should go. Clean up the rest of the headers that turn out to need this, but completely get rid of asserts from the interface headers. This should reduce the cost of including these headers, and stop them from polluting the namespace. 0707010000000E000081A4000000000000000000000001656C867F00000244000000000000000000000000000000000000002700000000wfmath-1701611135.403a8bd/appveyor.ymlversion: 1.0.{build} platform: - x64 install: - cmmd: echo "Downloading conan..." - cmmd: set PATH=%PATH%;%PYTHON%/Scripts/ - cmmd: pip.exe install conan - cmmd: conan user # Create the conan data directory - cmmd: conan --version - cmmd: conan remote add worldforge https://api.bintray.com/conan/worldforge/worldforge-conan build_script: - cmmd: mkdir build - cmmd: cd build - cmmd: conan install ../tools/conan - cmmd: cmake -DBUILD_TESTING=ON .. - cmmd: cmake --build . --config Release test_script: - cmmd: ctest 0707010000000F000041ED000000000000000000000002656C867F00000000000000000000000000000000000000000000001F00000000wfmath-1701611135.403a8bd/docs07070100000010000081A4000000000000000000000001656C867F000008C3000000000000000000000000000000000000002C00000000wfmath-1701611135.403a8bd/docs/CLASS_LAYOUTI'm trying to come up with a general class layout that all (significant) classes will obey. Friend functions are included under the corresponding section. Currently it's this: 1) Constructors and destructor The default constructor will not initialize the object. If the default constructor is used, the object must first be initialized with operator>>(), FromString(), FromAtlas(), operator=(), or one of the initializer functions given later in the class. There is no constructor from a string value, as such construction can fail. The destructor is not virtual, nor is any other function in the class, as this is a low-level library designed primarily for speed. 2) operator<<() and operator>>(), toAtlas() and fromAtlas() friend std::ostream& operator<<(std::ostream& os, const Foo& f); friend std::istream& operator>>(std::istream& is, Foo& f); operator>>() indicates a parse failure by setting the fail() flag on the stream. Failure also indicates that the object is in an invalid state. The definitions of these functions are placed in the file stream.h, so the class only needs to include <iosfwd>. The toAtlas() and fromAtlas() functions need a forward declaration of Atlas::Message::Object, which is done in const.h. They are only defined for certain classes (see Atlas protocol specs (where?) for details). The implementations of these functions belong in atlasconv.h, and must be done inline or as templates, so that the library can be built and used without libAtlas. 3) operator=() 4) isEqualTo() method this function is of the form bool C::isEqualTo(const C& c, CoordType tolerance = WFMATH_EPSILON); 5) operator==(), operator!=() these call isEqualTo() 6) Class initializers e.g. zero() for Vector<>, origin() for Point<>, etc. 7) operator<() sort only, if comparison makes sense stick others here too 8) math operators 9) other operators (e.g. operator[]()) 10) other functions 11) dimension-specific constructors/operators/functions e.g. Vector(CoordType& x, CoordType& y, CoordType& z) for Vector<3> Every class is also defines two non-member functions: ToString() and FromString(). These functions are automatically generated in stream.h using templates and the operator<<() and operator>>() functions. 07070100000011000081A4000000000000000000000001656C867F0001A692000000000000000000000000000000000000002B00000000wfmath-1701611135.403a8bd/docs/Doxyfile.in# Doxyfile 1.8.15 # This file describes the settings to be used by the documentation system # doxygen (www.doxygen.org) for a project. # # All text after a double hash (##) is considered a comment and is placed in # front of the TAG it is preceding. # # All text after a single hash (#) is considered a comment and will be ignored. # The format is: # TAG = value [value, ...] # For lists, items can also be appended using: # TAG += value [value, ...] # Values that contain spaces should be placed between quotes (\" \"). #--------------------------------------------------------------------------- # Project related configuration options #--------------------------------------------------------------------------- # This tag specifies the encoding used for all characters in the configuration # file that follow. The default is UTF-8 which is also the encoding used for all # text before the first occurrence of this tag. Doxygen uses libiconv (or the # iconv built into libc) for the transcoding. See # https://www.gnu.org/software/libiconv/ for the list of possible encodings. # The default value is: UTF-8. DOXYFILE_ENCODING = # The PROJECT_NAME tag is a single word (or a sequence of words surrounded by # double-quotes, unless you are using Doxywizard) that should identify the # project for which the documentation is generated. This name is used in the # title of most generated pages and in a few other places. # The default value is: My Project. PROJECT_NAME = @PROJECT_NAME@ # The PROJECT_NUMBER tag can be used to enter a project or revision number. This # could be handy for archiving the generated documentation or if some version # control system is used. PROJECT_NUMBER = @VERSION@ # Using the PROJECT_BRIEF tag one can provide an optional one line description # for a project that appears at the top of each page and should give viewer a # quick idea about the purpose of the project. Keep the description short. PROJECT_BRIEF = "@DESCRIPTION@" # With the PROJECT_LOGO tag one can specify a logo or an icon that is included # in the documentation. The maximum height of the logo should not exceed 55 # pixels and the maximum width should not exceed 200 pixels. Doxygen will copy # the logo to the output directory. PROJECT_LOGO = # The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path # into which the generated documentation will be written. If a relative path is # entered, it will be relative to the location where doxygen was started. If # left blank the current directory will be used. OUTPUT_DIRECTORY = @CMAKE_CURRENT_BINARY_DIR@/docs # If the CREATE_SUBDIRS tag is set to YES then doxygen will create 4096 sub- # directories (in 2 levels) under the output directory of each output format and # will distribute the generated files over these directories. Enabling this # option can be useful when feeding doxygen a huge amount of source files, where # putting all generated files in the same directory would otherwise causes # performance problems for the file system. # The default value is: NO. CREATE_SUBDIRS = # If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII # characters to appear in the names of generated files. If set to NO, non-ASCII # characters will be escaped, for example _xE3_x81_x84 will be used for Unicode # U+3044. # The default value is: NO. ALLOW_UNICODE_NAMES = # The OUTPUT_LANGUAGE tag is used to specify the language in which all # documentation generated by doxygen is written. Doxygen will use this # information to generate all constant output in the proper language. # Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Catalan, Chinese, # Chinese-Traditional, Croatian, Czech, Danish, Dutch, English (United States), # Esperanto, Farsi (Persian), Finnish, French, German, Greek, Hungarian, # Indonesian, Italian, Japanese, Japanese-en (Japanese with English messages), # Korean, Korean-en (Korean with English messages), Latvian, Lithuanian, # Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, Romanian, Russian, # Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, Swedish, Turkish, # Ukrainian and Vietnamese. # The default value is: English. OUTPUT_LANGUAGE = # The OUTPUT_TEXT_DIRECTION tag is used to specify the direction in which all # documentation generated by doxygen is written. Doxygen will use this # information to generate all generated output in the proper direction. # Possible values are: None, LTR, RTL and Context. # The default value is: None. OUTPUT_TEXT_DIRECTION = # If the BRIEF_MEMBER_DESC tag is set to YES, doxygen will include brief member # descriptions after the members that are listed in the file and class # documentation (similar to Javadoc). Set to NO to disable this. # The default value is: YES. BRIEF_MEMBER_DESC = # If the REPEAT_BRIEF tag is set to YES, doxygen will prepend the brief # description of a member or function before the detailed description # # Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the # brief descriptions will be completely suppressed. # The default value is: YES. REPEAT_BRIEF = # This tag implements a quasi-intelligent brief description abbreviator that is # used to form the text in various listings. Each string in this list, if found # as the leading text of the brief description, will be stripped from the text # and the result, after processing the whole list, is used as the annotated # text. Otherwise, the brief description is used as-is. If left blank, the # following values are used ($name is automatically replaced with the name of # the entity):The $name class, The $name widget, The $name file, is, provides, # specifies, contains, represents, a, an and the. ABBREVIATE_BRIEF = # If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then # doxygen will generate a detailed section even if there is only a brief # description. # The default value is: NO. ALWAYS_DETAILED_SEC = YES # If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all # inherited members of a class in the documentation of that class as if those # members were ordinary class members. Constructors, destructors and assignment # operators of the base classes will not be shown. # The default value is: NO. INLINE_INHERITED_MEMB = YES # If the FULL_PATH_NAMES tag is set to YES, doxygen will prepend the full path # before files name in the file list and in the header files. If set to NO the # shortest path that makes the file name unique will be used # The default value is: YES. FULL_PATH_NAMES = NO # The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path. # Stripping is only done if one of the specified strings matches the left-hand # part of the path. The tag can be used to show relative paths in the file list. # If left blank the directory from which doxygen is run is used as the path to # strip. # # Note that you can specify absolute paths here, but also relative paths, which # will be relative from the directory where doxygen is started. # This tag requires that the tag FULL_PATH_NAMES is set to YES. STRIP_FROM_PATH = # The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the # path mentioned in the documentation of a class, which tells the reader which # header file to include in order to use a class. If left blank only the name of # the header file containing the class definition is used. Otherwise one should # specify the list of include paths that are normally passed to the compiler # using the -I flag. STRIP_FROM_INC_PATH = # If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but # less readable) file names. This can be useful is your file systems doesn't # support long names like on DOS, Mac, or CD-ROM. # The default value is: NO. SHORT_NAMES = # If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the # first line (until the first dot) of a Javadoc-style comment as the brief # description. If set to NO, the Javadoc-style will behave just like regular Qt- # style comments (thus requiring an explicit @brief command for a brief # description.) # The default value is: NO. JAVADOC_AUTOBRIEF = # If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first # line (until the first dot) of a Qt-style comment as the brief description. If # set to NO, the Qt-style will behave just like regular Qt-style comments (thus # requiring an explicit \brief command for a brief description.) # The default value is: NO. QT_AUTOBRIEF = # The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a # multi-line C++ special comment block (i.e. a block of //! or /// comments) as # a brief description. This used to be the default behavior. The new default is # to treat a multi-line C++ comment block as a detailed description. Set this # tag to YES if you prefer the old behavior instead. # # Note that setting this tag to YES also means that rational rose comments are # not recognized any more. # The default value is: NO. MULTILINE_CPP_IS_BRIEF = # If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the # documentation from any documented member that it re-implements. # The default value is: YES. INHERIT_DOCS = # If the SEPARATE_MEMBER_PAGES tag is set to YES then doxygen will produce a new # page for each member. If set to NO, the documentation of a member will be part # of the file/class/namespace that contains it. # The default value is: NO. SEPARATE_MEMBER_PAGES = # The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen # uses this value to replace tabs by spaces in code fragments. # Minimum value: 1, maximum value: 16, default value: 4. TAB_SIZE = # This tag can be used to specify a number of aliases that act as commands in # the documentation. An alias has the form: # name=value # For example adding # "sideeffect=@par Side Effects:\n" # will allow you to put the command \sideeffect (or @sideeffect) in the # documentation, which will result in a user-defined paragraph with heading # "Side Effects:". You can put \n's in the value part of an alias to insert # newlines (in the resulting output). You can put ^^ in the value part of an # alias to insert a newline as if a physical newline was in the original file. # When you need a literal { or } or , in the value part of an alias you have to # escape them by means of a backslash (\), this can lead to conflicts with the # commands \{ and \} for these it is advised to use the version @{ and @} or use # a double escape (\\{ and \\}) ALIASES = # This tag can be used to specify a number of word-keyword mappings (TCL only). # A mapping has the form "name=value". For example adding "class=itcl::class" # will allow you to use the command class in the itcl::class meaning. TCL_SUBST = # Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources # only. Doxygen will then generate output that is more tailored for C. For # instance, some of the names that are used will be different. The list of all # members will be omitted, etc. # The default value is: NO. OPTIMIZE_OUTPUT_FOR_C = # Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or # Python sources only. Doxygen will then generate output that is more tailored # for that language. For instance, namespaces will be presented as packages, # qualified scopes will look different, etc. # The default value is: NO. OPTIMIZE_OUTPUT_JAVA = # Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran # sources. Doxygen will then generate output that is tailored for Fortran. # The default value is: NO. OPTIMIZE_FOR_FORTRAN = # Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL # sources. Doxygen will then generate output that is tailored for VHDL. # The default value is: NO. OPTIMIZE_OUTPUT_VHDL = # Set the OPTIMIZE_OUTPUT_SLICE tag to YES if your project consists of Slice # sources only. Doxygen will then generate output that is more tailored for that # language. For instance, namespaces will be presented as modules, types will be # separated into more groups, etc. # The default value is: NO. OPTIMIZE_OUTPUT_SLICE = # Doxygen selects the parser to use depending on the extension of the files it # parses. With this tag you can assign which parser to use for a given # extension. Doxygen has a built-in mapping, but you can override or extend it # using this tag. The format is ext=language, where ext is a file extension, and # language is one of the parsers supported by doxygen: IDL, Java, Javascript, # Csharp (C#), C, C++, D, PHP, md (Markdown), Objective-C, Python, Slice, # Fortran (fixed format Fortran: FortranFixed, free formatted Fortran: # FortranFree, unknown formatted Fortran: Fortran. In the later case the parser # tries to guess whether the code is fixed or free formatted code, this is the # default for Fortran type files), VHDL, tcl. For instance to make doxygen treat # .inc files as Fortran files (default is PHP), and .f files as C (default is # Fortran), use: inc=Fortran f=C. # # Note: For files without extension you can use no_extension as a placeholder. # # Note that for custom extensions you also need to set FILE_PATTERNS otherwise # the files are not read by doxygen. EXTENSION_MAPPING = # If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments # according to the Markdown format, which allows for more readable # documentation. See https://daringfireball.net/projects/markdown/ for details. # The output of markdown processing is further processed by doxygen, so you can # mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in # case of backward compatibilities issues. # The default value is: YES. MARKDOWN_SUPPORT = # When the TOC_INCLUDE_HEADINGS tag is set to a non-zero value, all headings up # to that level are automatically included in the table of contents, even if # they do not have an id attribute. # Note: This feature currently applies only to Markdown headings. # Minimum value: 0, maximum value: 99, default value: 0. # This tag requires that the tag MARKDOWN_SUPPORT is set to YES. TOC_INCLUDE_HEADINGS = # When enabled doxygen tries to link words that correspond to documented # classes, or namespaces to their corresponding documentation. Such a link can # be prevented in individual cases by putting a % sign in front of the word or # globally by setting AUTOLINK_SUPPORT to NO. # The default value is: YES. AUTOLINK_SUPPORT = # If you use STL classes (i.e. std::string, std::vector, etc.) but do not want # to include (a tag file for) the STL sources as input, then you should set this # tag to YES in order to let doxygen match functions declarations and # definitions whose arguments contain STL classes (e.g. func(std::string); # versus func(std::string) {}). This also make the inheritance and collaboration # diagrams that involve STL classes more complete and accurate. # The default value is: NO. BUILTIN_STL_SUPPORT = YES # If you use Microsoft's C++/CLI language, you should set this option to YES to # enable parsing support. # The default value is: NO. CPP_CLI_SUPPORT = # Set the SIP_SUPPORT tag to YES if your project consists of sip (see: # https://www.riverbankcomputing.com/software/sip/intro) sources only. Doxygen # will parse them like normal C++ but will assume all classes use public instead # of private inheritance when no explicit protection keyword is present. # The default value is: NO. SIP_SUPPORT = # For Microsoft's IDL there are propget and propput attributes to indicate # getter and setter methods for a property. Setting this option to YES will make # doxygen to replace the get and set methods by a property in the documentation. # This will only work if the methods are indeed getting or setting a simple # type. If this is not the case, or you want to show the methods anyway, you # should set this option to NO. # The default value is: YES. IDL_PROPERTY_SUPPORT = # If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC # tag is set to YES then doxygen will reuse the documentation of the first # member in the group (if any) for the other members of the group. By default # all members of a group must be documented explicitly. # The default value is: NO. DISTRIBUTE_GROUP_DOC = # If one adds a struct or class to a group and this option is enabled, then also # any nested class or struct is added to the same group. By default this option # is disabled and one has to add nested compounds explicitly via \ingroup. # The default value is: NO. GROUP_NESTED_COMPOUNDS = # Set the SUBGROUPING tag to YES to allow class member groups of the same type # (for instance a group of public functions) to be put as a subgroup of that # type (e.g. under the Public Functions section). Set it to NO to prevent # subgrouping. Alternatively, this can be done per class using the # \nosubgrouping command. # The default value is: YES. SUBGROUPING = # When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions # are shown inside the group in which they are included (e.g. using \ingroup) # instead of on a separate page (for HTML and Man pages) or section (for LaTeX # and RTF). # # Note that this feature does not work in combination with # SEPARATE_MEMBER_PAGES. # The default value is: NO. INLINE_GROUPED_CLASSES = # When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions # with only public data fields or simple typedef fields will be shown inline in # the documentation of the scope in which they are defined (i.e. file, # namespace, or group documentation), provided this scope is documented. If set # to NO, structs, classes, and unions are shown on a separate page (for HTML and # Man pages) or section (for LaTeX and RTF). # The default value is: NO. INLINE_SIMPLE_STRUCTS = # When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or # enum is documented as struct, union, or enum with the name of the typedef. So # typedef struct TypeS {} TypeT, will appear in the documentation as a struct # with name TypeT. When disabled the typedef will appear as a member of a file, # namespace, or class. And the struct will be named TypeS. This can typically be # useful for C code in case the coding convention dictates that all compound # types are typedef'ed and only the typedef is referenced, never the tag name. # The default value is: NO. TYPEDEF_HIDES_STRUCT = # The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This # cache is used to resolve symbols given their name and scope. Since this can be # an expensive process and often the same symbol appears multiple times in the # code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small # doxygen will become slower. If the cache is too large, memory is wasted. The # cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range # is 0..9, the default is 0, corresponding to a cache size of 2^16=65536 # symbols. At the end of a run doxygen will report the cache usage and suggest # the optimal cache size from a speed point of view. # Minimum value: 0, maximum value: 9, default value: 0. LOOKUP_CACHE_SIZE = #--------------------------------------------------------------------------- # Build related configuration options #--------------------------------------------------------------------------- # If the EXTRACT_ALL tag is set to YES, doxygen will assume all entities in # documentation are documented, even if no documentation was available. Private # class members and static file members will be hidden unless the # EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES. # Note: This will also disable the warnings about undocumented members that are # normally produced when WARNINGS is set to YES. # The default value is: NO. EXTRACT_ALL = # If the EXTRACT_PRIVATE tag is set to YES, all private members of a class will # be included in the documentation. # The default value is: NO. EXTRACT_PRIVATE = # If the EXTRACT_PACKAGE tag is set to YES, all members with package or internal # scope will be included in the documentation. # The default value is: NO. EXTRACT_PACKAGE = # If the EXTRACT_STATIC tag is set to YES, all static members of a file will be # included in the documentation. # The default value is: NO. EXTRACT_STATIC = # If the EXTRACT_LOCAL_CLASSES tag is set to YES, classes (and structs) defined # locally in source files will be included in the documentation. If set to NO, # only classes defined in header files are included. Does not have any effect # for Java sources. # The default value is: YES. EXTRACT_LOCAL_CLASSES = # This flag is only useful for Objective-C code. If set to YES, local methods, # which are defined in the implementation section but not in the interface are # included in the documentation. If set to NO, only methods in the interface are # included. # The default value is: NO. EXTRACT_LOCAL_METHODS = # If this flag is set to YES, the members of anonymous namespaces will be # extracted and appear in the documentation as a namespace called # 'anonymous_namespace{file}', where file will be replaced with the base name of # the file that contains the anonymous namespace. By default anonymous namespace # are hidden. # The default value is: NO. EXTRACT_ANON_NSPACES = # If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all # undocumented members inside documented classes or files. If set to NO these # members will be included in the various overviews, but no documentation # section is generated. This option has no effect if EXTRACT_ALL is enabled. # The default value is: NO. HIDE_UNDOC_MEMBERS = # If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all # undocumented classes that are normally visible in the class hierarchy. If set # to NO, these classes will be included in the various overviews. This option # has no effect if EXTRACT_ALL is enabled. # The default value is: NO. HIDE_UNDOC_CLASSES = # If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend # (class|struct|union) declarations. If set to NO, these declarations will be # included in the documentation. # The default value is: NO. HIDE_FRIEND_COMPOUNDS = # If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any # documentation blocks found inside the body of a function. If set to NO, these # blocks will be appended to the function's detailed documentation block. # The default value is: NO. HIDE_IN_BODY_DOCS = # The INTERNAL_DOCS tag determines if documentation that is typed after a # \internal command is included. If the tag is set to NO then the documentation # will be excluded. Set it to YES to include the internal documentation. # The default value is: NO. INTERNAL_DOCS = # If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file # names in lower-case letters. If set to YES, upper-case letters are also # allowed. This is useful if you have classes or files whose names only differ # in case and if your file system supports case sensitive file names. Windows # and Mac users are advised to set this option to NO. # The default value is: system dependent. CASE_SENSE_NAMES = YES # If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with # their full class and namespace scopes in the documentation. If set to YES, the # scope will be hidden. # The default value is: NO. HIDE_SCOPE_NAMES = # If the HIDE_COMPOUND_REFERENCE tag is set to NO (default) then doxygen will # append additional text to a page's title, such as Class Reference. If set to # YES the compound reference will be hidden. # The default value is: NO. HIDE_COMPOUND_REFERENCE= # If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of # the files that are included by a file in the documentation of that file. # The default value is: YES. SHOW_INCLUDE_FILES = # If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each # grouped member an include statement to the documentation, telling the reader # which file to include in order to use the member. # The default value is: NO. SHOW_GROUPED_MEMB_INC = # If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include # files with double quotes in the documentation rather than with sharp brackets. # The default value is: NO. FORCE_LOCAL_INCLUDES = # If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the # documentation for inline members. # The default value is: YES. INLINE_INFO = # If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the # (detailed) documentation of file and class members alphabetically by member # name. If set to NO, the members will appear in declaration order. # The default value is: YES. SORT_MEMBER_DOCS = # If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief # descriptions of file, namespace and class members alphabetically by member # name. If set to NO, the members will appear in declaration order. Note that # this will also influence the order of the classes in the class list. # The default value is: NO. SORT_BRIEF_DOCS = # If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the # (brief and detailed) documentation of class members so that constructors and # destructors are listed first. If set to NO the constructors will appear in the # respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS. # Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief # member documentation. # Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting # detailed member documentation. # The default value is: NO. SORT_MEMBERS_CTORS_1ST = # If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy # of group names into alphabetical order. If set to NO the group names will # appear in their defined order. # The default value is: NO. SORT_GROUP_NAMES = # If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by # fully-qualified names, including namespaces. If set to NO, the class list will # be sorted only by class name, not including the namespace part. # Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. # Note: This option applies only to the class list, not to the alphabetical # list. # The default value is: NO. SORT_BY_SCOPE_NAME = # If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper # type resolution of all parameters of a function it will reject a match between # the prototype and the implementation of a member function even if there is # only one candidate or it is obvious which candidate to choose by doing a # simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still # accept a match between prototype and implementation in such cases. # The default value is: NO. STRICT_PROTO_MATCHING = # The GENERATE_TODOLIST tag can be used to enable (YES) or disable (NO) the todo # list. This list is created by putting \todo commands in the documentation. # The default value is: YES. GENERATE_TODOLIST = # The GENERATE_TESTLIST tag can be used to enable (YES) or disable (NO) the test # list. This list is created by putting \test commands in the documentation. # The default value is: YES. GENERATE_TESTLIST = # The GENERATE_BUGLIST tag can be used to enable (YES) or disable (NO) the bug # list. This list is created by putting \bug commands in the documentation. # The default value is: YES. GENERATE_BUGLIST = # The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or disable (NO) # the deprecated list. This list is created by putting \deprecated commands in # the documentation. # The default value is: YES. GENERATE_DEPRECATEDLIST= # The ENABLED_SECTIONS tag can be used to enable conditional documentation # sections, marked by \if <section_label> ... \endif and \cond <section_label> # ... \endcond blocks. ENABLED_SECTIONS = # The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the # initial value of a variable or macro / define can have for it to appear in the # documentation. If the initializer consists of more lines than specified here # it will be hidden. Use a value of 0 to hide initializers completely. The # appearance of the value of individual variables and macros / defines can be # controlled using \showinitializer or \hideinitializer command in the # documentation regardless of this setting. # Minimum value: 0, maximum value: 10000, default value: 30. MAX_INITIALIZER_LINES = # Set the SHOW_USED_FILES tag to NO to disable the list of files generated at # the bottom of the documentation of classes and structs. If set to YES, the # list will mention the files that were used to generate the documentation. # The default value is: YES. SHOW_USED_FILES = # Set the SHOW_FILES tag to NO to disable the generation of the Files page. This # will remove the Files entry from the Quick Index and from the Folder Tree View # (if specified). # The default value is: YES. SHOW_FILES = # Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces # page. This will remove the Namespaces entry from the Quick Index and from the # Folder Tree View (if specified). # The default value is: YES. SHOW_NAMESPACES = # The FILE_VERSION_FILTER tag can be used to specify a program or script that # doxygen should invoke to get the current version for each file (typically from # the version control system). Doxygen will invoke the program by executing (via # popen()) the command command input-file, where command is the value of the # FILE_VERSION_FILTER tag, and input-file is the name of an input file provided # by doxygen. Whatever the program writes to standard output is used as the file # version. For an example see the documentation. FILE_VERSION_FILTER = # The LAYOUT_FILE tag can be used to specify a layout file which will be parsed # by doxygen. The layout file controls the global structure of the generated # output files in an output format independent way. To create the layout file # that represents doxygen's defaults, run doxygen with the -l option. You can # optionally specify a file name after the option, if omitted DoxygenLayout.xml # will be used as the name of the layout file. # # Note that if you run doxygen from a directory containing a file called # DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE # tag is left empty. LAYOUT_FILE = # The CITE_BIB_FILES tag can be used to specify one or more bib files containing # the reference definitions. This must be a list of .bib files. The .bib # extension is automatically appended if omitted. This requires the bibtex tool # to be installed. See also https://en.wikipedia.org/wiki/BibTeX for more info. # For LaTeX the style of the bibliography can be controlled using # LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the # search path. See also \cite for info how to create references. CITE_BIB_FILES = #--------------------------------------------------------------------------- # Configuration options related to warning and progress messages #--------------------------------------------------------------------------- # The QUIET tag can be used to turn on/off the messages that are generated to # standard output by doxygen. If QUIET is set to YES this implies that the # messages are off. # The default value is: NO. QUIET = YES # The WARNINGS tag can be used to turn on/off the warning messages that are # generated to standard error (stderr) by doxygen. If WARNINGS is set to YES # this implies that the warnings are on. # # Tip: Turn warnings on while writing the documentation. # The default value is: YES. WARNINGS = # If the WARN_IF_UNDOCUMENTED tag is set to YES then doxygen will generate # warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag # will automatically be disabled. # The default value is: YES. WARN_IF_UNDOCUMENTED = NO # If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for # potential errors in the documentation, such as not documenting some parameters # in a documented function, or documenting parameters that don't exist or using # markup commands wrongly. # The default value is: YES. WARN_IF_DOC_ERROR = # This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that # are documented, but have no documentation for their parameters or return # value. If set to NO, doxygen will only warn about wrong or incomplete # parameter documentation, but not about the absence of documentation. If # EXTRACT_ALL is set to YES then this flag will automatically be disabled. # The default value is: NO. WARN_NO_PARAMDOC = # If the WARN_AS_ERROR tag is set to YES then doxygen will immediately stop when # a warning is encountered. # The default value is: NO. WARN_AS_ERROR = # The WARN_FORMAT tag determines the format of the warning messages that doxygen # can produce. The string should contain the $file, $line, and $text tags, which # will be replaced by the file and line number from which the warning originated # and the warning text. Optionally the format may contain $version, which will # be replaced by the version of the file (if it could be obtained via # FILE_VERSION_FILTER) # The default value is: $file:$line: $text. WARN_FORMAT = # The WARN_LOGFILE tag can be used to specify a file to which warning and error # messages should be written. If left blank the output is written to standard # error (stderr). WARN_LOGFILE = @CMAKE_CURRENT_BINARY_DIR@/doxygen-errors.log #--------------------------------------------------------------------------- # Configuration options related to the input files #--------------------------------------------------------------------------- # The INPUT tag is used to specify the files and/or directories that contain # documented source files. You may enter file names like myfile.cpp or # directories like /usr/src/myproject. Separate the files or directories with # spaces. See also FILE_PATTERNS and EXTENSION_MAPPING # Note: If this tag is empty the current directory is searched. INPUT = @PROJECT_SOURCE_DIR@/docs \ @PROJECT_SOURCE_DIR@/src # This tag can be used to specify the character encoding of the source files # that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses # libiconv (or the iconv built into libc) for the transcoding. See the libiconv # documentation (see: https://www.gnu.org/software/libiconv/) for the list of # possible encodings. # The default value is: UTF-8. INPUT_ENCODING = # If the value of the INPUT tag contains directories, you can use the # FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and # *.h) to filter out the source-files in the directories. # # Note that for custom extensions or not directly supported extensions you also # need to set EXTENSION_MAPPING for the extension otherwise the files are not # read by doxygen. # # If left blank the following patterns are tested:*.c, *.cc, *.cxx, *.cpp, # *.c++, *.java, *.ii, *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h, # *.hh, *.hxx, *.hpp, *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc, # *.m, *.markdown, *.md, *.mm, *.dox, *.py, *.pyw, *.f90, *.f95, *.f03, *.f08, # *.f, *.for, *.tcl, *.vhd, *.vhdl, *.ucf, *.qsf and *.ice. FILE_PATTERNS = # The RECURSIVE tag can be used to specify whether or not subdirectories should # be searched for input files as well. # The default value is: NO. RECURSIVE = YES # The EXCLUDE tag can be used to specify files and/or directories that should be # excluded from the INPUT source files. This way you can easily exclude a # subdirectory from a directory tree whose root is specified with the INPUT tag. # # Note that relative paths are relative to the directory from which doxygen is # run. EXCLUDE = # The EXCLUDE_SYMLINKS tag can be used to select whether or not files or # directories that are symbolic links (a Unix file system feature) are excluded # from the input. # The default value is: NO. EXCLUDE_SYMLINKS = YES # If the value of the INPUT tag contains directories, you can use the # EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude # certain files from those directories. # # Note that the wildcards are matched against the file with absolute path, so to # exclude all test directories for example use the pattern */test/* EXCLUDE_PATTERNS = # The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names # (namespaces, classes, functions, etc.) that should be excluded from the # output. The symbol name can be a fully qualified name, a word, or if the # wildcard * is used, a substring. Examples: ANamespace, AClass, # AClass::ANamespace, ANamespace::*Test # # Note that the wildcards are matched against the file with absolute path, so to # exclude all test directories use the pattern */test/* EXCLUDE_SYMBOLS = # The EXAMPLE_PATH tag can be used to specify one or more files or directories # that contain example code fragments that are included (see the \include # command). EXAMPLE_PATH = # If the value of the EXAMPLE_PATH tag contains directories, you can use the # EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and # *.h) to filter out the source-files in the directories. If left blank all # files are included. EXAMPLE_PATTERNS = * # If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be # searched for input files to be used with the \include or \dontinclude commands # irrespective of the value of the RECURSIVE tag. # The default value is: NO. EXAMPLE_RECURSIVE = # The IMAGE_PATH tag can be used to specify one or more files or directories # that contain images that are to be included in the documentation (see the # \image command). IMAGE_PATH = # The INPUT_FILTER tag can be used to specify a program that doxygen should # invoke to filter for each input file. Doxygen will invoke the filter program # by executing (via popen()) the command: # # <filter> <input-file> # # where <filter> is the value of the INPUT_FILTER tag, and <input-file> is the # name of an input file. Doxygen will then use the output that the filter # program writes to standard output. If FILTER_PATTERNS is specified, this tag # will be ignored. # # Note that the filter must not add or remove lines; it is applied before the # code is scanned, but not when the output code is generated. If lines are added # or removed, the anchors will not be placed correctly. # # Note that for custom extensions or not directly supported extensions you also # need to set EXTENSION_MAPPING for the extension otherwise the files are not # properly processed by doxygen. INPUT_FILTER = # The FILTER_PATTERNS tag can be used to specify filters on a per file pattern # basis. Doxygen will compare the file name with each pattern and apply the # filter if there is a match. The filters are a list of the form: pattern=filter # (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how # filters are used. If the FILTER_PATTERNS tag is empty or if none of the # patterns match the file name, INPUT_FILTER is applied. # # Note that for custom extensions or not directly supported extensions you also # need to set EXTENSION_MAPPING for the extension otherwise the files are not # properly processed by doxygen. FILTER_PATTERNS = # If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using # INPUT_FILTER) will also be used to filter the input files that are used for # producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES). # The default value is: NO. FILTER_SOURCE_FILES = # The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file # pattern. A pattern will override the setting for FILTER_PATTERN (if any) and # it is also possible to disable source filtering for a specific pattern using # *.ext= (so without naming a filter). # This tag requires that the tag FILTER_SOURCE_FILES is set to YES. FILTER_SOURCE_PATTERNS = # If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that # is part of the input, its contents will be placed on the main page # (index.html). This can be useful if you have a project on for instance GitHub # and want to reuse the introduction page also for the doxygen output. USE_MDFILE_AS_MAINPAGE = #--------------------------------------------------------------------------- # Configuration options related to source browsing #--------------------------------------------------------------------------- # If the SOURCE_BROWSER tag is set to YES then a list of source files will be # generated. Documented entities will be cross-referenced with these sources. # # Note: To get rid of all source code in the generated output, make sure that # also VERBATIM_HEADERS is set to NO. # The default value is: NO. SOURCE_BROWSER = YES # Setting the INLINE_SOURCES tag to YES will include the body of functions, # classes and enums directly into the documentation. # The default value is: NO. INLINE_SOURCES = # Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any # special comment blocks from generated source code fragments. Normal C, C++ and # Fortran comments will always remain visible. # The default value is: YES. STRIP_CODE_COMMENTS = # If the REFERENCED_BY_RELATION tag is set to YES then for each documented # entity all documented functions referencing it will be listed. # The default value is: NO. REFERENCED_BY_RELATION = YES # If the REFERENCES_RELATION tag is set to YES then for each documented function # all documented entities called/used by that function will be listed. # The default value is: NO. REFERENCES_RELATION = YES # If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set # to YES then the hyperlinks from functions in REFERENCES_RELATION and # REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will # link to the documentation. # The default value is: YES. REFERENCES_LINK_SOURCE = # If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the # source code will show a tooltip with additional information such as prototype, # brief description and links to the definition and documentation. Since this # will make the HTML file larger and loading of large files a bit slower, you # can opt to disable this feature. # The default value is: YES. # This tag requires that the tag SOURCE_BROWSER is set to YES. SOURCE_TOOLTIPS = # If the USE_HTAGS tag is set to YES then the references to source code will # point to the HTML generated by the htags(1) tool instead of doxygen built-in # source browser. The htags tool is part of GNU's global source tagging system # (see https://www.gnu.org/software/global/global.html). You will need version # 4.8.6 or higher. # # To use it do the following: # - Install the latest version of global # - Enable SOURCE_BROWSER and USE_HTAGS in the configuration file # - Make sure the INPUT points to the root of the source tree # - Run doxygen as normal # # Doxygen will invoke htags (and that will in turn invoke gtags), so these # tools must be available from the command line (i.e. in the search path). # # The result: instead of the source browser generated by doxygen, the links to # source code will now point to the output of htags. # The default value is: NO. # This tag requires that the tag SOURCE_BROWSER is set to YES. USE_HTAGS = # If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a # verbatim copy of the header file for each class for which an include is # specified. Set to NO to disable this. # See also: Section \class. # The default value is: YES. VERBATIM_HEADERS = #--------------------------------------------------------------------------- # Configuration options related to the alphabetical class index #--------------------------------------------------------------------------- # If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all # compounds will be generated. Enable this if the project contains a lot of # classes, structs, unions or interfaces. # The default value is: YES. ALPHABETICAL_INDEX = # The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in # which the alphabetical index list will be split. # Minimum value: 1, maximum value: 20, default value: 5. # This tag requires that the tag ALPHABETICAL_INDEX is set to YES. COLS_IN_ALPHA_INDEX = # In case all classes in a project start with a common prefix, all classes will # be put under the same header in the alphabetical index. The IGNORE_PREFIX tag # can be used to specify a prefix (or a list of prefixes) that should be ignored # while generating the index headers. # This tag requires that the tag ALPHABETICAL_INDEX is set to YES. IGNORE_PREFIX = #--------------------------------------------------------------------------- # Configuration options related to the HTML output #--------------------------------------------------------------------------- # If the GENERATE_HTML tag is set to YES, doxygen will generate HTML output # The default value is: YES. GENERATE_HTML = YES # The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a # relative path is entered the value of OUTPUT_DIRECTORY will be put in front of # it. # The default directory is: html. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_OUTPUT = # The HTML_FILE_EXTENSION tag can be used to specify the file extension for each # generated HTML page (for example: .htm, .php, .asp). # The default value is: .html. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_FILE_EXTENSION = # The HTML_HEADER tag can be used to specify a user-defined HTML header file for # each generated HTML page. If the tag is left blank doxygen will generate a # standard header. # # To get valid HTML the header file that includes any scripts and style sheets # that doxygen needs, which is dependent on the configuration options used (e.g. # the setting GENERATE_TREEVIEW). It is highly recommended to start with a # default header using # doxygen -w html new_header.html new_footer.html new_stylesheet.css # YourConfigFile # and then modify the file new_header.html. See also section "Doxygen usage" # for information on how to generate the default header that doxygen normally # uses. # Note: The header is subject to change so you typically have to regenerate the # default header when upgrading to a newer version of doxygen. For a description # of the possible markers and block names see the documentation. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_HEADER = # The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each # generated HTML page. If the tag is left blank doxygen will generate a standard # footer. See HTML_HEADER for more information on how to generate a default # footer and what special commands can be used inside the footer. See also # section "Doxygen usage" for information on how to generate the default footer # that doxygen normally uses. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_FOOTER = # The HTML_STYLESHEET tag can be used to specify a user-defined cascading style # sheet that is used by each HTML page. It can be used to fine-tune the look of # the HTML output. If left blank doxygen will generate a default style sheet. # See also section "Doxygen usage" for information on how to generate the style # sheet that doxygen normally uses. # Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as # it is more robust and this tag (HTML_STYLESHEET) will in the future become # obsolete. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_STYLESHEET = # The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined # cascading style sheets that are included after the standard style sheets # created by doxygen. Using this option one can overrule certain style aspects. # This is preferred over using HTML_STYLESHEET since it does not replace the # standard style sheet and is therefore more robust against future updates. # Doxygen will copy the style sheet files to the output directory. # Note: The order of the extra style sheet files is of importance (e.g. the last # style sheet in the list overrules the setting of the previous ones in the # list). For an example see the documentation. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_EXTRA_STYLESHEET = # The HTML_EXTRA_FILES tag can be used to specify one or more extra images or # other source files which should be copied to the HTML output directory. Note # that these files will be copied to the base HTML output directory. Use the # $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these # files. In the HTML_STYLESHEET file, use the file name only. Also note that the # files will be copied as-is; there are no commands or markers available. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_EXTRA_FILES = # The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen # will adjust the colors in the style sheet and background images according to # this color. Hue is specified as an angle on a colorwheel, see # https://en.wikipedia.org/wiki/Hue for more information. For instance the value # 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300 # purple, and 360 is red again. # Minimum value: 0, maximum value: 359, default value: 220. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_COLORSTYLE_HUE = # The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors # in the HTML output. For a value of 0 the output will use grayscales only. A # value of 255 will produce the most vivid colors. # Minimum value: 0, maximum value: 255, default value: 100. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_COLORSTYLE_SAT = # The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the # luminance component of the colors in the HTML output. Values below 100 # gradually make the output lighter, whereas values above 100 make the output # darker. The value divided by 100 is the actual gamma applied, so 80 represents # a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not # change the gamma. # Minimum value: 40, maximum value: 240, default value: 80. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_COLORSTYLE_GAMMA = # If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML # page will contain the date and time when the page was generated. Setting this # to YES can help to show when doxygen was last run and thus if the # documentation is up to date. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_TIMESTAMP = # If the HTML_DYNAMIC_MENUS tag is set to YES then the generated HTML # documentation will contain a main index with vertical navigation menus that # are dynamically created via Javascript. If disabled, the navigation index will # consists of multiple levels of tabs that are statically embedded in every HTML # page. Disable this option to support browsers that do not have Javascript, # like the Qt help browser. # The default value is: YES. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_DYNAMIC_MENUS = # If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML # documentation will contain sections that can be hidden and shown after the # page has loaded. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_DYNAMIC_SECTIONS = # With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries # shown in the various tree structured indices initially; the user can expand # and collapse entries dynamically later on. Doxygen will expand the tree to # such a level that at most the specified number of entries are visible (unless # a fully collapsed tree already exceeds this amount). So setting the number of # entries 1 will produce a full collapsed tree by default. 0 is a special value # representing an infinite number of entries and will result in a full expanded # tree by default. # Minimum value: 0, maximum value: 9999, default value: 100. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_INDEX_NUM_ENTRIES = # If the GENERATE_DOCSET tag is set to YES, additional index files will be # generated that can be used as input for Apple's Xcode 3 integrated development # environment (see: https://developer.apple.com/xcode/), introduced with OSX # 10.5 (Leopard). To create a documentation set, doxygen will generate a # Makefile in the HTML output directory. Running make will produce the docset in # that directory and running make install will install the docset in # ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at # startup. See https://developer.apple.com/library/archive/featuredarticles/Doxy # genXcode/_index.html for more information. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. GENERATE_DOCSET = # This tag determines the name of the docset feed. A documentation feed provides # an umbrella under which multiple documentation sets from a single provider # (such as a company or product suite) can be grouped. # The default value is: Doxygen generated docs. # This tag requires that the tag GENERATE_DOCSET is set to YES. DOCSET_FEEDNAME = # This tag specifies a string that should uniquely identify the documentation # set bundle. This should be a reverse domain-name style string, e.g. # com.mycompany.MyDocSet. Doxygen will append .docset to the name. # The default value is: org.doxygen.Project. # This tag requires that the tag GENERATE_DOCSET is set to YES. DOCSET_BUNDLE_ID = # The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify # the documentation publisher. This should be a reverse domain-name style # string, e.g. com.mycompany.MyDocSet.documentation. # The default value is: org.doxygen.Publisher. # This tag requires that the tag GENERATE_DOCSET is set to YES. DOCSET_PUBLISHER_ID = # The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher. # The default value is: Publisher. # This tag requires that the tag GENERATE_DOCSET is set to YES. DOCSET_PUBLISHER_NAME = # If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three # additional HTML index files: index.hhp, index.hhc, and index.hhk. The # index.hhp is a project file that can be read by Microsoft's HTML Help Workshop # (see: https://www.microsoft.com/en-us/download/details.aspx?id=21138) on # Windows. # # The HTML Help Workshop contains a compiler that can convert all HTML output # generated by doxygen into a single compiled HTML file (.chm). Compiled HTML # files are now used as the Windows 98 help format, and will replace the old # Windows help format (.hlp) on all Windows platforms in the future. Compressed # HTML files also contain an index, a table of contents, and you can search for # words in the documentation. The HTML workshop also contains a viewer for # compressed HTML files. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. GENERATE_HTMLHELP = # The CHM_FILE tag can be used to specify the file name of the resulting .chm # file. You can add a path in front of the file if the result should not be # written to the html output directory. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. CHM_FILE = # The HHC_LOCATION tag can be used to specify the location (absolute path # including file name) of the HTML help compiler (hhc.exe). If non-empty, # doxygen will try to run the HTML help compiler on the generated index.hhp. # The file has to be specified with full path. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. HHC_LOCATION = # The GENERATE_CHI flag controls if a separate .chi index file is generated # (YES) or that it should be included in the master .chm file (NO). # The default value is: NO. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. GENERATE_CHI = # The CHM_INDEX_ENCODING is used to encode HtmlHelp index (hhk), content (hhc) # and project file content. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. CHM_INDEX_ENCODING = # The BINARY_TOC flag controls whether a binary table of contents is generated # (YES) or a normal table of contents (NO) in the .chm file. Furthermore it # enables the Previous and Next buttons. # The default value is: NO. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. BINARY_TOC = # The TOC_EXPAND flag can be set to YES to add extra items for group members to # the table of contents of the HTML help documentation and to the tree view. # The default value is: NO. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. TOC_EXPAND = # If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and # QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that # can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help # (.qch) of the generated HTML documentation. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. GENERATE_QHP = # If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify # the file name of the resulting .qch file. The path specified is relative to # the HTML output folder. # This tag requires that the tag GENERATE_QHP is set to YES. QCH_FILE = # The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help # Project output. For more information please see Qt Help Project / Namespace # (see: http://doc.qt.io/archives/qt-4.8/qthelpproject.html#namespace). # The default value is: org.doxygen.Project. # This tag requires that the tag GENERATE_QHP is set to YES. QHP_NAMESPACE = # The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt # Help Project output. For more information please see Qt Help Project / Virtual # Folders (see: http://doc.qt.io/archives/qt-4.8/qthelpproject.html#virtual- # folders). # The default value is: doc. # This tag requires that the tag GENERATE_QHP is set to YES. QHP_VIRTUAL_FOLDER = # If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom # filter to add. For more information please see Qt Help Project / Custom # Filters (see: http://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom- # filters). # This tag requires that the tag GENERATE_QHP is set to YES. QHP_CUST_FILTER_NAME = # The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the # custom filter to add. For more information please see Qt Help Project / Custom # Filters (see: http://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom- # filters). # This tag requires that the tag GENERATE_QHP is set to YES. QHP_CUST_FILTER_ATTRS = # The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this # project's filter section matches. Qt Help Project / Filter Attributes (see: # http://doc.qt.io/archives/qt-4.8/qthelpproject.html#filter-attributes). # This tag requires that the tag GENERATE_QHP is set to YES. QHP_SECT_FILTER_ATTRS = # The QHG_LOCATION tag can be used to specify the location of Qt's # qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the # generated .qhp file. # This tag requires that the tag GENERATE_QHP is set to YES. QHG_LOCATION = # If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be # generated, together with the HTML files, they form an Eclipse help plugin. To # install this plugin and make it available under the help contents menu in # Eclipse, the contents of the directory containing the HTML and XML files needs # to be copied into the plugins directory of eclipse. The name of the directory # within the plugins directory should be the same as the ECLIPSE_DOC_ID value. # After copying Eclipse needs to be restarted before the help appears. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. GENERATE_ECLIPSEHELP = # A unique identifier for the Eclipse help plugin. When installing the plugin # the directory name containing the HTML and XML files should also have this # name. Each documentation set should have its own identifier. # The default value is: org.doxygen.Project. # This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES. ECLIPSE_DOC_ID = # If you want full control over the layout of the generated HTML pages it might # be necessary to disable the index and replace it with your own. The # DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top # of each HTML page. A value of NO enables the index and the value YES disables # it. Since the tabs in the index contain the same information as the navigation # tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. DISABLE_INDEX = # The GENERATE_TREEVIEW tag is used to specify whether a tree-like index # structure should be generated to display hierarchical information. If the tag # value is set to YES, a side panel will be generated containing a tree-like # index structure (just like the one that is generated for HTML Help). For this # to work a browser that supports JavaScript, DHTML, CSS and frames is required # (i.e. any modern browser). Windows users are probably better off using the # HTML help feature. Via custom style sheets (see HTML_EXTRA_STYLESHEET) one can # further fine-tune the look of the index. As an example, the default style # sheet generated by doxygen has an example that shows how to put an image at # the root of the tree instead of the PROJECT_NAME. Since the tree basically has # the same information as the tab index, you could consider setting # DISABLE_INDEX to YES when enabling this option. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. GENERATE_TREEVIEW = YES # The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that # doxygen will group on one line in the generated HTML documentation. # # Note that a value of 0 will completely suppress the enum values from appearing # in the overview section. # Minimum value: 0, maximum value: 20, default value: 4. # This tag requires that the tag GENERATE_HTML is set to YES. ENUM_VALUES_PER_LINE = # If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used # to set the initial width (in pixels) of the frame in which the tree is shown. # Minimum value: 0, maximum value: 1500, default value: 250. # This tag requires that the tag GENERATE_HTML is set to YES. TREEVIEW_WIDTH = # If the EXT_LINKS_IN_WINDOW option is set to YES, doxygen will open links to # external symbols imported via tag files in a separate window. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. EXT_LINKS_IN_WINDOW = # Use this tag to change the font size of LaTeX formulas included as images in # the HTML documentation. When you change the font size after a successful # doxygen run you need to manually remove any form_*.png images from the HTML # output directory to force them to be regenerated. # Minimum value: 8, maximum value: 50, default value: 10. # This tag requires that the tag GENERATE_HTML is set to YES. FORMULA_FONTSIZE = # Use the FORMULA_TRANSPARENT tag to determine whether or not the images # generated for formulas are transparent PNGs. Transparent PNGs are not # supported properly for IE 6.0, but are supported on all modern browsers. # # Note that when changing this option you need to delete any form_*.png files in # the HTML output directory before the changes have effect. # The default value is: YES. # This tag requires that the tag GENERATE_HTML is set to YES. FORMULA_TRANSPARENT = # Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see # https://www.mathjax.org) which uses client side Javascript for the rendering # instead of using pre-rendered bitmaps. Use this if you do not have LaTeX # installed or if you want to formulas look prettier in the HTML output. When # enabled you may also need to install MathJax separately and configure the path # to it using the MATHJAX_RELPATH option. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. USE_MATHJAX = # When MathJax is enabled you can set the default output format to be used for # the MathJax output. See the MathJax site (see: # http://docs.mathjax.org/en/latest/output.html) for more details. # Possible values are: HTML-CSS (which is slower, but has the best # compatibility), NativeMML (i.e. MathML) and SVG. # The default value is: HTML-CSS. # This tag requires that the tag USE_MATHJAX is set to YES. MATHJAX_FORMAT = # When MathJax is enabled you need to specify the location relative to the HTML # output directory using the MATHJAX_RELPATH option. The destination directory # should contain the MathJax.js script. For instance, if the mathjax directory # is located at the same level as the HTML output directory, then # MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax # Content Delivery Network so you can quickly see the result without installing # MathJax. However, it is strongly recommended to install a local copy of # MathJax from https://www.mathjax.org before deployment. # The default value is: https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/. # This tag requires that the tag USE_MATHJAX is set to YES. MATHJAX_RELPATH = # The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax # extension names that should be enabled during MathJax rendering. For example # MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols # This tag requires that the tag USE_MATHJAX is set to YES. MATHJAX_EXTENSIONS = # The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces # of code that will be used on startup of the MathJax code. See the MathJax site # (see: http://docs.mathjax.org/en/latest/output.html) for more details. For an # example see the documentation. # This tag requires that the tag USE_MATHJAX is set to YES. MATHJAX_CODEFILE = # When the SEARCHENGINE tag is enabled doxygen will generate a search box for # the HTML output. The underlying search engine uses javascript and DHTML and # should work on any modern browser. Note that when using HTML help # (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET) # there is already a search function so this one should typically be disabled. # For large projects the javascript based search engine can be slow, then # enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to # search using the keyboard; to jump to the search box use <access key> + S # (what the <access key> is depends on the OS and browser, but it is typically # <CTRL>, <ALT>/<option>, or both). Inside the search box use the <cursor down # key> to jump into the search results window, the results can be navigated # using the <cursor keys>. Press <Enter> to select an item or <escape> to cancel # the search. The filter options can be selected when the cursor is inside the # search box by pressing <Shift>+<cursor down>. Also here use the <cursor keys> # to select a filter and <Enter> or <escape> to activate or cancel the filter # option. # The default value is: YES. # This tag requires that the tag GENERATE_HTML is set to YES. SEARCHENGINE = # When the SERVER_BASED_SEARCH tag is enabled the search engine will be # implemented using a web server instead of a web client using Javascript. There # are two flavors of web server based searching depending on the EXTERNAL_SEARCH # setting. When disabled, doxygen will generate a PHP script for searching and # an index file used by the script. When EXTERNAL_SEARCH is enabled the indexing # and searching needs to be provided by external tools. See the section # "External Indexing and Searching" for details. # The default value is: NO. # This tag requires that the tag SEARCHENGINE is set to YES. SERVER_BASED_SEARCH = # When EXTERNAL_SEARCH tag is enabled doxygen will no longer generate the PHP # script for searching. Instead the search results are written to an XML file # which needs to be processed by an external indexer. Doxygen will invoke an # external search engine pointed to by the SEARCHENGINE_URL option to obtain the # search results. # # Doxygen ships with an example indexer (doxyindexer) and search engine # (doxysearch.cgi) which are based on the open source search engine library # Xapian (see: https://xapian.org/). # # See the section "External Indexing and Searching" for details. # The default value is: NO. # This tag requires that the tag SEARCHENGINE is set to YES. EXTERNAL_SEARCH = # The SEARCHENGINE_URL should point to a search engine hosted by a web server # which will return the search results when EXTERNAL_SEARCH is enabled. # # Doxygen ships with an example indexer (doxyindexer) and search engine # (doxysearch.cgi) which are based on the open source search engine library # Xapian (see: https://xapian.org/). See the section "External Indexing and # Searching" for details. # This tag requires that the tag SEARCHENGINE is set to YES. SEARCHENGINE_URL = # When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed # search data is written to a file for indexing by an external tool. With the # SEARCHDATA_FILE tag the name of this file can be specified. # The default file is: searchdata.xml. # This tag requires that the tag SEARCHENGINE is set to YES. SEARCHDATA_FILE = # When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the # EXTERNAL_SEARCH_ID tag can be used as an identifier for the project. This is # useful in combination with EXTRA_SEARCH_MAPPINGS to search through multiple # projects and redirect the results back to the right project. # This tag requires that the tag SEARCHENGINE is set to YES. EXTERNAL_SEARCH_ID = # The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through doxygen # projects other than the one defined by this configuration file, but that are # all added to the same external search index. Each project needs to have a # unique id set via EXTERNAL_SEARCH_ID. The search mapping then maps the id of # to a relative location where the documentation can be found. The format is: # EXTRA_SEARCH_MAPPINGS = tagname1=loc1 tagname2=loc2 ... # This tag requires that the tag SEARCHENGINE is set to YES. EXTRA_SEARCH_MAPPINGS = #--------------------------------------------------------------------------- # Configuration options related to the LaTeX output #--------------------------------------------------------------------------- # If the GENERATE_LATEX tag is set to YES, doxygen will generate LaTeX output. # The default value is: YES. GENERATE_LATEX = NO # The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. If a # relative path is entered the value of OUTPUT_DIRECTORY will be put in front of # it. # The default directory is: latex. # This tag requires that the tag GENERATE_LATEX is set to YES. LATEX_OUTPUT = # The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be # invoked. # # Note that when not enabling USE_PDFLATEX the default is latex when enabling # USE_PDFLATEX the default is pdflatex and when in the later case latex is # chosen this is overwritten by pdflatex. For specific output languages the # default can have been set differently, this depends on the implementation of # the output language. # This tag requires that the tag GENERATE_LATEX is set to YES. LATEX_CMD_NAME = latex # The MAKEINDEX_CMD_NAME tag can be used to specify the command name to generate # index for LaTeX. # Note: This tag is used in the Makefile / make.bat. # See also: LATEX_MAKEINDEX_CMD for the part in the generated output file # (.tex). # The default file is: makeindex. # This tag requires that the tag GENERATE_LATEX is set to YES. MAKEINDEX_CMD_NAME = # The LATEX_MAKEINDEX_CMD tag can be used to specify the command name to # generate index for LaTeX. # Note: This tag is used in the generated output file (.tex). # See also: MAKEINDEX_CMD_NAME for the part in the Makefile / make.bat. # The default value is: makeindex. # This tag requires that the tag GENERATE_LATEX is set to YES. LATEX_MAKEINDEX_CMD = # If the COMPACT_LATEX tag is set to YES, doxygen generates more compact LaTeX # documents. This may be useful for small projects and may help to save some # trees in general. # The default value is: NO. # This tag requires that the tag GENERATE_LATEX is set to YES. COMPACT_LATEX = # The PAPER_TYPE tag can be used to set the paper type that is used by the # printer. # Possible values are: a4 (210 x 297 mm), letter (8.5 x 11 inches), legal (8.5 x # 14 inches) and executive (7.25 x 10.5 inches). # The default value is: a4. # This tag requires that the tag GENERATE_LATEX is set to YES. PAPER_TYPE = # The EXTRA_PACKAGES tag can be used to specify one or more LaTeX package names # that should be included in the LaTeX output. The package can be specified just # by its name or with the correct syntax as to be used with the LaTeX # \usepackage command. To get the times font for instance you can specify : # EXTRA_PACKAGES=times or EXTRA_PACKAGES={times} # To use the option intlimits with the amsmath package you can specify: # EXTRA_PACKAGES=[intlimits]{amsmath} # If left blank no extra packages will be included. # This tag requires that the tag GENERATE_LATEX is set to YES. EXTRA_PACKAGES = # The LATEX_HEADER tag can be used to specify a personal LaTeX header for the # generated LaTeX document. The header should contain everything until the first # chapter. If it is left blank doxygen will generate a standard header. See # section "Doxygen usage" for information on how to let doxygen write the # default header to a separate file. # # Note: Only use a user-defined header if you know what you are doing! The # following commands have a special meaning inside the header: $title, # $datetime, $date, $doxygenversion, $projectname, $projectnumber, # $projectbrief, $projectlogo. Doxygen will replace $title with the empty # string, for the replacement values of the other commands the user is referred # to HTML_HEADER. # This tag requires that the tag GENERATE_LATEX is set to YES. LATEX_HEADER = # The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for the # generated LaTeX document. The footer should contain everything after the last # chapter. If it is left blank doxygen will generate a standard footer. See # LATEX_HEADER for more information on how to generate a default footer and what # special commands can be used inside the footer. # # Note: Only use a user-defined footer if you know what you are doing! # This tag requires that the tag GENERATE_LATEX is set to YES. LATEX_FOOTER = # The LATEX_EXTRA_STYLESHEET tag can be used to specify additional user-defined # LaTeX style sheets that are included after the standard style sheets created # by doxygen. Using this option one can overrule certain style aspects. Doxygen # will copy the style sheet files to the output directory. # Note: The order of the extra style sheet files is of importance (e.g. the last # style sheet in the list overrules the setting of the previous ones in the # list). # This tag requires that the tag GENERATE_LATEX is set to YES. LATEX_EXTRA_STYLESHEET = # The LATEX_EXTRA_FILES tag can be used to specify one or more extra images or # other source files which should be copied to the LATEX_OUTPUT output # directory. Note that the files will be copied as-is; there are no commands or # markers available. # This tag requires that the tag GENERATE_LATEX is set to YES. LATEX_EXTRA_FILES = # If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated is # prepared for conversion to PDF (using ps2pdf or pdflatex). The PDF file will # contain links (just like the HTML output) instead of page references. This # makes the output suitable for online browsing using a PDF viewer. # The default value is: YES. # This tag requires that the tag GENERATE_LATEX is set to YES. PDF_HYPERLINKS = # If the USE_PDFLATEX tag is set to YES, doxygen will use pdflatex to generate # the PDF file directly from the LaTeX files. Set this option to YES, to get a # higher quality PDF documentation. # The default value is: YES. # This tag requires that the tag GENERATE_LATEX is set to YES. USE_PDFLATEX = # If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \batchmode # command to the generated LaTeX files. This will instruct LaTeX to keep running # if errors occur, instead of asking the user for help. This option is also used # when generating formulas in HTML. # The default value is: NO. # This tag requires that the tag GENERATE_LATEX is set to YES. LATEX_BATCHMODE = # If the LATEX_HIDE_INDICES tag is set to YES then doxygen will not include the # index chapters (such as File Index, Compound Index, etc.) in the output. # The default value is: NO. # This tag requires that the tag GENERATE_LATEX is set to YES. LATEX_HIDE_INDICES = # If the LATEX_SOURCE_CODE tag is set to YES then doxygen will include source # code with syntax highlighting in the LaTeX output. # # Note that which sources are shown also depends on other settings such as # SOURCE_BROWSER. # The default value is: NO. # This tag requires that the tag GENERATE_LATEX is set to YES. LATEX_SOURCE_CODE = # The LATEX_BIB_STYLE tag can be used to specify the style to use for the # bibliography, e.g. plainnat, or ieeetr. See # https://en.wikipedia.org/wiki/BibTeX and \cite for more info. # The default value is: plain. # This tag requires that the tag GENERATE_LATEX is set to YES. LATEX_BIB_STYLE = # If the LATEX_TIMESTAMP tag is set to YES then the footer of each generated # page will contain the date and time when the page was generated. Setting this # to NO can help when comparing the output of multiple runs. # The default value is: NO. # This tag requires that the tag GENERATE_LATEX is set to YES. LATEX_TIMESTAMP = # The LATEX_EMOJI_DIRECTORY tag is used to specify the (relative or absolute) # path from which the emoji images will be read. If a relative path is entered, # it will be relative to the LATEX_OUTPUT directory. If left blank the # LATEX_OUTPUT directory will be used. # This tag requires that the tag GENERATE_LATEX is set to YES. LATEX_EMOJI_DIRECTORY = #--------------------------------------------------------------------------- # Configuration options related to the RTF output #--------------------------------------------------------------------------- # If the GENERATE_RTF tag is set to YES, doxygen will generate RTF output. The # RTF output is optimized for Word 97 and may not look too pretty with other RTF # readers/editors. # The default value is: NO. GENERATE_RTF = YES # The RTF_OUTPUT tag is used to specify where the RTF docs will be put. If a # relative path is entered the value of OUTPUT_DIRECTORY will be put in front of # it. # The default directory is: rtf. # This tag requires that the tag GENERATE_RTF is set to YES. RTF_OUTPUT = # If the COMPACT_RTF tag is set to YES, doxygen generates more compact RTF # documents. This may be useful for small projects and may help to save some # trees in general. # The default value is: NO. # This tag requires that the tag GENERATE_RTF is set to YES. COMPACT_RTF = YES # If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated will # contain hyperlink fields. The RTF file will contain links (just like the HTML # output) instead of page references. This makes the output suitable for online # browsing using Word or some other Word compatible readers that support those # fields. # # Note: WordPad (write) and others do not support links. # The default value is: NO. # This tag requires that the tag GENERATE_RTF is set to YES. RTF_HYPERLINKS = YES # Load stylesheet definitions from file. Syntax is similar to doxygen's # configuration file, i.e. a series of assignments. You only have to provide # replacements, missing definitions are set to their default value. # # See also section "Doxygen usage" for information on how to generate the # default style sheet that doxygen normally uses. # This tag requires that the tag GENERATE_RTF is set to YES. RTF_STYLESHEET_FILE = # Set optional variables used in the generation of an RTF document. Syntax is # similar to doxygen's configuration file. A template extensions file can be # generated using doxygen -e rtf extensionFile. # This tag requires that the tag GENERATE_RTF is set to YES. RTF_EXTENSIONS_FILE = # If the RTF_SOURCE_CODE tag is set to YES then doxygen will include source code # with syntax highlighting in the RTF output. # # Note that which sources are shown also depends on other settings such as # SOURCE_BROWSER. # The default value is: NO. # This tag requires that the tag GENERATE_RTF is set to YES. RTF_SOURCE_CODE = #--------------------------------------------------------------------------- # Configuration options related to the man page output #--------------------------------------------------------------------------- # If the GENERATE_MAN tag is set to YES, doxygen will generate man pages for # classes and files. # The default value is: NO. GENERATE_MAN = NO # The MAN_OUTPUT tag is used to specify where the man pages will be put. If a # relative path is entered the value of OUTPUT_DIRECTORY will be put in front of # it. A directory man3 will be created inside the directory specified by # MAN_OUTPUT. # The default directory is: man. # This tag requires that the tag GENERATE_MAN is set to YES. MAN_OUTPUT = # The MAN_EXTENSION tag determines the extension that is added to the generated # man pages. In case the manual section does not start with a number, the number # 3 is prepended. The dot (.) at the beginning of the MAN_EXTENSION tag is # optional. # The default value is: .3. # This tag requires that the tag GENERATE_MAN is set to YES. MAN_EXTENSION = # The MAN_SUBDIR tag determines the name of the directory created within # MAN_OUTPUT in which the man pages are placed. If defaults to man followed by # MAN_EXTENSION with the initial . removed. # This tag requires that the tag GENERATE_MAN is set to YES. MAN_SUBDIR = # If the MAN_LINKS tag is set to YES and doxygen generates man output, then it # will generate one additional man file for each entity documented in the real # man page(s). These additional files only source the real man page, but without # them the man command would be unable to find the correct page. # The default value is: NO. # This tag requires that the tag GENERATE_MAN is set to YES. MAN_LINKS = #--------------------------------------------------------------------------- # Configuration options related to the XML output #--------------------------------------------------------------------------- # If the GENERATE_XML tag is set to YES, doxygen will generate an XML file that # captures the structure of the code including all documentation. # The default value is: NO. GENERATE_XML = YES # The XML_OUTPUT tag is used to specify where the XML pages will be put. If a # relative path is entered the value of OUTPUT_DIRECTORY will be put in front of # it. # The default directory is: xml. # This tag requires that the tag GENERATE_XML is set to YES. XML_OUTPUT = # If the XML_PROGRAMLISTING tag is set to YES, doxygen will dump the program # listings (including syntax highlighting and cross-referencing information) to # the XML output. Note that enabling this will significantly increase the size # of the XML output. # The default value is: YES. # This tag requires that the tag GENERATE_XML is set to YES. XML_PROGRAMLISTING = # If the XML_NS_MEMB_FILE_SCOPE tag is set to YES, doxygen will include # namespace members in file scope as well, matching the HTML output. # The default value is: NO. # This tag requires that the tag GENERATE_XML is set to YES. XML_NS_MEMB_FILE_SCOPE = #--------------------------------------------------------------------------- # Configuration options related to the DOCBOOK output #--------------------------------------------------------------------------- # If the GENERATE_DOCBOOK tag is set to YES, doxygen will generate Docbook files # that can be used to generate PDF. # The default value is: NO. GENERATE_DOCBOOK = # The DOCBOOK_OUTPUT tag is used to specify where the Docbook pages will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be put in # front of it. # The default directory is: docbook. # This tag requires that the tag GENERATE_DOCBOOK is set to YES. DOCBOOK_OUTPUT = # If the DOCBOOK_PROGRAMLISTING tag is set to YES, doxygen will include the # program listings (including syntax highlighting and cross-referencing # information) to the DOCBOOK output. Note that enabling this will significantly # increase the size of the DOCBOOK output. # The default value is: NO. # This tag requires that the tag GENERATE_DOCBOOK is set to YES. DOCBOOK_PROGRAMLISTING = #--------------------------------------------------------------------------- # Configuration options for the AutoGen Definitions output #--------------------------------------------------------------------------- # If the GENERATE_AUTOGEN_DEF tag is set to YES, doxygen will generate an # AutoGen Definitions (see http://autogen.sourceforge.net/) file that captures # the structure of the code including all documentation. Note that this feature # is still experimental and incomplete at the moment. # The default value is: NO. GENERATE_AUTOGEN_DEF = #--------------------------------------------------------------------------- # Configuration options related to the Perl module output #--------------------------------------------------------------------------- # If the GENERATE_PERLMOD tag is set to YES, doxygen will generate a Perl module # file that captures the structure of the code including all documentation. # # Note that this feature is still experimental and incomplete at the moment. # The default value is: NO. GENERATE_PERLMOD = # If the PERLMOD_LATEX tag is set to YES, doxygen will generate the necessary # Makefile rules, Perl scripts and LaTeX code to be able to generate PDF and DVI # output from the Perl module output. # The default value is: NO. # This tag requires that the tag GENERATE_PERLMOD is set to YES. PERLMOD_LATEX = # If the PERLMOD_PRETTY tag is set to YES, the Perl module output will be nicely # formatted so it can be parsed by a human reader. This is useful if you want to # understand what is going on. On the other hand, if this tag is set to NO, the # size of the Perl module output will be much smaller and Perl will parse it # just the same. # The default value is: YES. # This tag requires that the tag GENERATE_PERLMOD is set to YES. PERLMOD_PRETTY = # The names of the make variables in the generated doxyrules.make file are # prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. This is useful # so different doxyrules.make files included by the same Makefile don't # overwrite each other's variables. # This tag requires that the tag GENERATE_PERLMOD is set to YES. PERLMOD_MAKEVAR_PREFIX = #--------------------------------------------------------------------------- # Configuration options related to the preprocessor #--------------------------------------------------------------------------- # If the ENABLE_PREPROCESSING tag is set to YES, doxygen will evaluate all # C-preprocessor directives found in the sources and include files. # The default value is: YES. ENABLE_PREPROCESSING = # If the MACRO_EXPANSION tag is set to YES, doxygen will expand all macro names # in the source code. If set to NO, only conditional compilation will be # performed. Macro expansion can be done in a controlled way by setting # EXPAND_ONLY_PREDEF to YES. # The default value is: NO. # This tag requires that the tag ENABLE_PREPROCESSING is set to YES. MACRO_EXPANSION = YES # If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES then # the macro expansion is limited to the macros specified with the PREDEFINED and # EXPAND_AS_DEFINED tags. # The default value is: NO. # This tag requires that the tag ENABLE_PREPROCESSING is set to YES. EXPAND_ONLY_PREDEF = # If the SEARCH_INCLUDES tag is set to YES, the include files in the # INCLUDE_PATH will be searched if a #include is found. # The default value is: YES. # This tag requires that the tag ENABLE_PREPROCESSING is set to YES. SEARCH_INCLUDES = # The INCLUDE_PATH tag can be used to specify one or more directories that # contain include files that are not input files but should be processed by the # preprocessor. # This tag requires that the tag SEARCH_INCLUDES is set to YES. INCLUDE_PATH = # You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard # patterns (like *.h and *.hpp) to filter out the header-files in the # directories. If left blank, the patterns specified with FILE_PATTERNS will be # used. # This tag requires that the tag ENABLE_PREPROCESSING is set to YES. INCLUDE_FILE_PATTERNS = # The PREDEFINED tag can be used to specify one or more macro names that are # defined before the preprocessor is started (similar to the -D option of e.g. # gcc). The argument of the tag is a list of macros of the form: name or # name=definition (no spaces). If the definition and the "=" are omitted, "=1" # is assumed. To prevent a macro definition from being undefined via #undef or # recursively expanded use the := operator instead of the = operator. # This tag requires that the tag ENABLE_PREPROCESSING is set to YES. PREDEFINED = # If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this # tag can be used to specify a list of macro names that should be expanded. The # macro definition that is found in the sources will be used. Use the PREDEFINED # tag if you want to use a different macro definition that overrules the # definition found in the source code. # This tag requires that the tag ENABLE_PREPROCESSING is set to YES. EXPAND_AS_DEFINED = # If the SKIP_FUNCTION_MACROS tag is set to YES then doxygen's preprocessor will # remove all references to function-like macros that are alone on a line, have # an all uppercase name, and do not end with a semicolon. Such function macros # are typically used for boiler-plate code, and will confuse the parser if not # removed. # The default value is: YES. # This tag requires that the tag ENABLE_PREPROCESSING is set to YES. SKIP_FUNCTION_MACROS = #--------------------------------------------------------------------------- # Configuration options related to external references #--------------------------------------------------------------------------- # The TAGFILES tag can be used to specify one or more tag files. For each tag # file the location of the external documentation should be added. The format of # a tag file without this location is as follows: # TAGFILES = file1 file2 ... # Adding location for the tag files is done as follows: # TAGFILES = file1=loc1 "file2 = loc2" ... # where loc1 and loc2 can be relative or absolute paths or URLs. See the # section "Linking to external documentation" for more information about the use # of tag files. # Note: Each tag file must have a unique name (where the name does NOT include # the path). If a tag file is not located in the directory in which doxygen is # run, you must also specify the path to the tagfile here. TAGFILES = # When a file name is specified after GENERATE_TAGFILE, doxygen will create a # tag file that is based on the input files it reads. See section "Linking to # external documentation" for more information about the usage of tag files. GENERATE_TAGFILE = @CMAKE_CURRENT_BINARY_DIR@/@PROJECT_NAME@.tag # If the ALLEXTERNALS tag is set to YES, all external class will be listed in # the class index. If set to NO, only the inherited external classes will be # listed. # The default value is: NO. ALLEXTERNALS = # If the EXTERNAL_GROUPS tag is set to YES, all external groups will be listed # in the modules index. If set to NO, only the current project's groups will be # listed. # The default value is: YES. EXTERNAL_GROUPS = # If the EXTERNAL_PAGES tag is set to YES, all external pages will be listed in # the related pages index. If set to NO, only the current project's pages will # be listed. # The default value is: YES. EXTERNAL_PAGES = # The PERL_PATH should be the absolute path and name of the perl script # interpreter (i.e. the result of 'which perl'). # The default file (with absolute path) is: /usr/bin/perl. PERL_PATH = #--------------------------------------------------------------------------- # Configuration options related to the dot tool #--------------------------------------------------------------------------- # If the CLASS_DIAGRAMS tag is set to YES, doxygen will generate a class diagram # (in HTML and LaTeX) for classes with base or super classes. Setting the tag to # NO turns the diagrams off. Note that this option also works with HAVE_DOT # disabled, but it is recommended to install and use dot, since it yields more # powerful graphs. # The default value is: YES. CLASS_DIAGRAMS = # You can define message sequence charts within doxygen comments using the \msc # command. Doxygen will then run the mscgen tool (see: # http://www.mcternan.me.uk/mscgen/)) to produce the chart and insert it in the # documentation. The MSCGEN_PATH tag allows you to specify the directory where # the mscgen tool resides. If left empty the tool is assumed to be found in the # default search path. MSCGEN_PATH = # You can include diagrams made with dia in doxygen documentation. Doxygen will # then run dia to produce the diagram and insert it in the documentation. The # DIA_PATH tag allows you to specify the directory where the dia binary resides. # If left empty dia is assumed to be found in the default search path. DIA_PATH = # If set to YES the inheritance and collaboration graphs will hide inheritance # and usage relations if the target is undocumented or is not a class. # The default value is: YES. HIDE_UNDOC_RELATIONS = # If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is # available from the path. This tool is part of Graphviz (see: # http://www.graphviz.org/), a graph visualization toolkit from AT&T and Lucent # Bell Labs. The other options in this section have no effect if this option is # set to NO # The default value is: NO. HAVE_DOT = YES # The DOT_NUM_THREADS specifies the number of dot invocations doxygen is allowed # to run in parallel. When set to 0 doxygen will base this on the number of # processors available in the system. You can set it explicitly to a value # larger than 0 to get control over the balance between CPU load and processing # speed. # Minimum value: 0, maximum value: 32, default value: 0. # This tag requires that the tag HAVE_DOT is set to YES. DOT_NUM_THREADS = # When you want a differently looking font in the dot files that doxygen # generates you can specify the font name using DOT_FONTNAME. You need to make # sure dot is able to find the font, which can be done by putting it in a # standard location or by setting the DOTFONTPATH environment variable or by # setting DOT_FONTPATH to the directory containing the font. # The default value is: Helvetica. # This tag requires that the tag HAVE_DOT is set to YES. DOT_FONTNAME = # The DOT_FONTSIZE tag can be used to set the size (in points) of the font of # dot graphs. # Minimum value: 4, maximum value: 24, default value: 10. # This tag requires that the tag HAVE_DOT is set to YES. DOT_FONTSIZE = # By default doxygen will tell dot to use the default font as specified with # DOT_FONTNAME. If you specify a different font using DOT_FONTNAME you can set # the path where dot can find it using this tag. # This tag requires that the tag HAVE_DOT is set to YES. DOT_FONTPATH = # If the CLASS_GRAPH tag is set to YES then doxygen will generate a graph for # each documented class showing the direct and indirect inheritance relations. # Setting this tag to YES will force the CLASS_DIAGRAMS tag to NO. # The default value is: YES. # This tag requires that the tag HAVE_DOT is set to YES. CLASS_GRAPH = # If the COLLABORATION_GRAPH tag is set to YES then doxygen will generate a # graph for each documented class showing the direct and indirect implementation # dependencies (inheritance, containment, and class references variables) of the # class with other documented classes. # The default value is: YES. # This tag requires that the tag HAVE_DOT is set to YES. COLLABORATION_GRAPH = # If the GROUP_GRAPHS tag is set to YES then doxygen will generate a graph for # groups, showing the direct groups dependencies. # The default value is: YES. # This tag requires that the tag HAVE_DOT is set to YES. GROUP_GRAPHS = # If the UML_LOOK tag is set to YES, doxygen will generate inheritance and # collaboration diagrams in a style similar to the OMG's Unified Modeling # Language. # The default value is: NO. # This tag requires that the tag HAVE_DOT is set to YES. UML_LOOK = # If the UML_LOOK tag is enabled, the fields and methods are shown inside the # class node. If there are many fields or methods and many nodes the graph may # become too big to be useful. The UML_LIMIT_NUM_FIELDS threshold limits the # number of items for each type to make the size more manageable. Set this to 0 # for no limit. Note that the threshold may be exceeded by 50% before the limit # is enforced. So when you set the threshold to 10, up to 15 fields may appear, # but if the number exceeds 15, the total amount of fields shown is limited to # 10. # Minimum value: 0, maximum value: 100, default value: 10. # This tag requires that the tag HAVE_DOT is set to YES. UML_LIMIT_NUM_FIELDS = # If the TEMPLATE_RELATIONS tag is set to YES then the inheritance and # collaboration graphs will show the relations between templates and their # instances. # The default value is: NO. # This tag requires that the tag HAVE_DOT is set to YES. TEMPLATE_RELATIONS = # If the INCLUDE_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are set to # YES then doxygen will generate a graph for each documented file showing the # direct and indirect include dependencies of the file with other documented # files. # The default value is: YES. # This tag requires that the tag HAVE_DOT is set to YES. INCLUDE_GRAPH = # If the INCLUDED_BY_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are # set to YES then doxygen will generate a graph for each documented file showing # the direct and indirect include dependencies of the file with other documented # files. # The default value is: YES. # This tag requires that the tag HAVE_DOT is set to YES. INCLUDED_BY_GRAPH = # If the CALL_GRAPH tag is set to YES then doxygen will generate a call # dependency graph for every global function or class method. # # Note that enabling this option will significantly increase the time of a run. # So in most cases it will be better to enable call graphs for selected # functions only using the \callgraph command. Disabling a call graph can be # accomplished by means of the command \hidecallgraph. # The default value is: NO. # This tag requires that the tag HAVE_DOT is set to YES. CALL_GRAPH = # If the CALLER_GRAPH tag is set to YES then doxygen will generate a caller # dependency graph for every global function or class method. # # Note that enabling this option will significantly increase the time of a run. # So in most cases it will be better to enable caller graphs for selected # functions only using the \callergraph command. Disabling a caller graph can be # accomplished by means of the command \hidecallergraph. # The default value is: NO. # This tag requires that the tag HAVE_DOT is set to YES. CALLER_GRAPH = # If the GRAPHICAL_HIERARCHY tag is set to YES then doxygen will graphical # hierarchy of all classes instead of a textual one. # The default value is: YES. # This tag requires that the tag HAVE_DOT is set to YES. GRAPHICAL_HIERARCHY = # If the DIRECTORY_GRAPH tag is set to YES then doxygen will show the # dependencies a directory has on other directories in a graphical way. The # dependency relations are determined by the #include relations between the # files in the directories. # The default value is: YES. # This tag requires that the tag HAVE_DOT is set to YES. DIRECTORY_GRAPH = # The DOT_IMAGE_FORMAT tag can be used to set the image format of the images # generated by dot. For an explanation of the image formats see the section # output formats in the documentation of the dot tool (Graphviz (see: # http://www.graphviz.org/)). # Note: If you choose svg you need to set HTML_FILE_EXTENSION to xhtml in order # to make the SVG files visible in IE 9+ (other browsers do not have this # requirement). # Possible values are: png, jpg, gif, svg, png:gd, png:gd:gd, png:cairo, # png:cairo:gd, png:cairo:cairo, png:cairo:gdiplus, png:gdiplus and # png:gdiplus:gdiplus. # The default value is: png. # This tag requires that the tag HAVE_DOT is set to YES. DOT_IMAGE_FORMAT = # If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to # enable generation of interactive SVG images that allow zooming and panning. # # Note that this requires a modern browser other than Internet Explorer. Tested # and working are Firefox, Chrome, Safari, and Opera. # Note: For IE 9+ you need to set HTML_FILE_EXTENSION to xhtml in order to make # the SVG files visible. Older versions of IE do not have SVG support. # The default value is: NO. # This tag requires that the tag HAVE_DOT is set to YES. INTERACTIVE_SVG = # The DOT_PATH tag can be used to specify the path where the dot tool can be # found. If left blank, it is assumed the dot tool can be found in the path. # This tag requires that the tag HAVE_DOT is set to YES. DOT_PATH = # The DOTFILE_DIRS tag can be used to specify one or more directories that # contain dot files that are included in the documentation (see the \dotfile # command). # This tag requires that the tag HAVE_DOT is set to YES. DOTFILE_DIRS = # The MSCFILE_DIRS tag can be used to specify one or more directories that # contain msc files that are included in the documentation (see the \mscfile # command). MSCFILE_DIRS = # The DIAFILE_DIRS tag can be used to specify one or more directories that # contain dia files that are included in the documentation (see the \diafile # command). DIAFILE_DIRS = # When using plantuml, the PLANTUML_JAR_PATH tag should be used to specify the # path where java can find the plantuml.jar file. If left blank, it is assumed # PlantUML is not used or called during a preprocessing step. Doxygen will # generate a warning when it encounters a \startuml command in this case and # will not generate output for the diagram. PLANTUML_JAR_PATH = # When using plantuml, the PLANTUML_CFG_FILE tag can be used to specify a # configuration file for plantuml. PLANTUML_CFG_FILE = # When using plantuml, the specified paths are searched for files specified by # the !include statement in a plantuml block. PLANTUML_INCLUDE_PATH = # The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of nodes # that will be shown in the graph. If the number of nodes in a graph becomes # larger than this value, doxygen will truncate the graph, which is visualized # by representing a node as a red box. Note that doxygen if the number of direct # children of the root node in a graph is already larger than # DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note that # the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH. # Minimum value: 0, maximum value: 10000, default value: 50. # This tag requires that the tag HAVE_DOT is set to YES. DOT_GRAPH_MAX_NODES = # The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the graphs # generated by dot. A depth value of 3 means that only nodes reachable from the # root by following a path via at most 3 edges will be shown. Nodes that lay # further from the root node will be omitted. Note that setting this option to 1 # or 2 may greatly reduce the computation time needed for large code bases. Also # note that the size of a graph can be further restricted by # DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction. # Minimum value: 0, maximum value: 1000, default value: 0. # This tag requires that the tag HAVE_DOT is set to YES. MAX_DOT_GRAPH_DEPTH = # Set the DOT_TRANSPARENT tag to YES to generate images with a transparent # background. This is disabled by default, because dot on Windows does not seem # to support this out of the box. # # Warning: Depending on the platform used, enabling this option may lead to # badly anti-aliased labels on the edges of a graph (i.e. they become hard to # read). # The default value is: NO. # This tag requires that the tag HAVE_DOT is set to YES. DOT_TRANSPARENT = YES # Set the DOT_MULTI_TARGETS tag to YES to allow dot to generate multiple output # files in one run (i.e. multiple -o and -T options on the command line). This # makes dot run faster, but since only newer versions of dot (>1.8.10) support # this, this feature is disabled by default. # The default value is: NO. # This tag requires that the tag HAVE_DOT is set to YES. DOT_MULTI_TARGETS = YES # If the GENERATE_LEGEND tag is set to YES doxygen will generate a legend page # explaining the meaning of the various boxes and arrows in the dot generated # graphs. # The default value is: YES. # This tag requires that the tag HAVE_DOT is set to YES. GENERATE_LEGEND = # If the DOT_CLEANUP tag is set to YES, doxygen will remove the intermediate dot # files that are used to generate the various graphs. # The default value is: YES. # This tag requires that the tag HAVE_DOT is set to YES. DOT_CLEANUP = 07070100000012000081A4000000000000000000000001656C867F000009B2000000000000000000000000000000000000002900000000wfmath-1701611135.403a8bd/docs/index.txtThis is the Worldforge math library. It's licensed under the GPL (see file COPYING), and basic compilation instructions are in the file INSTALL. The current maintainer is Ron Steinke <rsteinke@w-link.net>. The only library that WFMath checks for is Atlas, and it only does this for the sake of some test functions. The only dependency on Atlas is in the file atlasconv.h. This header file contains some inline functions which can be used to convert the various objects in WFMath to Atlas::Message::Object and back. This header file will be installed whether Atlas is present or not, but to use it you must of course have the Atlas headers installed. The currently implemented classes can be divided into two sorts. The first kind are basic mathematical objects, whose members are all fundamental types. The second kind are shapes, which implement the shape class interface described in doc/shape.h. There are four classes of the first kind: Vector<> A basic mathematical vector RotMatrix<> An orthogonal matrix of determinant 1, useful for describing rotations. Point<> A point in space. This basic class also implements the shape interface in doc/shape.h. Quaternion A quaternion The shape classes are: AxisBox<> A box oriented parallel to the coordinate axes Ball<> Ball<2> is a circle, Ball<3> is a sphere, etc. Segment<> A line segment, defined by its endpoints RotBox<> Like AxisBox<>, but it can be rotated to arbitrary angles Polygon<> A 2 dimensional polygon contained in a (possibly) larger dimensional space Anyone interested in contributing to this project should do three things: 1) Send me an email. This is mostly to let me know someone else is working with the CVS repository, so I can be careful about merging commits. 2) Look at the file doc/CLASS_LAYOUT, which specifies which member functions all classes should have, and what order they should appear in. This only applies to significant classes, not things like ColinearVectors in error.h, which is only there to be thrown as as exception. 3) Update the ChangeLog _every_ time you commit to CVS. This makes it possible for other people to have some idea what you're working on. The documentation is at this point confined to the doc/CLASS_LAYOUT file and comments in the code. There's also a sample shape class definition in the file shape.h in the doc directory. This has comments about what member functions all shape classes are supposed to have, and what they do. 07070100000013000081A4000000000000000000000001656C867F00001BCE000000000000000000000000000000000000002700000000wfmath-1701611135.403a8bd/docs/shape.h// shape.h (A general base class for shapes) // // The WorldForge Project // Copyright (C) 2001 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // // Author: Ron Steinke // This class borrows heavily from the base shape class in libCoal, // plus certain intersection ideas from stage/shepherd/sylvanus #ifndef WFMATH_SHAPE_H #define WFMATH_SHAPE_H #include <wfmath/vector.h> #include <wfmath/point.h> #include <wfmath/const.h> #include <wfmath/rotmatrix.h> #include <wfmath/axisbox.h> #include <wfmath/ball.h> #include <wfmath/intersect_decls.h> namespace WFMath { /// A fake class which documents the generic parts of the WFMath interface /** * This fake class documents two parts of the WFMath generic * class interface. With a few exceptions (e.g. classes derived * from std::exception), every class in WFMath implements * the part of the interface labeled as 'generic'. The 'shape' * interface is implemented by several classes, which identify * themselves in their own documentation. Every class which * implements the 'shape' interface also implements the 'generic' * interface. Classes will not generally document their * generic and shape interface functions. **/ template<const int dim> class Shape { public: // The first things in the Shape class are the functions required // by CLASS_LAYOUT for all classes /// Shape() {} /// Shape(const Shape<dim>& s) {} /// ~Shape() {} /// generic: Print an instance to a stream friend std::ostream& operator<< <dim>(std::ostream& os, const Shape& s); /// generic: Parse an instance from a stream friend std::istream& operator>> <dim>(std::istream& is, Shape& s); /// Shape& operator=(const Shape& a); /// generic: check if two classes are equal, up to a given tolerance bool isEqualTo(const Shape& s, CoordType tolerance = numeric_constants<CoordType>::epsilon()) const; /// generic: check if two classes are equal, up to tolerance WFMATH_EPSILON bool operator==(const Shape& s) const {return isEqualTo(s);} /// generic: check if two classes are not equal, up to tolerance WFMATH_EPSILON bool operator!=(const Shape& s) const {return !isEqualTo(s);} /// generic: returns true if the class instance has been initialized bool isValid() const {return m_valid;} // Now we begin with the functions in the shape interface // Descriptive characteristics /// shape: return the number of corners in the shape. /** * For many shape classes, this is a fixed constant **/ size_t numCorners() const; // The number of corners, returns zero for Ball<> /// shape: return the position of the i'th corner, where 0 <= i < numCorners() Point<dim> getCorner(size_t i) const; // Must have i >= 0 && i < numCorners() /// shape: return the position of the center of the shape Point<dim> getCenter() const; // Returns the barycenter of the object // Movement functions /// shape: move the shape by an amount given by the Vector v Shape& shift(const Vector<dim>& v); // Move the shape a certain distance /// shape: move the shape, moving the given corner to the Point p /** * The corner in question is getCorner(corner). **/ Shape& moveCornerTo(const Point<dim>& p, size_t corner) {return shift(p - getCorner(corner));} /// shape: move the shape, moving the center to the Point p /** * The center is defined by getCenter() **/ Shape& moveCenterTo(const Point<dim>& p) {return shift(p - getCenter());} /// shape: rotate the shape while holding the given corner fixed /** * The corner in question is getCorner(corner). **/ Shape& rotateCorner(const RotMatrix<dim>& m, size_t corner) {return rotatePoint(m, getCorner(corner));} /// shape: rotate the shape while holding the center fixed /** * The center is defined by getCenter() **/ Shape& rotateCenter(const RotMatrix<dim>& m) {return rotatePoint(m, getCenter());} /// shape: rotate the shape while holding the Point p fixed. /** * Note that p can be any Point, it does not have to lie within * the shape. **/ Shape& rotatePoint(const RotMatrix<dim>& m, const Point<dim>& p); // Intersection functions /// shape: return the minimal axis-aligned bounding box AxisBox<dim> boundingBox() const; /// shape: return the minimal bounding sphere Ball<dim> boundingSphere() const; /// shape: return an approximate bounding sphere, guaranteed /// to contain the minimal bounding sphere /** * boundingSphereSloppy() uses * SloppyDistance() instead of Distance() to calculate it's * radius, except in cases like Point<> and Ball<> where it * would be silly. Thus, the result of boundingSphereSloppy() * is guaranteed to contain the result of boundingSphere(). **/ Ball<dim> boundingSphereSloppy() const; /// shape: Returns true if the two shapes intersect. /** * If the 'proper' argument is true, shapes which only touch on their * boundary do not count as intersecting. If it is false, they do. * This function is symmetric in its first two arguments * (Intersect(a, b, proper) == Intersect(b, a, proper)). * The two shapes do * not have to be the same class, but must have the same dimension. **/ friend bool Intersect<dim>(Shape<dim>& s1, Shape<dim>& s2, bool proper); /// shape: Returns true if the first shape contains the second. /** * If the 'proper' argument is true, the inner shape is not contained * if it touches the boundary of the outer shape. Otherwise, it * does. Therefore, any shape contains itself * (Contains(foo, foo, false) == true), but no shape contains itself * properly (Contains(foo, foo, true) == false). Because of this, * an empty shape (e.g. a Polygon with zero corners) * is properly contained by any other shape. A Point, or any single * point shape (e.g. a Segment where the endpoints are equal) * properly contains an empty shape, and contains (but not properly) * any other single point shape which occupies the same point. * The two shapes do * not have to be the same class, but must have the same dimension. **/ friend bool Contains<dim>(Shape<dim>& s1, Shape<dim>& s2, bool proper); private: bool m_valid; }; //#include<wfmath/shape_funcs.h> } // namespace WFMath #endif // WFMATH_SHAPE_H 07070100000014000041ED000000000000000000000003656C867F00000000000000000000000000000000000000000000001E00000000wfmath-1701611135.403a8bd/src07070100000015000081A4000000000000000000000001656C867F0000066B000000000000000000000000000000000000002D00000000wfmath-1701611135.403a8bd/src/CMakeLists.txtset(SOURCE_FILES wfmath/axisbox.cpp wfmath/axisbox_funcs.h wfmath/ball.cpp wfmath/ball_funcs.h wfmath/const.cpp wfmath/int_to_string.cpp wfmath/intersect.cpp wfmath/line.cpp wfmath/line_funcs.h wfmath/point.cpp wfmath/point_funcs.h wfmath/polygon.cpp wfmath/polygon_intersect.cpp wfmath/polygon_funcs.h wfmath/probability.cpp wfmath/quaternion.cpp wfmath/randgen.cpp wfmath/rotbox.cpp wfmath/rotbox_funcs.h wfmath/rotmatrix.cpp wfmath/rotmatrix_funcs.h wfmath/segment.cpp wfmath/segment_funcs.h wfmath/stream.cpp wfmath/timestamp.cpp wfmath/vector.cpp wfmath/vector_funcs.h wfmath/miniball_funcs.h ) set(HEADER_FILES wfmath/atlasconv.h wfmath/axisbox.h wfmath/ball.h wfmath/basis.h wfmath/const.h wfmath/error.h wfmath/int_to_string.h wfmath/intersect.h wfmath/intersect_decls.h wfmath/line.h wfmath/MersenneTwister.h wfmath/miniball.h wfmath/point.h wfmath/polygon.h wfmath/polygon_intersect.h wfmath/probability.h wfmath/quaternion.h wfmath/randgen.h wfmath/rotbox.h wfmath/rotmatrix.h wfmath/segment.h wfmath/shuffle.h wfmath/stream.h wfmath/timestamp.h wfmath/vector.h wfmath/wfmath.h wfmath/wrapped_array.h wfmath/zero.h) wf_add_library(${PROJECT_NAME} SOURCE_FILES HEADER_FILES) 07070100000016000041ED000000000000000000000003656C867F00000000000000000000000000000000000000000000002500000000wfmath-1701611135.403a8bd/src/wfmath07070100000017000081A4000000000000000000000001656C867F00000CBD000000000000000000000000000000000000003700000000wfmath-1701611135.403a8bd/src/wfmath/MersenneTwister.h// MersenneTwister.h // // The WorldForge Project // Copyright (C) 2013 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // #ifndef WFMATH_MERSENNE_TWISTER_H_ #define WFMATH_MERSENNE_TWISTER_H_ #include <iosfwd> #include <cstdint> namespace WFMath { class MTRand { public: typedef uint32_t uint32; static const uint32 state_size = 624; public: MTRand(); explicit MTRand(uint32 oneSeed); explicit MTRand(uint32 bigSeed[], uint32 seedLength = state_size); // real-valued random numbers on [0, 1] or [0, n] template<typename FloatT> FloatT rand(); double rand(); double rand(const double& n); // integer-valued random numbers on [0, 2^32-1] or [0, n] uint32 randInt(); uint32 randInt(uint32 n); void seed(); void seed(uint32 oneSeed); void seed(const uint32 init_vector[], uint32 init_vector_length = state_size); std::ostream& save(std::ostream&) const; std::istream& load(std::istream&); static MTRand instance; private: uint32 state[state_size]; uint32 index; }; inline MTRand::MTRand(uint32 oneSeed) : index(0) { seed(oneSeed); } inline MTRand::MTRand(uint32 bigSeed[], uint32 seedLength) : index(0) { seed(bigSeed, seedLength); } inline MTRand::MTRand() : index(0) { seed(); } template<> inline float MTRand::rand<float>() { return float(randInt()) * (1.0f/4294967295.0f); } template<> inline double MTRand::rand<double>() { return double(randInt()) * (1.0/4294967295.0); } inline double MTRand::rand() { return double(randInt()) * (1.0/4294967295.0); } inline double MTRand::rand( const double& n ) { return rand() * n; } inline MTRand::uint32 MTRand::randInt(uint32 n) { uint32 used = n; used |= used >> 1u; used |= used >> 2u; used |= used >> 4u; used |= used >> 8u; used |= used >> 16u; uint32 i; do i = randInt() & used; while( i > n ); return i; } #if 0 inline void MTRand::save(uint32* saveArray) const { uint32 *sa = saveArray; const uint32 *s = state; int i = state_size; for( ; i--; *sa++ = *s++ ) {} *sa = left; } inline void MTRand::load(uint32 *const loadArray) { uint32 *s = state; uint32 *la = loadArray; int i = state_size; for( ; i--; *s++ = *la++ ) {} left = *la; pNext = &state[state_size-left]; } #endif std::ostream& operator<<(std::ostream& os, MTRand const& mtrand); std::istream& operator>>(std::istream& is, MTRand& mtrand); } // namespace #endif // WFMATH_MERSENNE_TWISTER_H_ 07070100000018000081A4000000000000000000000001656C867F00003079000000000000000000000000000000000000003100000000wfmath-1701611135.403a8bd/src/wfmath/atlasconv.h// atlasconv.h (Functions to convert WFMath library object to/from an Atlas Message) // // The WorldForge Project // Copyright (C) 2001 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Ron Steinke // Created: 2001-12-11 // Since we don't want WFMath and Atlas to depend on each other, // we're putting all the atlas interface functions into this header. // WARNING! WARNING! Do not include this file in any other file in wfmath. #ifndef WFMATH_ATLAS_CONV_H #define WFMATH_ATLAS_CONV_H #include "point.h" #include "vector.h" #include "quaternion.h" #include "axisbox.h" #include "polygon.h" #include "ball.h" #include "rotbox.h" #include "line.h" #include <cmath> namespace WFMath { #ifndef ATLAS_MESSAGE_ELEMENT_H #error "You must include Atlas/Message/Element.h before wfmath/atlasconv.h" #endif typedef Atlas::Message::WrongTypeException _AtlasBadParse; class AtlasInType { public: AtlasInType(const Atlas::Message::Element& val) : m_val(val) {} // allow nice conversions when necessary template<class C> AtlasInType(C c) : m_obj(c), m_val(m_obj) {} operator const Atlas::Message::Element&() const {return m_val;} bool IsList() const {return m_val.isList();} const Atlas::Message::ListType& AsList() const {return m_val.asList();} private: Atlas::Message::Element m_obj; const Atlas::Message::Element& m_val; }; class AtlasOutType { public: AtlasOutType(const Atlas::Message::ListType& l) : m_val(l) {} AtlasOutType(const Atlas::Message::MapType& l) : m_val(l) {} operator Atlas::Message::Element&() {return m_val;} operator const Atlas::Message::Element&() const {return m_val;} private: Atlas::Message::Element m_val; }; inline AtlasOutType _ArrayToAtlas(const CoordType* array, unsigned len) { Atlas::Message::ListType a(len); for(unsigned i = 0; i < len; ++i) a[i] = array[i]; return a; } inline void _ArrayFromAtlas(CoordType* array, unsigned len, const AtlasInType& a) { if(!a.IsList()) throw _AtlasBadParse(); const Atlas::Message::ListType& list(a.AsList()); if(list.size() != (unsigned int) len) throw _AtlasBadParse(); for(unsigned i = 0; i < len; ++i) array[i] = static_cast<CoordType>(list[i].asNum()); } template<int dim> inline Vector<dim>::Vector(const AtlasInType& a) { fromAtlas(a); } template<int dim> inline void Vector<dim>::fromAtlas(const AtlasInType& a) { _ArrayFromAtlas(m_elem, dim, a); for (int i = 0; i < dim; ++i) { if (!std::isfinite(m_elem[i])) { m_valid = false; return; } } m_valid = true; } template<int dim> inline AtlasOutType Vector<dim>::toAtlas() const { return _ArrayToAtlas(m_elem, dim); } inline void Quaternion::fromAtlas(const AtlasInType& a) { if(!a.IsList()) throw _AtlasBadParse(); const Atlas::Message::ListType& list(a.AsList()); if(list.size() != 4) throw _AtlasBadParse(); for(int i = 0; i < 3; ++i) m_vec[i] = static_cast<CoordType>(list[i].asNum()); for (int i = 0; i < 3; ++i) { if (!std::isfinite(m_vec[i])) { m_valid = false; m_vec.setValid(false); return; } } m_w = static_cast<CoordType>(list[3].asNum()); if (!std::isfinite(m_w)) { m_valid = false; return; } CoordType norm = std::sqrt(m_w * m_w + m_vec.sqrMag()); if (norm <= numeric_constants<CoordType>::epsilon()) { m_valid = false; m_vec.setValid(false); return; } m_vec /= norm; m_w /= norm; m_valid = true; m_age = 1; m_vec.setValid(); } inline AtlasOutType Quaternion::toAtlas() const { Atlas::Message::ListType a(4); for(int i = 0; i < 3; ++i) a[i] = m_vec[i]; a[3] = m_w; return a; } template<int dim> inline Point<dim>::Point(const AtlasInType& a) { fromAtlas(a); } template<int dim> inline void Point<dim>::fromAtlas(const AtlasInType& a) { _ArrayFromAtlas(m_elem, dim, a); for (int i = 0; i < dim; ++i) { if (!std::isfinite(m_elem[i])) { m_valid = false; return; } } m_valid = true; } template<int dim> inline AtlasOutType Point<dim>::toAtlas() const { return _ArrayToAtlas(m_elem, dim); } template<int dim> inline AxisBox<dim>::AxisBox(const AtlasInType& a) { fromAtlas(a); } template<int dim> inline void AxisBox<dim>::fromAtlas(const AtlasInType& a) { if(!a.IsList()) throw _AtlasBadParse(); const Atlas::Message::ListType& list(a.AsList()); switch(list.size()) { case dim: m_low.setToOrigin(); m_high.fromAtlas(a); break; case (2 * dim): for(int i = 0; i < dim; ++i) { m_low[i] = list[i].asNum(); if (!std::isfinite((m_low[i]))) { m_low.setValid(false); return; } m_high[i] = list[i+dim].asNum(); if (!std::isfinite((m_high[i]))) { m_high.setValid(false); return; } } m_low.setValid(); m_high.setValid(); break; default: throw _AtlasBadParse(); } for(int i = 0; i < dim; ++i) { if(m_low[i] > m_high[i]) { // spec may allow this? CoordType tmp = m_low[i]; m_low[i] = m_high[i]; m_high[i] = tmp; } } } template<int dim> inline AtlasOutType AxisBox<dim>::toAtlas() const { int i; for(i = 0; i < dim; ++i) if(m_low[i] != 0) break; if(i == dim) return m_high.toAtlas(); // matches case 'dim' above // Do case '2 * dim' above Atlas::Message::ListType a(2*dim); for(i = 0; i < dim; ++i) { a[i] = m_low[i]; a[dim+i] = m_high[i]; } return a; } template<int dim> inline void Ball<dim>::fromAtlas(const AtlasInType& a) { const Atlas::Message::Element& message(a); if (message.isMap()) { const Atlas::Message::MapType& shapeElement(message.asMap()); // Get sphere's radius auto shape_I = shapeElement.find("radius"); if (shape_I != shapeElement.end()) { const Atlas::Message::Element& shapeRadiusElem(shape_I->second); if (shapeRadiusElem.isNum()) { m_radius = shapeRadiusElem.asNum(); //Perhaps we should add a check to Ball::isValid for non-nan radius? Until that we'll just invalidate the center instead. if (!std::isfinite(m_radius)) { m_center.setValid(false); return; } } } auto pos_I = shapeElement.find("position"); if (pos_I != shapeElement.end()) { const Atlas::Message::Element& posElem(pos_I->second); if (posElem.isList()) { m_center.fromAtlas(posElem); } } } } template<int dim> inline AtlasOutType Ball<dim>::toAtlas() const { Atlas::Message::MapType map; map.insert(Atlas::Message::MapType::value_type("radius", m_radius)); map.insert(Atlas::Message::MapType::value_type("position", m_center.toAtlas())); return map; } template<int dim> inline Ball<dim>::Ball(const AtlasInType& a) : m_center(Point<dim>::ZERO()), m_radius(0) { fromAtlas(a); } inline bool _ListNumCheck(const Atlas::Message::ListType & list, int dim) { for(int i = 0; i < dim; ++i) { if (!list[i].isNum()) { return false; } } return true; } template<template <int> class ShapeT> inline void _AddCorner(ShapeT<3> & shape, const Atlas::Message::ListType & point) { Point<3> wpt(point[0].asNum(), point[1].asNum(), point[2].asNum()); if (!std::isfinite(wpt.x()) || !std::isfinite(wpt.y()) || !std::isfinite(wpt.z())) { return; } shape.addCorner(shape.numCorners(), wpt); } template<template <int> class ShapeT> inline void _AddCorner(ShapeT<2> & shape, const Atlas::Message::ListType & point) { Point<2> wpt(point[0].asNum(), point[1].asNum()); if (!std::isfinite(wpt.x()) || !std::isfinite(wpt.y())) { return; } shape.addCorner(shape.numCorners(), wpt); } template<template <int> class ShapeT, int dim> inline void _CornersFromAtlas(ShapeT<dim> & shape, const Atlas::Message::Element& message) { if (message.isList()) { const Atlas::Message::ListType& pointsData(message.asList()); for (const auto & p : pointsData) { if (!p.isList()) { continue; } const Atlas::Message::ListType& point(p.asList()); if ((point.size() < dim) || !_ListNumCheck(point, dim)) { continue; } _AddCorner(shape, point); } } } inline void Polygon<2>::fromAtlas(const AtlasInType& a) { const Atlas::Message::Element& message(a); if (message.isMap()) { const Atlas::Message::MapType& shapeElement(message.asMap()); auto it = shapeElement.find("points"); if ((it != shapeElement.end()) && it->second.isList()) { _CornersFromAtlas(*this, it->second); if (numCorners() > 2) { return; } } } else if (message.isList()) { _CornersFromAtlas(*this, message); if (numCorners() > 2) { return; } } throw _AtlasBadParse(); } inline AtlasOutType Polygon<2>::toAtlas() const { Atlas::Message::ListType points; for (const auto & point : m_points) { points.push_back(point.toAtlas()); } Atlas::Message::MapType map; map.insert(Atlas::Message::MapType::value_type("points", points)); return map; } template<int dim> inline void Line<dim>::fromAtlas(const AtlasInType& a) { const Atlas::Message::Element& message(a); if (message.isMap()) { const Atlas::Message::MapType& shapeElement(message.asMap()); auto it = shapeElement.find("points"); if ((it != shapeElement.end()) && it->second.isList()) { _CornersFromAtlas(*this, it->second); if (numCorners() > 0) { return; } } } else if (message.isList()) { _CornersFromAtlas(*this, message); if (numCorners() > 0) { return; } } throw _AtlasBadParse(); } template<int dim> inline AtlasOutType Line<dim>::toAtlas() const { Atlas::Message::ListType points; for (const_iterator I = m_points.begin(); I != m_points.end(); ++I) { points.push_back(I->toAtlas()); } Atlas::Message::MapType map; map.insert(Atlas::Message::MapType::value_type("points", points)); return map; } template<int dim> inline Line<dim>::Line(const AtlasInType& a) { fromAtlas(a); } template<int dim> inline void RotBox<dim>::fromAtlas(const AtlasInType& a) { const Atlas::Message::Element& message(a); if (message.isMap()) { const Atlas::Message::MapType& shapeElement(message.asMap()); // Get rotbox's position auto shape_I = shapeElement.find("point"); if (shape_I != shapeElement.end()) { const Atlas::Message::Element& shapePointElem(shape_I->second); Point<dim> shapePoint; shapePoint.fromAtlas(shapePointElem); // Get rotbox's vector shape_I = shapeElement.find("size"); if (shape_I != shapeElement.end()) { const Atlas::Message::Element& shapeVectorElem(shape_I->second); Vector<dim> shapeVector; shapeVector.fromAtlas(shapeVectorElem); m_corner0 = shapePoint; m_size = shapeVector; m_orient = RotMatrix<dim>().identity(); //TODO: parse rotation matrix (is it needed?) return; } } } throw _AtlasBadParse(); } template<int dim> inline AtlasOutType RotBox<dim>::toAtlas() const { Atlas::Message::MapType map; map.insert(Atlas::Message::MapType::value_type("point", m_corner0.toAtlas())); map.insert(Atlas::Message::MapType::value_type("size", m_size.toAtlas())); //TODO: also add the rotmatrix return map; } template<int dim> inline RotBox<dim>::RotBox(const AtlasInType& a) { fromAtlas(a); } } // namespace WFMath #endif // WFMATH_ATLAS_CONV_H 07070100000019000081A4000000000000000000000001656C867F0000093B000000000000000000000000000000000000003100000000wfmath-1701611135.403a8bd/src/wfmath/axisbox.cpp// vector.cpp (Vector<> implementation) // // The WorldForge Project // Copyright (C) 2001 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Alistair Riddoch // Created: 2009-01-12 #include "axisbox_funcs.h" #include "rotmatrix.h" #include "vector.h" #include <vector> #include <cmath> namespace WFMath { template class AxisBox<3>; template class AxisBox<2>; template bool Intersection<3>(const AxisBox<3>&, const AxisBox<3>&, AxisBox<3>&); template bool Intersection<2>(const AxisBox<2>&, const AxisBox<2>&, AxisBox<2>&); template AxisBox<3> Union<3>(const AxisBox<3> &, const AxisBox<3> &); template AxisBox<2> Union<2>(const AxisBox<2>&, const AxisBox<2>&); template AxisBox<3> BoundingBox<3, std::vector>(const std::vector<AxisBox<3>, std::allocator<AxisBox<3> > > &); template AxisBox<2> BoundingBox<2, std::vector>(const std::vector<AxisBox<2>, std::allocator<AxisBox<2> > > &); template AxisBox<3> BoundingBox<3, std::vector>(const std::vector<Point<3>, std::allocator<Point<3> > >&); template AxisBox<2> BoundingBox<2, std::vector>(const std::vector<Point<2>, std::allocator<Point<2> > >&); static_assert(std::is_standard_layout<AxisBox<3>>::value, "AxisBox should be standard layout."); static_assert(std::is_trivially_copyable<AxisBox<3>>::value, "AxisBox should be trivially copyable."); static_assert(std::is_standard_layout<AxisBox<2>>::value, "AxisBox should be standard layout."); static_assert(std::is_trivially_copyable<AxisBox<2>>::value, "AxisBox should be trivially copyable."); } 0707010000001A000081A4000000000000000000000001656C867F00001D4D000000000000000000000000000000000000002F00000000wfmath-1701611135.403a8bd/src/wfmath/axisbox.h// axisbox.h (An axis-aligned box) // // The WorldForge Project // Copyright (C) 2000, 2001 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // // Author: Ron Steinke // The implementation of this class is based on the geometric // parts of the Tree and Placement classes from stage/shepherd/sylvanus #ifndef WFMATH_AXIS_BOX_H #define WFMATH_AXIS_BOX_H #include <wfmath/intersect_decls.h> #include <wfmath/point.h> namespace WFMath { template<int dim> bool Intersection(const AxisBox<dim>& a1, const AxisBox<dim>& a2, AxisBox<dim>& out); template<int dim> AxisBox<dim> Union(const AxisBox<dim>& a1, const AxisBox<dim>& a2); template<int dim> std::ostream& operator<<(std::ostream& os, const AxisBox<dim>& m); template<int dim> std::istream& operator>>(std::istream& is, AxisBox<dim>& m); /// Get the axis-aligned bounding box for a set of boxes template<int dim, template<class, class> class container> AxisBox<dim> BoundingBox(const container<AxisBox<dim>, std::allocator<AxisBox<dim> > >& c); /// Get the axis-aligned bounding box for a set of points template<int dim, template<class, class> class container> AxisBox<dim> BoundingBox(const container<Point<dim>, std::allocator<Point<dim> > >& c); /// A dim dimensional axis-aligned box /** * This class implements the full shape interface, as described in * the fake class Shape, with the exception of the rotation functions. **/ template<int dim = 3> class AxisBox { public: /// Construct an uninitialized box AxisBox() = default; /// Construct a box with opposite corners p1 and p2 AxisBox(const Point<dim>& p1, const Point<dim>& p2, bool ordered = false) : m_low(), m_high() {setCorners(p1, p2, ordered);} /// Construct a copy of a box AxisBox(const AxisBox& a) = default; /// Construct a box from an object passed by Atlas explicit AxisBox(const AtlasInType& a); friend std::ostream& operator<< <dim>(std::ostream& os, const AxisBox& a); friend std::istream& operator>> <dim>(std::istream& is, AxisBox& a); /// Create an Atlas object from the box AtlasOutType toAtlas() const; /// Set the box's value to that given by an Atlas object void fromAtlas(const AtlasInType& a); AxisBox& operator=(const AxisBox& a) = default; bool isEqualTo(const AxisBox& b, CoordType epsilon = numeric_constants<CoordType>::epsilon()) const; bool operator==(const AxisBox& a) const {return isEqualTo(a);} bool operator!=(const AxisBox& a) const {return !isEqualTo(a);} bool isValid() const {return m_low.isValid() && m_high.isValid();} // Descriptive characteristics size_t numCorners() const {return 1 << dim;} Point<dim> getCorner(size_t i) const; Point<dim> getCenter() const {return Midpoint(m_low, m_high);} /// Get a reference to corner 0 const Point<dim>& lowCorner() const {return m_low;} Point<dim>& lowCorner() {return m_low;} /// Get a reference to corner (2^dim)-1 const Point<dim>& highCorner() const {return m_high;} Point<dim>& highCorner() {return m_high;} /// Get the lower bound of the box on the i'th axis CoordType lowerBound(const int axis) const {return m_low[axis];} /// Get the upper bound of the box on the i'th axis CoordType upperBound(const int axis) const {return m_high[axis];} /// Set the box to have opposite corners p1 and p2 /** * The 'ordered' variable may be set to true if p1[i] <= p2[i] for all * i. It is always safe to leave 'ordered' as false, it is a speed * optimization primarily intended for use inside the library. **/ AxisBox& setCorners(const Point<dim>& p1, const Point<dim>& p2, bool ordered = false); // Movement functions AxisBox& shift(const Vector<dim>& v) {m_low += v; m_high += v; return *this;} AxisBox& moveCornerTo(const Point<dim>& p, size_t corner) {return shift(p - getCorner(corner));} AxisBox& moveCenterTo(const Point<dim>& p) {return shift(p - getCenter());} // No rotation functions, this shape can't rotate // Intersection functions AxisBox boundingBox() const {return *this;} Ball<dim> boundingSphere() const; Ball<dim> boundingSphereSloppy() const; AxisBox toParentCoords(const Point<dim>& origin) const {return AxisBox(m_low.toParentCoords(origin), m_high.toParentCoords(origin), true);} AxisBox toParentCoords(const AxisBox<dim>& coords) const {return AxisBox(m_low.toParentCoords(coords), m_high.toParentCoords(coords), true);} // toLocal is just like toParent, expect we reverse the order of // translation and rotation and use the opposite sense of the rotation // matrix AxisBox toLocalCoords(const Point<dim>& origin) const {return AxisBox(m_low.toLocalCoords(origin), m_high.toLocalCoords(origin), true);} AxisBox toLocalCoords(const AxisBox<dim>& coords) const {return AxisBox(m_low.toLocalCoords(coords), m_high.toLocalCoords(coords), true);} /// Return true if the boxes intersect, and set 'out' to their intersection friend bool Intersection<dim>(const AxisBox& a1, const AxisBox& a2, AxisBox& out); /// Get the minimal box that contains a1 and a2 friend AxisBox Union<dim>(const AxisBox& a1, const AxisBox& a2); friend bool Intersect<dim>(const AxisBox& b, const Point<dim>& p, bool proper); friend bool Contains<dim>(const Point<dim>& p, const AxisBox& b, bool proper); friend bool Intersect<dim>(const AxisBox& b1, const AxisBox& b2, bool proper); friend bool Contains<dim>(const AxisBox& outer, const AxisBox& inner, bool proper); friend bool Intersect<dim>(const Ball<dim>& b, const AxisBox& a, bool proper); friend bool Contains<dim>(const Ball<dim>& b, const AxisBox& a, bool proper); friend bool Contains<dim>(const AxisBox& a, const Ball<dim>& b, bool proper); friend bool Intersect<dim>(const Segment<dim>& s, const AxisBox& b, bool proper); friend bool Contains<dim>(const Segment<dim>& s, const AxisBox& b, bool proper); friend bool Intersect<dim>(const RotBox<dim>& r, const AxisBox& b, bool proper); friend bool Contains<dim>(const RotBox<dim>& r, const AxisBox& b, bool proper); friend bool Contains<dim>(const AxisBox& b, const RotBox<dim>& r, bool proper); friend bool Intersect<dim>(const Polygon<dim>& p, const AxisBox& b, bool proper); friend bool Contains<dim>(const Polygon<dim>& p, const AxisBox& b, bool proper); friend bool Contains<dim>(const AxisBox& b, const Polygon<dim>& p, bool proper); private: Point<dim> m_low, m_high; }; template<int dim> inline bool AxisBox<dim>::isEqualTo(const AxisBox<dim>& b, CoordType epsilon) const { return Equal(m_low, b.m_low, epsilon) && Equal(m_high, b.m_high, epsilon); } } // namespace WFMath #endif // WFMATH_AXIS_BOX_H 0707010000001B000081A4000000000000000000000001656C867F000014EA000000000000000000000000000000000000003500000000wfmath-1701611135.403a8bd/src/wfmath/axisbox_funcs.h// axisbox_funcs.h (Axis-aligned box implementation) // // The WorldForge Project // Copyright (C) 2000, 2001 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // // Author: Ron Steinke // The implementation of this class is based on the geometric // parts of the Tree and Placement classes from stage/shepherd/sylvanus #ifndef WFMATH_AXIS_BOX_FUNCS_H #define WFMATH_AXIS_BOX_FUNCS_H #include <wfmath/axisbox.h> #include <wfmath/point.h> #include <wfmath/ball.h> namespace WFMath { template<int dim> bool Intersection(const AxisBox<dim>& a1, const AxisBox<dim>& a2, AxisBox<dim>& out) { for(int i = 0; i < dim; ++i) { out.m_low[i] = FloatMax(a1.m_low[i], a2.m_low[i]); out.m_high[i] = FloatMin(a1.m_high[i], a2.m_high[i]); if(out.m_low[i] > out.m_high[i]) return false; } out.m_low.setValid(a1.m_low.isValid() && a2.m_low.isValid()); out.m_high.setValid(a1.m_high.isValid() && a2.m_high.isValid()); return true; } template<int dim> AxisBox<dim> Union(const AxisBox<dim>& a1, const AxisBox<dim>& a2) { AxisBox<dim> out; for(int i = 0; i < dim; ++i) { out.m_low[i] = FloatMin(a1.m_low[i], a2.m_low[i]); out.m_high[i] = FloatMax(a1.m_high[i], a2.m_high[i]); } out.m_low.setValid(a1.m_low.isValid() && a2.m_low.isValid()); out.m_high.setValid(a1.m_high.isValid() && a2.m_high.isValid()); return out; } template<int dim> AxisBox<dim>& AxisBox<dim>::setCorners(const Point<dim>& p1, const Point<dim>& p2, bool ordered) { if(ordered) { m_low = p1; m_high = p2; return *this; } for(int i = 0; i < dim; ++i) { if(p1[i] > p2[i]) { m_low[i] = p2[i]; m_high[i] = p1[i]; } else { m_low[i] = p1[i]; m_high[i] = p2[i]; } } m_low.setValid(); m_high.setValid(); return *this; } template<int dim> Point<dim> AxisBox<dim>::getCorner(size_t i) const { if(i < 1) return m_low; if(i >= (1 << dim) - 1) return m_high; Point<dim> out; for(int j = 0; j < dim; ++j) out[j] = (i & (1 << j)) ? m_high[j] : m_low[j]; out.setValid(m_low.isValid() && m_high.isValid()); return out; } template<int dim> inline Ball<dim> AxisBox<dim>::boundingSphere() const { return Ball<dim>(getCenter(), Distance(m_low, m_high) / 2); } template<int dim> inline Ball<dim> AxisBox<dim>::boundingSphereSloppy() const { return Ball<dim>(getCenter(), SloppyDistance(m_low, m_high) / 2); } template<int dim, template<class, class> class container> AxisBox<dim> BoundingBox(const container<AxisBox<dim>, std::allocator<AxisBox<dim> > >& c) { typename container<AxisBox<dim>, std::allocator<AxisBox<dim> > >::const_iterator i = c.begin(), end = c.end(); if(i == end) { return AxisBox<dim>(); } Point<dim> low = i->lowCorner(), high = i->highCorner(); bool low_valid = low.isValid(), high_valid = high.isValid(); while(++i != end) { const Point<dim> &new_low = i->lowCorner(), &new_high = i->highCorner(); low_valid = low_valid && new_low.isValid(); high_valid = high_valid && new_high.isValid(); for(int j = 0; j < dim; ++j) { low[j] = FloatMin(low[j], new_low[j]); high[j] = FloatMax(high[j], new_high[j]); } } low.setValid(low_valid); high.setValid(high_valid); return AxisBox<dim>(low, high, true); } template<int dim, template<class, class> class container> AxisBox<dim> BoundingBox(const container<Point<dim>, std::allocator<Point<dim> > >& c) { typename container<Point<dim>, std::allocator<Point<dim> > >::const_iterator i = c.begin(), end = c.end(); if(i == end) { return AxisBox<dim>(); } Point<dim> low = *i, high = *i; bool valid = i->isValid(); while(++i != end) { valid = valid && i->isValid(); for(int j = 0; j < dim; ++j) { low[j] = FloatMin(low[j], (*i)[j]); high[j] = FloatMax(high[j], (*i)[j]); } } low.setValid(valid); high.setValid(valid); return AxisBox<dim>(low, high, true); } // This is here, instead of defined in the class, to // avoid include order problems template<int dim> inline AxisBox<dim> Point<dim>::boundingBox() const { return AxisBox<dim>(*this, *this, true); } template<int dim> Point<dim> Point<dim>::toParentCoords(const AxisBox<dim>& coords) const { return coords.lowCorner() + (*this - Point().setToOrigin()); } template<int dim> Point<dim> Point<dim>::toLocalCoords(const AxisBox<dim>& coords) const { return Point().setToOrigin() + (*this - coords.lowCorner()); } } // namespace WFMath #endif // WFMATH_AXIS_BOX_FUNCS_H 0707010000001C000081A4000000000000000000000001656C867F00000D20000000000000000000000000000000000000002E00000000wfmath-1701611135.403a8bd/src/wfmath/ball.cpp// vector.cpp (Vector<> implementation) // // The WorldForge Project // Copyright (C) 2011 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Alistair Riddoch // Created: 2011-1-27 // Extensive amounts of this material come from the Vector2D // and Vector3D classes from stage/math, written by Bryce W. // Harrington, Kosh, and Jari Sundell (Rakshasa). #include "ball_funcs.h" #include "miniball_funcs.h" #include "vector.h" #include <vector> #include <cmath> namespace WFMath { template<> Ball<3>& Ball<3>::rotateCorner(const Quaternion&, size_t) { return *this; } template<> Ball<3>& Ball<3>::rotateCenter(const Quaternion&) { return *this; } template<> Ball<3>& Ball<3>::rotatePoint(const Quaternion& q, const Point<3>& p) { m_center.rotate(q, p); return *this; } template<> Ball<3> Ball<3>::toParentCoords(const Point<3>& origin, const Quaternion& rotation) const { return Ball<3>(m_center.toParentCoords(origin, rotation), m_radius); } template<> Ball<3> Ball<3>::toLocalCoords(const Point<3>& origin, const Quaternion& rotation) const { return Ball<3>(m_center.toLocalCoords(origin, rotation), m_radius); } template Ball<2> BoundingSphere<2, std::vector>(std::vector<Point<2>, std::allocator<Point<2> > > const&); template Ball<2> BoundingSphereSloppy<2, std::vector>(std::vector<Point<2>, std::allocator<Point<2> > > const&); template Ball<3> BoundingSphere<3, std::vector>(std::vector<Point<3>, std::allocator<Point<3> > > const&); template Ball<3> BoundingSphereSloppy<3, std::vector>(std::vector<Point<3>, std::allocator<Point<3> > > const&); template Ball<2> Point<2>::boundingSphere() const; template Ball<2> Point<2>::boundingSphereSloppy() const; template Ball<3> Point<3>::boundingSphere() const; template Ball<3> Point<3>::boundingSphereSloppy() const; template class Ball<2>; template class Ball<3>; static_assert(std::is_standard_layout<Ball<3>>::value, "Ball should be standard layout."); static_assert(std::is_trivially_copyable<Ball<3>>::value, "Ball should be trivially copyable."); static_assert(std::is_standard_layout<Ball<2>>::value, "Ball should be standard layout."); static_assert(std::is_trivially_copyable<Ball<2>>::value, "Ball should be trivially copyable."); } 0707010000001D000081A4000000000000000000000001656C867F00001DAF000000000000000000000000000000000000002C00000000wfmath-1701611135.403a8bd/src/wfmath/ball.h// ball.h (A n-dimensional ball) // // The WorldForge Project // Copyright (C) 2000, 2001 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // // Author: Ron Steinke #ifndef WFMATH_BALL_H #define WFMATH_BALL_H #include <wfmath/point.h> #include <wfmath/intersect_decls.h> namespace WFMath { template<int dim> class Ball; /// get the minimal bounding sphere for a set of points template<int dim, template<class, class> class container> Ball<dim> BoundingSphere(const container<Point<dim>, std::allocator<Point<dim> > >& c); /// get a bounding sphere for a set of points template<int dim, template<class, class> class container> Ball<dim> BoundingSphereSloppy(const container<Point<dim>, std::allocator<Point<dim> > >& c); template<int dim> std::ostream& operator<<(std::ostream& os, const Ball<dim>& m); template<int dim> std::istream& operator>>(std::istream& is, Ball<dim>& m); /// A dim dimensional ball /** * This class implements the full shape interface, as described in * the fake class Shape. * * This class is called Ball<> instead of Sphere to be more in tune * with the usual mathematical naming conventions, where a ball is * a filled object, while a sphere is just the outer shell. It also * helps that a Ball<n> corresponds to an n-ball, while a Sphere<n> * would correspond to an (n-1)-sphere. **/ template<int dim = 3> class Ball { public: /// construct an uninitialized ball Ball() : m_center{}, m_radius(0) {} /// construct a ball with the given center and radius Ball(const Point<dim>& center, CoordType radius) : m_center(center), m_radius(radius) { if (radius < 0) m_center.setValid(false); } /// construct a copy of a ball Ball(const Ball& b) = default; /// Construct a ball from an object passed by Atlas explicit Ball(const AtlasInType& a); ~Ball() = default; friend std::ostream& operator<< <dim>(std::ostream& os, const Ball& b); friend std::istream& operator>> <dim>(std::istream& is, Ball& b); /// Create an Atlas object from the box AtlasOutType toAtlas() const; /// Set the box's value to that given by an Atlas object void fromAtlas(const AtlasInType& a); Ball& operator=(const Ball& b) = default; bool isEqualTo(const Ball& b, CoordType epsilon = numeric_constants<CoordType>::epsilon()) const; bool operator==(const Ball& b) const {return isEqualTo(b);} bool operator!=(const Ball& b) const {return !isEqualTo(b);} bool isValid() const {return m_center.isValid();} // Descriptive characteristics size_t numCorners() const {return 0;} // This next function exists so that Ball can be used by code // that finds the number of corners with numCorners(), and does something // with each corner with getCorner(). No idea how useful that is, but // it's not a particularly complicated function to write. Point<dim> getCorner(size_t) const {return m_center;} Point<dim> getCenter() const {return m_center;} /// get the center of the ball const Point<dim>& center() const {return m_center;} /// get the center of the ball Point<dim>& center() {return m_center;} /// get the radius of the ball CoordType radius() const {return m_radius;} /// get the radius of the ball CoordType& radius() {return m_radius;} // Movement functions Ball& shift(const Vector<dim>& v) {m_center += v; return *this;} Ball& moveCornerTo(const Point<dim>&, size_t) {return *this;} Ball& moveCenterTo(const Point<dim>& p) {m_center = p; return *this;} Ball& rotateCorner(const RotMatrix<dim>&, size_t) {return *this;} Ball& rotateCenter(const RotMatrix<dim>&) {return *this;} Ball& rotatePoint(const RotMatrix<dim>& m, const Point<dim>& p) {m_center.rotate(m, p); return *this;} // 3D rotation function Ball& rotateCorner(const Quaternion&, size_t corner); Ball& rotateCenter(const Quaternion&); Ball& rotatePoint(const Quaternion& q, const Point<dim>& p); // Intersection functions AxisBox<dim> boundingBox() const; Ball boundingSphere() const {return *this;} Ball boundingSphereSloppy() const {return *this;} Ball toParentCoords(const Point<dim>& origin, const RotMatrix<dim>& rotation = RotMatrix<dim>().identity()) const {return Ball(m_center.toParentCoords(origin, rotation), m_radius);} Ball toParentCoords(const AxisBox<dim>& coords) const {return Ball(m_center.toParentCoords(coords), m_radius);} Ball toParentCoords(const RotBox<dim>& coords) const {return Ball(m_center.toParentCoords(coords), m_radius);} // toLocal is just like toParent, expect we reverse the order of // translation and rotation and use the opposite sense of the rotation // matrix Ball toLocalCoords(const Point<dim>& origin, const RotMatrix<dim>& rotation = RotMatrix<dim>().identity()) const {return Ball(m_center.toLocalCoords(origin, rotation), m_radius);} Ball toLocalCoords(const AxisBox<dim>& coords) const {return Ball(m_center.toLocalCoords(coords), m_radius);} Ball toLocalCoords(const RotBox<dim>& coords) const {return Ball(m_center.toLocalCoords(coords), m_radius);} // 3D only Ball toParentCoords(const Point<dim>& origin, const Quaternion& rotation) const; Ball toLocalCoords(const Point<dim>& origin, const Quaternion& rotation) const; friend bool Intersect<dim>(const Ball& b, const Point<dim>& p, bool proper); friend bool Contains<dim>(const Point<dim>& p, const Ball& b, bool proper); friend bool Intersect<dim>(const Ball& b, const AxisBox<dim>& a, bool proper); friend bool Contains<dim>(const Ball& b, const AxisBox<dim>& a, bool proper); friend bool Contains<dim>(const AxisBox<dim>& a, const Ball& b, bool proper); friend bool Intersect<dim>(const Ball& b1, const Ball& b2, bool proper); friend bool Contains<dim>(const Ball& outer, const Ball& inner, bool proper); friend bool Intersect<dim>(const Segment<dim>& s, const Ball& b, bool proper); friend bool Contains<dim>(const Segment<dim>& s, const Ball& b, bool proper); friend bool Intersect<dim>(const RotBox<dim>& r, const Ball& b, bool proper); friend bool Contains<dim>(const RotBox<dim>& r, const Ball& b, bool proper); friend bool Contains<dim>(const Ball& b, const RotBox<dim>& r, bool proper); friend bool Intersect<dim>(const Polygon<dim>& p, const Ball& b, bool proper); friend bool Contains<dim>(const Polygon<dim>& p, const Ball& b, bool proper); friend bool Contains<dim>(const Ball& b, const Polygon<dim>& p, bool proper); private: Point<dim> m_center; CoordType m_radius; }; template<int dim> inline bool Ball<dim>::isEqualTo(const Ball<dim>& b, CoordType epsilon) const { return Equal(m_center, b.m_center, epsilon) && Equal(m_radius, b.m_radius, epsilon); } } // namespace WFMath #endif // WFMATH_BALL_H 0707010000001E000081A4000000000000000000000001656C867F00001304000000000000000000000000000000000000003200000000wfmath-1701611135.403a8bd/src/wfmath/ball_funcs.h// ball_funcs.h (n-dimensional ball implementation) // // The WorldForge Project // Copyright (C) 2000, 2001 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // // Author: Ron Steinke #ifndef WFMATH_BALL_FUNCS_H #define WFMATH_BALL_FUNCS_H #include <wfmath/ball.h> #include <wfmath/axisbox.h> #include <wfmath/miniball.h> #include <cassert> namespace WFMath { template<int dim> AxisBox<dim> Ball<dim>::boundingBox() const { Point<dim> p_low, p_high; for(int i = 0; i < dim; ++i) { p_low[i] = m_center[i] - m_radius; p_high[i] = m_center[i] + m_radius; } bool valid = m_center.isValid(); p_low.setValid(valid); p_high.setValid(valid); return AxisBox<dim>(p_low, p_high, true); } template<int dim, template<class, class> class container> Ball<dim> BoundingSphere(const container<Point<dim>, std::allocator<Point<dim> > >& c) { _miniball::Miniball<dim> m; _miniball::Wrapped_array<dim> w; typename container<Point<dim>, std::allocator<Point<dim> > >::const_iterator i, end = c.end(); bool valid = true; for(i = c.begin(); i != end; ++i) { valid = valid && i->isValid(); for(int j = 0; j < dim; ++j) w[j] = (*i)[j]; m.check_in(w); } m.build(); #ifndef NDEBUG double dummy; #endif assert("Check that bounding sphere is good to library accuracy" && m.accuracy(dummy) < numeric_constants<CoordType>::epsilon()); w = m.center(); Point<dim> center; for(int j = 0; j < dim; ++j) center[j] = w[j]; center.setValid(valid); return Ball<dim>(center, std::sqrt(m.squared_radius())); } template<int dim, template<class, class> class container> Ball<dim> BoundingSphereSloppy(const container<Point<dim>, std::allocator<Point<dim> > >& c) { // This is based on the algorithm given by Jack Ritter // in Volume 2, Number 4 of Ray Tracing News // <http://www.acm.org/tog/resources/RTNews/html/rtnews7b.html> typename container<Point<dim>, std::allocator<Point<dim> > >::const_iterator i = c.begin(), end = c.end(); if (i == end) { return Ball<dim>(); } CoordType min[dim], max[dim]; typename container<Point<dim>, std::allocator<Point<dim> > >::const_iterator min_p[dim], max_p[dim]; bool valid = i->isValid(); for(int j = 0; j < dim; ++j) { min[j] = max[j] = (*i)[j]; min_p[j] = max_p[j] = i; } while(++i != end) { valid = valid && i->isValid(); for(int j = 0; j < dim; ++j) { if(min[j] > (*i)[j]) { min[j] = (*i)[j]; min_p[j] = i; } if(max[j] < (*i)[j]) { max[j] = (*i)[j]; max_p[j] = i; } } } CoordType span = -1; int direction = -1; for(int j = 0; j < dim; ++j) { CoordType new_span = max[j] - min[j]; if(new_span > span) { span = new_span; direction = j; } } assert("Have a direction of maximum size" && direction != -1); Point<dim> center = Midpoint(*(min_p[direction]), *(max_p[direction])); CoordType dist = SloppyDistance(*(min_p[direction]), center); for(i = c.begin(); i != end; ++i) { if(i == min_p[direction] || i == max_p[direction]) continue; // We already have these CoordType new_dist = SloppyDistance(*i, center); if(new_dist > dist) { CoordType delta_dist = (new_dist - dist) / 2; // Even though new_dist may be too large, delta_dist / new_dist // always gives enough of a shift to include the new point. center += (*i - center) * delta_dist / new_dist; dist += delta_dist; assert("Shifted ball contains new point" && SquaredDistance(*i, center) <= dist * dist); } } center.setValid(valid); return Ball<dim>(center, dist); } // These two are here, instead of defined in the class, to // avoid include order problems template<int dim> inline Ball<dim> Point<dim>::boundingSphere() const { return Ball<dim>(*this, 0); } template<int dim> inline Ball<dim> Point<dim>::boundingSphereSloppy() const { return Ball<dim>(*this, 0); } } // namespace WFMath #endif // WFMATH_BALL_FUNCS_H 0707010000001F000081A4000000000000000000000001656C867F00000970000000000000000000000000000000000000002D00000000wfmath-1701611135.403a8bd/src/wfmath/basis.h// basis.h (Cartesian/polar/spherical conversion for the WFMath library) // // The WorldForge Project // Copyright (C) 2001 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Ron Steinke // Created: 2001-12-15 #ifndef WFMATH_BASIS_H #define WFMATH_BASIS_H #include <wfmath/const.h> #include <cmath> namespace WFMath { // These are used internally in point.cpp and vector.cpp. This header // file is not included in any other, nor are these functions exported, // so we don't install this in $(includedir)/wfmath. // Expects (r, theta) for polar, (x, y) for cart inline void _CartToPolar(const CoordType *in, CoordType *out) { out[0] = std::sqrt(in[0] * in[0] + in[1] * in[1]); out[1] = std::atan2(in[0], in[1]); } // Expects (r, theta) for polar, (x, y) for cart inline void _PolarToCart(const CoordType *in, CoordType *out) { out[0] = in[0] * std::cos(in[1]); out[1] = in[0] * std::sin(in[1]); } // Expects (r, theta, phi) for spherical, (x, y, z) for cart inline void _CartToSpherical(const CoordType *in, CoordType *out) { out[0] = std::sqrt(in[0] * in[0] + in[1] * in[1] + in[2] * in[2]); out[1] = std::atan2(in[2], std::sqrt(in[0] * in[0] + in[1] * in[1])); out[2] = std::atan2(in[0], in[1]); } // Expects (r, theta, phi) for spherical, (x, y, z) for cart inline void _SphericalToCart(const CoordType *in, CoordType *out) { CoordType stheta = std::sin(in[1]); out[0] = in[0] * stheta * std::cos(in[2]); out[1] = in[0] * stheta * std::sin(in[2]); out[2] = in[0] * std::cos(in[1]); } } // namespace WFMath #endif // WFMATH_BASIS_H 07070100000020000081A4000000000000000000000001656C867F00000305000000000000000000000000000000000000003500000000wfmath-1701611135.403a8bd/src/wfmath/bc_sloppy_mag_3print "This is a bc script which computes sloppyMagMax for Vector<3>.\n" print "You have to run it with the -l option to take advantage of the\n" print "math library.\n" scale = 50 p = sqrt(2) - 1 q = sqrt(3) + 1 - (2 * sqrt(2)) print "p = ", p, "\n" print "q = ", q, "\n" r = p / (-2 * q) f = (q - 1) / (3 * q) print "r = ", r, "\n" print "f = ", f, "\n" s = sqrt((f^3) + (r^2)) print "s = ", s, "\n" /* Cube roots */ z1 = e(l(r + s) / 3) z2 = -e(l(s - r) / 3) print "z1 = ", z1, "\n" print "z2 = ", z2, "\n" test = e((l(e(3)) / 3) - 1) print "Test? ", test, "\n" point = z1 + z2 print "point = ", point, "\n" val = 1 / sqrt((1 + (2 * (point^2)))/((1 + (2 * p * point) + (q * (point^2)))^2)) print "val = ", val, "\n" print "sqrt(val) = ", sqrt(val), "\n" 07070100000021000081A4000000000000000000000001656C867F00000E5B000000000000000000000000000000000000002F00000000wfmath-1701611135.403a8bd/src/wfmath/const.cpp// const.cpp (basic comparison functions) // // The WorldForge Project // Copyright (C) 2000, 2001, 2002 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // // Author: Ron Steinke #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <wfmath/const.h> #include <cmath> #include <cassert> // Implementation of IsFloatEqual() is borrowed from Jesse Jones (thanks!). // The comments also belong to him. The names have been changed // to protect the innocent.... // // Comparing floating point numbers for equality is tricky because // the limited precision of the hardware introduces small errors // so that two numbers that should compare equal don't. So what // we do is consider the numbers equal if their difference is less // than some epsilon value. But choosing this epsilon is also tricky // because if the numbers are large epsilon should also be large, // and if the numbers are very small the epsilon must be even smaller. // To get around this we'll use a technique from Knuth's "Seminumerical // Algorithms" section 4.2.2 and scale epsilon by the exponent of // one of the specified numbers. // //--------------------------------------------------------------- namespace WFMath { bool Equal(double x1, double x2, double epsilon) { // If the difference between the numbers is smaller than the // scaled epsilon we'll consider the numbers to be equal. return std::fabs(x1 - x2) <= _ScaleEpsilon(x1, x2, epsilon); } bool Equal(float x1, float x2, float epsilon) { // If the difference between the numbers is smaller than the // scaled epsilon we'll consider the numbers to be equal. return std::fabs(x1 - x2) <= _ScaleEpsilon(x1, x2, epsilon); } double _ScaleEpsilon(double x1, double x2, double epsilon) { // Get the exponent of the smaller of the two numbers (using the // smaller of the two gives us a tighter epsilon value). int exponent; (void) std::frexp(std::fabs(x1) < std::fabs(x2) ? x1 : x2, &exponent); // Scale epsilon by the exponent. return std::ldexp(epsilon, exponent); } float _ScaleEpsilon(float x1, float x2, float epsilon) { // Get the exponent of the smaller of the two numbers (using the // smaller of the two gives us a tighter epsilon value). int exponent; (void) std::frexp(std::fabs(x1) < std::fabs(x2) ? x1 : x2, &exponent); // Scale epsilon by the exponent. return std::ldexp(epsilon, exponent); } CoordType _ScaleEpsilon(const CoordType* x1, const CoordType* x2, int length, CoordType epsilon) { assert(length > 0); CoordType max1 = 0, max2 = 0; for(int i = 0; i < length; ++i) { auto val1 = std::fabs(x1[i]), val2 = std::fabs(x2[i]); if(val1 > max1) max1 = val1; if(val2 > max2) max2 = val2; } return _ScaleEpsilon(max1, max2, epsilon); } } 07070100000022000081A4000000000000000000000001656C867F00001734000000000000000000000000000000000000002D00000000wfmath-1701611135.403a8bd/src/wfmath/const.h// const.h (Defined constants for the WFMath library) // // The WorldForge Project // Copyright (C) 2001, 2002 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Ron Steinke // Created: 2001-12-7 #ifndef WFMATH_CONST_H #define WFMATH_CONST_H #include <limits> #ifdef _MSC_VER #if _MSC_VER < 1500 #error "You are using an older version of MSVC++ with extremely poor" #error "template support. Please use at least version 2008," #error "or try a different compiler." #endif #endif /// Generic library namespace namespace WFMath { // WFMath::Foo::toAtlas() has to return a definite type, // we deal with supporting both 0.4 and 0.6 by forward declaring // types which we define in the AtlasConv header class AtlasInType; class AtlasOutType; template<int dim> class AxisBox; template<int dim> class Ball; template<int dim> class Point; template<int dim> class Polygon; template<int dim> class RotBox; template<int dim> class RotMatrix; template<int dim> class Segment; template<int dim> class Vector; class Quaternion; // Constants /// Determines how close to machine precision the library tries to come. #define WFMATH_PRECISION_FUDGE_FACTOR 30 template<typename FloatType> struct numeric_constants { /// The constant pi static FloatType pi(); /// The square root of pi static FloatType sqrt_pi(); /// The natural logarithm of pi static FloatType log_pi(); /// The square root of 2 static FloatType sqrt2(); /// The square root of 3 static FloatType sqrt3(); /// The natural logarithm of 2 static FloatType log2(); /// This is the attempted precision of the library. static FloatType epsilon(); }; template<> struct numeric_constants<float> { static float pi() { return 3.14159265358979323846264338327950288419716939937508F; } static float sqrt_pi() { return 1.77245385090551602729816748334114518279754945612237F; } static float log_pi() { return 1.14472988584940017414342735135305871164729481291530F; } static float sqrt2() { return 1.41421356237309504880168872420969807856967187537693F; } static float sqrt3() { return 1.73205080756887729352744634150587236694280525381037F; } static float log2() { return 0.69314718055994530941723212145817656807550013436025F; } static float epsilon() { return (WFMATH_PRECISION_FUDGE_FACTOR * std::numeric_limits<float>::epsilon()); } }; template<> struct numeric_constants<double> { static double pi() { return 3.14159265358979323846264338327950288419716939937508; } static double sqrt_pi() { return 1.77245385090551602729816748334114518279754945612237; } static double log_pi() { return 1.14472988584940017414342735135305871164729481291530; } static double sqrt2() { return 1.41421356237309504880168872420969807856967187537693; } static double sqrt3() { return 1.73205080756887729352744634150587236694280525381037; } static double log2() { return 0.69314718055994530941723212145817656807550013436025; } static double epsilon() { return (WFMATH_PRECISION_FUDGE_FACTOR * std::numeric_limits<double>::epsilon()); } }; /// How long we can let RotMatrix and Quaternion go before fixing normalization #define WFMATH_MAX_NORM_AGE ((WFMATH_PRECISION_FUDGE_FACTOR * 2) / 3) /// Basic floating point type typedef double CoordType; // Basic comparisons double _ScaleEpsilon(double x1, double x2, double epsilon); float _ScaleEpsilon(float x1, float x2, float epsilon); CoordType _ScaleEpsilon(const CoordType* x1, const CoordType* x2, int length, CoordType epsilon = numeric_constants<CoordType>::epsilon()); /// Test for equality up to precision epsilon /** * Returns true if the difference between the numbers is less * than epsilon. Note that epsilon is multiplied by 2 raised * to the power of the exponent of the smaller number. So, * for example, Equal(0.00010000, 0.00010002, 1.0e-4) will not * compare equal, but Equal(0.00010000, 0.00010002, 1.0e-3) will. **/ template<class C> inline bool Equal(const C& c1, const C& c2, CoordType epsilon = numeric_constants<CoordType>::epsilon()) {return c1.isEqualTo(c2, epsilon);} bool Equal(double x1, double x2, double epsilon = numeric_constants<double>::epsilon()); // Avoid template and expensive casts from float to doubles. bool Equal(float x1, float x2, float epsilon = numeric_constants<float>::epsilon()); // These let us avoid including <algorithm> for the sake of // std::max() and std::min(). inline CoordType FloatMax(CoordType a, CoordType b) {return (a > b) ? a : b;} inline CoordType FloatMin(CoordType a, CoordType b) {return (a < b) ? a : b;} inline CoordType FloatClamp(CoordType val, CoordType min, CoordType max) {return (min >= val) ? min : (max <= val ? max : val);} inline double DoubleMax(double a, double b) {return (a > b) ? a : b;} inline double DoubleMin(double a, double b) {return (a < b) ? a : b;} inline double DoubleClamp(double val, double min, double max) {return (min >= val) ? min : (max <= val ? max : val);} } // namespace WFMath #endif // WFMATH_CONST_H 07070100000023000081A4000000000000000000000001656C867F000007E1000000000000000000000000000000000000002D00000000wfmath-1701611135.403a8bd/src/wfmath/error.h// -*-C++-*- // error.h (Class structures for errors thrown by the WFMath library) // // The WorldForge Project // Copyright (C) 2001 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Ron Steinke // Created: 2001-12-7 #ifndef WFMATH_ERROR_H #define WFMATH_ERROR_H #include <stdexcept> #include <wfmath/vector.h> namespace WFMath { /// An error thrown by certain functions when passed parallel vectors. template<int dim> struct ColinearVectors : virtual public std::exception { ColinearVectors(const Vector <dim>& v1_in, const Vector <dim>& v2_in) : v1(v1_in), v2(v2_in) {} ColinearVectors(const ColinearVectors& rhs) noexcept : v1(rhs.v1), v2(rhs.v2) {} ~ColinearVectors() noexcept override = default; Vector <dim> v1, v2; const char* what() const noexcept override { return "WFMath::ColinearVectors exception. Supplied vectors are parallel."; } }; /// An error thrown by operator>>() when it fails to parse wfmath types struct ParseError : virtual public std::runtime_error { ParseError() : std::runtime_error("WFMath::ParseError exception.") {} ~ParseError() noexcept override = default; }; } // namespace WFMath #endif // WFMATH_ERROR_H 07070100000024000081A4000000000000000000000001656C867F000008A7000000000000000000000000000000000000003700000000wfmath-1701611135.403a8bd/src/wfmath/int_to_string.cpp#include "const.h" #include "int_to_string.h" #include <climits> namespace WFMath { // This takes a pointer pointing to the character after the end of // a buffer, prints the number into the tail of the buffer, // and returns a pointer to the first character in the number. // Make sure your buffer's big enough, this doesn't check. static char* DoIntToString(unsigned long val, char* bufhead) { // deal with any possible encoding problems const char digits[10] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; *(--bufhead) = '\0'; if(val == 0) *(--bufhead) = '0'; else do { *(--bufhead) = digits[val % 10]; val /= 10; } while(val); return bufhead; } #ifndef _MSC_VER // note that all floating point math is done at compile time static const double log_10_of_2 = 0.30102995664; static const unsigned ul_max_digits = (unsigned) (8 * sizeof(unsigned long) // number of bits * log_10_of_2 // base 10 vs. base 2 digits + 1 // log(1) == 0, have to add one for leading digit + numeric_constants<CoordType>::epsilon()); // err on the safe side of roundoff #else // _MSC_VER static const unsigned ul_max_digits = 10; #endif // _MSC_VER std::string IntToString(unsigned long val) { static const unsigned bufsize = ul_max_digits + 1; // add one for \0 char buffer[bufsize]; return DoIntToString(val, buffer + bufsize); } // Deals with the fact that while, e.g. 0x80000000 (in 32 bit), // is a valid (negative) signed value, the negative // of it can only be expressed as an unsigned quantity. static unsigned long SafeAbs(long val) { #if LONG_MAX + LONG_MIN >= 0 // a signed variable can hold -LONG_MIN, we're completely safe return (val >= 0) ? val : -val; #else if(val >= 0) return val; else if(val >= -LONG_MAX) // -LONG_MAX is a valid signed long return -val; else // LONG_MAX + val < 0 return LONG_MAX + (unsigned long) (-(LONG_MAX + val)); #endif } std::string IntToString(long val) { static const unsigned bufsize = ul_max_digits + 2; // one for \0, one for minus sign char buffer[bufsize]; char* bufhead = DoIntToString(SafeAbs(val), buffer + bufsize); if(val < 0) *(--bufhead) = '-'; return bufhead; } } // namespace WFMath 07070100000025000081A4000000000000000000000001656C867F00000652000000000000000000000000000000000000003500000000wfmath-1701611135.403a8bd/src/wfmath/int_to_string.h// int_to_string.h (Simple integer to std::string conversion) // // The WorldForge Project // Copyright (C) 2001, 2002 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Ron Steinke // Created: 2003-8-4 #ifndef WFMATH_INT_TO_STRING_H #define WFMATH_INT_TO_STRING_H #include <string> namespace WFMath { std::string IntToString(unsigned long); std::string IntToString(long); inline std::string IntToString(unsigned int val) {return IntToString((unsigned long) val);} inline std::string IntToString(int val) {return IntToString((long) val);} inline std::string IntToString(unsigned short val) {return IntToString((unsigned long) val);} inline std::string IntToString(short val) {return IntToString((long) val);} } // namespace WFMath #endif // WFMATH_INT_TO_STRING_H 07070100000026000081A4000000000000000000000001656C867F0000398D000000000000000000000000000000000000003300000000wfmath-1701611135.403a8bd/src/wfmath/intersect.cpp// intersect.cpp (Backends to intersection functions) // // The WorldForge Project // Copyright (C) 2002 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // // Author: Ron Steinke #include "intersect.h" #include <cmath> #include <cassert> namespace WFMath { // The 2d implementation was inspired as a simplification of the 3d. // It used the fact that two not-similarly-oriented rectangles a and b // intersect each other if and only if a's bounding box in b's coordinate // system intersects b, and vice versa. // // To see this, it is only necessary to consider the bounding box intersection // => intersection side of the assertion, since if the rectangles intersect, // clearly their bounding boxes will as well. Let B(a) be the bounding box of // a in b's coordinate system, and A(b) be the bounding box of b in a's coordinate // system. Let the symbol ^ denote intersection. The thing we need to prove is: // // a ^ A(b) && b ^ B(a) => a ^ b // // I will discuss the equivalent statement // // a ^ A(b) && !(a ^ b) => !(b ^ B(a)) // // If a intersects b's bounding box, but does not intersect b, // the intersection of a and A(b) is a rectangle which lies in // one of the four corners of the region A(b) - b (the set of all // points which lie in the bounding box, but not in b). Without // loss of generality, let a ^ A(b) lie in the lower left corner // of A(b) - b. This is a triangular region, two of whose sides // are parts of edges of A(b), the third being a side of b. // Construct a line parallel to the side of b, passing between // b and a ^ A(b). This line never intersects b, since b is a rectangle. // It also never intersects a, since it passes above and to the // right of the upper right corner of a. It also never intersects // B(a), since the upper right side of B(a) is parallel to the // line, but passes through the upper right corner of a. Thus, // this line separates b from B(a), and they do not intersect. QED. template<> bool Intersect<2>(const RotBox<2>& r, const AxisBox<2>& b, bool proper) { const AxisBox<2> b2 = r.boundingBox(); if(!Intersect(b2, b, proper)) return false; RotMatrix<2> m = r.m_orient.inverse(); const AxisBox<2> b3 = RotBox<2>(Point<2>(b.m_low).rotate(m, r.m_corner0), b.m_high - b.m_low, m).boundingBox(); const AxisBox<2> b4(r.m_corner0, r.m_corner0 + r.m_size); return Intersect(b3, b4, proper); } // The 3d implementation is based on the following theorem: // // Theorem: // // Two convex polyhedra do not intersect if and only if there exists a separating // plane which is either parallel to the face of one polyhedron or which is // parallel to at least one edge of each polyhedron. // // Found this in the abstract to the paper: // // Surface-to-surface intersection based on triangular parameter domain subdivision // Ernst Huber // Institute of Computer Graphics // Vienna University of Technology // A-1040 Vienna, Karlsplatz 13/186/1, Austria // // online postscript version of the abstract (where I got this from): // // http://www.cs.ubc.ca/conferences/CCCG/elec_proc/c48.ps.gz // // The paper gives a reference for the theorem (probably the one to really look at // for proof/details): // // S. Gottschalk // Separating Axis Theorem // Technical Report TR96-024 // Department of Computer Science // UNC Chapel Hill // 1996 template<> bool Intersect<3>(const RotBox<3>& r, const AxisBox<3>& b, bool proper) { // Checking intersection of each with the bounding box of // the other in the coordinate system of the first will take care // of the "plane parallel to face" case const AxisBox<3> b2 = r.boundingBox(); if(!Intersect(b2, b, proper)) return false; RotMatrix<3> minv = r.m_orient.inverse(); Vector<3> b_size = b.m_high - b.m_low; const AxisBox<3> b3 = RotBox<3>(Point<3>(b.m_low).rotate(minv, r.m_corner0), b_size, minv).boundingBox(); const AxisBox<3> b4(r.m_corner0, r.m_corner0 + r.m_size); if(!Intersect(b3, b4, proper)) return false; // Now for the "plane parallel to at least one edge of each" case Vector<3> sep = b.m_low - r.m_corner0; const RotMatrix<3> &m = r.m_orient; // Generate normals to the 9 possible separating planes for(int i = 0; i < 3; ++i) { // Generate edge vectors for the RotBox, ignore size, only care about direction // Just access m_orient directly below instead of using r_vec // Vector<3> r_vec = m.row(i); for(int j = 0; j < 3; ++j) { Vector<3> axis; // Cross product, ignore size of b since we only care about direction switch(j) { case 0: axis[0] = 0; axis[1] = -m.elem(i, 2); axis[2] = m.elem(i, 1); break; case 1: axis[0] = m.elem(i, 2); axis[1] = 0; axis[2] = -m.elem(i, 0); break; case 2: axis[0] = -m.elem(i, 1); axis[1] = m.elem(i, 0); axis[2] = 0; break; default: assert(false); } if(axis.sqrMag() < numeric_constants<CoordType>::epsilon() * numeric_constants<CoordType>::epsilon()) { // Parallel edges, this reduces to the 2d case above. We've already // checked the bounding box intersections, so we know they intersect. // We don't need to scale WFMATH_EPSILON, det(m_orient) = 1 // essentially takes care of that. return true; } // Project both boxes on this axis, check for separating plane. // We only need to project two axes per box, the one parallel // to the plane doesn't contribute const int next[] = {1, 2, 0}; CoordType val; CoordType b_low, b_high, r_low, r_high, dist; int k; // AxisBox projection k = next[j]; val = axis[k] * b_size[k]; if(val > 0) { b_high = val; b_low = 0; } else { b_low = val; b_high = 0; } k = next[k]; val = axis[k] * b_size[k]; if(val > 0) b_high += val; else b_low += val; // RotBox projection k = next[i]; val = Dot(m.row(k), axis) * r.m_size[k]; if(val > 0) { r_high = val; r_low = 0; } else { r_low = val; r_high = 0; } k = next[k]; val = Dot(m.row(k), axis) * r.m_size[k]; if(val > 0) r_high += val; else r_low += val; // Distance between basepoints for boxes along this axis dist = Dot(sep, axis); if(_Greater(r_low - dist, b_high, proper) || _Less(r_high - dist, b_low, proper)) return false; } } return true; } // force a bunch of instantiations template bool Intersect<2>(const Point<2>&, const Point<2>&, bool); template bool Intersect<3>(const Point<3>&, const Point<3>&, bool); template bool Contains<2>(const Point<2>&, const Point<2>&, bool); template bool Contains<3>(const Point<3>&, const Point<3>&, bool); template bool Intersect<Point<2>,AxisBox<2> >(const Point<2>&, const AxisBox<2>&, bool); template bool Intersect<Point<3>,AxisBox<3> >(const Point<3>&, const AxisBox<3>&, bool); template bool Contains<2>(const Point<2>&, const AxisBox<2>&, bool); template bool Contains<3>(const Point<3>&, const AxisBox<3>&, bool); template bool Intersect<2>(const AxisBox<2>&, const Point<2>&, bool); template bool Intersect<3>(const AxisBox<3>&, const Point<3>&, bool); template bool Contains<2>(const AxisBox<2>&, const Point<2>&, bool); template bool Contains<3>(const AxisBox<3>&, const Point<3>&, bool); template bool Intersect<2>(const AxisBox<2>&, const AxisBox<2>&, bool); template bool Intersect<3>(const AxisBox<3>&, const AxisBox<3>&, bool); template bool Contains<2>(const AxisBox<2>&, const AxisBox<2>&, bool); template bool Contains<3>(const AxisBox<3>&, const AxisBox<3>&, bool); template bool Intersect<Point<2>,Ball<2> >(const Point<2>&, const Ball<2>&, bool); template bool Intersect<Point<3>,Ball<3> >(const Point<3>&, const Ball<3>&, bool); template bool Contains<2>(const Point<2>&, const Ball<2>&, bool); template bool Contains<3>(const Point<3>&, const Ball<3>&, bool); template bool Intersect<2>(const Ball<2>&, const Point<2>&, bool); template bool Intersect<3>(const Ball<3>&, const Point<3>&, bool); template bool Contains<2>(const Ball<2>&, const Point<2>&, bool); template bool Contains<3>(const Ball<3>&, const Point<3>&, bool); template bool Intersect<AxisBox<2>,Ball<2> >(const AxisBox<2>&, const Ball<2>&, bool); template bool Intersect<AxisBox<3>,Ball<3> >(const AxisBox<3>&, const Ball<3>&, bool); template bool Contains<2>(const AxisBox<2>&, const Ball<2>&, bool); template bool Contains<3>(const AxisBox<3>&, const Ball<3>&, bool); template bool Intersect<2>(const Ball<2>&, const AxisBox<2>&, bool); template bool Intersect<3>(const Ball<3>&, const AxisBox<3>&, bool); template bool Contains<2>(const Ball<2>&, const AxisBox<2>&, bool); template bool Contains<3>(const Ball<3>&, const AxisBox<3>&, bool); template bool Intersect<2>(const Ball<2>&, const Ball<2>&, bool); template bool Intersect<3>(const Ball<3>&, const Ball<3>&, bool); template bool Contains<2>(const Ball<2>&, const Ball<2>&, bool); template bool Contains<3>(const Ball<3>&, const Ball<3>&, bool); template bool Intersect<Point<2>,Segment<2> >(const Point<2>&, const Segment<2>&, bool); template bool Intersect<Point<3>,Segment<3> >(const Point<3>&, const Segment<3>&, bool); template bool Contains<2>(const Point<2>&, const Segment<2>&, bool); template bool Contains<3>(const Point<3>&, const Segment<3>&, bool); template bool Intersect<2>(const Segment<2>&, const Point<2>&, bool); template bool Intersect<3>(const Segment<3>&, const Point<3>&, bool); template bool Contains<2>(const Segment<2>&, const Point<2>&, bool); template bool Contains<3>(const Segment<3>&, const Point<3>&, bool); template bool Intersect<AxisBox<2>,Segment<2> >(const AxisBox<2>&, const Segment<2>&, bool); template bool Intersect<AxisBox<3>,Segment<3> >(const AxisBox<3>&, const Segment<3>&, bool); template bool Contains<2>(const AxisBox<2>&, const Segment<2>&, bool); template bool Contains<3>(const AxisBox<3>&, const Segment<3>&, bool); template bool Intersect<2>(const Segment<2>&, const AxisBox<2>&, bool); template bool Intersect<3>(const Segment<3>&, const AxisBox<3>&, bool); template bool Contains<2>(const Segment<2>&, const AxisBox<2>&, bool); template bool Contains<3>(const Segment<3>&, const AxisBox<3>&, bool); template bool Intersect<Ball<2>,Segment<2> >(const Ball<2>&, const Segment<2>&, bool); template bool Intersect<Ball<3>,Segment<3> >(const Ball<3>&, const Segment<3>&, bool); template bool Contains<2>(const Ball<2>&, const Segment<2>&, bool); template bool Contains<3>(const Ball<3>&, const Segment<3>&, bool); template bool Intersect<2>(const Segment<2>&, const Ball<2>&, bool); template bool Intersect<3>(const Segment<3>&, const Ball<3>&, bool); template bool Contains<2>(const Segment<2>&, const Ball<2>&, bool); template bool Contains<3>(const Segment<3>&, const Ball<3>&, bool); template bool Intersect<2>(const Segment<2>&, const Segment<2>&, bool); template bool Intersect<3>(const Segment<3>&, const Segment<3>&, bool); template bool Contains<2>(const Segment<2>&, const Segment<2>&, bool); template bool Contains<3>(const Segment<3>&, const Segment<3>&, bool); template bool Intersect<Point<2>,RotBox<2> >(const Point<2>&, const RotBox<2>&, bool); template bool Intersect<Point<3>,RotBox<3> >(const Point<3>&, const RotBox<3>&, bool); template bool Contains<2>(const Point<2>&, const RotBox<2>&, bool); template bool Contains<3>(const Point<3>&, const RotBox<3>&, bool); template bool Intersect<2>(const RotBox<2>&, const Point<2>&, bool); template bool Intersect<3>(const RotBox<3>&, const Point<3>&, bool); template bool Contains<2>(const RotBox<2>&, const Point<2>&, bool); template bool Contains<3>(const RotBox<3>&, const Point<3>&, bool); template bool Intersect<AxisBox<2>,RotBox<2> >(const AxisBox<2>&, const RotBox<2>&, bool); template bool Intersect<AxisBox<3>,RotBox<3> >(const AxisBox<3>&, const RotBox<3>&, bool); template bool Contains<2>(const AxisBox<2>&, const RotBox<2>&, bool); template bool Contains<3>(const AxisBox<3>&, const RotBox<3>&, bool); template bool Contains<2>(const RotBox<2>&, const AxisBox<2>&, bool); template bool Contains<3>(const RotBox<3>&, const AxisBox<3>&, bool); template bool Intersect<Ball<2>,RotBox<2> >(const Ball<2>&, const RotBox<2>&, bool); template bool Intersect<Ball<3>,RotBox<3> >(const Ball<3>&, const RotBox<3>&, bool); template bool Contains<2>(const Ball<2>&, const RotBox<2>&, bool); template bool Contains<3>(const Ball<3>&, const RotBox<3>&, bool); template bool Intersect<2>(const RotBox<2>&, const Ball<2>&, bool); template bool Intersect<3>(const RotBox<3>&, const Ball<3>&, bool); template bool Contains<2>(const RotBox<2>&, const Ball<2>&, bool); template bool Contains<3>(const RotBox<3>&, const Ball<3>&, bool); template bool Intersect<Segment<2>,RotBox<2> >(const Segment<2>&, const RotBox<2>&, bool); template bool Intersect<Segment<3>,RotBox<3> >(const Segment<3>&, const RotBox<3>&, bool); template bool Contains<2>(const Segment<2>&, const RotBox<2>&, bool); template bool Contains<3>(const Segment<3>&, const RotBox<3>&, bool); template bool Intersect<2>(const RotBox<2>&, const Segment<2>&, bool); template bool Intersect<3>(const RotBox<3>&, const Segment<3>&, bool); template bool Contains<2>(const RotBox<2>&, const Segment<2>&, bool); template bool Contains<3>(const RotBox<3>&, const Segment<3>&, bool); template bool Intersect<2>(const RotBox<2>&, const RotBox<2>&, bool); template bool Intersect<3>(const RotBox<3>&, const RotBox<3>&, bool); template bool Contains<2>(const RotBox<2>&, const RotBox<2>&, bool); template bool Contains<3>(const RotBox<3>&, const RotBox<3>&, bool); } 07070100000027000081A4000000000000000000000001656C867F000038AD000000000000000000000000000000000000003100000000wfmath-1701611135.403a8bd/src/wfmath/intersect.h// intersect.h (Shape intersection functions) // // The WorldForge Project // Copyright (C) 2002 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // #ifndef WFMATH_INTERSECT_H #define WFMATH_INTERSECT_H #include <wfmath/vector.h> #include <wfmath/point.h> #include <wfmath/const.h> #include <wfmath/intersect_decls.h> #include <wfmath/axisbox.h> #include <wfmath/ball.h> #include <wfmath/segment.h> #include <wfmath/rotbox.h> #include <cmath> namespace WFMath { // Get the reversed order intersect functions (is this safe? FIXME) // No it's not. In the case of an unknown intersection we end up in // a stack crash loop. template<class S1, class S2> inline bool Intersect(const S1& s1, const S2& s2, bool proper) { return Intersect(s2, s1, proper); } // Point<> template<int dim> inline bool Intersect(const Point<dim>& p1, const Point<dim>& p2, bool proper) { return !proper && p1 == p2; } template<int dim, class S> inline bool Contains(const S& s, const Point<dim>& p, bool proper) { return Intersect(p, s, proper); } template<int dim> inline bool Contains(const Point<dim>& p1, const Point<dim>& p2, bool proper) { return !proper && p1 == p2; } // AxisBox<> template<int dim> inline bool Intersect(const AxisBox<dim>& b, const Point<dim>& p, bool proper) { for(int i = 0; i < dim; ++i) if(_Greater(b.m_low[i], p[i], proper) || _Less(b.m_high[i], p[i], proper)) return false; return true; } template<int dim> inline bool Contains(const Point<dim>& p, const AxisBox<dim>& b, bool proper) { return !proper && p == b.m_low && p == b.m_high; } template<int dim> inline bool Intersect(const AxisBox<dim>& b1, const AxisBox<dim>& b2, bool proper) { for(int i = 0; i < dim; ++i) if(_Greater(b1.m_low[i], b2.m_high[i], proper) || _Less(b1.m_high[i], b2.m_low[i], proper)) return false; return true; } template<int dim> inline bool Contains(const AxisBox<dim>& outer, const AxisBox<dim>& inner, bool proper) { for(int i = 0; i < dim; ++i) if(_Less(inner.m_low[i], outer.m_low[i], proper) || _Greater(inner.m_high[i], outer.m_high[i], proper)) return false; return true; } // Ball<> template<int dim> inline bool Intersect(const Ball<dim>& b, const Point<dim>& p, bool proper) { return _LessEq(SquaredDistance(b.m_center, p), b.m_radius * b.m_radius * (1 + numeric_constants<CoordType>::epsilon()), proper); } template<int dim> inline bool Contains(const Point<dim>& p, const Ball<dim>& b, bool proper) { return !proper && b.m_radius == 0 && p == b.m_center; } template<int dim> inline bool Intersect(const Ball<dim>& b, const AxisBox<dim>& a, bool proper) { CoordType dist = 0; for(int i = 0; i < dim; ++i) { CoordType dist_i; if(b.m_center[i] < a.m_low[i]) dist_i = b.m_center[i] - a.m_low[i]; else if(b.m_center[i] > a.m_high[i]) dist_i = b.m_center[i] - a.m_high[i]; else continue; dist+= dist_i * dist_i; } return _LessEq(dist, b.m_radius * b.m_radius, proper); } template<int dim> inline bool Contains(const Ball<dim>& b, const AxisBox<dim>& a, bool proper) { CoordType sqr_dist = 0; for(int i = 0; i < dim; ++i) { CoordType furthest = FloatMax(std::fabs(b.m_center[i] - a.m_low[i]), std::fabs(b.m_center[i] - a.m_high[i])); sqr_dist += furthest * furthest; } return _LessEq(sqr_dist, b.m_radius * b.m_radius * (1 + numeric_constants<CoordType>::epsilon()), proper); } template<int dim> inline bool Contains(const AxisBox<dim>& a, const Ball<dim>& b, bool proper) { for(int i = 0; i < dim; ++i) if(_Less(b.m_center[i] - b.m_radius, a.lowerBound(i), proper) || _Greater(b.m_center[i] + b.m_radius, a.upperBound(i), proper)) return false; return true; } template<int dim> inline bool Intersect(const Ball<dim>& b1, const Ball<dim>& b2, bool proper) { CoordType sqr_dist = SquaredDistance(b1.m_center, b2.m_center); CoordType rad_sum = b1.m_radius + b2.m_radius; return _LessEq(sqr_dist, rad_sum * rad_sum, proper); } template<int dim> inline bool Contains(const Ball<dim>& outer, const Ball<dim>& inner, bool proper) { CoordType rad_diff = outer.m_radius - inner.m_radius; if(_Less(rad_diff, 0, proper)) return false; CoordType sqr_dist = SquaredDistance(outer.m_center, inner.m_center); return _LessEq(sqr_dist, rad_diff * rad_diff, proper); } // Segment<> template<int dim> inline bool Intersect(const Segment<dim>& s, const Point<dim>& p, bool proper) { // This is only true if p lies on the line between m_p1 and m_p2 Vector<dim> v1 = s.m_p1 - p, v2 = s.m_p2 - p; CoordType proj = Dot(v1, v2); if(_Greater(proj, 0, proper)) // p is on the same side of both ends, not between them return false; // Check for colinearity return Equal(proj * proj, v1.sqrMag() * v2.sqrMag()); } template<int dim> inline bool Contains(const Point<dim>& p, const Segment<dim>& s, bool proper) { return !proper && p == s.m_p1 && p == s.m_p2; } template<int dim> bool Intersect(const Segment<dim>& s, const AxisBox<dim>& b, bool proper) { // Use parametric coordinates on the line, where 0 is the location // of m_p1 and 1 is the location of m_p2 // Find the parametric coordinates of the portion of the line // which lies betweens b.lowerBound(i) and b.upperBound(i) for // each i. Find the intersection of those segments and the // segment (0, 1), and check if it's nonzero. CoordType min = 0, max = 1; for(int i = 0; i < dim; ++i) { CoordType dist = s.m_p2[i] - s.m_p1[i]; if(dist == 0) { if(_Less(s.m_p1[i], b.m_low[i], proper) || _Greater(s.m_p1[i], b.m_high[i], proper)) return false; } else { CoordType low = (b.m_low[i] - s.m_p1[i]) / dist; CoordType high = (b.m_high[i] - s.m_p1[i]) / dist; if(low > high) { CoordType tmp = high; high = low; low = tmp; } if(low > min) min = low; if(high < max) max = high; } } return _LessEq(min, max, proper); } template<int dim> inline bool Contains(const Segment<dim>& s, const AxisBox<dim>& b, bool proper) { // This is only possible for zero width or zero height box, // in which case we check for containment of the endpoints. bool got_difference = false; for(int i = 0; i < dim; ++i) { if(b.m_low[i] == b.m_high[i]) continue; if(got_difference) return false; else // It's okay to be different on one axis got_difference = true; } return Contains(s, b.m_low, proper) && (got_difference ? Contains(s, b.m_high, proper) : true); } template<int dim> inline bool Contains(const AxisBox<dim>& b, const Segment<dim>& s, bool proper) { return Contains(b, s.m_p1, proper) && Contains(b, s.m_p2, proper); } template<int dim> bool Intersect(const Segment<dim>& s, const Ball<dim>& b, bool proper) { Vector<dim> line = s.m_p2 - s.m_p1, offset = b.m_center - s.m_p1; // First, see if the closest point on the line to the center of // the ball lies inside the segment CoordType proj = Dot(line, offset); // If the nearest point on the line is outside the segment, // intersection reduces to checking the nearest endpoint. if(proj <= 0) return Intersect(b, s.m_p1, proper); CoordType lineSqrMag = line.sqrMag(); if (proj >= lineSqrMag) return Intersect(b, s.m_p2, proper); Vector<dim> perp_part = offset - line * (proj / lineSqrMag); return _LessEq(perp_part.sqrMag(), b.m_radius * b.m_radius, proper); } template<int dim> inline bool Contains(const Ball<dim>& b, const Segment<dim>& s, bool proper) { return Contains(b, s.m_p1, proper) && Contains(b, s.m_p2, proper); } template<int dim> inline bool Contains(const Segment<dim>& s, const Ball<dim>& b, bool proper) { return b.m_radius == 0 && Contains(s, b.m_center, proper); } template<int dim> bool Intersect(const Segment<dim>& s1, const Segment<dim>& s2, bool proper) { // Check that the lines that contain the segments intersect, and then check // that the intersection point lies within the segments Vector<dim> v1 = s1.m_p2 - s1.m_p1, v2 = s2.m_p2 - s2.m_p1, deltav = s2.m_p1 - s1.m_p1; CoordType v1sqr = v1.sqrMag(), v2sqr = v2.sqrMag(); CoordType proj12 = Dot(v1, v2), proj1delta = Dot(v1, deltav), proj2delta = Dot(v2, deltav); CoordType denom = v1sqr * v2sqr - proj12 * proj12; if(dim > 2 && !Equal(v2sqr * proj1delta * proj1delta + v1sqr * proj2delta * proj2delta, 2 * proj12 * proj1delta * proj2delta + deltav.sqrMag() * denom)) return false; // Skew lines; don't intersect if(denom > 0) { // Find the location of the intersection point in parametric coordinates, // where one end of the segment is at zero and the other at one CoordType coord1 = (v2sqr * proj1delta - proj12 * proj2delta) / denom; CoordType coord2 = -(v1sqr * proj2delta - proj12 * proj1delta) / denom; return _LessEq(coord1, 0, proper) && _LessEq(coord1, 1, proper) && _GreaterEq(coord2, 0, proper) && _GreaterEq(coord2, 1, proper); } else { // Parallel segments, see if one contains an endpoint of the other return Contains(s1, s2.m_p1, proper) || Contains(s1, s2.m_p2, proper) || Contains(s2, s1.m_p1, proper) || Contains(s2, s1.m_p2, proper) // Degenerate case (identical segments), nonzero length || ((proper && s1.m_p1 != s1.m_p2) && ((s1.m_p1 == s2.m_p1 && s1.m_p2 == s2.m_p2) || (s1.m_p1 == s2.m_p2 && s1.m_p2 == s2.m_p1))); } } template<int dim> inline bool Contains(const Segment<dim>& s1, const Segment<dim>& s2, bool proper) { return Contains(s1, s2.m_p1, proper) && Contains(s1, s2.m_p2, proper); } // RotBox<> template<int dim> inline bool Intersect(const RotBox<dim>& r, const Point<dim>& p, bool proper) { // Rotate the point into the internal coordinate system of the box Vector<dim> shift = ProdInv(p - r.m_corner0, r.m_orient); for(int i = 0; i < dim; ++i) { if(r.m_size[i] < 0) { if(_Less(shift[i], r.m_size[i], proper) || _Greater(shift[i], 0, proper)) return false; } else { if(_Greater(shift[i], r.m_size[i], proper) || _Less(shift[i], 0, proper)) return false; } } return true; } template<int dim> inline bool Contains(const Point<dim>& p, const RotBox<dim>& r, bool proper) { if(proper) return false; for(int i = 0; i < dim; ++i) if(r.m_size[i] != 0) return false; return p == r.m_corner0; } template<int dim> bool Intersect(const RotBox<dim>& r, const AxisBox<dim>& b, bool proper); template<int dim> inline bool Contains(const RotBox<dim>& r, const AxisBox<dim>& b, bool proper) { RotMatrix<dim> m = r.m_orient.inverse(); return Contains(AxisBox<dim>(r.m_corner0, r.m_corner0 + r.m_size), RotBox<dim>(Point<dim>(b.m_low).rotate(m, r.m_corner0), b.m_high - b.m_low, m), proper); } template<int dim> inline bool Contains(const AxisBox<dim>& b, const RotBox<dim>& r, bool proper) { return Contains(b, r.boundingBox(), proper); } template<int dim> inline bool Intersect(const RotBox<dim>& r, const Ball<dim>& b, bool proper) { return Intersect(AxisBox<dim>(r.m_corner0, r.m_corner0 + r.m_size), Ball<dim>(r.m_corner0 + ProdInv(b.m_center - r.m_corner0, r.m_orient), b.m_radius), proper); } template<int dim> inline bool Contains(const RotBox<dim>& r, const Ball<dim>& b, bool proper) { return Contains(AxisBox<dim>(r.m_corner0, r.m_corner0 + r.m_size), Ball<dim>(r.m_corner0 + ProdInv(b.m_center - r.m_corner0, r.m_orient), b.m_radius), proper); } template<int dim> inline bool Contains(const Ball<dim>& b, const RotBox<dim>& r, bool proper) { return Contains(Ball<dim>(r.m_corner0 + ProdInv(b.m_center - r.m_corner0, r.m_orient), b.m_radius), AxisBox<dim>(r.m_corner0, r.m_corner0 + r.m_size), proper); } template<int dim> inline bool Intersect(const RotBox<dim>& r, const Segment<dim>& s, bool proper) { Point<dim> p1 = r.m_corner0 + ProdInv(s.m_p1 - r.m_corner0, r.m_orient); Point<dim> p2 = r.m_corner0 + ProdInv(s.m_p2 - r.m_corner0, r.m_orient); return Intersect(AxisBox<dim>(r.m_corner0, r.m_corner0 + r.m_size), Segment<dim>(p1, p2), proper); } template<int dim> inline bool Contains(const RotBox<dim>& r, const Segment<dim>& s, bool proper) { Point<dim> p1 = r.m_corner0 + ProdInv(s.m_p1 - r.m_corner0, r.m_orient); Point<dim> p2 = r.m_corner0 + ProdInv(s.m_p2 - r.m_corner0, r.m_orient); return Contains(AxisBox<dim>(r.m_corner0, r.m_corner0 + r.m_size), Segment<dim>(p1, p2), proper); } template<int dim> inline bool Contains(const Segment<dim>& s, const RotBox<dim>& r, bool proper) { Point<dim> p1 = r.m_corner0 + ProdInv(s.m_p1 - r.m_corner0, r.m_orient); Point<dim> p2 = r.m_corner0 + ProdInv(s.m_p2 - r.m_corner0, r.m_orient); return Contains(Segment<dim>(p1, p2), AxisBox<dim>(r.m_corner0, r.m_corner0 + r.m_size), proper); } template<int dim> inline bool Intersect(const RotBox<dim>& r1, const RotBox<dim>& r2, bool proper) { return Intersect(RotBox<dim>(r1).rotatePoint(r2.m_orient.inverse(), r2.m_corner0), AxisBox<dim>(r2.m_corner0, r2.m_corner0 + r2.m_size), proper); } template<int dim> inline bool Contains(const RotBox<dim>& outer, const RotBox<dim>& inner, bool proper) { return Contains(AxisBox<dim>(outer.m_corner0, outer.m_corner0 + outer.m_size), RotBox<dim>(inner).rotatePoint(outer.m_orient.inverse(), outer.m_corner0), proper); } // Polygon<> intersection functions are in polygon_funcs.h, to avoid // unnecessary inclusion of <vector> } // namespace WFMath #endif // WFMATH_INTERSECT_H 07070100000028000081A4000000000000000000000001656C867F000018D8000000000000000000000000000000000000003700000000wfmath-1701611135.403a8bd/src/wfmath/intersect_decls.h// intersect_decls.h (Declarations for "friend" intersection functions) // // The WorldForge Project // Copyright (C) 2002 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // // Author: Ron Steinke #ifndef WFMATH_INTERSECT_DECLS_H #define WFMATH_INTERSECT_DECLS_H #include <wfmath/const.h> namespace WFMath { // Some Intersect and Contains helper functions inline bool _Less(CoordType x1, CoordType x2, bool proper) { return proper ? x1 <= x2 : (x2 - x1) > numeric_constants<CoordType>::epsilon(); } inline bool _LessEq(CoordType x1, CoordType x2, bool proper) { return !proper ? x1 <= x2 : x1 < x2; } inline bool _Greater(CoordType x1, CoordType x2, bool proper) { return proper ? x1 >= x2 : (x1 - x2) > numeric_constants<CoordType>::epsilon(); } inline bool _GreaterEq(CoordType x1, CoordType x2, bool proper) { return !proper ? x1 >= x2 : x1 > x2; } template<int dim> bool Intersect(const AxisBox<dim>& b, const Point<dim>& p, bool proper); template<int dim> bool Contains(const Point<dim>& p, const AxisBox<dim>& b, bool proper); template<int dim> bool Intersect(const Ball<dim>& b, const Point<dim>& p, bool proper); template<int dim> bool Contains(const Point<dim>& p, const Ball<dim>& b, bool proper); template<int dim> bool Intersect(const Segment<dim>& s, const Point<dim>& p, bool proper); template<int dim> bool Contains(const Point<dim>& p, const Segment<dim>& s, bool proper); template<int dim> bool Intersect(const RotBox<dim>& r, const Point<dim>& p, bool proper); template<int dim> bool Contains(const Point<dim>& p, const RotBox<dim>& r, bool proper); template<int dim> bool Intersect(const AxisBox<dim>& b1, const AxisBox<dim>& b2, bool proper); template<int dim> bool Contains(const AxisBox<dim>& outer, const AxisBox<dim>& inner, bool proper); template<int dim> bool Intersect(const Ball<dim>& b, const AxisBox<dim>& a, bool proper); template<int dim> bool Contains(const Ball<dim>& b, const AxisBox<dim>& a, bool proper); template<int dim> bool Contains(const AxisBox<dim>& a, const Ball<dim>& b, bool proper); template<int dim> bool Intersect(const Segment<dim>& s, const AxisBox<dim>& b, bool proper); template<int dim> bool Contains(const Segment<dim>& s, const AxisBox<dim>& b, bool proper); template<int dim> bool Contains(const AxisBox<dim>& b, const Segment<dim>& s, bool proper); template<int dim> bool Intersect(const RotBox<dim>& r, const AxisBox<dim>& b, bool proper); template<int dim> bool Contains(const RotBox<dim>& r, const AxisBox<dim>& b, bool proper); template<int dim> bool Contains(const AxisBox<dim>& b, const RotBox<dim>& r, bool proper); template<int dim> bool Intersect(const Ball<dim>& b1, const Ball<dim>& b2, bool proper); template<int dim> bool Contains(const Ball<dim>& outer, const Ball<dim>& inner, bool proper); template<int dim> bool Intersect(const Segment<dim>& s, const Ball<dim>& b, bool proper); template<int dim> bool Contains(const Ball<dim>& b, const Segment<dim>& s, bool proper); template<int dim> bool Contains(const Segment<dim>& s, const Ball<dim>& b, bool proper); template<int dim> bool Intersect(const RotBox<dim>& r, const Ball<dim>& b, bool proper); template<int dim> bool Contains(const RotBox<dim>& r, const Ball<dim>& b, bool proper); template<int dim> bool Contains(const Ball<dim>& b, const RotBox<dim>& r, bool proper); template<int dim> bool Intersect(const Segment<dim>& s1, const Segment<dim>& s2, bool proper); template<int dim> bool Contains(const Segment<dim>& s1, const Segment<dim>& s2, bool proper); template<int dim> bool Intersect(const RotBox<dim>& r, const Segment<dim>& s, bool proper); template<int dim> bool Contains(const RotBox<dim>& r, const Segment<dim>& s, bool proper); template<int dim> bool Contains(const Segment<dim>& s, const RotBox<dim>& r, bool proper); template<int dim> bool Intersect(const RotBox<dim>& r1, const RotBox<dim>& r2, bool proper); template<int dim> bool Contains(const RotBox<dim>& outer, const RotBox<dim>& inner, bool proper); template<int dim> bool Intersect(const Polygon<dim>& r, const Point<dim>& p, bool proper); template<int dim> bool Contains(const Point<dim>& p, const Polygon<dim>& r, bool proper); template<int dim> bool Intersect(const Polygon<dim>& p, const AxisBox<dim>& b, bool proper); template<int dim> bool Contains(const Polygon<dim>& p, const AxisBox<dim>& b, bool proper); template<int dim> bool Contains(const AxisBox<dim>& b, const Polygon<dim>& p, bool proper); template<int dim> bool Intersect(const Polygon<dim>& p, const Ball<dim>& b, bool proper); template<int dim> bool Contains(const Polygon<dim>& p, const Ball<dim>& b, bool proper); template<int dim> bool Contains(const Ball<dim>& b, const Polygon<dim>& p, bool proper); template<int dim> bool Intersect(const Polygon<dim>& p, const Segment<dim>& s, bool proper); template<int dim> bool Contains(const Polygon<dim>& p, const Segment<dim>& s, bool proper); template<int dim> bool Contains(const Segment<dim>& s, const Polygon<dim>& p, bool proper); template<int dim> bool Intersect(const Polygon<dim>& p, const RotBox<dim>& r, bool proper); template<int dim> bool Contains(const Polygon<dim>& p, const RotBox<dim>& r, bool proper); template<int dim> bool Contains(const RotBox<dim>& r, const Polygon<dim>& p, bool proper); template<int dim> bool Intersect(const Polygon<dim>& p1, const Polygon<dim>& p2, bool proper); template<int dim> bool Contains(const Polygon<dim>& outer, const Polygon<dim>& inner, bool proper); } // namespace WFMath #endif // WFMATH_INTERSECT_DECLS_H 07070100000029000081A4000000000000000000000001656C867F0000056A000000000000000000000000000000000000002E00000000wfmath-1701611135.403a8bd/src/wfmath/line.cpp// line.cpp (Line<> implementation) // // The WorldForge Project // Copyright (C) 2012 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Alistair Riddoch // Created: 2011-1-27 #include "line_funcs.h" #include <wfmath/axisbox.h> #include <wfmath/ball.h> #include <wfmath/vector.h> namespace WFMath { template class Line<2>; template class Line<3>; static_assert(std::is_standard_layout<Line<3>>::value, "Line should be standard layout."); static_assert(std::is_standard_layout<Line<2>>::value, "Line should be standard layout."); } 0707010000002A000081A4000000000000000000000001656C867F000013E3000000000000000000000000000000000000002C00000000wfmath-1701611135.403a8bd/src/wfmath/line.h// line.h (A segmented line in n-dimensional space) // // The WorldForge Project // Copyright (C) 2012 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // // Author: Ron Steinke #ifndef WFMATH_LINE_H #define WFMATH_LINE_H #include <wfmath/const.h> #include <wfmath/point.h> #include <vector> namespace WFMath { /// A dim dimensional line /** * This class implements the full shape interface, as described in * the fake class Shape. **/ template<int dim = 3> class Line { public: /// Line() = default; /// Line(const Line<dim>& l) = default; /// explicit Line(const AtlasInType& a); /// ~Line() = default; /// Create an Atlas object from the line AtlasOutType toAtlas() const; /// Set the line's value to that given by an Atlas object void fromAtlas(const AtlasInType& a); /// Line& operator=(const Line& a) = default; /// generic: check if two classes are equal, up to a given tolerance bool isEqualTo(const Line& s, CoordType epsilon = numeric_constants<CoordType>::epsilon()) const; /// generic: check if two classes are equal, up to tolerance WFMATH_EPSILON bool operator==(const Line& s) const {return isEqualTo(s);} /// generic: check if two classes are not equal, up to tolerance WFMATH_EPSILON bool operator!=(const Line& s) const {return !isEqualTo(s);} /// generic: returns true if the class instance has been initialized bool isValid() const {return m_points.size() > 1;} // Now we begin with the functions in the shape interface // Descriptive characteristics /// shape: return the number of corners in the shape. /** * For many shape classes, this is a fixed constant **/ size_t numCorners() const {return m_points.size();} /// shape: return the position of the i'th corner, where 0 <= i < numCorners() Point<dim> getCorner(size_t i) const {return m_points[i];} /// shape: return the position of the center of the shape Point<dim> getCenter() const {return Barycenter(m_points);} // Add before i'th corner, zero is beginning, numCorners() is end bool addCorner(size_t i, const Point<dim>& p, CoordType = numeric_constants<CoordType>::epsilon()) {m_points.insert(m_points.begin() + i, p); return true;} // Remove the i'th corner void removeCorner(size_t i) {m_points.erase(m_points.begin() + i);} bool moveCorner(size_t i, const Point<dim>& p, CoordType = numeric_constants<CoordType>::epsilon()) {m_points[i] = p; return true;} // Movement functions /// shape: move the shape by an amount given by the Vector v Line& shift(const Vector<dim>& v); // Move the shape a certain distance /// shape: move the shape, moving the given corner to the Point p /** * The corner in question is getCorner(corner). **/ Line& moveCornerTo(const Point<dim>& p, size_t corner) {return shift(p - getCorner(corner));} /// shape: move the shape, moving the center to the Point p /** * The center is defined by getCenter() **/ Line& moveCenterTo(const Point<dim>& p) {return shift(p - getCenter());} /// shape: rotate the shape while holding the given corner fixed /** * The corner in question is getCorner(corner). **/ Line& rotateCorner(const RotMatrix<dim>& m, size_t corner) {return rotatePoint(m, getCorner(corner));} /// shape: rotate the shape while holding the center fixed /** * The center is defined by getCenter() **/ Line& rotateCenter(const RotMatrix<dim>& m) {return rotatePoint(m, getCenter());} /// shape: rotate the shape while holding the Point p fixed. /** * Note that p can be any Point, it does not have to lie within * the shape. **/ Line& rotatePoint(const RotMatrix<dim>& m, const Point<dim>& p); AxisBox<dim> boundingBox() const {return BoundingBox(m_points);} Ball<dim> boundingSphere() const {return BoundingSphere(m_points);} Ball<dim> boundingSphereSloppy() const {return BoundingSphereSloppy(m_points);} private: std::vector<Point<dim> > m_points; typedef typename std::vector<Point<dim> >::iterator iterator; typedef typename std::vector<Point<dim> >::const_iterator const_iterator; typedef typename std::vector<Point<dim> >::size_type size_type; }; } // namespace WFMath #endif // WFMATH_LINE_H 0707010000002B000081A4000000000000000000000001656C867F00000793000000000000000000000000000000000000003200000000wfmath-1701611135.403a8bd/src/wfmath/line_funcs.h// line_funcs.h (Line<> implementation) // // The WorldForge Project // Copyright (C) 2012 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // // Author: Al Riddoch #ifndef WFMATH_LINE_FUNCS_H #define WFMATH_LINE_FUNCS_H #include <wfmath/line.h> namespace WFMath { template<int dim> inline bool Line<dim>::isEqualTo(const Line<dim> & l, CoordType epsilon) const { size_type size = m_points.size(); if (size != l.m_points.size()) { return false; } for (size_type i = 0; i < size; ++i) { if (!Equal(m_points[i], l.m_points[i], epsilon)) { return false; } } return true; } template<int dim> inline Line<dim>& Line<dim>::shift(const Vector<dim>& v) { for (iterator i = m_points.begin(); i != m_points.end(); ++i) { *i += v; } return *this; } template<int dim> inline Line<dim>& Line<dim>::rotatePoint(const RotMatrix<dim>& m, const Point<dim>& p) { for (iterator i = m_points.begin(); i != m_points.end(); ++i) { i->rotate(m, p); } return *this; } } // namespace WFMath #endif // WFMATH_LINE_FUNCS_H 0707010000002C000081A4000000000000000000000001656C867F0000123E000000000000000000000000000000000000003000000000wfmath-1701611135.403a8bd/src/wfmath/miniball.h // Copright (C) 1999 // $Revision$ // $Date$ // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA, // or download the License terms from prep.ai.mit.edu/pub/gnu/COPYING-2.0. // // Contact: // -------- // Bernd Gaertner // Institut f. Informatik // ETH Zuerich // ETH-Zentrum // CH-8092 Zuerich, Switzerland // http://www.inf.ethz.ch/personal/gaertner // // 2001-1-9: included in WFMath backend. Namespace wrapping added // and filename changed to follow WFMath conventions, but otherwise // unchanged. #ifndef WFMATH_MINIBALL_H #define WFMATH_MINIBALL_H #include <list> #include <wfmath/wrapped_array.h> namespace WFMath { namespace _miniball { template <int d> class Miniball; template <int d> class Basis; // Miniball // -------- template <int d> class Miniball { public: // types typedef Wrapped_array<d> Point; typedef typename std::list<Point>::iterator It; typedef typename std::list<Point>::const_iterator Cit; private: // data members std::list<Point> L; // STL list keeping the points Basis<d> B; // basis keeping the current ball It support_end; // past-the-end iterator of support set // private methods void mtf_mb (It k); void pivot_mb (It k); void move_to_front (It j); double max_excess (It t, It i, It& pivot) const; double abs (double r) const {return (r>0)? r: (-r);} double sqr (double r) const {return r*r;} public: // construction Miniball() : L(), B(), support_end() {} void check_in (const Point& p); void build (bool pivoting = true); // access Point center() const; double squared_radius () const; int nr_points () const; Cit points_begin () const; Cit points_end () const; int nr_support_points () const; Cit support_points_begin () const; Cit support_points_end () const; // checking double accuracy (double& slack) const; bool is_valid (double tolerance = 1e-15) const; }; // Basis // ----- template <int d> class Basis { private: // types typedef Wrapped_array<d> Point; // data members int m, s; // size and number of support points double q0[d]; double z[d+1]; double f[d+1]; double v[d+1][d]; double a[d+1][d]; double c[d+1][d]; double sqr_r[d+1]; double* current_c; // points to some c[j] double current_sqr_r; double sqr (double r) const {return r*r;} public: Basis(); // access const double* center() const; double squared_radius() const; int size() const; int support_size() const; double excess (const Point& p) const; // modification void reset(); // generates empty sphere with m=s=0 bool push (const Point& p); void pop (); // checking double slack() const; }; }} // namespace WFMath::_miniball #endif // WFMATH_MINIBALL_H 0707010000002D000081A4000000000000000000000001656C867F00001F8B000000000000000000000000000000000000003600000000wfmath-1701611135.403a8bd/src/wfmath/miniball_funcs.h // Copright (C) 1999 // $Revision$ // $Date$ // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA, // or download the License terms from prep.ai.mit.edu/pub/gnu/COPYING-2.0. // // Contact: // -------- // Bernd Gaertner // Institut f. Informatik // ETH Zuerich // ETH-Zentrum // CH-8092 Zuerich, Switzerland // http://www.inf.ethz.ch/personal/gaertner // // 2001-1-9: included in WFMath backend. Namespace wrapping added // and filename changed to follow WFMath conventions, but otherwise // unchanged. #ifndef WFMATH_MINIBALL_FUNCS_H #define WFMATH_MINIBALL_FUNCS_H namespace WFMath { namespace _miniball { // Miniball // -------- template <int d> void Miniball<d>::check_in (const Point& p) { L.push_back(p); } template <int d> void Miniball<d>::build (bool pivoting) { B.reset(); support_end = L.begin(); if (pivoting) pivot_mb (L.end()); else mtf_mb (L.end()); } template <int d> void Miniball<d>::mtf_mb (It i) { support_end = L.begin(); if ((B.size())==d+1) return; for (It k=L.begin(); k!=i;) { It j=k++; if (B.excess(*j) > 0) { if (B.push(*j)) { mtf_mb (j); B.pop(); move_to_front(j); } } } } template <int d> void Miniball<d>::move_to_front (It j) { if (support_end == j) support_end++; L.splice (L.begin(), L, j); } template <int d> void Miniball<d>::pivot_mb (It i) { It t = ++L.begin(); mtf_mb (t); double max_e, old_sqr_r; do { It pivot; max_e = max_excess (t, i, pivot); if (max_e <= 0) break; t = support_end; if (t==pivot) ++t; old_sqr_r = B.squared_radius(); B.push (*pivot); mtf_mb (support_end); B.pop(); move_to_front (pivot); } while (B.squared_radius() > old_sqr_r); } template <int d> double Miniball<d>::max_excess (It t, It i, It& pivot) const { const double *c = B.center(), sqr_r = B.squared_radius(); double e, max_e = 0; for (It k=t; k!=i; ++k) { const double *p = (*k).begin(); e = -sqr_r; for (int j=0; j<d; ++j) e += sqr(p[j]-c[j]); if (e > max_e) { max_e = e; pivot = k; } } return max_e; } template <int d> typename Miniball<d>::Point Miniball<d>::center () const { return Point(B.center()); } template <int d> double Miniball<d>::squared_radius () const { return B.squared_radius(); } template <int d> int Miniball<d>::nr_points () const { return L.size(); } template <int d> typename Miniball<d>::Cit Miniball<d>::points_begin () const { return L.begin(); } template <int d> typename Miniball<d>::Cit Miniball<d>::points_end () const { return L.end(); } template <int d> int Miniball<d>::nr_support_points () const { return B.support_size(); } template <int d> typename Miniball<d>::Cit Miniball<d>::support_points_begin () const { return L.begin(); } template <int d> typename Miniball<d>::Cit Miniball<d>::support_points_end () const { return support_end; } template <int d> double Miniball<d>::accuracy (double& slack) const { double e, max_e = 0; int n_supp=0; Cit i; for (i=L.begin(); i!=support_end; ++i,++n_supp) if ((e = abs (B.excess (*i))) > max_e) max_e = e; // you've found a non-numerical problem if the following ever fails assert (n_supp == nr_support_points()); for (i=support_end; i!=L.end(); ++i) if ((e = B.excess (*i)) > max_e) max_e = e; slack = B.slack(); return (max_e/squared_radius()); } template <int d> bool Miniball<d>::is_valid (double tolerance) const { double slack; return ( (accuracy (slack) < tolerance) && (slack == 0) ); } // Basis // ----- template <int d> const double* Basis<d>::center () const { return current_c; } template <int d> double Basis<d>::squared_radius() const { return current_sqr_r; } template <int d> int Basis<d>::size() const { return m; } template <int d> int Basis<d>::support_size() const { return s; } template <int d> double Basis<d>::excess (const Point& p) const { double e = -current_sqr_r; for (int k=0; k<d; ++k) e += sqr(p[k]-current_c[k]); return e; } template <int d> void Basis<d>::reset () { m = s = 0; // we misuse c[0] for the center of the empty sphere for (int j=0; j<d; ++j) c[0][j]=0; current_c = c[0]; current_sqr_r = -1; } template <int d> Basis<d>::Basis () : m(0), s(0), current_c(0), current_sqr_r(-1.) { reset(); } template <int d> void Basis<d>::pop () { --m; } template <int d> bool Basis<d>::push (const Point& p) { int i, j; double eps = 1e-32; if (m==0) { for (i=0; i<d; ++i) q0[i] = p[i]; for (i=0; i<d; ++i) c[0][i] = q0[i]; sqr_r[0] = 0; } else { // set v_m to Q_m for (i=0; i<d; ++i) v[m][i] = p[i]-q0[i]; // compute the a_{m,i}, i< m for (i=1; i<m; ++i) { a[m][i] = 0; for (j=0; j<d; ++j) a[m][i] += v[i][j] * v[m][j]; a[m][i]*=(2/z[i]); } // update v_m to Q_m-\bar{Q}_m for (i=1; i<m; ++i) { for (j=0; j<d; ++j) v[m][j] -= a[m][i]*v[i][j]; } // compute z_m z[m]=0; for (j=0; j<d; ++j) z[m] += sqr(v[m][j]); z[m]*=2; // reject push if z_m too small if (z[m]<eps*current_sqr_r) { return false; } // update c, sqr_r double e = -sqr_r[m-1]; for (i=0; i<d; ++i) e += sqr(p[i]-c[m-1][i]); f[m]=e/z[m]; for (i=0; i<d; ++i) c[m][i] = c[m-1][i]+f[m]*v[m][i]; sqr_r[m] = sqr_r[m-1] + e*f[m]/2; } current_c = c[m]; current_sqr_r = sqr_r[m]; s = ++m; return true; } template <int d> double Basis<d>::slack () const { double l[d+1], min_l=0; l[0] = 1; for (int i=s-1; i>0; --i) { l[i] = f[i]; for (int k=s-1; k>i; --k) l[i]-=a[k][i]*l[k]; if (l[i] < min_l) min_l = l[i]; l[0] -= l[i]; } if (l[0] < min_l) min_l = l[0]; return ( (min_l < 0) ? -min_l : 0); } }} // namespace WFMath::_miniball #endif // WFMATH_MINIBALL_FUNCS_H 0707010000002E000081A4000000000000000000000001656C867F00001340000000000000000000000000000000000000002F00000000wfmath-1701611135.403a8bd/src/wfmath/point.cpp// point.cpp (Point<> backend) // // The WorldForge Project // Copyright (C) 2000, 2001 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // // Author: Ron Steinke #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "point_funcs.h" #include "axisbox_funcs.h" #include "basis.h" #include "quaternion.h" #include <vector> #include <list> namespace WFMath { template<> Point<2>& Point<2>::polar(CoordType r, CoordType theta) { CoordType d[2] = {r, theta}; _PolarToCart(d, m_elem); m_valid = true; return *this; } template<> void Point<2>::asPolar(CoordType& r, CoordType& theta) const { CoordType d[2]; _CartToPolar(m_elem, d); r = d[0]; theta = d[1]; } template<> Point<3>& Point<3>::polar(CoordType r, CoordType theta, CoordType z) { CoordType d[2] = {r, theta}; _PolarToCart(d, m_elem); m_elem[2] = z; m_valid = true; return *this; } template<> void Point<3>::asPolar(CoordType& r, CoordType& theta, CoordType& z) const { CoordType d[2]; _CartToPolar(m_elem, d); r = d[0]; theta = d[1]; z = m_elem[2]; } template<> Point<3>& Point<3>::spherical(CoordType r, CoordType theta, CoordType phi) { CoordType d[3] = {r, theta, phi}; _SphericalToCart(d, m_elem); m_valid = true; return *this; } template<> void Point<3>::asSpherical(CoordType& r, CoordType& theta, CoordType& phi) const { CoordType d[3]; _CartToSpherical(m_elem, d); r = d[0]; theta = d[1]; phi = d[2]; } template<> Point<3>& Point<3>::rotate(const Quaternion& q, const Point<3>& p) { return (*this = p + (*this - p).rotate(q)); } template<> Point<3>& Point<3>::rotatePoint(const Quaternion& q, const Point<3>& p) { return rotate(q, p); } template<> Point<3> Point<3>::toLocalCoords(const Point<3>& origin, const Quaternion& rotation) const { return Point().setToOrigin() + (*this - origin).rotate(rotation.inverse()); } template<> Point<3> Point<3>::toParentCoords(const Point<3>& origin, const Quaternion& rotation) const { return origin + (*this - Point().setToOrigin()).rotate(rotation); } template class Point<3>; template class Point<2>; static_assert(std::is_standard_layout<Point<3>>::value, "Point should be standard layout."); static_assert(std::is_trivially_copyable<Point<3>>::value, "Point should be trivially copyable."); static_assert(std::is_standard_layout<Point<2>>::value, "Point should be standard layout."); static_assert(std::is_trivially_copyable<Point<2>>::value, "Point should be trivially copyable."); template CoordType SquaredDistance<3>(const Point<3> &, const Point<3> &); template CoordType SquaredDistance<2>(const Point<2> &, const Point<2> &); template Point<3> Midpoint<3>(const Point<3> &, const Point<3> &, CoordType); template Point<2> Midpoint<2>(const Point<2> &, const Point<2> &, CoordType); template Point<3> Barycenter<3, std::vector>(const std::vector<Point<3> > &); template Point<3> Barycenter<3, std::vector, std::list>(const std::vector<Point<3> > &, const std::list<CoordType> &); template Point<2> Barycenter<2, std::vector>(const std::vector<Point<2> > &); template Point<2> Barycenter<2, std::vector, std::list>(const std::vector<Point<2> > &, const std::list<CoordType> &); template Vector<3> operator-<3>(const Point<3> &, const Point<3> &); template Vector<2> operator-<2>(const Point<2> &, const Point<2> &); template Point<3> operator-<3>(const Point<3> &, const Vector<3> &); template Point<2> operator-<2>(const Point<2> &, const Vector<2> &); template Point<3>& operator-=<3>(Point<3> &, const Vector<3> &); template Point<2>& operator-=<2>(Point<2> &, const Vector<2> &); template Point<3> operator+<3>(const Vector<3> &, const Point<3> &); template Point<2> operator+<2>(const Vector<2> &, const Point<2> &); template Point<3> operator+<3>(const Point<3> &, const Vector<3> &); template Point<2> operator+<2>(const Point<2> &, const Vector<2> &); template Point<3>& operator+=<3>(Point<3> &, const Vector<3> &); template Point<2>& operator+=<2>(Point<2> &, const Vector<2> &); } // namespace WFMath 0707010000002F000081A4000000000000000000000001656C867F000029C6000000000000000000000000000000000000002D00000000wfmath-1701611135.403a8bd/src/wfmath/point.h// point.h (point class copied from libCoal, subsequently modified) // // The WorldForge Project // Copyright (C) 2000, 2001, 2002 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // // Author: Ron Steinke #ifndef WFMATH_POINT_H #define WFMATH_POINT_H #include <wfmath/const.h> #include <memory> #include <iosfwd> #include <cmath> namespace WFMath { template<int dim> Point<dim>& operator+=(Point<dim>& p, const Vector<dim>& v); template<int dim> Point<dim>& operator-=(Point<dim>& p, const Vector<dim>& v); template<int dim> Vector<dim> operator-(const Point<dim>& c1, const Point<dim>& c2); template<int dim> Point<dim> operator+(const Point<dim>& c, const Vector<dim>& v); template<int dim> Point<dim> operator+(const Vector<dim>& v, const Point<dim>& c); template<int dim> Point<dim> operator-(const Point<dim>& c, const Vector<dim>& v); template<int dim> CoordType SquaredDistance(const Point<dim>& p1, const Point<dim>& p2); template<int dim> CoordType Distance(const Point<dim>& p1, const Point<dim>& p2) {return std::sqrt(SquaredDistance(p1, p2));} template<int dim> CoordType SloppyDistance(const Point<dim>& p1, const Point<dim>& p2) {return (p1 - p2).sloppyMag();} /// Find the center of a set of points, all weighted equally template<int dim, template<class, class> class container> Point<dim> Barycenter(const container<Point<dim>, std::allocator<Point<dim> > >& c); /// Find the center of a set of points with the given weights /** * If the number of points and the number of weights are not equal, * the excess of either is ignored. The weights (or that subset * which is used, if there are more weights than points), must not * sum to zero. **/ template<int dim, template<class, class> class container, template<class, class> class container2> Point<dim> Barycenter(const container<Point<dim>, std::allocator<Point<dim> > >& c, const container2<CoordType, std::allocator<CoordType> >& weights); // This is used a couple of places in the library template<int dim> Point<dim> Midpoint(const Point<dim>& p1, const Point<dim>& p2, CoordType dist = 0.5); template<int dim> std::ostream& operator<<(std::ostream& os, const Point<dim>& m); template<int dim> std::istream& operator>>(std::istream& is, Point<dim>& m); template<typename Shape> class ZeroPrimitive; /// A dim dimensional point /** * This class implements the full shape interface, as described in * the fake class Shape. **/ template<int dim = 3> class Point { friend class ZeroPrimitive<Point<dim> >; public: /// Construct an uninitialized point Point () : m_elem{}, m_valid(false) {}; /// Construct a copy of a point Point (const Point&) = default; /// Construct a point from an object passed by Atlas explicit Point (const AtlasInType& a); /// Construct a point from a vector. explicit Point(const Vector<dim>& vector); /** * @brief Provides a global instance preset to zero. */ static const Point<dim>& ZERO(); friend std::ostream& operator<< <dim>(std::ostream& os, const Point& p); friend std::istream& operator>> <dim>(std::istream& is, Point& p); /// Create an Atlas object from the point AtlasOutType toAtlas() const; /// Set the point's value to that given by an Atlas object void fromAtlas(const AtlasInType& a); Point& operator= (const Point& rhs) = default; bool isEqualTo(const Point &p, CoordType epsilon = numeric_constants<CoordType>::epsilon()) const; bool operator== (const Point& rhs) const {return isEqualTo(rhs);} bool operator!= (const Point& rhs) const {return !isEqualTo(rhs);} bool isValid() const {return m_valid;} /// make isValid() return true if you've initialized the point by hand void setValid(bool valid = true) {m_valid = valid;} /// Set point to (0,0,...,0) Point& setToOrigin(); // Operators // Documented in vector.h friend Vector<dim> operator-<dim>(const Point& c1, const Point& c2); friend Point operator+<dim>(const Point& c, const Vector<dim>& v); friend Point operator-<dim>(const Point& c, const Vector<dim>& v); friend Point operator+<dim>(const Vector<dim>& v, const Point& c); friend Point& operator+=<dim>(Point& p, const Vector<dim>& rhs); friend Point& operator-=<dim>(Point& p, const Vector<dim>& rhs); /// Rotate about point p Point& rotate(const RotMatrix<dim>& m, const Point& p) {return (*this = p + Prod(*this - p, m));} // Functions so that Point<> has the generic shape interface size_t numCorners() const {return 1;} Point<dim> getCorner(size_t) const { return *this;} Point<dim> getCenter() const {return *this;} Point shift(const Vector<dim>& v) {return *this += v;} Point moveCornerTo(const Point& p, size_t) {return operator=(p);} Point moveCenterTo(const Point& p) {return operator=(p);} Point& rotateCorner(const RotMatrix<dim>&, size_t) {return *this;} Point& rotateCenter(const RotMatrix<dim>&) {return *this;} Point& rotatePoint(const RotMatrix<dim>& m, const Point& p) {return rotate(m, p);} // 3D rotation functions Point& rotate(const Quaternion& q, const Point& p); Point& rotateCorner(const Quaternion&, size_t) { return *this;} Point& rotateCenter(const Quaternion&) {return *this;} Point& rotatePoint(const Quaternion& q, const Point& p); // The implementations of these lie in axisbox_funcs.h and // ball_funcs.h, to reduce include dependencies AxisBox<dim> boundingBox() const; Ball<dim> boundingSphere() const; Ball<dim> boundingSphereSloppy() const; Point toParentCoords(const Point& origin, const RotMatrix<dim>& rotation = RotMatrix<dim>().identity()) const {return origin + (*this - Point().setToOrigin()) * rotation;} Point toParentCoords(const AxisBox<dim>& coords) const; Point toParentCoords(const RotBox<dim>& coords) const; // toLocal is just like toParent, expect we reverse the order of // translation and rotation and use the opposite sense of the rotation // matrix Point toLocalCoords(const Point& origin, const RotMatrix<dim>& rotation = RotMatrix<dim>().identity()) const {return Point().setToOrigin() + rotation * (*this - origin);} Point toLocalCoords(const AxisBox<dim>& coords) const; Point toLocalCoords(const RotBox<dim>& coords) const; // 3D only Point toParentCoords(const Point& origin, const Quaternion& rotation) const; Point toLocalCoords(const Point& origin, const Quaternion& rotation) const; // Member access /// Access the i'th coordinate of the point CoordType operator[](const int i) const {return m_elem[i];} /// Access the i'th coordinate of the point CoordType& operator[](const int i) {return m_elem[i];} /// Get the square of the distance from p1 to p2 friend CoordType SquaredDistance<dim>(const Point& p1, const Point& p2); // FIXME instatiation problem when declared as friend // template<template<class> class container> // friend Point Barycenter(const container<Point>& c); /// Find a point on the line containing p1 and p2, by default the midpoint /** * The default value of 0.5 for dist gives the midpoint. A value of 0 gives * p1, and 1 gives p2. Values of dist outside the [0, 1] range are allowed, * and give points on the line which are not on the segment bounded by * p1 and p2. **/ friend Point<dim> Midpoint<dim>(const Point& p1, const Point& p2, CoordType dist); // 2D/3D stuff /// 2D only: construct a point from its (x, y) coordinates Point (CoordType x, CoordType y); // 2D only /// 3D only: construct a point from its (x, y, z) coordinates Point (CoordType x, CoordType y, CoordType z); // 3D only // Label the first three components of the vector as (x,y,z) for // 2D/3D convienience /// access the first component of a point CoordType x() const {return m_elem[0];} /// access the first component of a point CoordType& x() {return m_elem[0];} /// access the second component of a point CoordType y() const {return m_elem[1];} /// access the second component of a point CoordType& y() {return m_elem[1];} /// access the third component of a point CoordType z() const; /// access the third component of a point CoordType& z(); /// 2D only: construct a vector from polar coordinates Point& polar(CoordType r, CoordType theta); /// 2D only: convert a vector to polar coordinates void asPolar(CoordType& r, CoordType& theta) const; /// 3D only: construct a vector from polar coordinates Point& polar(CoordType r, CoordType theta, CoordType z); /// 3D only: convert a vector to polar coordinates void asPolar(CoordType& r, CoordType& theta, CoordType& z) const; /// 3D only: construct a vector from spherical coordinates Point& spherical(CoordType r, CoordType theta, CoordType phi); /// 3D only: convert a vector to spherical coordinates void asSpherical(CoordType& r, CoordType& theta, CoordType& phi) const; const CoordType* elements() const {return m_elem;} private: CoordType m_elem[dim]; bool m_valid; }; template<> inline CoordType Point<3>::z() const { return m_elem[2]; } template<> inline CoordType& Point<3>::z() { return m_elem[2]; } template<int dim> inline Point<dim> operator+(const Point<dim>& c, const Vector<dim>& v) { Point<dim> out(c); out += v; return out; } template<int dim> inline Point<dim> operator+(const Vector<dim>& v, const Point<dim>& c) { Point<dim> out(c); out += v; return out; } template<int dim> inline Point<dim> operator-(const Point<dim>& c, const Vector<dim>& v) { Point<dim> out(c); out -= v; return out; } template<> inline Point<2>::Point(CoordType x, CoordType y) : m_valid(true) { m_elem[0] = x; m_elem[1] = y; } template<> inline Point<3>::Point(CoordType x, CoordType y, CoordType z) : m_valid(true) { m_elem[0] = x; m_elem[1] = y; m_elem[2] = z; } } // namespace WFMath #endif // WFMATH_POINT_H 07070100000030000081A4000000000000000000000001656C867F00001780000000000000000000000000000000000000003300000000wfmath-1701611135.403a8bd/src/wfmath/point_funcs.h// point_funcs.h (point class copied from libCoal, subsequently modified) // // The WorldForge Project // Copyright (C) 2000, 2001, 2002 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // // Author: Ron Steinke #ifndef WFMATH_POINT_FUNCS_H #define WFMATH_POINT_FUNCS_H #include <wfmath/point.h> #include <wfmath/vector.h> #include <wfmath/zero.h> #include <cmath> namespace WFMath { template<int dim> inline Point<dim>::Point(const Vector<dim>& v) : m_valid(v.isValid()) { for(int i = 0; i < dim; ++i) { m_elem[i] = v.elements()[i]; } } template<int dim> const Point<dim>& Point<dim>::ZERO() { static ZeroPrimitive<Point<dim> > zeroPoint(dim); return zeroPoint.getShape(); } template<int dim> inline Point<dim>& Point<dim>::setToOrigin() { for(int i = 0; i < dim; ++i) { m_elem[i] = 0; } m_valid = true; return *this; } template<int dim> inline bool Point<dim>::isEqualTo(const Point<dim> &p, CoordType epsilon) const { //If anyone is invalid they are never equal if (!p.m_valid || !m_valid) { return false; } CoordType delta = _ScaleEpsilon(m_elem, p.m_elem, dim, epsilon); for(int i = 0; i < dim; ++i) { if(std::fabs(m_elem[i] - p.m_elem[i]) > delta) { return false; } } return true; } template<int dim> inline Vector<dim> operator-(const Point<dim>& c1, const Point<dim>& c2) { Vector<dim> out; for(int i = 0; i < dim; ++i) { out.m_elem[i] = c1.m_elem[i] - c2.m_elem[i]; } out.m_valid = c1.m_valid && c2.m_valid; return out; } template<int dim> inline Point<dim>& operator+=(Point<dim>& p, const Vector<dim> &rhs) { for(int i = 0; i < dim; ++i) { p.m_elem[i] += rhs.m_elem[i]; } p.m_valid = p.m_valid && rhs.m_valid; return p; } template<int dim> inline Point<dim>& operator-=(Point<dim>& p, const Vector<dim> &rhs) { for(int i = 0; i < dim; ++i) { p.m_elem[i] -= rhs.m_elem[i]; } p.m_valid = p.m_valid && rhs.m_valid; return p; } template<int dim> inline CoordType SquaredDistance(const Point<dim>& p1, const Point<dim>& p2) { CoordType ans = 0; for(int i = 0; i < dim; ++i) { CoordType diff = p1.m_elem[i] - p2.m_elem[i]; ans += diff * diff; } return (std::fabs(ans) >= _ScaleEpsilon(p1.m_elem, p2.m_elem, dim)) ? ans : 0; } template<int dim, template<class, class> class container, template<class, class> class container2> Point<dim> Barycenter(const container<Point<dim>, std::allocator<Point<dim> > >& c, const container2<CoordType, std::allocator<CoordType> >& weights) { // FIXME become friend typename container<Point<dim>, std::allocator<Point<dim> > >::const_iterator c_i = c.begin(), c_end = c.end(); typename container2<CoordType, std::allocator<CoordType> >::const_iterator w_i = weights.begin(), w_end = weights.end(); Point<dim> out; if (c_i == c_end || w_i == w_end) { return out; } bool valid = c_i->isValid(); CoordType tot_weight = *w_i, max_weight = std::fabs(*w_i); for(int j = 0; j < dim; ++j) { out[j] = (*c_i)[j] * *w_i; } while(++c_i != c_end && ++w_i != w_end) { tot_weight += *w_i; CoordType val = std::fabs(*w_i); if(val > max_weight) max_weight = val; if(!c_i->isValid()) valid = false; for(int j = 0; j < dim; ++j) out[j] += (*c_i)[j] * *w_i; } // Make sure the weights don't add up to zero if (max_weight <= 0 || std::fabs(tot_weight) <= max_weight * numeric_constants<CoordType>::epsilon()) { return out; } for(int j = 0; j < dim; ++j) { out[j] /= tot_weight; } out.setValid(valid); return out; } template<int dim, template<class, class> class container> Point<dim> Barycenter(const container<Point<dim>, std::allocator<Point<dim> > >& c) { // FIXME become friend typename container<Point<dim>, std::allocator<Point<dim> > >::const_iterator i = c.begin(), end = c.end(); if (i == end) { return Point<dim>(); } Point<dim> out = *i; CoordType num_points = 1; bool valid = i->isValid(); while(++i != end) { ++num_points; if(!i->isValid()) valid = false; for(int j = 0; j < dim; ++j) out[j] += (*i)[j]; } for(int j = 0; j < dim; ++j) { out[j] /= num_points; } out.setValid(valid); return out; } template<int dim> inline Point<dim> Midpoint(const Point<dim>& p1, const Point<dim>& p2, CoordType dist) { Point<dim> out; CoordType conj_dist = 1 - dist; for(int i = 0; i < dim; ++i) { out.m_elem[i] = p1.m_elem[i] * conj_dist + p2.m_elem[i] * dist; } out.m_valid = p1.m_valid && p2.m_valid; return out; } template<> Point<2>& Point<2>::polar(CoordType r, CoordType theta); template<> void Point<2>::asPolar(CoordType& r, CoordType& theta) const; template<> Point<3>& Point<3>::polar(CoordType r, CoordType theta, CoordType z); template<> void Point<3>::asPolar(CoordType& r, CoordType& theta, CoordType& z) const; template<> Point<3>& Point<3>::spherical(CoordType r, CoordType theta, CoordType phi); template<> void Point<3>::asSpherical(CoordType& r, CoordType& theta, CoordType& phi) const; } // namespace WFMath #endif // WFMATH_POINT_FUNCS_H 07070100000031000081A4000000000000000000000001656C867F000012E6000000000000000000000000000000000000003100000000wfmath-1701611135.403a8bd/src/wfmath/polygon.cpp// polygon.cpp (Polygon<> implementation) // // The WorldForge Project // Copyright (C) 2002 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Ron Steinke // Created: 2002-1-4 #include "polygon_funcs.h" #include "rotbox.h" namespace WFMath { void Poly2Reorient::reorient(Polygon<2>& poly, size_t skip) const { size_t end = poly.numCorners(); switch(m_type) { case WFMATH_POLY2REORIENT_NONE: return; case WFMATH_POLY2REORIENT_CLEAR_AXIS2: for(size_t i = 0; i != end; ++i) { if(i == skip) continue; (poly[i])[1] = 0; } return; case WFMATH_POLY2REORIENT_CLEAR_BOTH_AXES: for(size_t i = 0; i != end; ++i) { if(i == skip) continue; (poly[i])[0] = 0; (poly[i])[1] = 0; } return; case WFMATH_POLY2REORIENT_MOVE_AXIS2_TO_AXIS1: for(size_t i = 0; i != end; ++i) { if(i == skip) continue; (poly[i])[0] = (poly[i])[1]; (poly[i])[1] = 0; } return; case WFMATH_POLY2REORIENT_SCALE1_CLEAR2: for(size_t i = 0; i != end; ++i) { if(i == skip) continue; (poly[i])[0] *= m_scale; (poly[i])[1] = 0; } return; default: assert(false); return; } } //template<> bool Polygon<2>::isEqualTo(const Polygon<2>& p, CoordType epsilon) const { if(m_points.size() != p.m_points.size()) return false; auto i1 = m_points.begin(), i2 = p.m_points.begin(), end = m_points.end(); while(i1 != end) { if(!Equal(*i1, *i2, epsilon)) return false; ++i1; ++i2; } return true; } bool Polygon<2>::isValid() const { for(const auto & m_point : m_points) { if (!m_point.isValid()) { return false; } } return true; } //template<> Polygon<2>& Polygon<2>::shift(const Vector<2>& v) { for(auto & point : m_points) point += v; return *this; } //template<> Polygon<2>& Polygon<2>::rotatePoint(const RotMatrix<2>& m, const Point<2>& p) { for(auto & point : m_points) point.rotate(m, p); return *this; } //template<> Polygon<2> Polygon<2>::toParentCoords(const Point<2>& origin, const RotMatrix<2>& rotation) const { Polygon out; out.m_points.resize(m_points.size()); for(unsigned i = 0; i < m_points.size(); ++i) out.m_points[i] = m_points[i].toParentCoords(origin, rotation); return out; } //template<> Polygon<2> Polygon<2>::toParentCoords(const AxisBox<2>& coords) const { Polygon out; out.m_points.resize(m_points.size()); for(unsigned i = 0; i < m_points.size(); ++i) out.m_points[i] = m_points[i].toParentCoords(coords); return out; } //template<> Polygon<2> Polygon<2>::toParentCoords(const RotBox<2>& coords) const { Polygon out; out.m_points.resize(m_points.size()); for(unsigned i = 0; i < m_points.size(); ++i) out.m_points[i] = m_points[i].toParentCoords(coords); return out; } //template<> Polygon<2> Polygon<2>::toLocalCoords(const Point<2>& origin, const RotMatrix<2>& rotation) const { Polygon out; out.m_points.resize(m_points.size()); for(unsigned i = 0; i < m_points.size(); ++i) out.m_points[i] = m_points[i].toLocalCoords(origin, rotation); return out; } //template<> Polygon<2> Polygon<2>::toLocalCoords(const AxisBox<2>& coords) const { Polygon out; out.m_points.resize(m_points.size()); for(unsigned i = 0; i < m_points.size(); ++i) out.m_points[i] = m_points[i].toLocalCoords(coords); return out; } //template<> Polygon<2> Polygon<2>::toLocalCoords(const RotBox<2>& coords) const { Polygon out; out.m_points.resize(m_points.size()); for(unsigned i = 0; i < m_points.size(); ++i) out.m_points[i] = m_points[i].toLocalCoords(coords); return out; } template class Polygon<3>; template class Poly2Orient<3>; static_assert(std::is_standard_layout<Polygon<3>>::value, "Polygon should be standard layout."); static_assert(std::is_standard_layout<Polygon<2>>::value, "Polygon should be standard layout."); } 07070100000032000081A4000000000000000000000001656C867F0000491E000000000000000000000000000000000000002F00000000wfmath-1701611135.403a8bd/src/wfmath/polygon.h// polygon.h (A 2D polygon embeded in a <dim> dimensional space) // // The WorldForge Project // Copyright (C) 2002 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // // Author: Ron Steinke #ifndef WFMATH_POLYGON_H #define WFMATH_POLYGON_H #include <wfmath/const.h> #include <wfmath/axisbox.h> #include <wfmath/ball.h> #include <wfmath/quaternion.h> #include <vector> namespace WFMath { template<int dim> class Polygon; template<int dim> std::ostream& operator<<(std::ostream& os, const Polygon<dim>& r); template<int dim> std::istream& operator>>(std::istream& is, Polygon<dim>& r); /// The 2D specialization of the Polygon<> template template<> class Polygon<2> { public: Polygon() = default; Polygon(const Polygon& p) = default; /// Construct a polygon from an object passed by Atlas explicit Polygon(const AtlasInType& a) : m_points() {fromAtlas(a);} ~Polygon() = default; friend std::ostream& operator<< <2>(std::ostream& os, const Polygon& p); friend std::istream& operator>> <2>(std::istream& is, Polygon& p); /// Create an Atlas object from the box AtlasOutType toAtlas() const; /// Set the box's value to that given by an Atlas object void fromAtlas(const AtlasInType& a); Polygon& operator=(const Polygon& p) = default; bool isEqualTo(const Polygon& p, CoordType epsilon = numeric_constants<CoordType>::epsilon()) const; bool operator==(const Polygon& p) const {return isEqualTo(p);} bool operator!=(const Polygon& p) const {return !isEqualTo(p);} bool isValid() const; // Descriptive characteristics size_t numCorners() const {return m_points.size();} Point<2> getCorner(size_t i) const {return m_points[i];} Point<2> getCenter() const {return Barycenter(m_points);} // For a Polygon<2>, addCorner() and moveCorner() always succeed. // The return values are present for the sake of a unified template // interface, and the epsilon argument is ignored // Add before i'th corner, zero is beginning, numCorners() is end bool addCorner(size_t i, const Point<2>& p, CoordType = numeric_constants<CoordType>::epsilon()) {m_points.insert(m_points.begin() + i, p); return true;} // Remove the i'th corner void removeCorner(size_t i) {m_points.erase(m_points.begin() + i);} // Move the i'th corner to p bool moveCorner(size_t i, const Point<2>& p, CoordType = numeric_constants<CoordType>::epsilon()) {m_points[i] = p; return true;} // Remove all points void clear() {m_points.clear();} const Point<2>& operator[](size_t i) const {return m_points[i];} Point<2>& operator[](size_t i) {return m_points[i];} void resize(std::vector<Point<2> >::size_type size) {m_points.resize(size);} // Movement functions Polygon& shift(const Vector<2>& v); Polygon& moveCornerTo(const Point<2>& p, size_t corner) {return shift(p - getCorner(corner));} Polygon& moveCenterTo(const Point<2>& p) {return shift(p - getCenter());} Polygon& rotateCorner(const RotMatrix<2>& m, size_t corner) {rotatePoint(m, getCorner(corner)); return *this;} Polygon& rotateCenter(const RotMatrix<2>& m) {rotatePoint(m, getCenter()); return *this;} Polygon& rotatePoint(const RotMatrix<2>& m, const Point<2>& p); // Intersection functions AxisBox<2> boundingBox() const {return BoundingBox(m_points);} Ball<2> boundingSphere() const {return BoundingSphere(m_points);} Ball<2> boundingSphereSloppy() const {return BoundingSphereSloppy(m_points);} Polygon toParentCoords(const Point<2>& origin, const RotMatrix<2>& rotation = RotMatrix<2>().identity()) const; Polygon toParentCoords(const AxisBox<2>& coords) const; Polygon toParentCoords(const RotBox<2>& coords) const; // toLocal is just like toParent, expect we reverse the order of // translation and rotation and use the opposite sense of the rotation // matrix Polygon toLocalCoords(const Point<2>& origin, const RotMatrix<2>& rotation = RotMatrix<2>().identity()) const; Polygon toLocalCoords(const AxisBox<2>& coords) const; Polygon toLocalCoords(const RotBox<2>& coords) const; friend bool Intersect<2>(const Polygon& r, const Point<2>& p, bool proper); friend bool Contains<2>(const Point<2>& p, const Polygon& r, bool proper); friend bool Intersect<2>(const Polygon& p, const AxisBox<2>& b, bool proper); friend bool Contains<2>(const Polygon& p, const AxisBox<2>& b, bool proper); friend bool Contains<2>(const AxisBox<2>& b, const Polygon& p, bool proper); friend bool Intersect<2>(const Polygon& p, const Ball<2>& b, bool proper); friend bool Contains<2>(const Polygon& p, const Ball<2>& b, bool proper); friend bool Contains<2>(const Ball<2>& b, const Polygon& p, bool proper); friend bool Intersect<2>(const Polygon& p, const Segment<2>& s, bool proper); friend bool Contains<2>(const Polygon& p, const Segment<2>& s, bool proper); friend bool Contains<2>(const Segment<2>& s, const Polygon& p, bool proper); friend bool Intersect<2>(const Polygon& p, const RotBox<2>& r, bool proper); friend bool Contains<2>(const Polygon& p, const RotBox<2>& r, bool proper); friend bool Contains<2>(const RotBox<2>& r, const Polygon& p, bool proper); friend bool Intersect<2>(const Polygon& p1, const Polygon& p2, bool proper); friend bool Contains<2>(const Polygon& outer, const Polygon& inner, bool proper); private: std::vector<Point<2> > m_points; typedef std::vector<Point<2> >::iterator theIter; typedef std::vector<Point<2> >::const_iterator theConstIter; }; // Helper classes, to keep track of the orientation of // a 2D polygon in dim dimensions typedef enum { WFMATH_POLY2REORIENT_NONE, WFMATH_POLY2REORIENT_CLEAR_AXIS2, WFMATH_POLY2REORIENT_CLEAR_BOTH_AXES, WFMATH_POLY2REORIENT_MOVE_AXIS2_TO_AXIS1, WFMATH_POLY2REORIENT_SCALE1_CLEAR2 } Poly2ReorientType; // Reorient a 2D polygon to match a change in the basis // used by Poly2Orient class Poly2Reorient { public: explicit Poly2Reorient(Poly2ReorientType type, CoordType scale = 0.0) : m_type(type), m_scale(scale) {} ~Poly2Reorient() = default; void reorient(Polygon<2>& poly, size_t skip = std::numeric_limits<size_t>::max()) const; private: Poly2ReorientType m_type; CoordType m_scale; }; template<int dim> class Poly2Orient; struct Poly2OrientIntersectData { int dim; Point<2> p1, p2; Vector<2> v1, v2, off; bool o1_is_line, o2_is_line; }; // Finds the intersection of the two planes, returns the // dimension of the intersection space, the rest of the arguments // are various information returned depending on the dimension of // the intersection template<int dim> int Intersect(const Poly2Orient<dim> &, const Poly2Orient<dim> &, Poly2OrientIntersectData &); // Keep track of the orientation of a 2D polygon in dim dimensions template<int dim> class Poly2Orient { public: Poly2Orient() = default; Poly2Orient(const Poly2Orient& p) : m_origin() {operator=(p);} ~Poly2Orient() = default; Poly2Orient& operator=(const Poly2Orient& p) = default; // Convert a point in the 2D polygon to a point in dim dimensional space Point<dim> convert(const Point<2>& p) const; // Try to convert a point from dim dimensions into 2D, expanding the // basis if necessary. Returns true on success. On failure, the // basis is unchanged. bool expand(const Point<dim>& pd, Point<2>& p2, CoordType epsilon = numeric_constants<CoordType>::epsilon()); // Reduce the basis to the minimum necessary to span the points in // poly (with the exception of skip). Returns Poly2Reorient, which needs // to be used to reorient the points to match the new basis. Poly2Reorient reduce(const Polygon<2>& poly, size_t skip = std::numeric_limits<size_t>::max()); void shift(const Vector<dim>& v) {if(m_origin.isValid()) m_origin += v;} void rotate(const RotMatrix<dim>& m, const Point<dim>& p); // Rotates about the point which corresponds to "p" in the oriented plane void rotate2(const RotMatrix<dim>& m, const Point<2>& p); //3D only void rotate(const Quaternion& q, const Point<3>& p); // Rotates about the point which corresponds to "p" in the oriented plane void rotate2(const Quaternion& q, const Point<2>& p); Poly2Orient toParentCoords(const Point<dim>& origin, const RotMatrix<dim>& rotation = RotMatrix<dim>().identity()) const {Poly2Orient p(*this); p.m_origin = m_origin.toParentCoords(origin, rotation); p.m_axes[0].rotate(rotation); p.m_axes[1].rotate(rotation); return p;} Poly2Orient toParentCoords(const AxisBox<dim>& coords) const {Poly2Orient p(*this); p.m_origin = m_origin.toParentCoords(coords); return p;} Poly2Orient toParentCoords(const RotBox<dim>& coords) const {Poly2Orient p(*this); p.m_origin = m_origin.toParentCoords(coords); p.m_axes[0].rotate(coords.orientation()); p.m_axes[1].rotate(coords.orientation()); return p;} // toLocal is just like toParent, expect we reverse the order of // translation and rotation and use the opposite sense of the rotation // matrix Poly2Orient toLocalCoords(const Point<dim>& origin, const RotMatrix<dim>& rotation = RotMatrix<dim>().identity()) const {Poly2Orient p(*this); p.m_origin = m_origin.toLocalCoords(origin, rotation); p.m_axes[0] = rotation * p.m_axes[0]; p.m_axes[1] = rotation * p.m_axes[1]; return p;} Poly2Orient toLocalCoords(const AxisBox<dim>& coords) const {Poly2Orient p(*this); p.m_origin = m_origin.toLocalCoords(coords); return p;} Poly2Orient toLocalCoords(const RotBox<dim>& coords) const {Poly2Orient p(*this); p.m_origin = m_origin.toLocalCoords(coords); p.m_axes[0] = coords.orientation() * p.m_axes[0]; p.m_axes[1] = coords.orientation() * p.m_axes[1]; return p;} // 3D only Poly2Orient<3> toParentCoords(const Point<3>& origin, const Quaternion& rotation) const {Poly2Orient p(*this); p.m_origin = m_origin.toParentCoords(origin, rotation); p.m_axes[0].rotate(rotation); p.m_axes[0].rotate(rotation); return p;} Poly2Orient<3> toLocalCoords(const Point<3>& origin, const Quaternion& rotation) const {Poly2Orient p(*this); p.m_origin = m_origin.toLocalCoords(origin, rotation); p.m_axes[0].rotate(rotation.inverse()); p.m_axes[0].rotate(rotation.inverse()); return p;} // Gives the offset from pd to the space spanned by // the basis, and puts the nearest point in p2. Vector<dim> offset(const Point<dim>& pd, Point<2>& p2) const; // Like offset, but returns true if the point is in the plane bool checkContained(const Point<dim>& pd, Point<2> & p2) const; // Check if the AxisBox intersects the spanned space, and if so // return a point in the intersection. bool checkIntersect(const AxisBox<dim>& b, Point<2>& p2, bool proper) const; friend int Intersect<dim>(const Poly2Orient<dim> &, const Poly2Orient<dim> &, Poly2OrientIntersectData &); private: // special case of the above when both axes are valid bool checkIntersectPlane(const AxisBox<dim>& b, Point<2>& p2, bool proper) const; Point<dim> m_origin; Vector<dim> m_axes[2]; // Normalized to unit length }; /// A polygon, all of whose points lie in a plane, embedded in dim dimensions template<int dim = 3> class Polygon { public: Polygon() : m_orient(), m_poly() {} Polygon(const Polygon& p) : m_orient(p.m_orient), m_poly(p.m_poly) {} ~Polygon() = default; friend std::ostream& operator<< <dim>(std::ostream& os, const Polygon& p); friend std::istream& operator>> <dim>(std::istream& is, Polygon& p); Polygon& operator=(const Polygon& p) {m_orient = p.m_orient; m_poly = p.m_poly; return *this;} bool isEqualTo(const Polygon& p2, CoordType epsilon = numeric_constants<CoordType>::epsilon()) const; bool operator==(const Polygon& p) const {return isEqualTo(p);} bool operator!=(const Polygon& p) const {return !isEqualTo(p);} bool isValid() const {return m_poly.isValid();} // Descriptive characteristics size_t numCorners() const {return m_poly.numCorners();} Point<dim> getCorner(size_t i) const {return m_orient.convert(m_poly[i]);} Point<dim> getCenter() const {return m_orient.convert(m_poly.getCenter());} // The failure of the following functions does not invalidate the // polygon, but merely leaves it unchaged. // Add before i'th corner, zero is beginning, numCorners() is end // Only succeeds if p lies in a plane with all current points bool addCorner(size_t i, const Point<dim>& p, CoordType epsilon = numeric_constants<CoordType>::epsilon()); // Remove the i'th corner void removeCorner(size_t i); // Move the i'th corner to p, only succeeds if new location // lies in the same plane as all the other points. Note that, // under certain circumstances, this plane may not contain the // original location of the point. bool moveCorner(size_t i, const Point<dim>& p, CoordType epsilon = numeric_constants<CoordType>::epsilon()); // Remove all points void clear() {m_poly.clear(); m_orient = Poly2Orient<dim>();} // Movement functions Polygon& shift(const Vector<dim>& v) {m_orient.shift(v); return *this;} Polygon& moveCornerTo(const Point<dim>& p, size_t corner) {return shift(p - getCorner(corner));} Polygon& moveCenterTo(const Point<dim>& p) {return shift(p - getCenter());} Polygon& rotateCorner(const RotMatrix<dim>& m, size_t corner) {m_orient.rotate2(m, m_poly[corner]); return *this;} Polygon& rotateCenter(const RotMatrix<dim>& m) {if(m_poly.numCorners() > 0) m_orient.rotate2(m, m_poly.getCenter()); return *this;} Polygon& rotatePoint(const RotMatrix<dim>& m, const Point<dim>& p) {m_orient.rotate(m, p); return *this;} // 3D rotation functions Polygon<3>& rotateCorner(const Quaternion& q, size_t corner) {m_orient.rotate2(q, m_poly[corner]); return *this;} Polygon<3>& rotateCenter(const Quaternion& q) {if(m_poly.numCorners() > 0) m_orient.rotate2(q, m_poly.getCenter()); return *this;} Polygon<3>& rotatePoint(const Quaternion& q, const Point<3>& p) {m_orient.rotate(q, p); return *this;} // Intersection functions AxisBox<dim> boundingBox() const; Ball<dim> boundingSphere() const; Ball<dim> boundingSphereSloppy() const; Polygon toParentCoords(const Point<dim>& origin, const RotMatrix<dim>& rotation = RotMatrix<dim>().identity()) const {Polygon p(*this); p.m_orient = m_orient.toParentCoords(origin, rotation); return p;} Polygon toParentCoords(const AxisBox<dim>& coords) const {Polygon p(*this); p.m_orient = m_orient.toParentCoords(coords); return p;} Polygon toParentCoords(const RotBox<dim>& coords) const {Polygon p(*this); p.m_orient = m_orient.toParentCoords(coords); return p;} // toLocal is just like toParent, expect we reverse the order of // translation and rotation and use the opposite sense of the rotation // matrix Polygon toLocalCoords(const Point<dim>& origin, const RotMatrix<dim>& rotation = RotMatrix<dim>().identity()) const {Polygon p(*this); p.m_orient = m_orient.toLocalCoords(origin, rotation); return p;} Polygon toLocalCoords(const AxisBox<dim>& coords) const {Polygon p(*this); p.m_orient = m_orient.toLocalCoords(coords); return p;} Polygon toLocalCoords(const RotBox<dim>& coords) const {Polygon p(*this); p.m_orient = m_orient.toLocalCoords(coords); return p;} // 3D only Polygon<3> toParentCoords(const Point<3>& origin, const Quaternion& rotation) const {Polygon<3> p(*this); p.m_orient = m_orient.toParentCoords(origin, rotation); return p;} Polygon<3> toLocalCoords(const Point<3>& origin, const Quaternion& rotation) const {Polygon<3> p(*this); p.m_orient = m_orient.toLocalCoords(origin, rotation); return p;} friend bool Intersect<dim>(const Polygon& r, const Point<dim>& p, bool proper); friend bool Contains<dim>(const Point<dim>& p, const Polygon& r, bool proper); friend bool Intersect<dim>(const Polygon& p, const AxisBox<dim>& b, bool proper); friend bool Contains<dim>(const Polygon& p, const AxisBox<dim>& b, bool proper); friend bool Contains<dim>(const AxisBox<dim>& b, const Polygon& p, bool proper); friend bool Intersect<dim>(const Polygon& p, const Ball<dim>& b, bool proper); friend bool Contains<dim>(const Polygon& p, const Ball<dim>& b, bool proper); friend bool Contains<dim>(const Ball<dim>& b, const Polygon& p, bool proper); friend bool Intersect<dim>(const Polygon& p, const Segment<dim>& s, bool proper); friend bool Contains<dim>(const Polygon& p, const Segment<dim>& s, bool proper); friend bool Contains<dim>(const Segment<dim>& s, const Polygon& p, bool proper); friend bool Intersect<dim>(const Polygon& p, const RotBox<dim>& r, bool proper); friend bool Contains<dim>(const Polygon& p, const RotBox<dim>& r, bool proper); friend bool Contains<dim>(const RotBox<dim>& r, const Polygon& p, bool proper); friend bool Intersect<dim>(const Polygon& p1, const Polygon& p2, bool proper); friend bool Contains<dim>(const Polygon& outer, const Polygon& inner, bool proper); private: Poly2Orient<dim> m_orient; Polygon<2> m_poly; }; template<int dim> inline bool Polygon<dim>::addCorner(size_t i, const Point<dim>& p, CoordType epsilon) { Point<2> p2; bool succ = m_orient.expand(p, p2, epsilon); if(succ) m_poly.addCorner(i, p2, epsilon); return succ; } template<int dim> inline void Polygon<dim>::removeCorner(size_t i) { m_poly.removeCorner(i); Poly2Reorient r = m_orient.reduce(m_poly); r.reorient(m_poly); } template<int dim> inline bool Polygon<dim>::moveCorner(size_t i, const Point<dim>& p, CoordType epsilon) { Poly2Orient<dim> try_orient = m_orient; Poly2Reorient r = try_orient.reduce(m_poly, i); Point<2> p2; if(!try_orient.expand(p, p2, epsilon)) return false; r.reorient(m_poly, i); m_poly[i] = p2; m_orient = try_orient; return true; } } // namespace WFMath #endif // WFMATH_POLYGON_H 07070100000033000081A4000000000000000000000001656C867F00002419000000000000000000000000000000000000003500000000wfmath-1701611135.403a8bd/src/wfmath/polygon_funcs.h// polygon_funcs.h (line polygon implementation) // // The WorldForge Project // Copyright (C) 2002 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // // Author: Ron Steinke #ifndef WFMATH_POLYGON_FUNCS_H #define WFMATH_POLYGON_FUNCS_H #include <wfmath/polygon.h> #include <wfmath/vector.h> #include <wfmath/point.h> #include <wfmath/ball.h> #include <cmath> #include <cassert> #include <limits> namespace WFMath { template<int dim> inline bool Polygon<dim>::isEqualTo(const Polygon<dim>& p, CoordType epsilon) const { // The same polygon can be expressed in different ways in the interal // format, so we have to call getCorner(); size_t size = m_poly.numCorners(); if(size != p.m_poly.numCorners()) return false; for(size_t i = 0; i < size; ++i) if(!Equal(getCorner(i), p.getCorner(i), epsilon)) return false; return true; } template<int dim> inline Point<dim> Poly2Orient<dim>::convert(const Point<2>& p) const { assert(m_origin.isValid()); Point<dim> out = m_origin; for(int j = 0; j < 2; ++j) { if(m_axes[j].isValid()) out += m_axes[j] * p[j]; else assert(p[j] == 0); } out.setValid(p.isValid()); return out; } template<int dim> bool Poly2Orient<dim>::expand(const Point<dim>& pd, Point<2>& p2, CoordType epsilon) { p2[0] = p2[1] = 0; // initialize p2.setValid(); if(!m_origin.isValid()) { // Adding to an empty list m_origin = pd; m_origin.setValid(); return true; } Vector<dim> shift = pd - m_origin, start_shift = shift; CoordType bound = shift.sqrMag() * epsilon; int j = 0; while(true) { if(Dot(shift, start_shift) <= bound) // shift is effectively zero return true; if(j == 2) { // Have two axes, shift doesn't lie in their plane p2.setValid(false); return false; } if(!m_axes[j].isValid()) { // Didn't span this previously, now we do p2[j] = shift.mag(); m_axes[j] = shift / p2[j]; m_axes[j].setValid(); return true; } p2[j] = Dot(shift, m_axes[j]); shift -= m_axes[j] * p2[j]; // shift is now perpendicular to m_axes[j] ++j; } } template<int dim> Poly2Reorient Poly2Orient<dim>::reduce(const Polygon<2>& poly, size_t skip) { if(poly.numCorners() <= ((skip == 0) ? 1 : 0)) { // No corners left m_origin.setValid(false); m_axes[0].setValid(false); m_axes[1].setValid(false); return Poly2Reorient(WFMATH_POLY2REORIENT_NONE); } assert(m_origin.isValid()); if(!m_axes[0].isValid()) return Poly2Reorient(WFMATH_POLY2REORIENT_NONE); // Check that we still span both axes bool still_valid[2] = {false,}, got_ratio = false; CoordType ratio = std::numeric_limits<CoordType>::max(); CoordType size = std::numeric_limits<CoordType>::max(); CoordType epsilon; size_t i, end = poly.numCorners(); // scale epsilon for(i = 0; i < end; ++i) { if(i == skip) continue; const Point<2> &p = poly[i]; CoordType x = std::fabs(p[0]), y = std::fabs(p[1]), max = (x > y) ? x : y; if(i == 0 || max < size) size = max; } int exponent; (void) std::frexp(size, &exponent); epsilon = std::ldexp(numeric_constants<CoordType>::epsilon(), exponent); i = 0; if(skip == 0) ++i; assert(i != end); Point<2> first_point = poly[i]; first_point.setValid(); // in case someone stuck invalid points in the poly while(++i != end) { if(i == skip) continue; Vector<2> diff = poly[i] - first_point; if(diff.sqrMag() < epsilon * epsilon) // No addition to span continue; if(!m_axes[1].isValid()) // We span 1D return Poly2Reorient(WFMATH_POLY2REORIENT_NONE); for(int j = 0; j < 2; ++j) { if(std::fabs(diff[j]) < epsilon) { assert(diff[j ? 0 : 1] >= epsilon); // because diff != 0 if(still_valid[j ? 0 : 1] || got_ratio) // We span a 2D space return Poly2Reorient(WFMATH_POLY2REORIENT_NONE); still_valid[j] = true; } } // The point has both elements nonzero if(still_valid[0] || still_valid[1]) // We span a 2D space return Poly2Reorient(WFMATH_POLY2REORIENT_NONE); CoordType new_ratio = diff[1] / diff[0]; if(!got_ratio) { ratio = new_ratio; got_ratio = true; continue; } if(!Equal(ratio, new_ratio)) // We span a 2D space return Poly2Reorient(WFMATH_POLY2REORIENT_NONE); } // Okay, we don't span both vectors. What now? if(still_valid[0]) { assert(m_axes[1].isValid()); assert(!still_valid[1]); assert(!got_ratio); // This is easy, m_axes[1] is just invalid m_origin += m_axes[1] * first_point[1]; m_axes[1].setValid(false); return Poly2Reorient(WFMATH_POLY2REORIENT_CLEAR_AXIS2); } if(still_valid[1]) { assert(m_axes[1].isValid()); assert(!got_ratio); // This is a little harder, m_axes[0] is invalid, must swap axes m_origin += m_axes[0] * first_point[0]; m_axes[0] = m_axes[1]; m_axes[1].setValid(false); return Poly2Reorient(WFMATH_POLY2REORIENT_MOVE_AXIS2_TO_AXIS1); } // The !m_axes[1].isValid() case reducing to a point falls into here if(!got_ratio) { // Nothing's valid, all points are equal m_origin += m_axes[0] * first_point[0]; if(m_axes[1].isValid()) m_origin += m_axes[1] * first_point[1]; m_axes[0].setValid(false); m_axes[1].setValid(false); return Poly2Reorient(WFMATH_POLY2REORIENT_CLEAR_BOTH_AXES); } assert(m_axes[1].isValid()); // All the points are colinear, along some line which is not parallel // to either of the original axes Vector<dim> new0; new0 = m_axes[0] + m_axes[1] * ratio; CoordType norm = new0.mag(); new0 /= norm; // Vector diff = m_axes[0] * first_point[0] + m_axes[1] * first_point[1]; // // Causes Dot(diff, m_axes[0]) to vanish, so the point on the line // // with x coordinate zero is the new origin // diff -= new0 * (first_point[0] * norm); // m_origin += diff; // or, equivalently m_origin += m_axes[1] * (first_point[1] - ratio * first_point[0]); m_axes[0] = new0; m_axes[1].setValid(false); return Poly2Reorient(WFMATH_POLY2REORIENT_SCALE1_CLEAR2, norm); } template<int dim> inline void Poly2Orient<dim>::rotate(const RotMatrix<dim>& m, const Point<dim>& p) { m_origin.rotate(m, p); for(int j = 0; j < 2; ++j) m_axes[j] = Prod(m_axes[j], m); } template<int dim> void Poly2Orient<dim>::rotate2(const RotMatrix<dim>& m, const Point<2>& p) { assert(m_origin.isValid()); if(!m_axes[0].isValid()) { assert(p[0] == 0 && p[1] == 0); return; } Vector<dim> shift = m_axes[0] * p[0]; m_axes[0] = Prod(m_axes[0], m); if(m_axes[1].isValid()) { shift += m_axes[1] * p[1]; m_axes[1] = Prod(m_axes[1], m); } else assert(p[1] == 0); m_origin += shift - Prod(shift, m); } template<> inline void Poly2Orient<3>::rotate(const Quaternion& q, const Point<3>& p) { m_origin.rotate(q, p); for(int j = 0; j < 2; ++j) m_axes[j].rotate(q); } template<> inline void Poly2Orient<3>::rotate2(const Quaternion& q, const Point<2>& p) { assert(m_origin.isValid()); if(!m_axes[0].isValid()) { assert(p[0] == 0 && p[1] == 0); return; } Vector<3> shift = m_axes[0] * p[0]; m_axes[0].rotate(q); if(m_axes[1].isValid()) { shift += m_axes[1] * p[1]; m_axes[1].rotate(q); } else assert(p[1] == 0); m_origin += shift - shift.rotate(q); } template<int dim> AxisBox<dim> Polygon<dim>::boundingBox() const { assert(m_poly.numCorners() > 0); Point<dim> min = m_orient.convert(m_poly[0]), max = min; bool valid = min.isValid(); for(size_t i = 1; i != m_poly.numCorners(); ++i) { Point<dim> p = m_orient.convert(m_poly[i]); valid = valid && p.isValid(); for(int j = 0; j < dim; ++j) { if(p[j] < min[j]) min[j] = p[j]; if(p[j] > max[j]) max[j] = p[j]; } } min.setValid(valid); max.setValid(valid); return AxisBox<dim>(min, max, true); } template<int dim> inline Ball<dim> Polygon<dim>::boundingSphere() const { Ball<2> b = m_poly.boundingSphere(); return Ball<dim>(m_orient.convert(b.center()), b.radius()); } template<int dim> inline Ball<dim> Polygon<dim>::boundingSphereSloppy() const { Ball<2> b = m_poly.boundingSphereSloppy(); return Ball<dim>(m_orient.convert(b.center()), b.radius()); } } // namespace WFMath #endif // WFMATH_POLYGON_FUNCS_H 07070100000034000081A4000000000000000000000001656C867F0000C40D000000000000000000000000000000000000003B00000000wfmath-1701611135.403a8bd/src/wfmath/polygon_intersect.cpp// polygon_intersect.cpp (Polygon<2> intersection functions) // // The WorldForge Project // Copyright (C) 2002 Ron Steinke and The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Ron Steinke // Created: 2002-2-20 #include "polygon_intersect.h" #include "segment.h" #include "rotbox.h" #include <algorithm> #include <list> #include <cassert> namespace WFMath { template<int dim> inline Vector<dim> Poly2Orient<dim>::offset(const Point<dim>& pd, Point<2>& p2) const { assert(m_origin.isValid()); // Check for empty polygon before calling this Vector<dim> out = pd - m_origin; for(int j = 0; j < 2; ++j) { p2[j] = Dot(out, m_axes[j]); out -= p2[j] * m_axes[j]; } return out; } template<int dim> inline bool Poly2Orient<dim>::checkContained(const Point<dim>& pd, Point<2> & p2) const { Vector<dim> off = offset(pd, p2); CoordType sqrsum = 0; for(int i = 0; i < dim; ++i) sqrsum += pd[i] * pd[i]; return off.sqrMag() < numeric_constants<CoordType>::epsilon() * sqrsum; } template<> bool Poly2Orient<3>::checkIntersectPlane(const AxisBox<3>& b, Point<2>& p2, bool proper) const; template<int dim> bool Poly2Orient<dim>::checkIntersect(const AxisBox<dim>& b, Point<2>& p2, bool proper) const { assert(m_origin.isValid()); if(!m_axes[0].isValid()) { // Single point p2[0] = p2[1] = 0; return Intersect(b, convert(p2), proper); } if(m_axes[1].isValid()) { // A plane // I only know how to do this in 3D, so write a function which will // specialize to different dimensions return checkIntersectPlane(b, p2, proper); } // A line // This is a modified version of AxisBox<>/Segment<> intersection CoordType min = 0, max = 0; // Initialize to avoid compiler warnings bool got_bounds = false; for(int i = 0; i < dim; ++i) { const CoordType dist = (m_axes[0])[i]; // const may optimize away better if(dist == 0) { if(_Less(m_origin[i], b.lowCorner()[i], proper) || _Greater(m_origin[i], b.highCorner()[i], proper)) return false; } else { CoordType low = (b.lowCorner()[i] - m_origin[i]) / dist; CoordType high = (b.highCorner()[i] - m_origin[i]) / dist; if(low > high) { CoordType tmp = high; high = low; low = tmp; } if(got_bounds) { if(low > min) min = low; if(high < max) max = high; } else { min = low; max = high; got_bounds = true; } } } assert(got_bounds); // We can't be parallel in _all_ dimensions if(_LessEq(min, max, proper)) { p2[0] = (max - min) / 2; p2[1] = 0; return true; } else return false; } template<int dim> int Intersect(const Poly2Orient<dim> &o1, const Poly2Orient<dim> &o2, Poly2OrientIntersectData &data) { if(!o1.m_origin.isValid() || !o2.m_origin.isValid()) { // No points return -1; } // Check for single point basis if(!o1.m_axes[0].isValid()) { if(!o2.checkContained(o1.m_origin, data.p2)) return -1; // no intersect //Poly2OrientIntersectData data; data.p1[0] = data.p1[1] = 0; return 0; // point intersect } if(!o2.m_axes[0].isValid()) { if(!o1.checkContained(o2.m_origin, data.p1)) return -1; // no intersect data.p2[0] = data.p2[1] = 0; return 0; // point intersect } // Find a common basis for the plane's orientations // by projecting out the part of o1's basis that lies // in o2's basis Vector<dim> basis1, basis2; CoordType sqrmag1, sqrmag2; int basis_size = 0; basis1 = o2.m_axes[0] * Dot(o2.m_axes[0], o1.m_axes[0]); if(o2.m_axes[1].isValid()) basis1 += o2.m_axes[1] * Dot(o2.m_axes[1], o1.m_axes[0]); // Don't need to scale, the m_axes are unit vectors sqrmag1 = basis1.sqrMag(); if(sqrmag1 > numeric_constants<CoordType>::epsilon() * numeric_constants<CoordType>::epsilon()) basis_size = 1; if(o1.m_axes[1].isValid()) { basis2 = o2.m_axes[0] * Dot(o2.m_axes[0], o1.m_axes[1]); if(o2.m_axes[1].isValid()) basis2 += o2.m_axes[1] * Dot(o2.m_axes[1], o1.m_axes[1]); // Project out part parallel to basis1 if(basis_size == 1) basis2 -= basis1 * (Dot(basis1, basis2) / sqrmag1); sqrmag2 = basis2.sqrMag(); if(sqrmag2 > numeric_constants<CoordType>::epsilon() * numeric_constants<CoordType>::epsilon()) { if(basis_size++ == 0) { basis1 = basis2; sqrmag1 = sqrmag2; } } } Vector<dim> off = o2.m_origin - o1.m_origin; switch(basis_size) { case 0: { // All vectors are orthogonal, check for a common point in the plane // This can happen even in 3d for degenerate bases data.p1[0] = Dot(o1.m_axes[0], off); Vector<dim> off1 = o1.m_axes[0] * data.p1[0]; if(o1.m_axes[1].isValid()) { data.p1[1] = Dot(o1.m_axes[1], off); off1 += o1.m_axes[1] * data.p1[1]; } else data.p1[1] = 0; data.p2[0] = -Dot(o2.m_axes[0], off); Vector<dim> off2 = o2.m_axes[0] * data.p2[0]; if(o1.m_axes[1].isValid()) { data.p2[1] = -Dot(o2.m_axes[1], off); off2 += o1.m_axes[1] * data.p2[1]; } else data.p2[1] = 0; if(off1 - off2 != off) // No common point return -1; else // Got a point return 1; } case 1: { // Check for an intersection line data.o1_is_line = !o1.m_axes[1].isValid(); data.o2_is_line = !o2.m_axes[1].isValid(); if(!o1.m_axes[1].isValid() && !o2.m_axes[1].isValid()) { CoordType proj = Dot(off, o2.m_axes[0]); if(off != o2.m_axes[0] * proj) return -1; data.v1[0] = 1; data.v1[1] = 0; data.p1[0] = data.p1[1] = 0; data.v2[0] = (Dot(o1.m_axes[0], o2.m_axes[0]) > 0) ? 1 : -1; data.v2[1] = 0; data.p2[0] = -proj; data.p2[1] = 0; return 1; } if(!o1.m_axes[1].isValid()) { data.p2[0] = -Dot(off, o2.m_axes[0]); data.p2[1] = -Dot(off, o2.m_axes[1]); if(off != - data.p2[0] * o2.m_axes[0] - data.p2[1] * o2.m_axes[1]) return -1; data.v1[0] = 1; data.v1[1] = 0; data.p1[0] = data.p1[1] = 0; data.v2[0] = Dot(o1.m_axes[0], o2.m_axes[0]); data.v2[1] = Dot(o1.m_axes[0], o2.m_axes[1]); return 1; } if(!o2.m_axes[1].isValid()) { data.p1[0] = Dot(off, o1.m_axes[0]); data.p1[1] = Dot(off, o1.m_axes[1]); if(off != data.p1[0] * o1.m_axes[0] + data.p1[1] * o1.m_axes[1]) return -1; data.v2[0] = 1; data.v2[1] = 0; data.p2[0] = data.p2[1] = 0; data.v1[0] = Dot(o1.m_axes[0], o2.m_axes[0]); data.v1[1] = Dot(o1.m_axes[1], o2.m_axes[0]); return 1; } data.p1[0] = Dot(off, o1.m_axes[0]); data.p1[1] = Dot(off, o1.m_axes[1]); data.p2[0] = -Dot(off, o2.m_axes[0]); data.p2[1] = -Dot(off, o2.m_axes[1]); if(off != data.p1[0] * o1.m_axes[0] + data.p1[1] * o1.m_axes[1] - data.p2[0] * o2.m_axes[0] - data.p2[1] * o2.m_axes[1]) return -1; basis1 /= std::sqrt(sqrmag1); data.v1[0] = Dot(o1.m_axes[0], basis1); data.v1[1] = Dot(o1.m_axes[1], basis1); data.v2[0] = Dot(o2.m_axes[0], basis1); data.v2[1] = Dot(o2.m_axes[1], basis1); return 1; } case 2: { assert(o1.m_axes[1].isValid() && o2.m_axes[1].isValid()); // The planes are parallel, check if they are the same plane CoordType off_sqr_mag = data.off.sqrMag(); // Find the offset between the origins in o2's coordnates if(off_sqr_mag != 0) { // The offsets aren't identical Vector<dim> off_copy = off; data.off[0] = Dot(o2.m_axes[0], off); off_copy -= o1.m_axes[0] * data.off[0]; data.off[1] = Dot(o2.m_axes[1], off); off_copy -= o1.m_axes[1] * data.off[1]; if(off_copy.sqrMag() > off_sqr_mag * numeric_constants<CoordType>::epsilon()) return -1; // The planes are different } else data.off[0] = data.off[1] = 0; // Define o2's basis vectors in o1's coordinates data.v1[0] = Dot(o2.m_axes[0], o1.m_axes[0]); data.v1[1] = Dot(o2.m_axes[0], o1.m_axes[1]); data.v2[0] = Dot(o2.m_axes[1], o1.m_axes[0]); data.v2[1] = Dot(o2.m_axes[1], o1.m_axes[1]); return 2; } default: assert(false); return -1; } } template<int dim> inline bool Intersect(const Polygon<dim>& r, const Point<dim>& p, bool proper) { Point<2> p2; return r.m_poly.numCorners() > 0 && r.m_orient.checkContained(p, p2) && Intersect(r.m_poly, p2, proper); } template<int dim> inline bool Contains(const Point<dim>& p, const Polygon<dim>& r, bool proper) { if(r.m_poly.numCorners() == 0) return true; if(proper) return false; for(size_t i = 1; i < r.m_poly.numCorners(); ++i) if(r.m_poly[i] != r.m_poly[0]) return false; Point<2> p2; return r.m_orient.checkContained(p, p2) && p2 == r.m_poly[0]; } template<int dim> bool Intersect(const Polygon<dim>& p, const AxisBox<dim>& b, bool proper) { size_t corners = p.m_poly.numCorners(); if(corners == 0) return false; Point<2> p2; if(!p.m_orient.checkIntersect(b, p2, proper)) return false; Segment<dim> s; s.endpoint(0) = p.m_orient.convert(p.m_poly.getCorner(corners-1)); int next_end = 1; for(size_t i = 0; i < corners; ++i) { s.endpoint(next_end) = p.m_orient.convert(p.m_poly.getCorner(i)); if(Intersect(b, s, proper)) return true; next_end = next_end ? 0 : 1; } return Contains(p, p2, proper); } template<int dim> bool _PolyContainsBox(const Poly2Orient<dim> &orient, const Polygon<2> &poly, const Point<dim> &corner, const Vector<dim> &size, bool proper) { int num_dim = 0, nonzero_dim = -1; for(int i = 0; i < dim; ++i) { if(size[i] == 0) continue; if(num_dim == 2) return false; if(nonzero_dim == -1 || std::fabs(size[nonzero_dim]) < std::fabs(size[i])) nonzero_dim = i; ++num_dim; } Point<2> corner1; if(!orient.checkContained(corner, corner1)) return false; if(num_dim == 0) return Contains(poly, corner1, proper); Point<2> corner2; if(!orient.checkContained(corner + size, corner2)) return false; if(num_dim == 1) return Contains(poly, Segment<2>(corner1, corner2), proper); Point<dim> other_corner = corner; other_corner[nonzero_dim] += size[nonzero_dim]; Point<2> corner3; if(!orient.checkContained(other_corner, corner3)) return false; // Create a RotBox<2> Vector<2> vec1(corner2 - corner1), vec2(corner3 - corner1); RotMatrix<2> m; // A matrix which gives the rotation from the x-axis to vec1 try { m.rotation(Vector<2>(1, 0), vec1); } catch(const ColinearVectors<2>&) { // vec1 is parallel to (-1, 0), so we're fine m.identity(); } RotBox<2> box(corner1, ProdInv(vec2, m), m); return Contains(poly, box, proper); } template<int dim> inline bool Contains(const Polygon<dim>& p, const AxisBox<dim>& b, bool proper) { return _PolyContainsBox(p.m_orient, p.m_poly, b.m_low, b.m_high - b.m_low, proper); } template<int dim> inline bool Contains(const AxisBox<dim>& b, const Polygon<dim>& p, bool proper) { for(size_t i = 0; i < p.m_poly.numCorners(); ++i) if(!Contains(b, p.getCorner(i), proper)) return false; return true; } template<int dim> inline bool Intersect(const Polygon<dim>& p, const Ball<dim>& b, bool proper) { if(p.m_poly.numCorners() == 0) return false; Point<2> c2; CoordType dist; dist = b.m_radius * b.m_radius - p.m_orient.offset(b.m_center, c2).sqrMag(); if(_Less(dist, 0, proper)) return false; return Intersect(p.m_poly, Ball<2>(c2, std::sqrt(dist)), proper); } template<int dim> inline bool Contains(const Polygon<dim>& p, const Ball<dim>& b, bool proper) { if(p.m_poly.numCorners() == 0) return false; if(b.m_radius > 0) return false; Point<2> c2; if(!p.m_orient.checkContained(b.m_center, c2)) return false; return Contains(p.m_poly, c2, proper); } template<int dim> inline bool Contains(const Ball<dim>& b, const Polygon<dim>& p, bool proper) { if(p.m_poly.numCorners() == 0) return true; Point<2> c2; CoordType dist; dist = b.m_radius * b.m_radius - p.m_orient.offset(b.m_center, c2).sqrMag(); if(_Less(dist, 0, proper)) return false; for(size_t i = 0; i != p.m_poly.numCorners(); ++i) if(_Less(dist, SquaredDistance(c2, p.m_poly[i]), proper)) return false; return true; } template<int dim> bool Intersect(const Polygon<dim>& p, const Segment<dim>& s, bool proper) { if(p.m_poly.numCorners() == 0) return false; Point<2> p1, p2; CoordType d1, d2; Vector<dim> v1, v2; v1 = p.m_orient.offset(s.m_p1, p1); v2 = p.m_orient.offset(s.m_p2, p2); if(Dot(v1, v2) > 0) // Both points on same side of sheet return false; d1 = v1.mag(); d2 = v2.mag(); Point<2> p_intersect; if(d1 + d2 == 0) // Avoid divide by zero later return Intersect(p.m_poly, Segment<2>(p1, p2), proper); for(int i = 0; i < 2; ++i) p_intersect[i] = (p1[i] * d2 + p2[i] * d1) / (d1 + d2); return Intersect(p.m_poly, p_intersect, proper); } template<int dim> inline bool Contains(const Polygon<dim>& p, const Segment<dim>& s, bool proper) { if(p.m_poly.numCorners() == 0) return false; Segment<2> s2; if(!p.m_orient.checkContained(s.m_p1, s2.endpoint(0))) return false; if(!p.m_orient.checkContained(s.m_p2, s2.endpoint(1))) return false; return Contains(p.m_poly, s2, proper); } template<int dim> inline bool Contains(const Segment<dim>& s, const Polygon<dim>& p, bool proper) { if(p.m_poly.numCorners() == 0) return true; // Expand the basis to include the segment, this deals well with // degenerate polygons Segment<2> s2; Poly2Orient<dim> orient(p.m_orient); for(int i = 0; i < 2; ++i) if(!orient.expand(s.endpoint(i), s2.endpoint(i))) return false; return Contains(s2, p.m_poly, proper); } template<int dim> bool Intersect(const Polygon<dim>& p, const RotBox<dim>& r, bool proper) { size_t corners = p.m_poly.numCorners(); if(corners == 0) return false; Poly2Orient<dim> orient(p.m_orient); // FIXME rotateInverse() orient.rotate(r.m_orient.inverse(), r.m_corner0); AxisBox<dim> b(r.m_corner0, r.m_corner0 + r.m_size); Point<2> p2; if(!orient.checkIntersect(b, p2, proper)) return false; Segment<dim> s; s.endpoint(0) = orient.convert(p.m_poly.getCorner(corners-1)); int next_end = 1; for(size_t i = 0; i < corners; ++i) { s.endpoint(next_end) = orient.convert(p.m_poly.getCorner(i)); if(Intersect(b, s, proper)) return true; next_end = next_end ? 0 : 1; } return Contains(p, p2, proper); } template<int dim> inline bool Contains(const Polygon<dim>& p, const RotBox<dim>& r, bool proper) { Poly2Orient<dim> orient(p.m_orient); orient.rotate(r.m_orient.inverse(), r.m_corner0); return _PolyContainsBox(orient, p.m_poly, r.m_corner0, r.m_size, proper); } template<int dim> inline bool Contains(const RotBox<dim>& r, const Polygon<dim>& p, bool proper) { if(p.m_poly.numCorners() == 0) return true; AxisBox<dim> b(r.m_corner0, r.m_corner0 + r.m_size); Poly2Orient<dim> orient(p.m_orient); orient.rotate(r.m_orient.inverse(), r.m_corner0); for(size_t i = 0; i < p.m_poly.numCorners(); ++i) if(!Contains(b, orient.convert(p.m_poly[i]), proper)) return false; return true; } bool PolyPolyIntersect(const Polygon<2> &poly1, const Polygon<2> &poly2, int intersect_dim, const Poly2OrientIntersectData &data, bool proper); template<int dim> inline bool Intersect(const Polygon<dim>& p1, const Polygon<dim>& p2, bool proper) { Poly2OrientIntersectData data; int intersect_dim = Intersect(p1.m_orient, p2.m_orient, data); return PolyPolyIntersect(p1.m_poly, p2.m_poly, intersect_dim, data, proper); } bool PolyPolyContains(const Polygon<2> &outer, const Polygon<2> &inner, int intersect_dim, const Poly2OrientIntersectData &data, bool proper); template<int dim> inline bool Contains(const Polygon<dim>& outer, const Polygon<dim>& inner, bool proper) { if(outer.m_poly.numCorners() == 0) return !proper && inner.m_poly.numCorners() == 0; if(inner.m_poly.numCorners() == 0) return true; Poly2OrientIntersectData data; int intersect_dim = Intersect(outer.m_orient, inner.m_orient, data); return PolyPolyContains(outer.m_poly, inner.m_poly, intersect_dim, data, proper); } // instantiations, only need 3d because 2d is a specialization, // except for the reverse-order intersect template bool Intersect<Point<2>,Polygon<2> >(const Point<2>&, const Polygon<2>&, bool); template bool Intersect<Point<3>,Polygon<3> >(const Point<3>&, const Polygon<3>&, bool); template bool Contains<3>(const Point<3>&, const Polygon<3>&, bool); template bool Intersect<3>(const Polygon<3>&, const Point<3>&, bool); template bool Contains<3>(const Polygon<3>&, const Point<3>&, bool); template bool Intersect<AxisBox<2>,Polygon<2> >(const AxisBox<2>&, const Polygon<2>&, bool); template bool Intersect<AxisBox<3>,Polygon<3> >(const AxisBox<3>&, const Polygon<3>&, bool); template bool Contains<3>(const AxisBox<3>&, const Polygon<3>&, bool); template bool Intersect<3>(const Polygon<3>&, const AxisBox<3>&, bool); template bool Contains<3>(const Polygon<3>&, const AxisBox<3>&, bool); template bool Intersect<Ball<2>,Polygon<2> >(const Ball<2>&, const Polygon<2>&, bool); template bool Intersect<Ball<3>,Polygon<3> >(const Ball<3>&, const Polygon<3>&, bool); template bool Contains<3>(const Ball<3>&, const Polygon<3>&, bool); template bool Intersect<3>(const Polygon<3>&, const Ball<3>&, bool); template bool Contains<3>(const Polygon<3>&, const Ball<3>&, bool); template bool Intersect<Segment<2>,Polygon<2> >(const Segment<2>&, const Polygon<2>&, bool); template bool Intersect<Segment<3>,Polygon<3> >(const Segment<3>&, const Polygon<3>&, bool); template bool Contains<3>(const Segment<3>&, const Polygon<3>&, bool); template bool Intersect<3>(const Polygon<3>&, const Segment<3>&, bool); template bool Contains<3>(const Polygon<3>&, const Segment<3>&, bool); template bool Intersect<RotBox<2>,Polygon<2> >(const RotBox<2>&, const Polygon<2>&, bool); template bool Intersect<RotBox<3>,Polygon<3> >(const RotBox<3>&, const Polygon<3>&, bool); template bool Contains<3>(const RotBox<3>&, const Polygon<3>&, bool); template bool Intersect<3>(const Polygon<3>&, const RotBox<3>&, bool); template bool Contains<3>(const Polygon<3>&, const RotBox<3>&, bool); template bool Intersect<3>(const Polygon<3>&, const Polygon<3>&, bool); template bool Contains<3>(const Polygon<3>&, const Polygon<3>&, bool); template<> bool Poly2Orient<3>::checkIntersectPlane(const AxisBox<3>& b, Point<2>& p2, bool proper) const { assert("This function should only be called if the orientation represents a plane" && m_origin.isValid() && m_axes[0].isValid() && m_axes[1].isValid()); Vector<3> normal = Cross(m_axes[0], m_axes[1]); // normal to the plane // enum { // AXIS_UP, // AXIS_DOWN, // AXIS_FLAT // } axis_direction[3]; CoordType normal_mag = normal.sloppyMag(); int high_corner_num = 0; for(int i = 0; i < 3; ++i) { if(std::fabs(normal[i]) < normal_mag * numeric_constants<CoordType>::epsilon()) { // axis_direction[i] = AXIS_FLAT; } else if(normal[i] > 0) { // axis_direction[i] = AXIS_UP; high_corner_num |= (1 << i); } // else // axis_direction[i] = AXIS_DOWN; } int low_corner_num = high_corner_num ^ 7; Point<3> high_corner = b.getCorner(high_corner_num); Point<3> low_corner = b.getCorner(low_corner_num); // If these are on opposite sides of the plane, we have an intersection CoordType perp_size = Dot(normal, high_corner - low_corner) / normal_mag; assert(perp_size >= 0); if(perp_size < normal_mag * numeric_constants<CoordType>::epsilon()) { // We have a very flat box, lying parallel to the plane return !proper && checkContained(Midpoint(high_corner, low_corner), p2); } if(_Less(Dot(high_corner - m_origin, normal), 0, proper) || _Less(Dot(low_corner - m_origin, normal), 0, proper)) return false; // box lies above or below the plane // Find the intersection of the line through the corners with the plane Point<2> p2_high, p2_low; CoordType high_dist = offset(high_corner, p2_high).mag(); CoordType low_dist = offset(low_corner, p2_low).mag(); p2 = Midpoint(p2_high, p2_low, high_dist / (high_dist + low_dist)); return true; } // This assumes the y coordinates of the points are all zero static void LinePolyGetBounds(const Polygon<2> &poly, CoordType &low, CoordType &high) { low = high = poly[0][0]; for(size_t i = 0; i < poly.numCorners(); ++i) { CoordType val = poly[i][0]; if(val < low) low = val; if(val > high) high = val; } } // For use in GetCrossings() struct LinePointData { CoordType low, high; bool cross; }; // This finds the intervals where the polygon intersects the line // through p parallel to v, and puts the endpoints of those // intervals in the vector "cross" static bool GetCrossings(const Polygon<2> &poly, const Point<2> &p, const Vector<2> &v, std::vector<CoordType> &cross, bool proper) { assert(poly.numCorners() == cross.size()); // Already allocated assert(Equal(v.sqrMag(), 1)); // The sign of the cross product changes when you cross the line Point<2> old_p = poly.getCorner(poly.numCorners() - 1); bool old_below = (Cross(v, old_p - p) < 0); int next_cross = 0; // Stuff for when multiple sequential corners lie on the line std::list<LinePointData> line_point_data; for(size_t i = 0; i < poly.numCorners(); ++i) { Point<2> p_i = poly.getCorner(i); Vector<2> v_i = p_i - p; CoordType v_i_sqr_mag = v_i.sqrMag(), proj = Dot(v_i, v); if(Equal(v_i_sqr_mag, proj * proj)) { // corner lies on line Point<2> p_j; Vector<2> v_j; CoordType proj_j, low_proj = proj, high_proj = proj; size_t j; for(j = i + 1; j != i; j == poly.numCorners() - 1 ? j = 0 : ++j) { p_j = poly.getCorner(j); v_j = p_j - p; proj_j = Dot(v_j, v); if(!Equal(v_j.sqrMag(), proj_j * proj_j)) break; if(proj_j < low_proj) low_proj = proj_j; if(proj_j > high_proj) high_proj = proj_j; } assert(j != i); // We know that the polygon spans a 2d space bool below = (Cross(v, v_j) < 0); if(below == old_below && proper) { old_p = p_j; continue; } if(j == i + 1) { // just one point on the line if(below != old_below) { old_below = below; cross[next_cross++] = proj; } else { assert(!proper); // Just touches, adding it twice will give a zero length "hit" region cross[next_cross++] = proj; cross[next_cross++] = proj; } old_p = p_j; continue; } LinePointData data = {low_proj, high_proj, below != old_below}; std::list<LinePointData>::iterator I; for(I = line_point_data.begin(); I != line_point_data.end(); ++I) { if(data.low > I->high) continue; if(data.high < I->low) { line_point_data.insert(I, data); break; } // overlap I->low = (I->low < data.low) ? I->low : data.low; I->high = (I->high > data.high) ? I->high : data.high; I->cross = (I->cross != data.cross); auto J = I; ++J; if(J->low < I->high) { I->high = J->high; I->cross = (I->cross != J->cross); line_point_data.erase(J); } } if(I == line_point_data.end()) line_point_data.push_back(data); old_below = below; old_p = p_j; continue; } // the corner doesn't lie on the line, compute the intersection point bool below = (Cross(v, v_i) < 0); if(below != old_below) { old_below = below; Vector<2> dist = p - old_p; CoordType dist_sqr_mag = dist.sqrMag(); CoordType dist_proj = Dot(dist, v); CoordType denom = dist_proj * dist_proj - dist_sqr_mag; assert(denom != 0); // We got a crossing, the vectors can't be parallel CoordType line_pos = (dist_proj * Dot(v_i, dist) + dist_sqr_mag * proj) / denom; cross[next_cross++] = line_pos; } old_p = p; } cross.resize(next_cross); std::sort(cross.begin(), cross.end()); if(!line_point_data.empty()) { auto I = line_point_data.begin(); auto cross_num = cross.begin(); bool hit = false; while(cross_num != cross.end() && I != line_point_data.end()) { if(*cross_num < I->low) { ++cross_num; hit = !hit; continue; } bool hit_between; if(*cross_num > I->high) { hit_between = I->cross; } else { auto high_cross_num = cross_num; do { ++high_cross_num; } while(*high_cross_num < I->high); hit_between = (((high_cross_num - cross_num) % 2) != 0) != I->cross; cross_num = cross.erase(cross_num, high_cross_num); } if(hit_between) { cross_num = cross.insert(cross_num, proper == hit ? I->low : I->high); ++cross_num; hit = !hit; } else if(!proper) { cross_num = cross.insert(cross_num, I->low); ++cross_num; cross_num = cross.insert(cross_num, I->high); ++cross_num; } ++I; } while(I != line_point_data.end()) { if(I->cross) { cross.push_back(proper == hit ? I->low : I->high); hit = !hit; } else if(!proper) { cross.push_back(I->low); cross.push_back(I->high); } ++I; } assert(!hit); // end outside the polygon } return !cross.empty(); } bool PolyPolyIntersect(const Polygon<2> &poly1, const Polygon<2> &poly2, const int intersect_dim, const Poly2OrientIntersectData &data, bool proper) { switch(intersect_dim) { case -1: return false; case 0: return Intersect(poly1, data.p1, proper) && Intersect(poly2, data.p2, proper); case 1: if(proper && (data.o1_is_line || data.o2_is_line)) return false; if(data.o1_is_line && data.o2_is_line) { assert(!proper); CoordType low1, low2, high1, high2; LinePolyGetBounds(poly1, low1, high1); low1 -= data.p1[0]; high1 -= data.p1[0]; if(data.v1[0] < 0) { // v1 = (-1, 0) CoordType tmp = low1; low1 = -high1; high1 = -tmp; } LinePolyGetBounds(poly2, low2, high2); low2 -= data.p2[0]; high2 -= data.p2[0]; if(data.v2[0] < 0) { // v2 = (-1, 0) CoordType tmp = low2; low2 = -high2; high2 = -tmp; } return high1 >= low2 && high2 >= low1; } if(data.o1_is_line) { assert(!proper); CoordType min, max; LinePolyGetBounds(poly1, min, max); min -= data.p1[0]; max -= data.p1[0]; if(data.v1[0] < 0) { // v1 = (-1, 0) CoordType tmp = min; min = -max; max = -tmp; } Segment<2> s(data.p2 + min * data.v2, data.p1 + max * data.v2); return Intersect(poly2, s, false); } if(data.o2_is_line) { assert(!proper); CoordType min, max; LinePolyGetBounds(poly2, min, max); min -= data.p2[0]; max -= data.p2[0]; if(data.v2[0] < 0) { // v2 = (-1, 0) CoordType tmp = min; min = -max; max = -tmp; } Segment<2> s(data.p1 + min * data.v1, data.p1 + max * data.v1); return Intersect(poly1, s, false); } { std::vector<CoordType> cross1(poly1.numCorners()); if(!GetCrossings(poly1, data.p1, data.v1, cross1, proper)) return false; // line misses polygon std::vector<CoordType> cross2(poly2.numCorners()); if(!GetCrossings(poly2, data.p2, data.v2, cross2, proper)) return false; // line misses polygon auto i1 = cross1.begin(), i2 = cross2.begin(); bool hit1 = false, hit2 = false; while(i1 != cross1.end() && i2 != cross2.end()) { if(Equal(*i1, *i2)) { if(!proper) return true; hit1 = !hit1; ++i1; hit2 = !hit2; ++i2; } if(*i1 < *i2) { hit1 = !hit1; ++i1; } else { hit2 = !hit2; ++i2; } if(hit1 && hit2) return true; } return false; } case 2: // Shift one polygon into the other's coordinates. // Perhaps not the most efficient, but this is a // rare special case. { Polygon<2> tmp_poly(poly2); for(size_t i = 0; i < tmp_poly.numCorners(); ++i) { Point<2> &p = tmp_poly[i]; Point<2> shift_p = p + data.off; p[0] = shift_p[0] * data.v1[0] + shift_p[1] * data.v2[0]; p[1] = shift_p[0] * data.v1[1] + shift_p[1] * data.v2[1]; } return Intersect(poly1, tmp_poly, proper); } default: assert(false); return false; } } bool PolyPolyContains(const Polygon<2> &outer, const Polygon<2> &inner, const int intersect_dim, const Poly2OrientIntersectData &data, bool proper) { switch(intersect_dim) { case -1: return false; case 0: return Contains(data.p2, inner, false) && Contains(outer, data.p1, proper); case 1: if(!data.o2_is_line) // The inner poly isn't contained by the intersect line return false; // The inner poly lies on a line, so it reduces to a line segment { CoordType min, max; LinePolyGetBounds(inner, min, max); min -= data.p2[0]; max -= data.p2[0]; if(data.v2[0] < 0) { // v2 = (-1, 0) CoordType tmp = min; min = -max; max = -tmp; } Segment<2> s(data.p1 + min * data.v1, data.p1 + max * data.v1); return Contains(outer, s, proper); } case 2: // Shift one polygon into the other's coordinates. // Perhaps not the most efficient, but this is a // rare special case. { Polygon<2> tmp_poly(inner); for(size_t i = 0; i < tmp_poly.numCorners(); ++i) { Point<2> &p = tmp_poly[i]; Point<2> shift_p = p + data.off; p[0] = shift_p[0] * data.v1[0] + shift_p[1] * data.v2[0]; p[1] = shift_p[0] * data.v1[1] + shift_p[1] * data.v2[1]; } return Contains(outer, tmp_poly, proper); } default: assert(false); return false; } } // Polygon<2> intersection functions // FIXME deal with round off error in _all_ these intersection functions // The Polygon<2>/Point<2> intersection function was stolen directly // from shape.cpp in libCoal template<> bool Intersect<2>(const Polygon<2>& r, const Point<2>& p, bool proper) { const Polygon<2>::theConstIter begin = r.m_points.begin(), end = r.m_points.end(); bool hit = false; for (Polygon<2>::theConstIter i = begin, j = end - 1; i != end; j = i++) { bool vertically_between = (((*i)[1] <= p[1] && p[1] < (*j)[1]) || ((*j)[1] <= p[1] && p[1] < (*i)[1])); if (!vertically_between) continue; CoordType x_intersect = (*i)[0] + ((*j)[0] - (*i)[0]) * (p[1] - (*i)[1]) / ((*j)[1] - (*i)[1]); if(Equal(p[0], x_intersect)) return !proper; if(p[0] < x_intersect) hit = !hit; } return hit; } template<> bool Contains<2>(const Point<2>& p, const Polygon<2>& r, bool proper) { if(proper) // Weird degenerate case return r.numCorners() == 0; for(const auto & point : r.m_points) if(p != point) return false; return true; } template<> bool Intersect<2>(const Polygon<2>& p, const AxisBox<2>& b, bool proper) { const Polygon<2>::theConstIter begin = p.m_points.begin(), end = p.m_points.end(); bool hit = false; for (Polygon<2>::theConstIter i = begin, j = end - 1; i != end; j = i++) { bool low_vertically_between = (((*i)[1] <= b.m_low[1] && b.m_low[1] < (*j)[1]) || ((*j)[1] <= b.m_low[1] && b.m_low[1] < (*i)[1])); bool low_horizontally_between = (((*i)[0] <= b.m_low[0] && b.m_low[0] < (*j)[0]) || ((*j)[0] <= b.m_low[0] && b.m_low[0] < (*i)[0])); bool high_vertically_between = (((*i)[1] <= b.m_high[1] && b.m_high[1] < (*j)[1]) || ((*j)[1] <= b.m_high[1] && b.m_high[1] < (*i)[1])); bool high_horizontally_between = (((*i)[0] <= b.m_high[0] && b.m_high[0] < (*j)[0]) || ((*j)[0] <= b.m_high[0] && b.m_high[0] < (*i)[0])); CoordType xdiff = ((*j)[0] - (*i)[0]); CoordType ydiff = ((*j)[1] - (*i)[1]); if(low_vertically_between) { // Check for edge intersect CoordType x_intersect = (*i)[0] + (b.m_low[1] - (*i)[1]) * xdiff / ydiff; if(Equal(b.m_low[0], x_intersect) || Equal(b.m_high[0], x_intersect)) return !proper; if(b.m_low[0] < x_intersect && b.m_high[0] > x_intersect) return true; // Also check for point inclusion here, only need to do this for one point if(b.m_low[0] < x_intersect) hit = !hit; } if(low_horizontally_between) { // Check for edge intersect CoordType y_intersect = (*i)[1] + (b.m_low[0] - (*i)[0]) * ydiff / xdiff; if(Equal(b.m_low[1], y_intersect) || Equal(b.m_high[1], y_intersect)) return !proper; if(b.m_low[1] < y_intersect && b.m_high[1] > y_intersect) return true; } if(high_vertically_between) { // Check for edge intersect CoordType x_intersect = (*i)[0] + (b.m_high[1] - (*i)[1]) * xdiff / ydiff; if(Equal(b.m_low[0], x_intersect) || Equal(b.m_high[0], x_intersect)) return !proper; if(b.m_low[0] < x_intersect && b.m_high[0] > x_intersect) return true; } if(high_horizontally_between) { // Check for edge intersect CoordType y_intersect = (*i)[1] + (b.m_high[0] - (*i)[0]) * ydiff / xdiff; if(Equal(b.m_low[1], y_intersect) || Equal(b.m_high[1], y_intersect)) return !proper; if(b.m_low[1] < y_intersect && b.m_high[1] > y_intersect) return true; } } return hit; } template<> bool Contains<2>(const Polygon<2>& p, const AxisBox<2>& b, bool proper) { const Polygon<2>::theConstIter begin = p.m_points.begin(), end = p.m_points.end(); bool hit = false; for (Polygon<2>::theConstIter i = begin, j = end - 1; i != end; j = i++) { bool low_vertically_between = (((*i)[1] <= b.m_low[1] && b.m_low[1] < (*j)[1]) || ((*j)[1] <= b.m_low[1] && b.m_low[1] < (*i)[1])); bool low_horizontally_between = (((*i)[0] <= b.m_low[0] && b.m_low[0] < (*j)[0]) || ((*j)[0] <= b.m_low[0] && b.m_low[0] < (*i)[0])); bool high_vertically_between = (((*i)[1] <= b.m_high[1] && b.m_high[1] < (*j)[1]) || ((*j)[1] <= b.m_high[1] && b.m_high[1] < (*i)[1])); bool high_horizontally_between = (((*i)[0] <= b.m_high[0] && b.m_high[0] < (*j)[0]) || ((*j)[0] <= b.m_high[0] && b.m_high[0] < (*i)[0])); CoordType xdiff = ((*j)[0] - (*i)[0]); CoordType ydiff = ((*j)[1] - (*i)[1]); if(low_vertically_between) { // Check for edge intersect CoordType x_intersect = (*i)[0] + (b.m_low[1] - (*i)[1]) * xdiff / ydiff; bool on_corner = Equal(b.m_low[0], x_intersect) || Equal(b.m_high[0], x_intersect); if(on_corner && proper) return false; if(!on_corner && b.m_low[0] < x_intersect && b.m_high[0] > x_intersect) return false; // Also check for point inclusion here, only need to do this for one point if(!on_corner && b.m_low[0] < x_intersect) hit = !hit; } if(low_horizontally_between) { // Check for edge intersect CoordType y_intersect = (*i)[1] + (b.m_low[0] - (*i)[0]) * ydiff / xdiff; bool on_corner = Equal(b.m_low[1], y_intersect) || Equal(b.m_high[1], y_intersect); if(on_corner && proper) return false; if(!on_corner && b.m_low[1] < y_intersect && b.m_high[1] > y_intersect) return false; } if(high_vertically_between) { // Check for edge intersect CoordType x_intersect = (*i)[0] + (b.m_high[1] - (*i)[1]) * xdiff / ydiff; bool on_corner = Equal(b.m_low[0], x_intersect) || Equal(b.m_high[0], x_intersect); if(on_corner && proper) return false; if(!on_corner && b.m_low[0] < x_intersect && b.m_high[0] > x_intersect) return false; } if(high_horizontally_between) { // Check for edge intersect CoordType y_intersect = (*i)[1] + (b.m_high[0] - (*i)[0]) * ydiff / xdiff; bool on_corner = Equal(b.m_low[1], y_intersect) || Equal(b.m_high[1], y_intersect); if(on_corner && proper) return false; if(!on_corner && b.m_low[1] < y_intersect && b.m_high[1] > y_intersect) return false; } } return hit; } template<> bool Contains<2>(const AxisBox<2>& b, const Polygon<2>& p, bool proper) { for(const auto & point : p.m_points) if(!Contains(b, point, proper)) return false; return true; } template<> bool Intersect<2>(const Polygon<2>& p, const Ball<2>& b, bool proper) { if(Contains(p, b.m_center, proper)) return true; Segment<2> s2; s2.endpoint(0) = p.m_points.back(); int next_end = 1; for(const auto & point : p.m_points) { s2.endpoint(next_end) = point; if(Intersect(s2, b, proper)) return true; next_end = next_end ? 0 : 1; } return false; } template<> bool Contains<2>(const Polygon<2>& p, const Ball<2>& b, bool proper) { if(!Contains(p, b.m_center, proper)) return false; Segment<2> s2; s2.endpoint(0) = p.m_points.back(); int next_end = 1; for(const auto & point : p.m_points) { s2.endpoint(next_end) = point; if(Intersect(s2, b, !proper)) return false; next_end = next_end ? 0 : 1; } return true; } template<> bool Contains<2>(const Ball<2>& b, const Polygon<2>& p, bool proper) { CoordType sqr_dist = b.m_radius * b.m_radius; for(const auto & point : p.m_points) if(_Greater(SquaredDistance(b.m_center, point), sqr_dist, proper)) return false; return true; } template<> bool Intersect<2>(const Polygon<2>& p, const Segment<2>& s, bool proper) { if(Contains(p, s.endpoint(0), proper)) return true; const Polygon<2>::theConstIter begin = p.m_points.begin(), end = p.m_points.end(); Segment<2> s2; s2.endpoint(0) = p.m_points.back(); int next_point = 1; for(Polygon<2>::theConstIter i = begin; i != end; ++i) { s2.endpoint(next_point) = *i; if(Intersect(s, s2, proper)) return true; next_point = next_point ? 0 : 1; } return false; } template<> bool Contains<2>(const Polygon<2>& p, const Segment<2>& s, bool proper) { if(proper && !Contains(p, s.endpoint(0), true)) return false; const Polygon<2>::theConstIter begin = p.m_points.begin(), end = p.m_points.end(); Segment<2> s2; s2.endpoint(0) = p.m_points.back(); int next_point = 1; bool hit = false; for(Polygon<2>::theConstIter i = begin; i != end; ++i) { s2.endpoint(next_point) = *i; if(Intersect(s2, s, !proper)) return false; bool this_point = next_point; next_point = next_point ? 0 : 1; if(proper) continue; // Check for crossing at an endpoint if(Contains(s, *i, false) && (*i != s.m_p2)) { Vector<2> segment = s.m_p2 - s.m_p1; Vector<2> edge1 = *i - s2.endpoint(next_point); // Gives prev point in this case Vector<2> edge2 = *i - *(i + 1); CoordType c1 = Cross(segment, edge1), c2 = Cross(segment, edge2); if(c1 * c2 < 0) { // opposite sides if(*i == s.m_p1) { // really a containment issue if(edge1[1] * edge2[1] > 0 // Edges either both up or both down || ((edge1[1] > 0) ? c1 : c2) < 0) // segment lies to the left hit = !hit; continue; // Already checked containment for this point } else return false; } } // Check containment of one endpoint // next_point also gives prev_point bool vertically_between = ((s2.endpoint(this_point)[1] <= s.m_p1[1] && s.m_p1[1] < s2.endpoint(next_point)[1]) || (s2.endpoint(next_point)[1] <= s.m_p1[1] && s.m_p1[1] < s2.endpoint(this_point)[1])); if (!vertically_between) continue; CoordType x_intersect = s2.m_p1[0] + (s2.m_p2[0] - s2.m_p1[0]) * (s.m_p1[1] - s2.m_p1[1]) / (s2.m_p2[1] - s2.m_p1[1]); if(Equal(s.m_p1[0], x_intersect)) { // Figure out which side the segment's on // Equal points are handled in the crossing routine above if(s2.endpoint(next_point) == s.m_p1) continue; assert(s2.endpoint(this_point) != s.m_p1); Vector<2> poly_edge = (s2.m_p1[1] < s2.m_p2[1]) ? (s2.m_p2 - s2.m_p1) : (s2.m_p1 - s2.m_p2); Vector<2> segment = s.m_p2 - s.m_p1; if(Cross(segment, poly_edge) < 0) hit = !hit; } else if(s.m_p1[0] < x_intersect) hit = !hit; } return proper || hit; } template<> bool Contains<2>(const Segment<2>& s, const Polygon<2>& p, bool proper) { for(const auto & point : p.m_points) if(!Contains(s, point, proper)) return false; return true; } template<> bool Intersect<2>(const Polygon<2>& p, const RotBox<2>& r, bool proper) { CoordType m_low[2], m_high[2]; for(int j = 0; j < 2; ++j) { if(r.m_size[j] > 0) { m_low[j] = r.m_corner0[j]; m_high[j] = r.m_corner0[j] + r.m_size[j]; } else { m_high[j] = r.m_corner0[j]; m_low[j] = r.m_corner0[j] + r.m_size[j]; } } Point<2> ends[2]; ends[0] = p.m_points.back(); // FIXME Point<>::rotateInverse() ends[0].rotate(r.m_orient.inverse(), r.m_corner0); int next_end = 1; const Polygon<2>::theConstIter begin = p.m_points.begin(), end = p.m_points.end(); bool hit = false; for (Polygon<2>::theConstIter i = begin; i != end; ++i) { ends[next_end] = *i; // FIXME Point<>::rotateInverse() ends[next_end].rotate(r.m_orient.inverse(), r.m_corner0); next_end = next_end ? 0 : 1; bool low_vertically_between = (((ends[0])[1] <= m_low[1] && m_low[1] < (ends[1])[1]) || ((ends[1])[1] <= m_low[1] && m_low[1] < (ends[0])[1])); bool low_horizontally_between = (((ends[0])[0] <= m_low[0] && m_low[0] < (ends[1])[0]) || ((ends[1])[0] <= m_low[0] && m_low[0] < (ends[0])[0])); bool high_vertically_between = (((ends[0])[1] <= m_high[1] && m_high[1] < (ends[1])[1]) || ((ends[1])[1] <= m_high[1] && m_high[1] < (ends[0])[1])); bool high_horizontally_between = (((ends[0])[0] <= m_high[0] && m_high[0] < (ends[1])[0]) || ((ends[1])[0] <= m_high[0] && m_high[0] < (ends[0])[0])); CoordType xdiff = (ends[1])[0] - (ends[0])[0]; CoordType ydiff = (ends[1])[1] - (ends[0])[1]; if(low_vertically_between) { // Check for edge intersect CoordType x_intersect = (ends[0])[0] + (m_low[1] - (ends[0])[1]) * xdiff / ydiff; if(Equal(m_low[0], x_intersect) || Equal(m_high[0], x_intersect)) return !proper; if(m_low[0] < x_intersect && m_high[0] > x_intersect) return true; // Also check for point inclusion here, only need to do this for one point if(m_low[0] < x_intersect) hit = !hit; } if(low_horizontally_between) { // Check for edge intersect CoordType y_intersect = (ends[0])[1] + (m_low[0] - (ends[0])[0]) * ydiff / xdiff; if(Equal(m_low[1], y_intersect) || Equal(m_high[1], y_intersect)) return !proper; if(m_low[1] < y_intersect && m_high[1] > y_intersect) return true; } if(high_vertically_between) { // Check for edge intersect CoordType x_intersect = (ends[0])[0] + (m_high[1] - (ends[0])[1]) * xdiff / ydiff; if(Equal(m_low[0], x_intersect) || Equal(m_high[0], x_intersect)) return !proper; if(m_low[0] < x_intersect && m_high[0] > x_intersect) return true; } if(high_horizontally_between) { // Check for edge intersect CoordType y_intersect = (ends[0])[1] + (m_high[0] - (ends[0])[0]) * ydiff / xdiff; if(Equal(m_low[1], y_intersect) || Equal(m_high[1], y_intersect)) return !proper; if(m_low[1] < y_intersect && m_high[1] > y_intersect) return true; } } return hit; } template<> bool Contains<2>(const Polygon<2>& p, const RotBox<2>& r, bool proper) { CoordType m_low[2], m_high[2]; for(int j = 0; j < 2; ++j) { if(r.m_size[j] > 0) { m_low[j] = r.m_corner0[j]; m_high[j] = r.m_corner0[j] + r.m_size[j]; } else { m_high[j] = r.m_corner0[j]; m_low[j] = r.m_corner0[j] + r.m_size[j]; } } Point<2> ends[2]; ends[0] = p.m_points.back(); // FIXME Point<>::rotateInverse() ends[0].rotate(r.m_orient.inverse(), r.m_corner0); int next_end = 1; const Polygon<2>::theConstIter begin = p.m_points.begin(), end = p.m_points.end(); bool hit = false; for (Polygon<2>::theConstIter i = begin; i != end; ++i) { ends[next_end] = *i; // FIXME Point<>::rotateInverse() ends[next_end].rotate(r.m_orient.inverse(), r.m_corner0); next_end = next_end ? 0 : 1; bool low_vertically_between = (((ends[0])[1] <= m_low[1] && m_low[1] < (ends[1])[1]) || ((ends[1])[1] <= m_low[1] && m_low[1] < (ends[0])[1])); bool low_horizontally_between = (((ends[0])[0] <= m_low[0] && m_low[0] < (ends[1])[0]) || ((ends[1])[0] <= m_low[0] && m_low[0] < (ends[0])[0])); bool high_vertically_between = (((ends[0])[1] <= m_high[1] && m_high[1] < (ends[1])[1]) || ((ends[1])[1] <= m_high[1] && m_high[1] < (ends[0])[1])); bool high_horizontally_between = (((ends[0])[0] <= m_high[0] && m_high[0] < (ends[1])[0]) || ((ends[1])[0] <= m_high[0] && m_high[0] < (ends[0])[0])); CoordType xdiff = (ends[1])[0] - (ends[0])[0]; CoordType ydiff = (ends[1])[1] - (ends[0])[1]; if(low_vertically_between) { // Check for edge intersect CoordType x_intersect = (ends[0])[0] + (m_low[1] - (ends[0])[1]) * xdiff / ydiff; bool on_corner = Equal(m_low[0], x_intersect) || Equal(m_high[0], x_intersect); if(on_corner && proper) return false; if(!on_corner && m_low[0] < x_intersect && m_high[0] > x_intersect) return false; // Also check for point inclusion here, only need to do this for one point if(!on_corner && m_low[0] < x_intersect) hit = !hit; } if(low_horizontally_between) { // Check for edge intersect CoordType y_intersect = (ends[0])[1] + (m_low[0] - (ends[0])[0]) * ydiff / xdiff; bool on_corner = Equal(m_low[1], y_intersect) || Equal(m_high[1], y_intersect); if(on_corner && proper) return false; if(!on_corner && m_low[1] < y_intersect && m_high[1] > y_intersect) return false; } if(high_vertically_between) { // Check for edge intersect CoordType x_intersect = (ends[0])[0] + (m_high[1] - (ends[0])[1]) * xdiff / ydiff; bool on_corner = Equal(m_low[0], x_intersect) || Equal(m_high[0], x_intersect); if(on_corner && proper) return false; if(!on_corner && m_low[0] < x_intersect && m_high[0] > x_intersect) return false; } if(high_horizontally_between) { // Check for edge intersect CoordType y_intersect = (ends[0])[1] + (m_high[0] - (ends[0])[0]) * ydiff / xdiff; bool on_corner = Equal(m_low[1], y_intersect) || Equal(m_high[1], y_intersect); if(on_corner && proper) return false; if(!on_corner && m_low[1] < y_intersect && m_high[1] > y_intersect) return false; } } return hit; } template<> bool Contains<2>(const RotBox<2>& r, const Polygon<2>& p, bool proper) { for(const auto & point : p.m_points) if(!Contains(r, point, proper)) return false; return true; } template<> bool Intersect<2>(const Polygon<2>& p1, const Polygon<2>& p2, bool proper) { auto begin1 = p1.m_points.begin(), end1 = p1.m_points.end(); auto begin2 = p2.m_points.begin(), end2 = p2.m_points.end(); Segment<2> s1, s2; int next_end1, next_end2; s1.endpoint(0) = p1.m_points.back(); s2.endpoint(0) = p2.m_points.back(); next_end1 = next_end2 = 1; for(auto i1 = begin1; i1 != end1; ++i1) { s1.endpoint(next_end1) = *i1; next_end1 = next_end1 ? 0 : 1; for(auto i2 = begin2; i2 != end2; ++i2) { s2.endpoint(next_end2) = *i2; next_end2 = next_end2 ? 0 : 1; if(Intersect(s1, s2, proper)) return true; } } return Contains(p1, p2.m_points.front(), proper) || Contains(p2, p1.m_points.front(), proper); } template<> bool Contains<2>(const Polygon<2>& outer, const Polygon<2>& inner, bool proper) { if(proper && !Contains(outer, inner.m_points.front(), true)) return false; auto begin = inner.m_points.begin(), end = inner.m_points.end(); Segment<2> s; s.endpoint(0) = inner.m_points.back(); int next_end = 1; for(auto i = begin; i != end; ++i) { s.endpoint(next_end) = *i; next_end = next_end ? 0 : 1; if(!proper) { if(!Contains(outer, s, false)) return false; } else { auto begin2 = outer.m_points.begin(), end2 = outer.m_points.end(); Segment<2> s2; s2.endpoint(0) = outer.m_points.back(); int next_end2 = 1; for(auto i2 = begin2; i2 != end2; ++i2) { s2.endpoint(next_end2) = *i2; next_end2 = next_end2 ? 0 : 1; if(Intersect(s, s2, false)) return false; } } } return true; } } 07070100000035000081A4000000000000000000000001656C867F00000B48000000000000000000000000000000000000003900000000wfmath-1701611135.403a8bd/src/wfmath/polygon_intersect.h// polygon_funcs.h (Polygon<> intersection functions) // // The WorldForge Project // Copyright (C) 2002 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // // Author: Ron Steinke // Created: 2002-2-20 #ifndef WFMATH_POLYGON_INTERSECT_H #define WFMATH_POLYGON_INTERSECT_H #include <wfmath/axisbox.h> #include <wfmath/ball.h> #include <wfmath/polygon.h> #include <wfmath/intersect.h> #include <wfmath/error.h> // FIXME Work is needed on this code. At very least the following notes // from the original author apply: // "The Intersect() and Contains() functions involving WFMath::Polygon<>" // "are still under development, and probably shouldn't be used yet." namespace WFMath { template<> bool Intersect(const Polygon<2>& r, const Point<2>& p, bool proper); template<> bool Contains(const Point<2>& p, const Polygon<2>& r, bool proper); template<> bool Intersect(const Polygon<2>& p, const AxisBox<2>& b, bool proper); template<> bool Contains(const Polygon<2>& p, const AxisBox<2>& b, bool proper); template<> bool Contains(const AxisBox<2>& b, const Polygon<2>& p, bool proper); template<> bool Intersect(const Polygon<2>& p, const Ball<2>& b, bool proper); template<> bool Contains(const Polygon<2>& p, const Ball<2>& b, bool proper); template<> bool Contains(const Ball<2>& b, const Polygon<2>& p, bool proper); template<> bool Intersect(const Polygon<2>& p, const Segment<2>& s, bool proper); template<> bool Contains(const Polygon<2>& p, const Segment<2>& s, bool proper); template<> bool Contains(const Segment<2>& s, const Polygon<2>& p, bool proper); template<> bool Intersect(const Polygon<2>& p, const RotBox<2>& r, bool proper); template<> bool Contains(const Polygon<2>& p, const RotBox<2>& r, bool proper); template<> bool Contains(const RotBox<2>& r, const Polygon<2>& p, bool proper); template<> bool Intersect(const Polygon<2>& p1, const Polygon<2>& p2, bool proper); template<> bool Contains(const Polygon<2>& outer, const Polygon<2>& inner, bool proper); } // namespace WFMath #endif // WFMATH_POLYGON_INTERSECT_H 07070100000036000081A4000000000000000000000001656C867F0000299E000000000000000000000000000000000000003500000000wfmath-1701611135.403a8bd/src/wfmath/probability.cpp// probability.cpp (probability and statistics implementation) // // The WorldForge Project // Copyright (C) 2002 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Ron Steinke // Created: 2002-1-23 #include <wfmath/probability.h> #include <wfmath/const.h> #include <cmath> #include <cassert> namespace WFMath { template<typename FloatT> static FloatT LogPoisson(FloatT mean, unsigned int step); template<typename FloatT> static FloatT IncompleteGamma(FloatT a, FloatT z); template<typename FloatT> static FloatT IncompleteGammaNoPrefactor(FloatT a, FloatT z); template<typename FloatT> static FloatT IncompleteGammaComplement(FloatT a, FloatT z); template<typename FloatT> static FloatT IncompleteGammaComplementNoPrefactor(FloatT a, FloatT z); // Making this an int makes LogFactorial faster static const unsigned int GammaCutoff = 10; template<typename FloatT> FloatT GaussianConditional(FloatT mean, FloatT stddev, FloatT val) { assert(stddev != 0); FloatT diff = val - mean; FloatT diffnorm = diff / stddev; FloatT diffsqr_over_two = diffnorm * diffnorm / 2; /* Make sure round off error in Sqrt3 doesn't hit * assert() in IncompleteGammaComplementNoPrefactor() */ static const FloatT half = 0.5; if(diffnorm < numeric_constants<FloatT>::sqrt3() + 10 * std::numeric_limits<FloatT>::epsilon()) { FloatT erfc_norm = IncompleteGammaComplement(half, diffsqr_over_two); FloatT normalization = (diffnorm > 0) ? (erfc_norm / 2) : (1 - erfc_norm / 2); return Gaussian(mean, stddev, val) / normalization; } static const FloatT two = 2.0; return two / (std::fabs(diff) * IncompleteGammaComplementNoPrefactor<FloatT>(half, diffsqr_over_two)); } template<typename FloatT> FloatT Gaussian(FloatT mean, FloatT stddev, FloatT val) { assert(stddev != 0); FloatT diff = (mean - val) / stddev; return std::exp(-(diff * diff) / 2) / (std::fabs(stddev) * (numeric_constants<FloatT>::sqrt_pi() * numeric_constants<FloatT>::sqrt2())); } template<typename FloatT> FloatT PoissonConditional(FloatT mean, unsigned int step) { assert(mean >= 0); if(mean == 0) // Funky limit, but allow it return (step == 0) ? 1 : 0; if(step == 0) return std::exp(-mean); if(mean > step + 1) return Poisson(mean, step) / IncompleteGamma(static_cast<FloatT>(step), mean); static const FloatT one = 1.0; return one / IncompleteGammaNoPrefactor(static_cast<FloatT>(step), mean); } template<typename FloatT> FloatT Poisson(FloatT mean, unsigned int step) { assert(mean >= 0); if(mean == 0) // Funky limit, but allow it return (step == 0) ? 1 : 0; return std::exp(LogPoisson(mean, step)); } template<typename FloatT> static FloatT LogPoisson(FloatT mean, unsigned int step) { assert(mean > 0); if(step == 0) return -mean; FloatT first = static_cast<FloatT>(step) * std::log(mean); FloatT second = mean + LogFactorial<FloatT>(step); assert("LogFactorial() always returns positive" && second > 0); FloatT ans = first - second; // can only get probability == 1 for step == mean == 0 assert("must get probability < 1" && ans < 0); return ans; } template<typename FloatT> FloatT Factorial(unsigned int n) { if(n == 0 || n == 1) return 1; if(n < GammaCutoff) { FloatT ans = static_cast<FloatT>(n); while(--n > 1) // Don't need to multiply by 1 ans *= static_cast<FloatT>(n); return ans; } else return std::exp(LogGamma(static_cast<FloatT>(n + 1))); } template<typename FloatT> FloatT LogFactorial(unsigned int n) { if(n == 0 || n == 1) return 0; // ln(0!) = ln(1!) = ln(1) = 0 if(n < GammaCutoff) { FloatT ans = static_cast<FloatT>(n); while(--n > 1) // Don't need to multiply by 1 ans *= static_cast<FloatT>(n); return std::log(ans); } else return LogGamma(static_cast<FloatT>(n + 1)); } template<typename FloatT> FloatT Gamma(FloatT z) { if(z >= 0.5) return std::exp(LogGamma(z)); else return numeric_constants<FloatT>::pi() * std::exp(-LogGamma(1 - z)) / std::sin(numeric_constants<FloatT>::pi() * z); } template<typename FloatT> FloatT LogGamma(FloatT z) { /* This will return nan or something when z is a non-positive * integer (from trying to take log(0)), but that's what * should happen anyway. */ static const FloatT one = 1.0; if(z < 0.5) return numeric_constants<FloatT>::log_pi() - LogGamma<FloatT>(one - z) - std::log(std::fabs(std::sin(numeric_constants<FloatT>::pi() * z))); if(z == 0.5) // special case for Gaussian return numeric_constants<FloatT>::log_pi() / 2; if(z == 1 || z == 2) // 0! and 1! return 0; FloatT log_shift; if(z < GammaCutoff) { FloatT shift = 1; while(z < GammaCutoff) shift *= z++; log_shift = std::log(std::fabs(shift)); } else log_shift = 0; // Stirling approximation (see Gradshteyn + Ryzhik, Table of Integrals, // Series, and Products, fifth edition, formula 8.344 for a specific formula) static const FloatT half = 0.5, two = 2.0; FloatT ans = (z - half) * std::log(z) - log_shift - z + (numeric_constants<FloatT>::log_pi() + numeric_constants<FloatT>::log2()) / two; // coeffs[i] is the 2*(i+1)th Bernoulli number, divided by (2i + 1)*(2i + 2) static const FloatT coeffs[] = {1.0/12.0, -1.0/360.0, 1.0/1260.0, -1.0/1620.0, 5.0/5940.0, -691.0/360360.0, 7.0/1092.0, -3617.0/122400.0, 43867.0/244188.0, -174661.0/125400.0, 854513.0/63756.0,}; static const int num_coeffs = sizeof(coeffs) / sizeof(FloatT); FloatT z_power = 1/z; FloatT z_to_minus_two = z_power * z_power; FloatT small_enough = std::fabs(ans) * std::numeric_limits<FloatT>::epsilon(); int i; for(i = 0; i < num_coeffs; ++i) { FloatT next_term = coeffs[i] * z_power; ans += next_term; if(std::fabs(next_term) < small_enough) break; z_power *= z_to_minus_two; } assert(i < num_coeffs); // If someone hits this, tell me and I'll add more terms, // worst case is for n = cutoff = 10, which should work // for DBL_EPSILON > 1.048e-21 return ans; } template<typename FloatT> static FloatT IncompleteGamma(FloatT a, FloatT z) { assert(z >= 0 && a >= 0); // We only use this part of the parameter space if(a == 0) return 1; else if(z == 0) return 0; if(z > a + 1) return 1 - IncompleteGammaComplement(a, z); FloatT prefactor = std::exp(a * (std::log(z) + 1) - z - LogGamma(a)); return IncompleteGammaNoPrefactor(a, z) * prefactor; } template<typename FloatT> static FloatT IncompleteGammaNoPrefactor(FloatT a, FloatT z) { assert(z <= a + 1 && z > 0 && a > 0); // Power series FloatT term = 1; FloatT dividend = a; FloatT ans = term; while(std::fabs(term / ans) > std::numeric_limits<FloatT>::epsilon()) { term *= z / ++dividend; ans += term; } return ans; } template<typename FloatT> static FloatT IncompleteGammaComplement(FloatT a, FloatT z) { assert(z >= 0 && a >= 0); // We only use this part of the parameter space if(a == 0) return 0; else if(z == 0) return 1; if(z < a + 1) return 1 - IncompleteGamma(a, z); FloatT prefactor = std::exp(a * std::log(z) - z - LogGamma(a)); return IncompleteGammaComplementNoPrefactor(a, z) * prefactor; } template<typename FloatT> static FloatT IncompleteGammaComplementNoPrefactor(FloatT a, FloatT z) { assert(z >= a + 1 && a > 0); // Continued fraction static const FloatT fudge = 1000; FloatT b_contrib = z + 1 - a; FloatT a_last, b_last, a_next, b_next; FloatT term = 1; bool last_zero, next_zero = (std::fabs(b_contrib) <= std::numeric_limits<FloatT>::min() * fudge); if(next_zero) { a_last = 0; b_last = 1; a_next = 1; b_next = b_contrib; } else { a_last = 0; b_last = 1 / b_contrib; a_next = b_last; b_next = 1; } while(true) { FloatT a_tmp = a_next, b_tmp = b_next; FloatT a_contrib = term * (a - term); ++term; b_contrib += 2; a_next = b_contrib * a_tmp + a_contrib * a_last; b_next = b_contrib * b_tmp + a_contrib * b_last; a_last = a_tmp; b_last = b_tmp; last_zero = next_zero; next_zero = (std::fabs(b_next) <= std::fabs(a_next) * (std::numeric_limits<FloatT>::min() * fudge)); if(next_zero) continue; // b_next is about zero a_next /= b_next; if(!last_zero && std::fabs(a_next - a_last) < std::fabs(a_last) * std::numeric_limits<FloatT>::epsilon()) return a_next; // Can't compare if b_last was zero a_last /= b_next; b_last /= b_next; b_next = 1; } } template float GaussianConditional<float>(float mean, float stddev, float val); template float Gaussian<float>(float mean, float stddev, float val); template float PoissonConditional<float>(float mean, unsigned int step); template float Poisson<float>(float mean, unsigned int step); template float LogFactorial<float>(unsigned int n); template float Factorial<float>(unsigned int n); template float LogGamma<float>(float z); template float Gamma<float>(float z); template double GaussianConditional<double>(double mean, double stddev, double val); template double Gaussian<double>(double mean, double stddev, double val); template double PoissonConditional<double>(double mean, unsigned int step); template double Poisson<double>(double mean, unsigned int step); template double LogFactorial<double>(unsigned int n); template double Factorial<double>(unsigned int n); template double LogGamma<double>(double z); template double Gamma<double>(double z); } // namespace WFMath 07070100000037000081A4000000000000000000000001656C867F00000A2C000000000000000000000000000000000000003300000000wfmath-1701611135.403a8bd/src/wfmath/probability.h// probability.h (probability and statistics functions) // // The WorldForge Project // Copyright (C) 2002 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Ron Steinke // Created: 2002-1-23 // These functions will use double instead of CoordType, for accuracy #ifndef WFMATH_PROBABILTIY_H #define WFMATH_PROBABILTIY_H namespace WFMath { /// Gives the conditional probability of the Gaussian distribution at position val /** * The probability that a Gaussian random variable will fall between * val and val + delta, given that it is already known to be not * less than val, is given by this function multiplied by delta * (for small delta). **/ template<typename FloatT> FloatT GaussianConditional(FloatT mean, FloatT stddev, FloatT val); /// Gives the value of the Gaussian distribution at position val template<typename FloatT> FloatT Gaussian(FloatT mean, FloatT stddev, FloatT val); /// Gives the conditional probability of the Poisson distribution at position step /** * Returns the probability that a Poisson random variable will have value * step, given that it is already known not to be less than step. **/ template<typename FloatT> FloatT PoissonConditional(FloatT mean, unsigned int step); /// Gives the value of the Poisson distribution at position step template<typename FloatT> FloatT Poisson(FloatT mean, unsigned int step); /// Gives the natural log of n! template<typename FloatT> FloatT LogFactorial(unsigned int n); /// Gives n! template<typename FloatT> FloatT Factorial(unsigned int n); /// The natural log of Euler's Gamma function template<typename FloatT> FloatT LogGamma(FloatT z); /// Euler's Gamma function template<typename FloatT> FloatT Gamma(FloatT z); } // namespace WFMath #endif // WFMATH_PROBABILITY_H 07070100000038000081A4000000000000000000000001656C867F0000231C000000000000000000000000000000000000003400000000wfmath-1701611135.403a8bd/src/wfmath/quaternion.cpp// quaternion.cpp (Quaternion implementation) // // The WorldForge Project // Copyright (C) 2002 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // // Author: Ron Steinke // Some code here was taken from the quaternion implementation is // eris. Some of the other algorithms are based on information // found here <http://www.cs.ualberta.ca/~andreas/math/matrfaq_latest.html> // and here <http://www.cs.berkeley.edu/~laura/cs184/quat/quaternion.html>. #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "quaternion.h" #include "error.h" #include "rotmatrix.h" #include <cmath> #include <cassert> namespace WFMath { static_assert(std::is_standard_layout<Quaternion>::value, "Quaternion should be standard layout."); static_assert(std::is_trivially_copyable<Quaternion>::value, "Quaternion should be trivially copyable."); Quaternion::Quaternion (CoordType w_in, CoordType x_in, CoordType y_in, CoordType z_in) : m_w(0), m_vec(), m_valid(true), m_age(1) { CoordType norm = std::sqrt(w_in*w_in + x_in*x_in + y_in*y_in + z_in*z_in); m_w = w_in / norm; m_vec[0] = x_in / norm; m_vec[1] = y_in / norm; m_vec[2] = z_in / norm; m_vec.setValid(); } const Quaternion& Quaternion::IDENTITY() { static Quaternion ident = Quaternion(Identity()); return ident; } // The equality functions regard q and -q as equal, since they // correspond to the same rotation matrix. We consider the form // of the quaternion with w > 0 canonical. bool Quaternion::isEqualTo(const Quaternion &q, CoordType epsilon) const { // Since the sum of squares is 1, the magnitude of the largest // element must be between 1 and 0.5, so we don't need to scale epsilon. assert(epsilon > 0); //If anyone is invalid they are never equal if (!q.m_valid || !m_valid) { return false; } if(std::fabs(m_w - q.m_w) <= epsilon) { int i; for(i = 0; i < 3; ++i) if(std::fabs(m_vec[i] - q.m_vec[i]) > epsilon) break; // try again with swapped signs if(i == 3) // got through the loop return true; } // This makes q == -q true if(std::fabs(m_w + q.m_w) <= epsilon) { for(int i = 0; i < 3; ++i) if(std::fabs(m_vec[i] + q.m_vec[i]) > epsilon) return false; return true; } return false; } // order of multiplication vs sense of rotation // // v.rotate(q1).rotate(q2) is the same as v.rotate(q1 * q2), // the same as with matrices Quaternion& Quaternion::operator*= (const Quaternion& rhs) { m_valid = m_valid && rhs.m_valid; m_age = m_age + rhs.m_age; checkNormalization(); CoordType old_w = m_w; m_w = m_w * rhs.m_w - Dot(m_vec, rhs.m_vec); m_vec = old_w * rhs.m_vec + rhs.m_w * m_vec - Cross(m_vec, rhs.m_vec); return *this; } Quaternion& Quaternion::operator/= (const Quaternion& rhs) { m_valid = m_valid && rhs.m_valid; m_age = m_age + rhs.m_age; checkNormalization(); CoordType old_w = m_w; m_w = m_w * rhs.m_w + Dot(m_vec, rhs.m_vec); m_vec = rhs.m_w * m_vec - old_w * rhs.m_vec + Cross(m_vec, rhs.m_vec); return *this; } bool Quaternion::fromRotMatrix(const RotMatrix<3>& m) { RotMatrix<3> m_tmp; bool not_flip = !m.parity(); m_valid = m.isValid(); m_vec.setValid(m.isValid()); if(!not_flip) m_tmp = Prod(m, RotMatrix<3>().mirrorX()); const RotMatrix<3> &m_ref = not_flip ? m : m_tmp; CoordType s; const int nxt[3] = {1, 2, 0}; CoordType tr = m_ref.trace(); // check the diagonal if (tr > 0.0) { s = std::sqrt(tr + 1.0f); m_w = (s / 2.0f); s = (0.5f / s); m_vec[0] = (m_ref.elem(2, 1) - m_ref.elem(1, 2)) * s; m_vec[1] = (m_ref.elem(0, 2) - m_ref.elem(2, 0)) * s; m_vec[2] = (m_ref.elem(1, 0) - m_ref.elem(0, 1)) * s; } else { // diagonal is negative int i = 0; if (m_ref.elem(1, 1) > m_ref.elem(0, 0)) i = 1; if (m_ref.elem(2, 2) > m_ref.elem(i, i)) i = 2; int j = nxt[i], k = nxt[j]; s = std::sqrt (1.0f + m_ref.elem(i, i) - m_ref.elem(j, j) - m_ref.elem(k, k)); m_vec[i] = -(s * 0.5f); assert("sqrt() returns positive" && s > 0.0); s = (0.5f / s); m_w = (m_ref.elem(k, j) - m_ref.elem(j, k)) * s; m_vec[j] = (m_ref.elem(i, j) + m_ref.elem(j, i)) * s; m_vec[k] = (m_ref.elem(i, k) + m_ref.elem(k, i)) * s; } m_age = m.age(); return not_flip; } Quaternion Quaternion::inverse() const { Quaternion q(m_valid); q.m_w = m_w; q.m_vec = -m_vec; q.m_age = m_age; // no multiplication was done, so roundoff error does not increase return q; } Quaternion& Quaternion::rotate(const RotMatrix<3>& m) { // FIXME find a more efficient way to do this Quaternion tmp; tmp.fromRotMatrix(m); *this *= tmp; return *this; } Quaternion& Quaternion::rotation(int axis, CoordType angle) { if (axis < 0 || axis > 2) { m_valid = false; return *this; } CoordType half_angle = angle / 2; m_w = std::cos(half_angle); for(int i = 0; i < 3; ++i) // Note sin() only called once m_vec[i] = (i == axis) ? std::sin(half_angle) : 0; m_vec.setValid(); m_valid = true; m_age = 1; return *this; } Quaternion& Quaternion::rotation(const Vector<3>& axis, CoordType angle) { CoordType axis_mag = axis.mag(); CoordType half_angle = angle / 2; if (axis_mag < numeric_constants<CoordType>::epsilon()) { m_valid = false; return *this; } m_w = std::cos(half_angle); m_vec = axis * (std::sin(half_angle) / axis_mag); m_valid = axis.isValid(); m_age = 1; return *this; } Quaternion& Quaternion::rotation(const Vector<3>& axis) { CoordType axis_mag = axis.mag(); CoordType half_angle = axis_mag / 2; if (axis_mag < numeric_constants<CoordType>::epsilon()) { m_valid = false; return *this; } m_w = std::cos(half_angle); m_vec = axis * (std::sin(half_angle) / axis_mag); m_valid = axis.isValid(); m_age = 1; return *this; } Quaternion& Quaternion::rotation(const Vector<3>& from, const Vector<3>& to) { CoordType mag_prod = std::sqrt(from.sqrMag() * to.sqrMag()); CoordType ctheta_plus_1 = Dot(from, to) / mag_prod + 1; if (mag_prod < numeric_constants<CoordType>::epsilon()) { m_valid = false; return *this; } // antiparallel vectors if(ctheta_plus_1 < numeric_constants<CoordType>::epsilon()) // same check as used in the RotMatrix function throw ColinearVectors<3>(from, to); // cosine of half the angle m_w = std::sqrt(ctheta_plus_1 / 2.f); // vector in direction of axis, magnitude of cross product is proportional to // the sin of the angle, divide to make the magnitude the sin of half the angle, // sin(x) = 2sin(x/2)cos(x/2), so sin(x/2) = sin(x)/(2cos(x/2)) m_vec = Cross(from, to) / (2 * mag_prod * m_w); m_valid = from.isValid() && to.isValid(); m_age = 1; return *this; } Quaternion& Quaternion::rotation(const Vector<3>& from, const Vector<3>& to, const Vector<3>& fallbackAxis) { CoordType mag_prod = std::sqrt(from.sqrMag() * to.sqrMag()); CoordType ctheta_plus_1 = Dot(from, to) / mag_prod + 1; if (mag_prod < numeric_constants<CoordType>::epsilon()) { m_valid = false; return *this; } // antiparallel vectors if(ctheta_plus_1 < numeric_constants<CoordType>::epsilon()) { // same check as used in the RotMatrix function rotation(fallbackAxis, numeric_constants<CoordType>::pi()); } else { // cosine of half the angle m_w = std::sqrt(ctheta_plus_1 / 2.f); // vector in direction of axis, magnitude of cross product is proportional to // the sin of the angle, divide to make the magnitude the sin of half the angle, // sin(x) = 2sin(x/2)cos(x/2), so sin(x/2) = sin(x)/(2cos(x/2)) m_vec = Cross(from, to) / (2 * mag_prod * m_w); m_valid = from.isValid() && to.isValid(); m_age = 1; } return *this; } void Quaternion::normalize() { // Assume that we're not too far off, and compute the norm // only to linear order in the difference from 1. // If q.sqrMag() = 1 + x, q.mag() = 1 + x/2 = (q.SqrMag() + 1)/2 // to linear order. CoordType norm = (m_w * m_w + m_vec.sqrMag() + 1)/2; m_w /= norm; m_vec /= norm; m_age = 1; } } 07070100000039000081A4000000000000000000000001656C867F00001BA8000000000000000000000000000000000000003200000000wfmath-1701611135.403a8bd/src/wfmath/quaternion.h// quaternion.h (based on the Quaternion class from eris) // // The WorldForge Project // Copyright (C) 2002 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // // Author: Ron Steinke #ifndef WFMATH_QUATERNION_H #define WFMATH_QUATERNION_H #include <wfmath/vector.h> #include <wfmath/rotmatrix.h> namespace WFMath { /// A normalized quaternion class Quaternion { public: /** * Gets a static identity quaternion. * * @return A static identity quaternion. */ static const Quaternion& IDENTITY(); class Identity {}; /// Quaternion(const Identity &) : m_w(1), m_vec(WFMath::Vector<3>::ZERO()), m_valid(true), m_age(0) { } /// Construct a Quaternion Quaternion() : m_w(0), m_vec{}, m_valid(false), m_age(0){} /// Construct a Quaternion from (w, x, y, z) components /** * This normalizes the components so the sum of their squares is one. **/ Quaternion (CoordType w_in, CoordType x_in, CoordType y_in, CoordType z_in); /// Construct a Quaternion giving a rotation around axis by angle Quaternion (int axis, CoordType angle) : m_w(0), m_vec(), m_valid(false), m_age(0) {rotation(axis, angle);} /// Construct a Quaternion giving a rotation around the Vector axis by angle Quaternion (const Vector<3>& axis, CoordType angle) : m_w(0), m_vec(), m_valid(false), m_age(0) {rotation(axis, angle);} /// Construct a Quaternion giving a rotation around the Vector axis /** * The angle of rotating is equal to the magnitude of the Vector **/ explicit Quaternion (const Vector<3>& axis) : m_w(0), m_vec(), m_valid(false), m_age(0) {rotation(axis);} // angle == axis.mag() /// Construct a copy of a Quaternion Quaternion (const Quaternion& p) = default; /// Construct a Quaternion from an Atlas::Message::Object explicit Quaternion (const AtlasInType& a) : m_w(0), m_vec(), m_valid(false), m_age(0) {fromAtlas(a);} ~Quaternion() = default; friend std::ostream& operator<<(std::ostream& os, const Quaternion& p); friend std::istream& operator>>(std::istream& is, Quaternion& p); /// Create an Atlas object from the Quaternion AtlasOutType toAtlas() const; /// Set the Quaternion's value to that given by an Atlas object void fromAtlas(const AtlasInType& a); Quaternion& operator= (const Quaternion& rhs) = default; // This regards q and -1*q as equal, since they give the // same RotMatrix<3> bool isEqualTo(const Quaternion &q, CoordType epsilon = numeric_constants<CoordType>::epsilon()) const; bool operator== (const Quaternion& rhs) const {return isEqualTo(rhs);} bool operator!= (const Quaternion& rhs) const {return !isEqualTo(rhs);} bool isValid() const {return m_valid;} /// Set the Quaternion to the identity rotation Quaternion& identity() {m_w = 1; m_vec.zero(); m_valid = true; m_age = 0; return *this;} // Set to null rotation // Operators /// Quaternion& operator*= (const Quaternion& rhs); /// Quaternion& operator/= (const Quaternion& rhs); /// Quaternion operator* (const Quaternion& rhs) const { Quaternion out(*this); out *= rhs; return out; } /// Quaternion operator/ (const Quaternion& rhs) const { Quaternion out(*this); out /= rhs; return out; } // Functions // Returns "not_flip", similar to RotMatrix<>.toEuler() /// set a Quaternion's value from a RotMatrix /** * Since a Quaternion can only represent an even-parity * RotMatrix, this function returns false if the parity of * m is odd. In this case, the quaternion is set to the value * of m multiplied by a fixed parity-odd RotMatrix, so * the full RotMatrix can be recovered by passing * the Quaternion and the value of 'not_flip' returned * by this function to RotMatrix::fromQuaternion(). **/ bool fromRotMatrix(const RotMatrix<3>& m); /// returns the inverse of the Quaternion Quaternion inverse() const; /// Rotate quaternion using the matrix. Quaternion& rotate(const RotMatrix<3>&); /// rotate the quaternion using another quaternion Quaternion& rotate(const Quaternion& q) {return operator*=(q);} /// sets the Quaternion to a rotation by angle around axis Quaternion& rotation(int axis, CoordType angle); /// sets the Quaternion to a rotation by angle around the Vector axis Quaternion& rotation(const Vector<3>& axis, CoordType angle); /// sets the Quaternion to a rotation around the Vector axis /** * The rotation angle is given by the magnitude of the Vector **/ Quaternion& rotation(const Vector<3>& axis); // angle == axis.mag() /** * @brief Sets the Quaternion to rotate 'from' to be parallel to 'to'. * * @param from The vector to rotate from. * @param to The vector to rotate to. * * If the vectors are colinear a ColinearVectors exception is thrown. * If this is undesirable see rotation(const Vector<3>&, const Vector<3>&, const Vector<3>&) * instead */ Quaternion& rotation(const Vector<3>& from, const Vector<3>& to); /** * @brief Sets the Quaternion to rotate 'from' to be parallel to 'to'. * * @param from The vector to rotate from. * @param to The vector to rotate to. * @param fallbackAxis If the vectors are colinear, rotate around this axis instead. * */ Quaternion& rotation(const Vector<3>& from, const Vector<3>& to, const Vector<3>& fallbackAxis); /// returns the scalar (w) part of the Quaternion CoordType scalar() const {return m_w;} /// returns the Vector (x, y, z) part of the quaternion const Vector<3>& vector() const {return m_vec;} /// normalize to remove accumulated round-off error void normalize(); /// current round-off age unsigned age() const {return m_age;} private: Quaternion(bool valid) : m_w(0), m_vec(), m_valid(valid), m_age(1) {} void checkNormalization() {if(m_age >= WFMATH_MAX_NORM_AGE && m_valid) normalize();} CoordType m_w; Vector<3> m_vec; bool m_valid; unsigned m_age; }; } // namespace WFMath #endif // WFMATH_QUATERNION_H 0707010000003A000081A4000000000000000000000001656C867F000019AC000000000000000000000000000000000000003100000000wfmath-1701611135.403a8bd/src/wfmath/randgen.cpp// randgen.cpp (time and random number implementation) // // The WorldForge Project // Copyright (C) 2002, 2013 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // // Portions of the code in this file were copied and modified from // http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/CODES/mt19937ar.c // // Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, // All rights reserved. // // 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. The names of its contributors may not 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 OWNER 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. // // Original Author: Ron Steinke // Created: 2002-5-23 #include "randgen.h" #include <ctime> #include <cstdio> #include <istream> #include <ostream> #include <climits> #ifdef HAVE_CONFIG_H #include "config.h" #endif namespace WFMath { const MTRand::uint32 MTRand::state_size; MTRand MTRand::instance; static const MTRand::uint32 period = 397; static const MTRand::uint32 MATRIX_A = 0x9908b0df; static const MTRand::uint32 UPPER_MASK = 0x80000000; static const MTRand::uint32 LOWER_MASK = 0x7fffffff; static MTRand::uint32 hash( time_t t, clock_t c ) { // Get a uint32 from t and c // Better than uint32(x) in case x is floating point in [0,1] // Based on code by Lawrence Kirby (fred@genesis.demon.co.uk) typedef MTRand::uint32 uint32; // guarantee time-based seeds will change static uint32 differ = 0; uint32 h1 = 0; auto *p = (unsigned char *) &t; for( size_t i = 0; i < sizeof(t); ++i ) { h1 *= UCHAR_MAX + 2U; h1 += p[i]; } uint32 h2 = 0; p = (unsigned char *) &c; for( size_t j = 0; j < sizeof(c); ++j ) { h2 *= UCHAR_MAX + 2U; h2 += p[j]; } return ( h1 + differ++ ) ^ h2; } void MTRand::seed() { // First try getting an array from /dev/urandom FILE* urandom = fopen( "/dev/urandom", "rb" ); if( urandom ) { uint32 init_vector[state_size]; uint32 *s = init_vector; int i = state_size; bool success = true; while( success && i-- ) success = fread( s++, sizeof(uint32), 1, urandom ); fclose(urandom); if( success ) { seed( init_vector, state_size ); return; } } // Was not successful, so use time() and clock() instead seed( hash( time(nullptr), clock() ) ); } void MTRand::seed(uint32 s) { state[0] = s; for (index = 1; index < state_size; ++index) { state[index] = (1812433253UL * (state[index-1] ^ (state[index-1] >> 30u)) + index); } } void MTRand::seed(const uint32 init_vector[], const uint32 init_vector_length) { seed(19650218UL); uint32 i = 1; uint32 j = 0; uint32 k = (state_size > init_vector_length ? state_size : init_vector_length); for( ; k; --k ) { state[i] ^= ((state[i-1] ^ (state[i-1] >> 30u)) * 1664525UL); state[i] += (init_vector[j] & 0xffffffffUL) + j; ++i; ++j; if (i >= state_size) { state[0] = state[state_size-1]; i = 1; } if (j >= init_vector_length) j = 0; } for (k = state_size - 1; k; --k) { state[i] ^= ((state[i-1] ^ (state[i-1] >> 30u)) * 1566083941UL); state[i] -= i; ++i; if (i >= state_size) { state[0] = state[state_size-1]; i = 1; } } state[0] = 0x80000000UL; // MSB is 1, assuring non-zero initial array } MTRand::uint32 MTRand::randInt() { uint32 y; static unsigned long mag01[2]={0x0UL, MATRIX_A}; /* generate state_size words at one time */ if (index >= state_size) { uint32 kk; for (kk=0; kk < state_size - period; kk++) { y = (state[kk]&UPPER_MASK) | (state[kk+1]&LOWER_MASK); state[kk] = state[kk + period] ^ (y >> 1u) ^ mag01[y & 0x01u]; } for (; kk < state_size-1; kk++) { y = (state[kk]&UPPER_MASK) | (state[kk+1]&LOWER_MASK); state[kk] = state[kk+(period - state_size)] ^ (y >> 1u) ^ mag01[y & 0x01u]; } y = (state[state_size-1]&UPPER_MASK) | (state[0]&LOWER_MASK); state[state_size-1] = state[period-1] ^ (y >> 1u) ^ mag01[y & 0x1UL]; index = 0; } y = state[index++]; /* Tempering */ y ^= (y >> 11u); y ^= (y << 7u) & 0x9d2c5680UL; y ^= (y << 15u) & 0xefc60000UL; y ^= (y >> 18u); return y; } std::ostream& MTRand::save(std::ostream& ostr) const { for (auto i : state) { ostr << i << '\t'; } return ostr << index; } std::istream& MTRand::load(std::istream& istr) { for (auto & i : state) istr >> i; istr >> index; return istr; } } 0707010000003B000081A4000000000000000000000001656C867F00000474000000000000000000000000000000000000002F00000000wfmath-1701611135.403a8bd/src/wfmath/randgen.h// randgen.h (random number functions) // // The WorldForge Project // Copyright (C) 2002 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Ron Steinke // Created: 2002-5-23 #ifndef WFMATH_RANDGEN_H #define WFMATH_RANDGEN_H #include <wfmath/MersenneTwister.h> #endif // WFMATH_RANDGEN_H 0707010000003C000081A4000000000000000000000001656C867F00000BC6000000000000000000000000000000000000003000000000wfmath-1701611135.403a8bd/src/wfmath/rotbox.cpp// rotbox.cpp (RotBox<> implementation) // // The WorldForge Project // Copyright (C) 2011 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Alistair Riddoch // Created: 2011-1-27 // Extensive amounts of this material come from the Vector2D // and Vector3D classes from stage/math, written by Bryce W. // Harrington, Kosh, and Jari Sundell (Rakshasa). #include "rotbox_funcs.h" #include "quaternion.h" #include <cmath> namespace WFMath { template<> RotBox<3>& RotBox<3>::rotatePoint(const Quaternion& q, const Point<3>& p) { m_orient = m_orient.rotate(q); m_corner0.rotate(q, p); return *this; } template<> RotBox<3>& RotBox<3>::rotateCorner(const Quaternion& q, size_t corner) { rotatePoint(q, getCorner(corner)); return *this; } template<> RotBox<3>& RotBox<3>::rotateCenter(const Quaternion& q) { rotatePoint(q, getCenter()); return *this; } template<> RotBox<3> RotBox<3>::toParentCoords(const Point<3>& origin, const Quaternion& rotation) const { RotMatrix<3> orient = m_orient; return RotBox<3>(m_corner0.toParentCoords(origin, rotation), m_size, orient.rotate(rotation)); } template<> RotBox<3> RotBox<3>::toLocalCoords(const Point<3>& origin, const Quaternion& rotation) const { RotMatrix<3> orient = m_orient; return RotBox<3>(m_corner0.toLocalCoords(origin, rotation), m_size, orient.rotate(rotation.inverse())); } template class RotBox<2>; template class RotBox<3>; static_assert(std::is_standard_layout<RotBox<2>>::value, "RotBox should be standard layout."); static_assert(std::is_trivially_copyable<RotBox<2>>::value, "RotBox should be trivially copyable."); static_assert(std::is_standard_layout<RotBox<3>>::value, "RotBox should be standard layout."); static_assert(std::is_trivially_copyable<RotBox<3>>::value, "RotBox should be trivially copyable."); template Point<2> Point<2>::toLocalCoords(RotBox<2> const&) const; template Point<3> Point<3>::toLocalCoords(RotBox<3> const&) const; template Point<2> Point<2>::toParentCoords(RotBox<2> const&) const; template Point<3> Point<3>::toParentCoords(RotBox<3> const&) const; } 0707010000003D000081A4000000000000000000000001656C867F00001E8D000000000000000000000000000000000000002E00000000wfmath-1701611135.403a8bd/src/wfmath/rotbox.h// rotbox.h (A box with arbitrary orientation) // // The WorldForge Project // Copyright (C) 2000, 2001 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // // Author: Ron Steinke #ifndef WFMATH_ROT_BOX_H #define WFMATH_ROT_BOX_H #include <wfmath/point.h> #include <wfmath/rotmatrix.h> #include <wfmath/intersect_decls.h> namespace WFMath { template<int dim> std::ostream& operator<<(std::ostream& os, const RotBox<dim>& r); template<int dim> std::istream& operator>>(std::istream& is, RotBox<dim>& r); /// A dim dimensional box, lying at an arbitrary angle /** * This class implements the full shape interface, as described in * the fake class Shape. **/ template<int dim = 3> class RotBox { public: /// construct an uninitialized box RotBox() : m_corner0{}, m_size{}, m_orient{} {} /// construct a box from the given parameters /** * p gives corner 0 of the box, size gives the offset from corner * 0 to the opposite corner (corner 2^dim - 1), orientation gives * the rotation of the box relative to the coordinate axes **/ RotBox(const Point<dim>& p, const Vector<dim>& size, const RotMatrix<dim>& orientation) : m_corner0(p), m_size(size), m_orient(orientation) {} /// construct a copy of the box RotBox(const RotBox& b) = default; /// Construct a rotbox from an object passed by Atlas explicit RotBox(const AtlasInType& a); ~RotBox() = default; /// Create an Atlas object from the box AtlasOutType toAtlas() const; /// Set the box's value to that given by an Atlas object void fromAtlas(const AtlasInType& a); friend std::ostream& operator<< <dim>(std::ostream& os, const RotBox& r); friend std::istream& operator>> <dim>(std::istream& is, RotBox& r); RotBox& operator=(const RotBox& s) = default; bool isEqualTo(const RotBox& b, CoordType epsilon = numeric_constants<CoordType>::epsilon()) const; bool operator==(const RotBox& b) const {return isEqualTo(b);} bool operator!=(const RotBox& b) const {return !isEqualTo(b);} bool isValid() const {return m_corner0.isValid() && m_size.isValid() && m_orient.isValid();} // Descriptive characteristics size_t numCorners() const {return 1 << dim;} Point<dim> getCorner(size_t i) const; Point<dim> getCenter() const {return m_corner0 + Prod(m_size / 2, m_orient);} /// returns the base corner of the box const Point<dim>& corner0() const {return m_corner0;} /// returns the base corner of the box Point<dim>& corner0() {return m_corner0;} /// returns the size of the box const Vector<dim>& size() const {return m_size;} /// returns the size of the box Vector<dim>& size() {return m_size;} /// returns the orientation of the box const RotMatrix<dim>& orientation() const {return m_orient;} /// returns the orientation of the box RotMatrix<dim>& orientation() {return m_orient;} // Movement functions RotBox& shift(const Vector<dim>& v) {m_corner0 += v; return *this;} RotBox& moveCornerTo(const Point<dim>& p, size_t corner) {return shift(p - getCorner(corner));} RotBox& moveCenterTo(const Point<dim>& p) {return shift(p - getCenter());} RotBox& rotateCorner(const RotMatrix<dim>& m, size_t corner) {rotatePoint(m, getCorner(corner)); return *this;} RotBox& rotateCenter(const RotMatrix<dim>& m) {rotatePoint(m, getCenter()); return *this;} RotBox& rotatePoint(const RotMatrix<dim>& m, const Point<dim>& p) {m_orient = Prod(m_orient, m); m_corner0.rotate(m, p); return *this;} // 3D rotation functions RotBox& rotateCorner(const Quaternion& q, size_t corner); RotBox& rotateCenter(const Quaternion& q); RotBox& rotatePoint(const Quaternion& q, const Point<dim>& p); // Intersection functions AxisBox<dim> boundingBox() const; Ball<dim> boundingSphere() const {return Ball<dim>(getCenter(), m_size.mag() / 2);} Ball<dim> boundingSphereSloppy() const {return Ball<dim>(getCenter(), m_size.sqrMag() / 2);} RotBox toParentCoords(const Point<dim>& origin, const RotMatrix<dim>& rotation = RotMatrix<dim>().identity()) const {return RotBox(m_corner0.toParentCoords(origin, rotation), m_size, m_orient * rotation);} RotBox toParentCoords(const AxisBox<dim>& coords) const {return RotBox(m_corner0.toParentCoords(coords), m_size, m_orient);} RotBox toParentCoords(const RotBox<dim>& coords) const {return RotBox(m_corner0.toParentCoords(coords), m_size, m_orient * coords.m_orient);} // toLocal is just like toParent, expect we reverse the order of // translation and rotation and use the opposite sense of the rotation // matrix RotBox toLocalCoords(const Point<dim>& origin, const RotMatrix<dim>& rotation = RotMatrix<dim>().identity()) const {return RotBox(m_corner0.toLocalCoords(origin, rotation), m_size, rotation * m_orient);} RotBox toLocalCoords(const AxisBox<dim>& coords) const {return RotBox(m_corner0.toLocalCoords(coords), m_size, m_orient);} RotBox toLocalCoords(const RotBox<dim>& coords) const {return RotBox(m_corner0.toLocalCoords(coords), m_size, coords.m_orient * m_orient);} // 3D only RotBox toParentCoords(const Point<dim>& origin, const Quaternion& rotation) const; RotBox toLocalCoords(const Point<dim>& origin, const Quaternion& rotation) const; friend bool Intersect<dim>(const RotBox& r, const Point<dim>& p, bool proper); friend bool Contains<dim>(const Point<dim>& p, const RotBox& r, bool proper); friend bool Intersect<dim>(const RotBox& r, const AxisBox<dim>& b, bool proper); friend bool Contains<dim>(const RotBox& r, const AxisBox<dim>& b, bool proper); friend bool Contains<dim>(const AxisBox<dim>& b, const RotBox& r, bool proper); friend bool Intersect<dim>(const RotBox& r, const Ball<dim>& b, bool proper); friend bool Contains<dim>(const RotBox& r, const Ball<dim>& b, bool proper); friend bool Contains<dim>(const Ball<dim>& b, const RotBox& r, bool proper); friend bool Intersect<dim>(const RotBox& r, const Segment<dim>& s, bool proper); friend bool Contains<dim>(const RotBox& r, const Segment<dim>& s, bool proper); friend bool Contains<dim>(const Segment<dim>& s, const RotBox& r, bool proper); friend bool Intersect<dim>(const RotBox& r1, const RotBox& r2, bool proper); friend bool Contains<dim>(const RotBox& outer, const RotBox& inner, bool proper); friend bool Intersect<dim>(const Polygon<dim>& p, const RotBox& r, bool proper); friend bool Contains<dim>(const Polygon<dim>& p, const RotBox& r, bool proper); friend bool Contains<dim>(const RotBox& r, const Polygon<dim>& p, bool proper); private: Point<dim> m_corner0; Vector<dim> m_size; RotMatrix<dim> m_orient; }; template<int dim> inline bool RotBox<dim>::isEqualTo(const RotBox<dim>& b, CoordType epsilon) const { return Equal(m_corner0, b.m_corner0, epsilon) && Equal(m_size, b.m_size, epsilon) && Equal(m_orient, b.m_orient, epsilon); } } // namespace WFMath #endif // WFMATH_ROT_BOX_H 0707010000003E000081A4000000000000000000000001656C867F00000BBC000000000000000000000000000000000000003400000000wfmath-1701611135.403a8bd/src/wfmath/rotbox_funcs.h// rotbox_funcs.h (line rotbox implementation) // // The WorldForge Project // Copyright (C) 2000, 2001 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // // Author: Ron Steinke #ifndef WFMATH_ROT_BOX_FUNCS_H #define WFMATH_ROT_BOX_FUNCS_H #include <wfmath/rotbox.h> #include <wfmath/vector.h> #include <wfmath/point.h> #include <wfmath/axisbox.h> #include <wfmath/ball.h> #include <cassert> namespace WFMath { template<int dim> inline Point<dim> RotBox<dim>::getCorner(size_t i) const { assert(i < (1 << dim)); Vector<dim> dist; if(i == 0) return m_corner0; for(int j = 0; j < dim; ++j) dist[j] = (i & (1 << j)) ? m_size[j] : 0; dist.setValid(m_size.isValid()); return m_corner0 + Prod(dist, m_orient); } template<int dim> AxisBox<dim> RotBox<dim>::boundingBox() const { Point<dim> min = m_corner0, max = m_corner0; // for(int i = 0; i < dim; ++i) { // Vector<dim> edge; // edge.zero(); // edge[i] = m_size[i]; // edge = Prod(edge, m_orient); // // Edge now represents the i'th edge // // pointing away from m_corner0 // for(int j = 0; j < dim; ++j) { // if(edge[j] < 0) // min[j] += edge[j]; // else // max[j] += edge[j]; // } // } // The following is equivalent to the above. The above is easier to understand, // so leave it in as a comment. for(int i = 0; i < dim; ++i) { for(int j = 0; j < dim; ++j) { CoordType value = m_orient.elem(j, i) * m_size[j]; if(value < 0) min[i] += value; else max[i] += value; } } bool valid = isValid(); min.setValid(valid); max.setValid(valid); return AxisBox<dim>(min, max, true); } // This is here, instead of defined in the class, to // avoid include order problems template<int dim> Point<dim> Point<dim>::toParentCoords(const RotBox<dim>& coords) const { return coords.corner0() + (*this - Point().setToOrigin()) * coords.orientation(); } template<int dim> Point<dim> Point<dim>::toLocalCoords(const RotBox<dim>& coords) const { return Point().setToOrigin() + coords.orientation() * (*this - coords.corner0()); } } // namespace WFMath #endif // WFMATH_ROT_BOX_FUNCS_H 0707010000003F000081A4000000000000000000000001656C867F00002E98000000000000000000000000000000000000003300000000wfmath-1701611135.403a8bd/src/wfmath/rotmatrix.cpp// rotmatrix.cpp (RotMatrix<> implementation) // // The WorldForge Project // Copyright (C) 2001 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Ron Steinke // Created: 2001-12-7 #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "rotmatrix_funcs.h" #include "quaternion.h" #include <limits> namespace WFMath { static CoordType _MatrixDeterminantImpl(int size, CoordType* m); template<> RotMatrix<3>& RotMatrix<3>::fromQuaternion(const Quaternion& q, const bool not_flip) { CoordType xx, yy, zz, xy, xz, yz; const Vector<3> &vref = q.vector(); xx = vref[0] * vref[0]; xy = vref[0] * vref[1]; xz = vref[0] * vref[2]; yy = vref[1] * vref[1]; yz = vref[1] * vref[2]; zz = vref[2] * vref[2]; Vector<3> wvec = vref * q.scalar(); m_elem[0][0] = 1 - 2 * (yy + zz); m_elem[1][1] = 1 - 2 * (xx + zz); m_elem[2][2] = 1 - 2 * (xx + yy); m_elem[0][1] = 2 * (xy - wvec[2]); m_elem[0][2] = 2 * (xz + wvec[1]); m_elem[1][0] = 2 * (xy + wvec[2]); m_elem[1][2] = 2 * (yz - wvec[0]); m_elem[2][0] = 2 * (xz - wvec[1]); m_elem[2][1] = 2 * (yz + wvec[0]); m_flip = !not_flip; m_age = q.age(); if(!not_flip) *this = Prod(*this, RotMatrix<3>().mirror(0)); m_valid = true; return *this; } template<> RotMatrix<3>& RotMatrix<3>::rotate(const Quaternion& q) { Vector<3> vec; vec.setValid(); m_valid = m_valid && q.isValid(); m_age += q.age(); // rotate both sides by q for(auto & vec_num : m_elem) { for(int elem_num = 0; elem_num < 3; ++elem_num) vec[elem_num] = vec_num[elem_num]; vec.rotate(q); for(int elem_num = 0; elem_num < 3; ++elem_num) vec_num[elem_num] = vec[elem_num]; } checkNormalization(); return *this; } template<> RotMatrix<3>& RotMatrix<3>::rotation (const Vector<3>& axis, CoordType theta) { CoordType max = 0; int main_comp = -1; for(int i = 0; i < 3; ++i) { CoordType val = std::fabs(axis[i]); if(val > max) { max = val; main_comp = i; } } assert("Must pass a nonzero length vector as axis to avoid this" && main_comp != -1); Vector<3> tmp, v1, v2; int new_comp = main_comp ? main_comp - 1 : 2; // Not parallel to axis for(int i = 0; i < 3; ++i) tmp[i] = ((i == new_comp) ? 1.f : 0.f); v1 = Cross(axis, tmp); // 3D specific part v2 = Cross(axis, v1); return rotation(v1, v2, theta); } template<> RotMatrix<3>& RotMatrix<3>::rotation (const Vector<3>& axis) { CoordType max = 0; int main_comp = -1; CoordType angle = axis.mag(); if(angle == 0) { return identity(); } for(int i = 0; i < 3; ++i) { CoordType val = std::fabs(axis[i]); if(val > max) { max = val; main_comp = i; } } assert("Can't happen with nonzero angle" && main_comp != -1); Vector<3> tmp, v1, v2; int new_comp = main_comp ? main_comp - 1 : 2; // Not parallel to axis for(int i = 0; i < 3; ++i) tmp[i] = ((i == new_comp) ? 1.f : 0.f); v1 = Cross(axis, tmp); // 3D specific part v2 = Cross(axis, v1); return rotation(v1, v2, angle); } bool _MatrixSetValsImpl(const int size, CoordType* vals, bool& flip, CoordType* buf1, CoordType* buf2, CoordType precision) { precision = std::fabs(precision); if(precision >= .9) // Can get an infinite loop for precision == 1 return false; // Check that vals form an orthogonal matrix, also increase their // precision to WFMATH_EPSILON while(true) { CoordType try_prec = 0; for(int i = 0; i < size; ++i) { for(int j = 0; j < size; ++j) { CoordType ans = 0; for(int k = 0; k < size; ++k) { ans += vals[i*size+k] * vals[j*size+k]; } if(i == j) // Subtract identity matrix --ans; ans = std::fabs(ans); if(ans >= try_prec) try_prec = ans; } } if(try_prec > precision) return false; if(try_prec <= numeric_constants<CoordType>::epsilon()) break; // Precision needs improvement, use linear approximation scheme. // This scheme takes the original matrix (call it A) // and subtracts another matrix (delta), where // // delta = (A - (A^T)^-1) / 2 // // This is correct, up to errors of order delta^2, // if you assume you can choose a delta such that // A^T * delta is symmetric (delta is underdetermined // by the linear approximation scheme) // This procedure will not increase the precision of // the parameters which determine the matrix (i.e. the // Euler angles), but it will increase the precision // to which the matrix satisfies the condition // A^T * A == (identity matrix). // The symmetry condition on A^T * delta represents an // arbitrary condition which will determine the higher // precision components of the Euler angles. This // makes the problem of increasing the precision of // the matrix well determined, and solvable by this // perturbative method. for(int i = 0; i < size; ++i) { for(int j = 0; j < size; ++j) { buf1[i*size+j] = vals[j*size+i]; buf2[i*size+j] = ((i == j) ? 1.f : 0.f); } } bool ans = _MatrixInverseImpl(size, buf1, buf2); if(!ans) { // Degenerate matrix, something badly wrong return false; } for(int i = 0; i < size; ++i) { for(int j = 0; j < size; ++j) { CoordType& elem = vals[i*size+j]; elem += buf2[i*size+j]; elem /= 2; } } // The above scheme should approx. square the precision. // That is, try_prec -> try_prec * try_prec * (fudge factor) // in the next iteration. } // The determinant is either 1 or -1, depending on the parity. // Use that to calculate flip. for(int i = 0; i < size; ++i) for(int j = 0; j < size; ++j) buf1[i*size+j] = vals[i*size+j]; flip = _MatrixDeterminantImpl(size, buf1) < 0; return true; } static CoordType _MatrixDeterminantImpl(const int size, CoordType* m) { // First, construct an upper triangular matrix with the // same determinant as the original matrix. Then just // multiply the diagonal terms to get the determinant. for(int i = 0; i < size - 1; ++i) { CoordType minval = 0; for(int j = 0; j < size; ++j) minval += m[j*size+i] * m[j*size+i]; minval /= std::numeric_limits<CoordType>::max(); if(minval < std::numeric_limits<CoordType>::min()) minval = std::numeric_limits<CoordType>::min(); if(m[i*size+i] * m[i*size+i] < minval) { // Find a row with nonzero element int j; for(j = i + 1; j < size; ++j) if(m[j*size+i] * m[j*size+i] >= minval) break; if(j == size) // No nonzero element found, degenerate matrix, det == 0 return 0; m[i*size+i] = m[j*size+i]; for(int k = i + 1; k < size; ++k) // For k < i, m[j*size+k] == 0 m[i*size+k] += m[j*size+k]; } for(int j = i + 1; j < size; ++j) { CoordType factor = m[j*size+i] / m[i*size+i]; // We know factor isn't bigger than about sqrt(WFMATH_MAX), due to // the comparison with minval done above. m[j*size+i] = 0; if(factor != 0) { for(int k = i + 1; k < size; ++k) // For k < i, m[k*size+j] == 0 m[j*size+k] -= m[i*size+k] * factor; } } } CoordType out = 1; for(int i = 0; i < size; ++i) out *= m[i*size+i]; return out; } bool _MatrixInverseImpl(const int size, CoordType* in, CoordType* out) { // Invert using row operations. First, make m upper triangular, // with 1's on the diagonal for(int i = 0; i < size; ++i) { // Make sure in[i*size+i] is nonzero CoordType minval = 0; for(int j = 0; j < size; ++j) minval += in[j*size+i] * in[j*size+i]; minval /= std::numeric_limits<CoordType>::max(); if(minval < std::numeric_limits<CoordType>::min()) minval = std::numeric_limits<CoordType>::min(); if(in[i*size+i] * in[i*size+i] < minval) { // Find a nonzero element int j; for(j = i + 1; j < size; ++j) if(in[j*size+i] * in[j*size+i] >= minval) break; if(j == size) // degenerate matrix return false; for(int k = 0; k < size; ++k) { out[i*size+k] += out[j*size+k]; in[i*size+k] += in[j*size+k]; } } // We now know in[i*size+i] / in[j*size+i] >= sqrt(WFMATH_MIN) for any j // Normalize the row, so in[i*size+i] == 1 CoordType tmp = in[i*size+i]; in[i*size+i] = 1; for(int j = 0; j < size; ++j) { out[i*size+j] /= tmp; if(j > i) // in[i*size+j] == 0 for j < i in[i*size+j] /= tmp; } // Do row subtraction to make in[j*size+i] zero for j > i for(int j = i + 1; j < size; ++j) { CoordType tmp2 = in[j*size+i]; in[j*size+i] = 0; if(tmp2 != 0) { for(int k = 0; k < size; ++k) { out[j*size+k] -= out[i*size+k] * tmp2; in[j*size+k] -= in[i*size+k] * tmp2; } } } } // Now perform row operations on "out" which would make "m" // into the identity matrix for(int i = size - 1; i >= 1; --i) { for(int j = i - 1; j >= 0; --j) { CoordType tmp = in[j*size+i]; if(tmp != 0) for(int k = 0; k < size; ++k) out[j*size+k] -= out[i*size+k] * tmp; // Don't bother modifying in[j*size+k], we never use it again. } } return true; } template <> RotMatrix<3>::RotMatrix(const Quaternion& q, const bool not_flip) : m_flip(false), m_valid(false), m_age(0) { fromQuaternion(q, not_flip); } template class RotMatrix<2>; template class RotMatrix<3>; static_assert(std::is_standard_layout<RotMatrix<2>>::value, "RotMatrix should be standard layout."); static_assert(std::is_trivially_copyable<RotMatrix<2>>::value, "RotMatrix should be trivially copyable."); static_assert(std::is_standard_layout<RotMatrix<3>>::value, "RotMatrix should be standard layout."); static_assert(std::is_trivially_copyable<RotMatrix<3>>::value, "RotMatrix should be trivially copyable."); template RotMatrix<2> operator*<2>(RotMatrix<2> const&, RotMatrix<2> const&); template RotMatrix<3> operator*<3>(RotMatrix<3> const&, RotMatrix<3> const&); template RotMatrix<2> ProdInv<2>(RotMatrix<2> const&, RotMatrix<2> const&); template RotMatrix<3> ProdInv<3>(RotMatrix<3> const&, RotMatrix<3> const&); template Vector<2> operator*<2>(Vector<2> const&, RotMatrix<2> const&); template Vector<3> operator*<3>(Vector<3> const&, RotMatrix<3> const&); template Vector<2> operator*<2>(RotMatrix<2> const&, Vector<2> const&); template Vector<3> operator*<3>(RotMatrix<3> const&, Vector<3> const&); template Vector<2> ProdInv<2>(Vector<2> const&, RotMatrix<2> const&); template Vector<3> ProdInv<3>(Vector<3> const&, RotMatrix<3> const&); template Vector<3> Prod<3>(Vector<3> const&, RotMatrix<3> const&); template Vector<2> Prod<2>(Vector<2> const&, RotMatrix<2> const&); template RotMatrix<3> Prod<3>(RotMatrix<3> const&, RotMatrix<3> const&); template RotMatrix<2> Prod<2>(RotMatrix<2> const&, RotMatrix<2> const&); } 07070100000040000081A4000000000000000000000001656C867F000028A4000000000000000000000000000000000000003100000000wfmath-1701611135.403a8bd/src/wfmath/rotmatrix.h// rotmatrix.h (RotMatrix<> class definition) // // The WorldForge Project // Copyright (C) 2001 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Ron Steinke // Created: 2001-12-7 #ifndef WFMATH_ROTMATRIX_H #define WFMATH_ROTMATRIX_H #include <wfmath/const.h> #include <iosfwd> namespace WFMath { /// returns m1 * m2 template<int dim> // m1 * m2 RotMatrix<dim> Prod(const RotMatrix<dim>& m1, const RotMatrix<dim>& m2); /// returns m1 * m2^-1 template<int dim> // m1 * m2^-1 RotMatrix<dim> ProdInv(const RotMatrix<dim>& m1, const RotMatrix<dim>& m2); /// returns m1^-1 * m2 template<int dim> // m1^-1 * m2 RotMatrix<dim> InvProd(const RotMatrix<dim>& m1, const RotMatrix<dim>& m2); /// returns m1^-1 * m2^-1 template<int dim> // m1^-1 * m2^-1 RotMatrix<dim> InvProdInv(const RotMatrix<dim>& m1, const RotMatrix<dim>& m2); template<int dim> // m * v Vector<dim> Prod(const RotMatrix<dim>& m, const Vector<dim>& v); template<int dim> // m^-1 * v Vector<dim> InvProd(const RotMatrix<dim>& m, const Vector<dim>& v); template<int dim> // v * m Vector<dim> Prod(const Vector<dim>& v, const RotMatrix<dim>& m); template<int dim> // v * m^-1 Vector<dim> ProdInv(const Vector<dim>& v, const RotMatrix<dim>& m); /// returns m1 * m2 template<int dim> RotMatrix<dim> operator*(const RotMatrix<dim>& m1, const RotMatrix<dim>& m2); template<int dim> Vector<dim> operator*(const RotMatrix<dim>& m, const Vector<dim>& v); template<int dim> Vector<dim> operator*(const Vector<dim>& v, const RotMatrix<dim>& m); template<int dim> std::ostream& operator<<(std::ostream& os, const RotMatrix<dim>& m); template<int dim> std::istream& operator>>(std::istream& is, RotMatrix<dim>& m); /// A dim dimensional rotation matrix. Technically, a member of the group O(dim). /** * Elements of this class represent rotation matrices. The NxN dimensional * rotation matrices form a group called O(N), the orthogonal * matrices. They satisfy the following condition: * * They are orthogonal. That is, their transpose is equal to their inverse. * Hence, this class does not implement a transpose() method, only an * inverse(). * * A general N dimensional matrix of this type has N(N-1)/2 degrees of freedom. * This gives one rotation angle in 2D, the three Euler angles in 3D, etc. * * This class implements the 'generic' subset of the interface in * the fake class Shape. **/ template<int dim = 3> class RotMatrix { public: /// RotMatrix() : m_elem{}, m_flip(false), m_valid(false), m_age(0) {} /// RotMatrix(const RotMatrix& m) = default; friend std::ostream& operator<< <dim>(std::ostream& os, const RotMatrix& m); friend std::istream& operator>> <dim>(std::istream& is, RotMatrix& m); RotMatrix& operator=(const RotMatrix& m) = default; // No operator=(CoordType d[dim][dim]), since it can fail. // Use setVals() instead. bool isEqualTo(const RotMatrix& m, CoordType epsilon = numeric_constants<CoordType>::epsilon()) const; bool operator==(const RotMatrix& m) const {return isEqualTo(m);} bool operator!=(const RotMatrix& m) const {return !isEqualTo(m);} bool isValid() const {return m_valid;} /// set the matrix to the identity matrix RotMatrix& identity(); /// get the (i, j) element of the matrix CoordType elem(const int i, const int j) const {return m_elem[i][j];} /// Set the values of the elements of the matrix /** * Can't set one element at a time and keep it an O(N) matrix, * but can try to set all values at once, and see if they match. * This fails if the passed matrix is not orthogonal within the * passed precision, and orthogonalizes the matrix to within * precision WFMATH_EPSILON. **/ bool setVals(const CoordType vals[dim][dim], CoordType precision = numeric_constants<CoordType>::epsilon()); /// Set the values of the elements of the matrix /** * Can't set one element at a time and keep it an O(N) matrix, * but can try to set all values at once, and see if they match. * This fails if the passed matrix is not orthogonal within the * passed precision, and orthogonalizes the matrix to within * precision WFMATH_EPSILON. **/ bool setVals(const CoordType vals[dim*dim], CoordType precision = numeric_constants<CoordType>::epsilon()); /// Get a copy of the i'th row as a Vector Vector<dim> row(int i) const; /// Get a copy of the i'th column as a Vector Vector<dim> column(int i) const; /// Get the trace of the matrix CoordType trace() const; /// Get the determinant of the matrix /** * Since the matrix is orthogonal, the determinant is always either 1 or -1. **/ CoordType determinant() const {return (m_flip ? -1.f : 1.f);} /// Get the inverse of the matrix /** * Since the matrix is orthogonal, the inverse is equal to the transpose. **/ RotMatrix inverse() const; /// Get the parity of the matrix /** * Returns true for odd parity, false for even. **/ bool parity() const {return m_flip;} // documented outside the class friend RotMatrix Prod<dim> (const RotMatrix& m1, const RotMatrix& m2); friend RotMatrix ProdInv<dim> (const RotMatrix& m1, const RotMatrix& m2); friend RotMatrix InvProd<dim> (const RotMatrix& m1, const RotMatrix& m2); friend RotMatrix InvProdInv<dim> (const RotMatrix& m1, const RotMatrix& m2); friend Vector<dim> Prod<dim> (const RotMatrix& m, const Vector<dim>& v); friend Vector<dim> InvProd<dim> (const RotMatrix& m, const Vector<dim>& v); // Set the value to a given rotation /// set the matrix to a rotation by the angle theta in the (i, j) plane RotMatrix& rotation (int i, int j, CoordType theta); /// set the matrix to a rotation by the angle theta in the v1, v2 plane /** * Throws CollinearVectors if v1 and v2 are parallel **/ RotMatrix& rotation (const Vector<dim>& v1, const Vector<dim>& v2, CoordType theta); /// set the matrix to a rotation which will move "from" to lie parallel to "to" /** * Throws CollinearVectors if v1 and v2 are antiparallel (parallel but * pointing in opposite directions). If v1 and v2 point in the * same direction, the matrix is set to the identity. **/ RotMatrix& rotation (const Vector<dim>& from, const Vector<dim>& to); // Set the value to mirror image about a certain axis /// set the matrix to a mirror perpendicular to the i'th axis RotMatrix& mirror(int i); /// set the matrix to a mirror perpendicular to the Vector v RotMatrix& mirror(const Vector<dim>& v); /// set the matrix to mirror all axes /** * This is a good parity operator if dim is odd. **/ RotMatrix& mirror(); /// rotate the matrix using another matrix RotMatrix& rotate(const RotMatrix& m) {return *this = Prod(*this, m);} /// normalize to remove accumulated round-off error void normalize(); /// current round-off age unsigned age() const {return m_age;} // 2D/3D stuff /// 3D only: Construct a RotMatrix from a Quaternion /** * since Quaternions can only specify parity-even * rotations, you can pass the return value of * Quaternion::fromRotMatrix() as not_flip to * recover the full RotMatrix **/ RotMatrix(const Quaternion& q, bool not_flip = true); /// 2D only: Construct a RotMatrix from an angle theta RotMatrix& rotation(CoordType theta) {return rotation(0, 1, theta);} /// 3D only: set a RotMatrix to a rotation about the x axis by angle theta RotMatrix& rotationX(CoordType theta) {return rotation(1, 2, theta);} /// 3D only: set a RotMatrix to a rotation about the y axis by angle theta RotMatrix& rotationY(CoordType theta) {return rotation(2, 0, theta);} /// 3D only: set a RotMatrix to a rotation about the z axis by angle theta RotMatrix& rotationZ(CoordType theta) {return rotation(0, 1, theta);} /// 3D only: set a RotMatrix to a rotation about the axis given by the Vector RotMatrix& rotation(const Vector<dim>& axis, CoordType theta); /// 3D only: set a RotMatrix to a rotation about the axis given by the Vector /** * the rotation angle is taken from the Vector's magnitude **/ RotMatrix& rotation(const Vector<dim>& axis); // angle taken from magnitude of axis /// 3D only: set a RotMatrix from a Quaternion /** * since Quaternions can only specify parity-even * rotations, you can pass the return value of * Quaternion::fromRotMatrix() as not_flip to * recover the full RotMatrix **/ RotMatrix& fromQuaternion(const Quaternion& q, bool not_flip = true); /// rotate the matrix using the quaternion RotMatrix& rotate(const Quaternion&); /// set a RotMatrix to a mirror perpendicular to the x axis RotMatrix& mirrorX() {return mirror(0);} /// set a RotMatrix to a mirror perpendicular to the y axis RotMatrix& mirrorY() {return mirror(1);} /// set a RotMatrix to a mirror perpendicular to the z axis RotMatrix& mirrorZ(); private: CoordType m_elem[dim][dim]; bool m_flip; // True if the matrix is parity odd bool m_valid; unsigned m_age; // Backend to setVals() above, also used in fromStream() bool _setVals(CoordType *vals, CoordType precision = numeric_constants<CoordType>::epsilon()); void checkNormalization() {if(m_age >= WFMATH_MAX_NORM_AGE && m_valid) normalize();} }; template<> inline RotMatrix<3>& RotMatrix<3>::mirrorZ() { return mirror(2); } template<int dim> inline RotMatrix<dim>& RotMatrix<dim>::mirror(const int i) { identity(); m_elem[i][i] = -1; m_flip = true; // m_valid and m_age already set correctly return *this; } } // namespace WFMath #endif // WFMATH_ROTMATRIX_H 07070100000041000081A4000000000000000000000001656C867F00003845000000000000000000000000000000000000003700000000wfmath-1701611135.403a8bd/src/wfmath/rotmatrix_funcs.h// rotmatrix_funcs.h (RotMatrix<> template functions) // // The WorldForge Project // Copyright (C) 2001 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Ron Steinke // Created: 2001-12-7 #ifndef WFMATH_ROTMATRIX_FUNCS_H #define WFMATH_ROTMATRIX_FUNCS_H #include <wfmath/rotmatrix.h> #include <wfmath/vector.h> #include <wfmath/error.h> #include <wfmath/const.h> #include <cmath> #include <cassert> namespace WFMath { template<int dim> inline bool RotMatrix<dim>::isEqualTo(const RotMatrix<dim>& m, CoordType epsilon) const { // Since the sum of the squares of the elements in any row or column add // up to 1, all the elements lie between -1 and 1, and each row has // at least one element whose magnitude is at least 1/sqrt(dim). // Therefore, we don't need to scale epsilon, as we did for // Vector<> and Point<>. assert(epsilon > 0); //If anyone is invalid they are never equal if (!m.m_valid || !m_valid) { return false; } for(int i = 0; i < dim; ++i) for(int j = 0; j < dim; ++j) if(std::fabs(m_elem[i][j] - m.m_elem[i][j]) > epsilon) return false; // Don't need to test m_flip, it's determined by the values of m_elem. assert("Generated values, must be equal if all components are equal" && m_flip == m.m_flip); return true; } template<int dim> // m1 * m2 inline RotMatrix<dim> Prod(const RotMatrix<dim>& m1, const RotMatrix<dim>& m2) { RotMatrix<dim> out; for(int i = 0; i < dim; ++i) { for(int j = 0; j < dim; ++j) { out.m_elem[i][j] = 0; for(int k = 0; k < dim; ++k) { out.m_elem[i][j] += m1.m_elem[i][k] * m2.m_elem[k][j]; } } } out.m_flip = (m1.m_flip != m2.m_flip); // XOR out.m_valid = m1.m_valid && m2.m_valid; out.m_age = m1.m_age + m2.m_age; out.checkNormalization(); return out; } template<int dim> // m1 * m2^-1 inline RotMatrix<dim> ProdInv(const RotMatrix<dim>& m1, const RotMatrix<dim>& m2) { RotMatrix<dim> out; for(int i = 0; i < dim; ++i) { for(int j = 0; j < dim; ++j) { out.m_elem[i][j] = 0; for(int k = 0; k < dim; ++k) { out.m_elem[i][j] += m1.m_elem[i][k] * m2.m_elem[j][k]; } } } out.m_flip = (m1.m_flip != m2.m_flip); // XOR out.m_valid = m1.m_valid && m2.m_valid; out.m_age = m1.m_age + m2.m_age; out.checkNormalization(); return out; } template<int dim> // m1^-1 * m2 inline RotMatrix<dim> InvProd(const RotMatrix<dim>& m1, const RotMatrix<dim>& m2) { RotMatrix<dim> out; for(int i = 0; i < dim; ++i) { for(int j = 0; j < dim; ++j) { out.m_elem[i][j] = 0; for(int k = 0; k < dim; ++k) { out.m_elem[i][j] += m1.m_elem[k][i] * m2.m_elem[k][j]; } } } out.m_flip = (m1.m_flip != m2.m_flip); // XOR out.m_valid = m1.m_valid && m2.m_valid; out.m_age = m1.m_age + m2.m_age; out.checkNormalization(); return out; } template<int dim> // m1^-1 * m2^-1 inline RotMatrix<dim> InvProdInv(const RotMatrix<dim>& m1, const RotMatrix<dim>& m2) { RotMatrix<dim> out; for(int i = 0; i < dim; ++i) { for(int j = 0; j < dim; ++j) { out.m_elem[i][j] = 0; for(int k = 0; k < dim; ++k) { out.m_elem[i][j] += m1.m_elem[k][i] * m2.m_elem[j][k]; } } } out.m_flip = (m1.m_flip != m2.m_flip); // XOR out.m_valid = m1.m_valid && m2.m_valid; out.m_age = m1.m_age + m2.m_age; out.checkNormalization(); return out; } template<int dim> // m * v inline Vector<dim> Prod(const RotMatrix<dim>& m, const Vector<dim>& v) { Vector<dim> out; for(int i = 0; i < dim; ++i) { out.m_elem[i] = 0; for(int j = 0; j < dim; ++j) { out.m_elem[i] += m.m_elem[i][j] * v.m_elem[j]; } } out.m_valid = m.m_valid && v.m_valid; return out; } template<int dim> // m^-1 * v inline Vector<dim> InvProd(const RotMatrix<dim>& m, const Vector<dim>& v) { Vector<dim> out; for(int i = 0; i < dim; ++i) { out.m_elem[i] = 0; for(int j = 0; j < dim; ++j) { out.m_elem[i] += m.m_elem[j][i] * v.m_elem[j]; } } out.m_valid = m.m_valid && v.m_valid; return out; } template<int dim> // v * m inline Vector<dim> Prod(const Vector<dim>& v, const RotMatrix<dim>& m) { return InvProd(m, v); // Since transpose() and inverse() are the same } template<int dim> // v * m^-1 inline Vector<dim> ProdInv(const Vector<dim>& v, const RotMatrix<dim>& m) { return Prod(m, v); // Since transpose() and inverse() are the same } template<int dim> inline RotMatrix<dim> operator*(const RotMatrix<dim>& m1, const RotMatrix<dim>& m2) { return Prod(m1, m2); } template<int dim> inline Vector<dim> operator*(const RotMatrix<dim>& m, const Vector<dim>& v) { return Prod(m, v); } template<int dim> inline Vector<dim> operator*(const Vector<dim>& v, const RotMatrix<dim>& m) { return InvProd(m, v); // Since transpose() and inverse() are the same } template<int dim> inline bool RotMatrix<dim>::setVals(const CoordType vals[dim][dim], CoordType precision) { // Scratch space for the backend CoordType scratch_vals[dim*dim]; for(int i = 0; i < dim; ++i) for(int j = 0; j < dim; ++j) scratch_vals[i*dim+j] = vals[i][j]; return _setVals(scratch_vals, precision); } template<int dim> inline bool RotMatrix<dim>::setVals(const CoordType vals[dim*dim], CoordType precision) { // Scratch space for the backend CoordType scratch_vals[dim*dim]; for(int i = 0; i < dim*dim; ++i) scratch_vals[i] = vals[i]; return _setVals(scratch_vals, precision); } bool _MatrixSetValsImpl(int size, CoordType* vals, bool& flip, CoordType* buf1, CoordType* buf2, CoordType precision); template<int dim> inline bool RotMatrix<dim>::_setVals(CoordType *vals, CoordType precision) { // Cheaper to allocate space on the stack here than with // new in _MatrixSetValsImpl() CoordType buf1[dim*dim], buf2[dim*dim]; bool flip; if(!_MatrixSetValsImpl(dim, vals, flip, buf1, buf2, precision)) return false; // Do the assignment for(int i = 0; i < dim; ++i) for(int j = 0; j < dim; ++j) m_elem[i][j] = vals[i*dim+j]; m_flip = flip; m_valid = true; m_age = 1; return true; } template<int dim> inline Vector<dim> RotMatrix<dim>::row(const int i) const { Vector<dim> out; for(int j = 0; j < dim; ++j) out[j] = m_elem[i][j]; out.setValid(m_valid); return out; } template<int dim> inline Vector<dim> RotMatrix<dim>::column(const int i) const { Vector<dim> out; for(int j = 0; j < dim; ++j) out[j] = m_elem[j][i]; out.setValid(m_valid); return out; } template<int dim> inline RotMatrix<dim> RotMatrix<dim>::inverse() const { RotMatrix<dim> m; for(int i = 0; i < dim; ++i) for(int j = 0; j < dim; ++j) m.m_elem[j][i] = m_elem[i][j]; m.m_flip = m_flip; m.m_valid = m_valid; m.m_age = m_age + 1; return m; } template<int dim> inline RotMatrix<dim>& RotMatrix<dim>::identity() { for(int i = 0; i < dim; ++i) for(int j = 0; j < dim; ++j) m_elem[i][j] = ((i == j) ? 1.0f : 0.0f); m_flip = false; m_valid = true; m_age = 0; // 1 and 0 are exact, no roundoff error return *this; } template<int dim> inline CoordType RotMatrix<dim>::trace() const { CoordType out = 0; for(int i = 0; i < dim; ++i) out += m_elem[i][i]; return out; } template<int dim> RotMatrix<dim>& RotMatrix<dim>::rotation (const int i, const int j, CoordType theta) { assert(i >= 0 && i < dim && j >= 0 && j < dim && i != j); CoordType ctheta = std::cos(theta), stheta = std::sin(theta); for(int k = 0; k < dim; ++k) { for(int l = 0; l < dim; ++l) { if(k == l) { if(k == i || k == j) m_elem[k][l] = ctheta; else m_elem[k][l] = 1; } else { if(k == i && l == j) m_elem[k][l] = stheta; else if(k == j && l == i) m_elem[k][l] = -stheta; else m_elem[k][l] = 0; } } } m_flip = false; m_valid = true; m_age = 1; return *this; } template<int dim> RotMatrix<dim>& RotMatrix<dim>::rotation (const Vector<dim>& v1, const Vector<dim>& v2, CoordType theta) { CoordType v1_sqr_mag = v1.sqrMag(); assert("need nonzero length vector" && v1_sqr_mag > 0); // Get an in-plane vector which is perpendicular to v1 Vector<dim> vperp = v2 - v1 * Dot(v1, v2) / v1_sqr_mag; CoordType vperp_sqr_mag = vperp.sqrMag(); if((vperp_sqr_mag / v1_sqr_mag) < (dim * numeric_constants<CoordType>::epsilon() * numeric_constants<CoordType>::epsilon())) { assert("need nonzero length vector" && v2.sqrMag() > 0); // The original vectors were parallel throw ColinearVectors<dim>(v1, v2); } // If we were rotating a vector vin, the answer would be // vin + Dot(v1, vin) * (v1 (cos(theta) - 1)/ v1_sqr_mag // + vperp * sin(theta) / sqrt(v1_sqr_mag * vperp_sqr_mag)) // + Dot(vperp, vin) * (a similar term). From this, we find // the matrix components. CoordType mag_prod = std::sqrt(v1_sqr_mag * vperp_sqr_mag); CoordType ctheta = std::cos(theta), stheta = std::sin(theta); identity(); // Initialize to identity matrix for(int i = 0; i < dim; ++i) for(int j = 0; j < dim; ++j) m_elem[i][j] += ((ctheta - 1) * (v1[i] * v1[j] / v1_sqr_mag + vperp[i] * vperp[j] / vperp_sqr_mag) - stheta * (vperp[i] * v1[j] - v1[i] * vperp[j]) / mag_prod); m_flip = false; m_valid = true; m_age = 1; return *this; } template<int dim> RotMatrix<dim>& RotMatrix<dim>::rotation(const Vector<dim>& from, const Vector<dim>& to) { // This is sort of similar to the above, with the rotation angle determined // by the angle between the vectors CoordType fromSqrMag = from.sqrMag(); assert("need nonzero length vector" && fromSqrMag > 0); CoordType toSqrMag = to.sqrMag(); assert("need nonzero length vector" && toSqrMag > 0); CoordType dot = Dot(from, to); CoordType sqrmagprod = fromSqrMag * toSqrMag; CoordType magprod = std::sqrt(sqrmagprod); CoordType ctheta_plus_1 = dot / magprod + 1; if(ctheta_plus_1 < numeric_constants<CoordType>::epsilon()) { // 180 degree rotation, rotation plane indeterminate if(dim == 2) { // special case, only one rotation plane possible m_elem[0][0] = m_elem[1][1] = ctheta_plus_1 - 1; CoordType sin_theta = std::sqrt(2 * ctheta_plus_1); // to leading order bool direction = ((to[0] * from[1] - to[1] * from[0]) >= 0); m_elem[0][1] = direction ? sin_theta : -sin_theta; m_elem[1][0] = -m_elem[0][1]; m_flip = false; m_valid = true; m_age = 1; return *this; } throw ColinearVectors<dim>(from, to); } for(int i = 0; i < dim; ++i) { for(int j = i; j < dim; ++j) { CoordType projfrom = from[i] * from[j] / fromSqrMag; CoordType projto = to[i] * to[j] / toSqrMag; CoordType ijprod = from[i] * to[j], jiprod = to[i] * from[j]; CoordType termthree = (ijprod + jiprod) * dot / sqrmagprod; CoordType combined = (projfrom + projto - termthree) / ctheta_plus_1; if(i == j) { m_elem[i][i] = 1 - combined; } else { CoordType diffterm = (jiprod - ijprod) / magprod; m_elem[i][j] = -diffterm - combined; m_elem[j][i] = diffterm - combined; } } } m_flip = false; m_valid = true; m_age = 1; return *this; } template<> RotMatrix<3>& RotMatrix<3>::rotation (const Vector<3>& axis, CoordType theta); template<> RotMatrix<3>& RotMatrix<3>::rotation (const Vector<3>& axis); template<> RotMatrix<3>& RotMatrix<3>::fromQuaternion(const Quaternion& q, const bool not_flip); template<> RotMatrix<3>& RotMatrix<3>::rotate(const Quaternion&); template<int dim> inline RotMatrix<dim>& RotMatrix<dim>::mirror (const Vector<dim>& v) { // Get a flip by subtracting twice the projection operator in the // direction of the vector. A projection operator is idempotent (P*P == P), // and symmetric, so I - 2P is an orthogonal matrix. // // (I - 2P) * (I - 2P)^T == (I - 2P)^2 == I - 4P + 4P^2 == I CoordType sqr_mag = v.sqrMag(); assert("need nonzero length vector" && sqr_mag > 0); // off diagonal for(int i = 0; i < dim - 1; ++i) for(int j = i + 1; j < dim; ++j) m_elem[i][j] = m_elem[j][i] = -2 * v[i] * v[j] / sqr_mag; // diagonal for(int i = 0; i < dim; ++i) m_elem[i][i] = 1 - 2 * v[i] * v[i] / sqr_mag; m_flip = true; m_valid = true; m_age = 1; return *this; } template<int dim> inline RotMatrix<dim>& RotMatrix<dim>::mirror() { for(int i = 0; i < dim; ++i) for(int j = 0; j < dim; ++j) m_elem[i][j] = (i == j) ? -1 : 0; m_flip = dim%2; m_valid = true; m_age = 0; // -1 and 0 are exact, no roundoff error return *this; } bool _MatrixInverseImpl(int size, CoordType* in, CoordType* out); template<int dim> inline void RotMatrix<dim>::normalize() { // average the matrix with it's inverse transpose, // that will clean up the error to linear order CoordType buf1[dim*dim], buf2[dim*dim]; for(int i = 0; i < dim; ++i) { for(int j = 0; j < dim; ++j) { buf1[j*dim + i] = m_elem[i][j]; buf2[j*dim + i] = ((i == j) ? 1.f : 0.f); } } bool success = _MatrixInverseImpl(dim, buf1, buf2); assert(success); // matrix can't be degenerate if (!success) { return; } for(int i = 0; i < dim; ++i) { for(int j = 0; j < dim; ++j) { CoordType& elem = m_elem[i][j]; elem += buf2[i*dim + j]; elem /= 2; } } m_age = 1; } } // namespace WFMath #endif // WFMATH_ROTMATRIX_FUNCS_H 07070100000042000081A4000000000000000000000001656C867F00000A5B000000000000000000000000000000000000003100000000wfmath-1701611135.403a8bd/src/wfmath/segment.cpp// vector.cpp (Vector<> implementation) // // The WorldForge Project // Copyright (C) 2011 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Alistair Riddoch // Created: 2011-1-29 // Extensive amounts of this material come from the Vector2D // and Vector3D classes from stage/math, written by Bryce W. // Harrington, Kosh, and Jari Sundell (Rakshasa). #include "segment_funcs.h" #include "axisbox.h" #include "ball.h" #include "vector.h" #include <cmath> namespace WFMath { template<> Segment<3>& Segment<3>::rotatePoint(const Quaternion& q, const Point<3>& p) { m_p1.rotate(q, p); m_p2.rotate(q, p); return *this; } template<> Segment<3>& Segment<3>::rotateCenter(const Quaternion& q) { rotatePoint(q, getCenter()); return *this; } template<> Segment<3> Segment<3>::toParentCoords(const Point<3>& origin, const Quaternion& rotation) const { return Segment(m_p1.toParentCoords(origin, rotation), m_p2.toParentCoords(origin, rotation)); } template<> Segment<3> Segment<3>::toLocalCoords(const Point<3>& origin, const Quaternion& rotation) const { return Segment(m_p1.toLocalCoords(origin, rotation), m_p2.toLocalCoords(origin, rotation)); } template class Segment<2>; template class Segment<3>; static_assert(std::is_standard_layout<Segment<2>>::value, "Segment should be standard layout."); static_assert(std::is_trivially_copyable<Segment<2>>::value, "Segment should be trivially copyable."); static_assert(std::is_standard_layout<Segment<3>>::value, "Segment should be standard layout."); static_assert(std::is_trivially_copyable<Segment<3>>::value, "Segment should be trivially copyable."); } 07070100000043000081A4000000000000000000000001656C867F000019DE000000000000000000000000000000000000002F00000000wfmath-1701611135.403a8bd/src/wfmath/segment.h// segment.h (A line segment) // // The WorldForge Project // Copyright (C) 2000, 2001 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // // Author: Ron Steinke #ifndef WFMATH_SEGMENT_H #define WFMATH_SEGMENT_H #include <wfmath/point.h> #include <wfmath/intersect_decls.h> namespace WFMath { template<int dim> std::ostream& operator<<(std::ostream& os, const Segment<dim>& s); template<int dim> std::istream& operator>>(std::istream& is, Segment<dim>& s); /// A line segment embedded in dim dimensions /** * This class implements the full shape interface, as described in * the fake class Shape. **/ template<int dim = 3> class Segment { public: /// construct an uninitialized segment Segment() : m_p1{}, m_p2{} {} /// construct a segment with endpoints p1 and p2 Segment(const Point<dim>& p1, const Point<dim>& p2) : m_p1(p1), m_p2(p2) {} /// construct a copy of a segment Segment(const Segment& s) = default; ~Segment() = default; friend std::ostream& operator<< <dim>(std::ostream& os, const Segment& s); friend std::istream& operator>> <dim>(std::istream& is, Segment& s); Segment& operator=(const Segment& s) = default; bool isEqualTo(const Segment& s, CoordType epsilon = numeric_constants<CoordType>::epsilon()) const; bool operator==(const Segment& b) const {return isEqualTo(b);} bool operator!=(const Segment& b) const {return !isEqualTo(b);} bool isValid() const {return m_p1.isValid() && m_p2.isValid();} // Descriptive characteristics size_t numCorners() const {return 2;} Point<dim> getCorner(size_t i) const {return i ? m_p2 : m_p1;} Point<dim> getCenter() const {return Midpoint(m_p1, m_p2);} /// get one end of the segment const Point<dim>& endpoint(const int i) const {return i ? m_p2 : m_p1;} /// get one end of the segment Point<dim>& endpoint(const int i) {return i ? m_p2 : m_p1;} // Movement functions Segment& shift(const Vector<dim>& v) {m_p1 += v; m_p2 += v; return *this;} Segment& moveCornerTo(const Point<dim>& p, size_t corner); Segment& moveCenterTo(const Point<dim>& p) {return shift(p - getCenter());} Segment& rotateCorner(const RotMatrix<dim>& m, size_t corner); Segment& rotateCenter(const RotMatrix<dim>& m) {rotatePoint(m, getCenter()); return *this;} Segment<dim>& rotatePoint(const RotMatrix<dim>& m, const Point<dim>& p) {m_p1.rotate(m, p); m_p2.rotate(m, p); return *this;} // 3D rotation functions Segment& rotateCorner(const Quaternion& q, size_t corner); Segment& rotateCenter(const Quaternion& q); Segment& rotatePoint(const Quaternion& q, const Point<dim>& p); // Intersection functions AxisBox<dim> boundingBox() const {return AxisBox<dim>(m_p1, m_p2);} Ball<dim> boundingSphere() const {return Ball<dim>(getCenter(), Distance(m_p1, m_p2) / 2);} Ball<dim> boundingSphereSloppy() const {return Ball<dim>(getCenter(), SloppyDistance(m_p1, m_p2) / 2);} Segment toParentCoords(const Point<dim>& origin, const RotMatrix<dim>& rotation = RotMatrix<dim>().identity()) const {return Segment(m_p1.toParentCoords(origin, rotation), m_p2.toParentCoords(origin, rotation));} Segment toParentCoords(const AxisBox<dim>& coords) const {return Segment(m_p1.toParentCoords(coords), m_p2.toParentCoords(coords));} Segment toParentCoords(const RotBox<dim>& coords) const {return Segment(m_p1.toParentCoords(coords), m_p2.toParentCoords(coords));} // toLocal is just like toParent, expect we reverse the order of // translation and rotation and use the opposite sense of the rotation // matrix Segment toLocalCoords(const Point<dim>& origin, const RotMatrix<dim>& rotation = RotMatrix<dim>().identity()) const {return Segment(m_p1.toLocalCoords(origin, rotation), m_p2.toLocalCoords(origin, rotation));} Segment toLocalCoords(const AxisBox<dim>& coords) const {return Segment(m_p1.toLocalCoords(coords), m_p2.toLocalCoords(coords));} Segment toLocalCoords(const RotBox<dim>& coords) const {return Segment(m_p1.toLocalCoords(coords), m_p2.toLocalCoords(coords));} // 3D only Segment toParentCoords(const Point<dim>& origin, const Quaternion& rotation) const; Segment toLocalCoords(const Point<dim>& origin, const Quaternion& rotation) const; friend bool Intersect<dim>(const Segment& s, const Point<dim>& p, bool proper); friend bool Contains<dim>(const Point<dim>& p, const Segment& s, bool proper); friend bool Intersect<dim>(const Segment& s, const AxisBox<dim>& b, bool proper); friend bool Contains<dim>(const AxisBox<dim>& b, const Segment& s, bool proper); friend bool Intersect<dim>(const Segment& s, const Ball<dim>& b, bool proper); friend bool Contains<dim>(const Ball<dim>& b, const Segment& s, bool proper); friend bool Intersect<dim>(const Segment& s1, const Segment& s2, bool proper); friend bool Contains<dim>(const Segment& s1, const Segment& s2, bool proper); friend bool Intersect<dim>(const RotBox<dim>& r, const Segment& s, bool proper); friend bool Contains<dim>(const RotBox<dim>& r, const Segment& s, bool proper); friend bool Contains<dim>(const Segment& s, const RotBox<dim>& r, bool proper); friend bool Intersect<dim>(const Polygon<dim>& r, const Segment& s, bool proper); friend bool Contains<dim>(const Polygon<dim>& p, const Segment& s, bool proper); friend bool Contains<dim>(const Segment& s, const Polygon<dim>& p, bool proper); private: Point<dim> m_p1, m_p2; }; template<int dim> inline bool Segment<dim>::isEqualTo(const Segment<dim>& s, CoordType epsilon) const { return Equal(m_p1, s.m_p1, epsilon) && Equal(m_p2, s.m_p2, epsilon); } } // namespace WFMath #endif // WFMATH_SEGMENT_H 07070100000044000081A4000000000000000000000001656C867F000007B6000000000000000000000000000000000000003500000000wfmath-1701611135.403a8bd/src/wfmath/segment_funcs.h// segment_funcs.h (line segment implementation) // // The WorldForge Project // Copyright (C) 2000, 2001 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // // Author: Ron Steinke #ifndef WFMATH_SEGMENT_FUNCS_H #define WFMATH_SEGMENT_FUNCS_H #include <wfmath/segment.h> #include <cassert> namespace WFMath { template<int dim> inline Segment<dim>& Segment<dim>::moveCornerTo(const Point<dim>& p, size_t corner) { assert(corner == 0 || corner == 1); Vector<dim> diff = m_p2 - m_p1; if(!corner) { m_p1 = p; m_p2 = p + diff; } else { m_p2 = p; m_p1 = p - diff; } return *this; } template<int dim> inline Segment<dim>& Segment<dim>::rotateCorner(const RotMatrix<dim>& m, size_t corner) { assert(corner == 0 || corner == 1); if(corner) m_p1.rotate(m, m_p2); else m_p2.rotate(m, m_p1); return *this; } template<> inline Segment<3>& Segment<3>::rotateCorner(const Quaternion& q, size_t corner) { assert(corner == 0 || corner == 1); if(corner) m_p1.rotate(q, m_p2); else m_p2.rotate(q, m_p1); return *this; } } // namespace WFMath #endif // WFMATH_SEGMENT_FUNCS_H 07070100000045000081A4000000000000000000000001656C867F00000816000000000000000000000000000000000000002F00000000wfmath-1701611135.403a8bd/src/wfmath/shuffle.h// randgen.h (random number functions) // // The WorldForge Project // Copyright (C) 2002 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Ron Steinke // Created: 2002-5-23 #ifndef WFMATH_SHUFFLE_H #define WFMATH_SHUFFLE_H #include <wfmath/MersenneTwister.h> #include <vector> namespace WFMath { /// Randomly reorder the contents of a std::vector /** * For things like shuffling a deck of cards, etc. **/ template<class C> void Shuffle(std::vector<C>& v) // need vector for random access { typedef typename std::vector<C>::size_type size_type; size_type pos = v.size(); if(!pos) // handle size() == 0 nicely return; // This swaps each element with one of the ones before // it, starting with the last element. Essentially, // this generates an operation from the permutation // group of size() elements, and applies it to the // vector. Note that the loop only executes size() - 1 // times, as element 0 has nothing to swap with. while(--pos) { size_type new_pos = MTRand::instance.randInt(pos); // 0 <= new_pos <= pos if(new_pos == pos) continue; C tmp = v[pos]; v[pos] = v[new_pos]; v[new_pos] = tmp; } } } // namespace WFMath #endif // WFMATH_SHUFFLE_H 07070100000046000081A4000000000000000000000001656C867F0000254E000000000000000000000000000000000000003000000000wfmath-1701611135.403a8bd/src/wfmath/stream.cpp// stream.cpp (Stream conversion backend in the WFMath library) // // The WorldForge Project // Copyright (C) 2001 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Ron Steinke // Created: 2001-12-13 #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "stream.h" #include "quaternion.h" #include "MersenneTwister.h" #include <sstream> #include <cassert> #include <list> namespace WFMath { std::string _IOWrapper::ToStringImpl(const _IOWrapper::BaseWrite& b, std::streamsize precision) { std::ostringstream ost; ost.precision(precision); b.write(ost); return ost.str(); } void _IOWrapper::FromStringImpl(_IOWrapper::BaseRead& b, const std::string& s, std::streamsize precision) { std::istringstream ist(s); ist.precision(precision); b.read(ist); } // Can't stick this in operator>>(std::istream&, Polygon<>&), because // we use it as a template argument for list<>. Why isn't that allowed? template<int dim> struct PolyReader { Point<dim> pd; Point<2> p2; }; template<int dim> std::istream& operator>>(std::istream& is, Polygon<dim>& r) { char next; PolyReader<dim> read; std::list<PolyReader<dim> > read_list; // Read in the points do { is >> next; if(next == '<') { // empty polygon do { is >> next; } while(next != '>'); return is; } } while(next != '('); while(true) { is >> read.pd; read_list.push_back(read); is >> next; if(next == ')') break; if(next != ',') throw ParseError(); } // Convert to internal format. Be careful about the order points are // added to the orientation. If the first few points are too close together, // round off error can skew the plane, and later points that are further // away may fail. typename std::list<PolyReader<dim> >::iterator i, end = read_list.end(); bool succ; std::streamsize str_prec = is.precision(); float str_eps = 1; while(--str_prec > 0) // Precision of 6 gives epsilon = 1e-5 str_eps /= 10; CoordType epsilon = FloatMax(str_eps, numeric_constants<CoordType>::epsilon()); r.m_orient = Poly2Orient<dim>(); if(read_list.size() < 3) { // This will always work for(i = read_list.begin(); i != end; ++i) { succ = r.m_orient.expand(i->pd, i->p2, epsilon); assert(succ); } } else { // Find the three furthest apart points typename std::list<PolyReader<dim> >::iterator p1 = end, p2 = end, p3 = end, j; // invalid values CoordType dist = -1; for(i = read_list.begin(); i != end; ++i) { for(j = i, ++j; j != end; ++j) { CoordType new_dist = SloppyDistance(i->pd, j->pd); if(new_dist > dist) { p1 = i; p2 = j; dist = new_dist; } } } assert(p1 != end); assert(p2 != end); dist = -1; for(i = read_list.begin(); i != end; ++i) { // Don't want to be near either p1 or p2 if(i == p1 || i == p2) continue; CoordType new_dist = FloatMin(SloppyDistance(i->pd, p1->pd), SloppyDistance(i->pd, p2->pd)); if(new_dist > dist) { p3 = i; dist = new_dist; } } assert(p3 != end); // Add p1, p2, p3 first succ = r.m_orient.expand(p1->pd, p1->p2, epsilon); assert(succ); succ = r.m_orient.expand(p2->pd, p2->p2, epsilon); assert(succ); succ = r.m_orient.expand(p3->pd, p3->p2, epsilon); assert(succ); // Try to add the rest for(i = read_list.begin(); i != end; ++i) { if(i == p1 || i == p2 || i == p3) // Did these already continue; succ = r.m_orient.expand(i->pd, i->p2, epsilon); if(!succ) { r.clear(); throw ParseError(); } } } // Got valid points, add them to m_poly r.m_poly.resize(read_list.size()); int pnum; for(i = read_list.begin(), pnum = 0; i != end; ++i, ++pnum) r.m_poly[pnum] = i->p2; return is; } template<int dim> inline std::ostream& operator<<(std::ostream& os, const Polygon<dim>& r) { size_t size = r.m_poly.numCorners(); if(size == 0) { os << "<empty>"; return os; } os << "Polygon: ("; for(size_t i = 0; i < size; ++i) os << r.getCorner(i) << (i < (dim - 1) ? ',' : ')'); return os; } // force a bunch of instantiations template std::ostream& operator<< <3>(std::ostream& os, const Vector<3>& r); template std::istream& operator>> <3>(std::istream& is, Vector<3>& r); template std::ostream& operator<< <2>(std::ostream& os, const Vector<2>& r); template std::istream& operator>> <2>(std::istream& is, Vector<2>& r); template std::ostream& operator<< <3>(std::ostream& os, const Point<3>& r); template std::istream& operator>> <3>(std::istream& is, Point<3>& r); template std::ostream& operator<< <2>(std::ostream& os, const Point<2>& r); template std::istream& operator>> <2>(std::istream& is, Point<2>& r); template std::ostream& operator<< <3>(std::ostream& os, const RotMatrix<3>& r); template std::istream& operator>> <3>(std::istream& is, RotMatrix<3>& r); template std::ostream& operator<< <2>(std::ostream& os, const RotMatrix<2>& r); template std::istream& operator>> <2>(std::istream& is, RotMatrix<2>& r); template std::ostream& operator<< <3>(std::ostream& os, const AxisBox<3>& r); template std::istream& operator>> <3>(std::istream& is, AxisBox<3>& r); template std::ostream& operator<< <2>(std::ostream& os, const AxisBox<2>& r); template std::istream& operator>> <2>(std::istream& is, AxisBox<2>& r); template std::ostream& operator<< <3>(std::ostream& os, const Ball<3>& r); template std::istream& operator>> <3>(std::istream& is, Ball<3>& r); template std::ostream& operator<< <2>(std::ostream& os, const Ball<2>& r); template std::istream& operator>> <2>(std::istream& is, Ball<2>& r); template std::ostream& operator<< <3>(std::ostream& os, const Segment<3>& r); template std::istream& operator>> <3>(std::istream& is, Segment<3>& r); template std::ostream& operator<< <2>(std::ostream& os, const Segment<2>& r); template std::istream& operator>> <2>(std::istream& is, Segment<2>& r); template std::ostream& operator<< <3>(std::ostream& os, const RotBox<3>& r); template std::istream& operator>> <3>(std::istream& is, RotBox<3>& r); template std::ostream& operator<< <2>(std::ostream& os, const RotBox<2>& r); template std::istream& operator>> <2>(std::istream& is, RotBox<2>& r); // don't need 2d for Polygon, since it's a specialization template std::ostream& operator<< <3>(std::ostream& os, const Polygon<3>& r); template std::istream& operator>> <3>(std::istream& is, Polygon<3>& r); void WriteCoordList(std::ostream& os, const CoordType* d, const int num) { os << '('; for(int i = 0; i < num; ++i) os << d[i] << (i < (num - 1) ? ',' : ')'); } void ReadCoordList(std::istream& is, CoordType* d, const int num) { char next; is >> next; if(next != '(') throw ParseError(); for(int i = 0; i < num; ++i) { is >> d[i] >> next; char want = (i == num - 1) ? ')' : ','; if(next != want) throw ParseError(); } } CoordType GetEpsilon(std::istream& is) { std::streamsize str_prec = is.precision(); CoordType str_eps = 1; while(--str_prec > 0) // Precision of 6 gives epsilon = 1e-5 str_eps /= 10; return str_eps; } // This is the only way I could get the operator<<() and operator>>() // templates to recognize the declarations in the headers template<> std::ostream& operator<<(std::ostream& os, const Polygon<2>& r) { size_t size = r.m_points.size(); if(size == 0) { os << "<empty>"; return os; } os << "Polygon: ("; for(size_t i = 0; i < size; ++i) { os << r.m_points[i] << (i < (size - 1) ? ',' : ')'); } return os; } template<> std::istream& operator>>(std::istream& is, Polygon<2>& r) { char next; Point<2> p; r.m_points.clear(); do { is >> next; if(next == '<') { // empty polygon do { is >> next; } while(next != '>'); return is; } } while(next != '('); while(true) { is >> p; r.m_points.push_back(p); is >> next; if(next == ')') return is; if(next != ',') throw ParseError(); } } std::ostream& operator<<(std::ostream& os, const Quaternion& q) { return os << "Quaternion: (" << q.m_w << ',' << q.m_vec << ')'; } std::istream& operator>>(std::istream& is, Quaternion& q) { char next; do { is >> next; } while(next != '('); is >> q.m_w; is >> next; if(next != ',') throw ParseError(); is >> q.m_vec; CoordType norm = q.m_w * q.m_w + q.m_vec.sqrMag(); norm = std::sqrt(norm); q.m_w /= norm; q.m_vec /= norm; q.m_valid = true; is >> next; if(next != ')') throw ParseError(); return is; } std::ostream& operator<<(std::ostream& os, MTRand const& mtrand) { return mtrand.save(os); } std::istream& operator>>(std::istream& is, MTRand& mtrand) { return mtrand.load(is); } } // namespace WFMath 07070100000047000081A4000000000000000000000001656C867F00001A73000000000000000000000000000000000000002E00000000wfmath-1701611135.403a8bd/src/wfmath/stream.h// stream.h (Functions in the WFMath library that use streams) // // The WorldForge Project // Copyright (C) 2001,2002 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Ron Steinke // Created: 2001-12-7 #ifndef WFMATH_STREAM_H #define WFMATH_STREAM_H #include <wfmath/vector.h> #include <wfmath/rotmatrix.h> #include <wfmath/point.h> #include <wfmath/axisbox.h> #include <wfmath/ball.h> #include <wfmath/segment.h> #include <wfmath/rotbox.h> #include <wfmath/polygon.h> #include <wfmath/line.h> #include <wfmath/error.h> #include <iostream> namespace WFMath { // sstream vs. strstream compatibility wrapper namespace _IOWrapper { // Need separate read/write classes, since one is const C& and the other is C& class BaseRead { public: virtual ~BaseRead() {} virtual void read(std::istream& is) = 0; }; class BaseWrite { public: virtual ~BaseWrite() {} virtual void write(std::ostream& os) const = 0; }; template<class C> class ImplRead : public BaseRead { public: ImplRead(C& c) : m_data(c) {} virtual ~ImplRead() {} virtual void read(std::istream& is) {is >> m_data;} private: C &m_data; }; template<class C> class ImplWrite : public BaseWrite { public: ImplWrite(const C& c) : m_data(c) {} virtual ~ImplWrite() {} virtual void write(std::ostream& os) const {os << m_data;} private: const C &m_data; }; std::string ToStringImpl(const BaseWrite& b, std::streamsize precision); void FromStringImpl(BaseRead& b, const std::string& s, std::streamsize precision); } /// Output a WFMath type as a string /** * This uses operator<<() in its backend. **/ template<class C> inline std::string ToString(const C& c, std::streamsize precision = 6) { return _IOWrapper::ToStringImpl(_IOWrapper::ImplWrite<C>(c), precision); } /// Parse a WFMath type from a string /** * This uses operator>>() in its backend. **/ template<class C> inline void FromString(C& c, const std::string& s, std::streamsize = 6) { _IOWrapper::ImplRead<C> i(c); _IOWrapper::FromStringImpl(i, s, 6); } void ReadCoordList(std::istream& is, CoordType* d, const int num); void WriteCoordList(std::ostream& os, const CoordType* d, const int num); CoordType GetEpsilon(std::istream& is); template<int dim> inline std::ostream& operator<<(std::ostream& os, const Vector<dim>& v) { WriteCoordList(os, v.m_elem, dim); return os; } template<int dim> inline std::istream& operator>>(std::istream& is, Vector<dim>& v) { ReadCoordList(is, v.m_elem, dim); v.m_valid = true; return is; } template<int dim> inline std::ostream& operator<<(std::ostream& os, const RotMatrix<dim>& m) { os << '('; for(int i = 0; i < dim; ++i) { WriteCoordList(os, m.m_elem[i], dim); os << (i < (dim - 1) ? ',' : ')'); } return os; } template<int dim> inline std::istream& operator>>(std::istream& is, RotMatrix<dim>& m) { CoordType d[dim*dim]; char next; is >> next; if(next != '(') throw ParseError(); for(int i = 0; i < dim; ++i) { ReadCoordList(is, d + i * dim, dim); is >> next; char want = (i == dim - 1) ? ')' : ','; if(next != want) throw ParseError(); } if(!m._setVals(d, FloatMax(numeric_constants<CoordType>::epsilon(), GetEpsilon(is)))) throw ParseError(); return is; } template<int dim> inline std::ostream& operator<<(std::ostream& os, const Point<dim>& p) { WriteCoordList(os, p.m_elem, dim); return os; } template<int dim> inline std::istream& operator>>(std::istream& is, Point<dim>& p) { ReadCoordList(is, p.m_elem, dim); p.m_valid = true; return is; } template<int dim> inline std::ostream& operator<<(std::ostream& os, const AxisBox<dim>& a) { return os << "AxisBox: m_low = " << a.m_low << ", m_high = " << a.m_high; } template<int dim> inline std::istream& operator>>(std::istream& is, AxisBox<dim>& a) { char next; do { is >> next; } while(next != '='); is >> a.m_low; do { is >> next; } while(next != '='); is >> a.m_high; return is; } template<int dim> inline std::ostream& operator<<(std::ostream& os, const Ball<dim>& b) { return os << "Ball: m_center = " << b.m_center << + ", m_radius = " << b.m_radius; } template<int dim> inline std::istream& operator>>(std::istream& is, Ball<dim>& b) { char next; do { is >> next; } while(next != '='); is >> b.m_center; do { is >> next; } while(next != '='); is >> b.m_radius; return is; } template<int dim> inline std::ostream& operator<<(std::ostream& os, const Segment<dim>& s) { return os << "Segment: m_p1 = " << s.m_p1 << ", m_p2 = " << s.m_p2; } template<int dim> inline std::istream& operator>>(std::istream& is, Segment<dim>& s) { char next; do { is >> next; } while(next != '='); is >> s.m_p1; do { is >> next; } while(next != '='); is >> s.m_p2; return is; } template<int dim> inline std::ostream& operator<<(std::ostream& os, const RotBox<dim>& r) { return os << "RotBox: m_corner0 = " << r.m_corner0 << ", m_size = " << r.m_size << ", m_orient = " << r.m_orient; } template<int dim> inline std::istream& operator>>(std::istream& is, RotBox<dim>& r) { char next; do { is >> next; } while(next != '='); is >> r.m_corner0; do { is >> next; } while(next != '='); is >> r.m_size; do { is >> next; } while(next != '='); is >> r.m_orient; return is; } template<> std::ostream& operator<<(std::ostream& os, const Polygon<2>& r); template<> std::istream& operator>>(std::istream& is, Polygon<2>& r); template<int dim> inline std::ostream& operator<<(std::ostream& os, const Line<dim>& r) { size_t size = r.numCorners(); if(size == 0) { os << "<empty>"; return os; } os << "Line: ("; for(size_t i = 0; i < size; ++i) os << r.getCorner(i) << (i < (dim - 1) ? ',' : ')'); return os; } } // namespace WFMath #endif // WFMATH_STREAM_H 07070100000048000081A4000000000000000000000001656C867F0000151F000000000000000000000000000000000000003300000000wfmath-1701611135.403a8bd/src/wfmath/timestamp.cpp// timestamp.cpp (time and random number implementation) // // The WorldForge Project // Copyright (C) 2002 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Ron Steinke // Created: 2002-5-23 #if defined _WIN32 #include <sys/timeb.h> #else #include <unistd.h> #include <sys/time.h> #endif #include "timestamp.h" #ifdef _WIN32 #include <winsock2.h> #endif #ifdef HAVE_CONFIG_H #include "config.h" #endif static const long Million = 1000000; // apparently, some architectures use int instead of long // in struct timeval template<class T1, class T2> static void regularize(T1 &sec, T2 &usec) { if(usec >= Million) { usec -= Million; ++sec; } else if(usec < 0) { usec += Million; --sec; } } namespace WFMath { TimeDiff::TimeDiff(long sec, long usec, bool is_valid) : m_isvalid(is_valid), m_sec(sec), m_usec(usec) { if (m_isvalid) regularize(m_sec, m_usec); } TimeDiff::TimeDiff(long msec) : m_isvalid(true), m_sec(msec / 1000), m_usec(msec % 1000) { if(msec < 0) { --m_sec; if(m_usec < 0) // behavior of % is machine dependent m_usec += Million; } } long TimeDiff::milliseconds() const { return m_sec * 1000 + m_usec / 1000; } TimeDiff& operator+=(TimeDiff &val, const TimeDiff &d) { val.m_sec += d.m_sec; val.m_usec += d.m_usec; val.m_isvalid = val.m_isvalid && d.m_isvalid; if (val.m_isvalid) regularize(val.m_sec, val.m_usec); return val; } TimeDiff& operator-=(TimeDiff &val, const TimeDiff &d) { val.m_sec -= d.m_sec; val.m_usec -= d.m_usec; val.m_isvalid = val.m_isvalid && d.m_isvalid; if (val.m_isvalid) regularize(val.m_sec, val.m_usec); return val; } TimeDiff operator+(const TimeDiff &a, const TimeDiff &b) { return TimeDiff(a.m_sec + b.m_sec, a.m_usec + b.m_usec, a.m_isvalid && b.m_isvalid); } TimeDiff operator-(const TimeDiff &a, const TimeDiff &b) { return TimeDiff(a.m_sec - b.m_sec, a.m_usec - b.m_usec, a.m_isvalid && b.m_isvalid); } bool operator<(const TimeDiff &a, const TimeDiff &b) { return (a.m_sec < b.m_sec) || ((a.m_sec == b.m_sec) && (a.m_usec < b.m_usec)); } bool operator==(const TimeDiff &a, const TimeDiff &b) { return (a.m_sec == b.m_sec) && (a.m_usec == b.m_usec); } TimeStamp TimeStamp::now() { TimeStamp ret; #ifndef _WIN32 gettimeofday(&ret._val, nullptr); #else SYSTEMTIME sysTime; FILETIME fileTime = {0}; /* 100ns == 1 */ LARGE_INTEGER i; GetSystemTime(&sysTime); SystemTimeToFileTime(&sysTime, &fileTime); /* Documented as the way to get a 64 bit from a * FILETIME. */ memcpy(&i, &fileTime, sizeof(LARGE_INTEGER)); ret._val.tv_sec = i.QuadPart / 10000000; /*10e7*/ ret._val.tv_usec = (i.QuadPart / 10) % 1000000; /*10e6*/ #endif ret._isvalid = true; return ret; } TimeStamp TimeStamp::epochStart() { TimeStamp ret; ret._val.tv_sec = 0; ret._val.tv_usec = 0; ret._isvalid = true; return ret; } // FIXME C++0x supports initialising _val this way // _val({sec, usec}), TimeStamp::TimeStamp(long sec, long usec, bool isvalid) : _isvalid(isvalid) { _val.tv_sec = sec; _val.tv_usec = usec; if (_isvalid) regularize(_val.tv_sec, _val.tv_usec); } bool operator<(const TimeStamp &a, const TimeStamp &b) { if (a._val.tv_sec == b._val.tv_sec) return (a._val.tv_usec < b._val.tv_usec); else return a._val.tv_sec < b._val.tv_sec; } bool operator==(const TimeStamp &a, const TimeStamp &b) { return (a._val.tv_sec == b._val.tv_sec) && (a._val.tv_usec == b._val.tv_usec); } TimeStamp& operator+=(TimeStamp &a, const TimeDiff &d) { a._val.tv_sec += d.m_sec; a._val.tv_usec += d.m_usec; a._isvalid = a._isvalid && d.m_isvalid; if (a._isvalid) regularize(a._val.tv_sec, a._val.tv_usec); return a; } TimeStamp& operator-=(TimeStamp &a, const TimeDiff &d) { a._val.tv_sec -= d.m_sec; a._val.tv_usec -= d.m_usec; a._isvalid = a._isvalid && d.m_isvalid; if (a._isvalid) regularize(a._val.tv_sec, a._val.tv_usec); return a; } TimeStamp operator+(const TimeStamp &a, const TimeDiff &d) { return TimeStamp(a._val.tv_sec + d.m_sec, a._val.tv_usec + d.m_usec, a._isvalid && d.m_isvalid); } TimeStamp operator-(const TimeStamp &a, const TimeDiff &d) { return TimeStamp(a._val.tv_sec - d.m_sec, a._val.tv_usec - d.m_usec, a._isvalid && d.m_isvalid); } TimeDiff operator-(const TimeStamp &a, const TimeStamp &b) { return TimeDiff(a._val.tv_sec - b._val.tv_sec, a._val.tv_usec - b._val.tv_usec, a._isvalid && b._isvalid); } } 07070100000049000081A4000000000000000000000001656C867F000016ED000000000000000000000000000000000000003100000000wfmath-1701611135.403a8bd/src/wfmath/timestamp.h// timestamp.h (time functions, taken from Eris) // // The WorldForge Project // Copyright (C) 2002 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Ron Steinke // Created: 2002-5-23 #ifndef WFMATH_TIMESTAMP_H #define WFMATH_TIMESTAMP_H #include <wfmath/const.h> #include <algorithm> // For std::pair #include <iosfwd> /** Timing related primitives in a portable fashion - note this is for interval / elapsed time measurement, not displaying a human readable time. */ #ifdef _MSC_VER #include <sys/timeb.h> #else #include <sys/time.h> #endif namespace WFMath { class TimeStamp; /// The difference between two timestamps /** * This class implements the 'generic' subset of the interface in * the fake class Shape, with the exception of the stream operators. * It also has the full set of comparison * operators (<, <=, >, >=, ==, !=). **/ class TimeDiff { TimeDiff(long sec, long usec, bool is_valid); public: /// construct an uninitialized TimeDiff TimeDiff() : m_isvalid(false) {} /// construct a TimeDiff of a given number of milliseconds TimeDiff(long msec); // default copy constructor is fine /// Get the value of a TimeDiff in milliseconds /** * WARNING! This function does not check for overflow, if the * number of milliseconds is large **/ long milliseconds() const; /// Get the value of a TimeDiff in (seconds, microseconds) std::pair<long,long> full_time() const {return std::make_pair(m_sec,m_usec);} bool isValid() const {return m_isvalid;} /// increment a TimeDiff friend TimeDiff& operator+=(TimeDiff&, const TimeDiff&); /// decrement a TimeDiff friend TimeDiff& operator-=(TimeDiff&, const TimeDiff&); /// negate a TimeDiff TimeDiff operator-() const {return TimeDiff(-m_sec, -m_usec, m_isvalid);} /// add two TimeDiff instances friend TimeDiff operator+(const TimeDiff &a, const TimeDiff &b); /// subtract two TimeDiff instances friend TimeDiff operator-(const TimeDiff &a, const TimeDiff &b); /// advance a TimeStamp by a TimeDiff friend TimeStamp& operator+=(TimeStamp&, const TimeDiff&); /// regress a TimeStamp by a TimeDiff friend TimeStamp& operator-=(TimeStamp&, const TimeDiff&); /// find the result of advancing a TimeStamp friend TimeStamp operator+(const TimeStamp &a, const TimeDiff &msec); /// find the result of regressing a TimeStamp friend TimeStamp operator-(const TimeStamp &a, const TimeDiff &msec); /// find the time difference between two time stamps friend TimeDiff operator-(const TimeStamp &a, const TimeStamp &b); friend bool operator<(const TimeDiff&, const TimeDiff&); friend bool operator==(const TimeDiff&, const TimeDiff&); private: bool m_isvalid; long m_sec, m_usec; }; inline bool operator>(const TimeDiff &a, const TimeDiff &b) {return b < a;} inline bool operator<=(const TimeDiff &a, const TimeDiff &b) {return !(b < a);} inline bool operator>=(const TimeDiff &a, const TimeDiff &b) {return !(a < b);} inline bool operator!=(const TimeDiff &a, const TimeDiff &b) {return !(b == a);} /// A time stamp /** * This class implements the 'generic' subset of the interface in * the fake class Shape, with the exception of the stream operators. * It also has the full set of comparison operators (<, <=, >, >=, ==, !=). **/ class TimeStamp { private: #ifdef _WIN32 // We roll our own timeval... may only need to be done for mingw32. struct { long tv_sec; /* seconds */ long tv_usec; /* microseconds */ } _val; #else // POSIX, BeOS, .... struct timeval _val{}; #endif bool _isvalid; TimeStamp(long sec, long usec, bool isvalid); public: /// Construct an uninitialized TimeStamp TimeStamp() : _isvalid(false) {} // default copy constructor is fine friend bool operator<(const TimeStamp &a, const TimeStamp &b); friend bool operator==(const TimeStamp &a, const TimeStamp &b); friend std::ostream& operator<<(std::ostream& os, const TimeStamp&); friend std::istream& operator>>(std::istream& is, TimeStamp&); bool isValid() const {return _isvalid;} /// friend TimeStamp& operator+=(TimeStamp&, const TimeDiff&); /// friend TimeStamp& operator-=(TimeStamp&, const TimeDiff&); /// friend TimeStamp operator+(const TimeStamp &a, const TimeDiff &msec); /// friend TimeStamp operator-(const TimeStamp &a, const TimeDiff &msec); /// friend TimeDiff operator-(const TimeStamp &a, const TimeStamp &b); /// set a TimeStamp to the current time static TimeStamp now(); /// set a TimeStamp to Jan 1, 1970 static TimeStamp epochStart(); }; /// inline TimeStamp operator+(TimeDiff msec, const TimeStamp &a) {return a + msec;} inline bool operator>(const TimeStamp &a, const TimeStamp &b) {return b < a;} inline bool operator<=(const TimeStamp &a, const TimeStamp &b) {return !(b < a);} inline bool operator>=(const TimeStamp &a, const TimeStamp &b) {return !(a < b);} inline bool operator!=(const TimeStamp &a, const TimeStamp &b) {return !(b == a);} } // namespace WFMath #endif // WFMATH_TIMESTAMP_H 0707010000004A000041ED000000000000000000000002656C867F00000000000000000000000000000000000000000000002C00000000wfmath-1701611135.403a8bd/src/wfmath/unused0707010000004B000081A4000000000000000000000001656C867F000005AE000000000000000000000000000000000000003A00000000wfmath-1701611135.403a8bd/src/wfmath/unused/oldmatrix.cpp// -*-C++-*- // matrix.cpp (Matrix<> implementation) // // The WorldForge Project // Copyright (C) 2001 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Ron Steinke // Created: 2001-12-7 #include "matrix_funcs.h" #include "const.h" #include <float.h> namespace WF { namespace Math { Matrix<3> SkewSymmetric(const Vector<3>& v) { Matrix<3> out; out.elem(0, 0) = out.elem(1, 1) = out.elem(2, 2) = 0; out.elem(0, 1) = v[2]; out.elem(1, 0) = -v[2]; out.elem(1, 2) = v[0]; out.elem(2, 1) = -v[0]; out.elem(2, 0) = v[1]; out.elem(0, 2) = -v[1]; return out; } }} // namespace WF::Math 0707010000004C000081A4000000000000000000000001656C867F00001357000000000000000000000000000000000000003800000000wfmath-1701611135.403a8bd/src/wfmath/unused/oldmatrix.h// -*-C++-*- // matrix.h (Matrix<> class definition) // // The WorldForge Project // Copyright (C) 2001 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Ron Steinke // Created: 2001-12-7 #ifndef WFMATH_MATRIX_H #define WFMATH_MATRIX_H #include <wfmath/vector.h> namespace WF { namespace Math { template<const int rows, const int columns> class RowVector; template<const int rows, const int columns> Matrix<rows,columns> operator*(const double& d, const Matrix<rows,columns>& m); template<const int rows, const int columns> Matrix<rows,columns> OuterProduct(const Vector<rows>& v1, const Vector<columns>& v2); template<const int size> Matrix<size,size> DiagonalMatrix(const Vector<size>& v); template<const int size> double Trace(const Matrix<size,size>& m); template<const int size> double Determinant(const Matrix<size,size>& m); template<const int size> Matrix<size,size> Inverse(const Matrix<size,size>& m); template<const int rows, const int columns = rows> class Matrix { public: Matrix() {} Matrix(const Matrix<rows,columns>& m); bool operator==(const Matrix<rows,columns>& m) const; bool operator!=(const Matrix<rows,columns>& m) const {return !(*this == m);} // WARNING! This operator is for sorting only. It does not // reflect any property of the matrix. bool operator< (const Matrix<rows,columns>& m) const; // Division only makes sense for square matrices, make people use // inverse() explicitly Matrix<rows,columns> operator+(const Matrix<rows,columns>& m) const; Matrix<rows,columns> operator-(const Matrix<rows,columns>& m) const; template<const int i> Matrix<rows,i> operator*(const Matrix<columns,i>& m) const; Matrix<rows,columns> operator*(const double& d) const; Matrix<rows,columns> operator/(const double& d) const; Matrix<rows,columns> operator-() const; // Unary minus Matrix<rows,columns>& operator+=(const Matrix<rows,columns>& m); Matrix<rows,columns>& operator-=(const Matrix<rows,columns>& m); // Since we need to construct a matrix to hold the temporary values // anyway, just use operator* to implement this one Matrix<rows,columns>& operator*=(const Matrix<columns,columns>& m) {*this = *this * m; return *this;} Matrix<rows,columns>& operator*=(const double& d); Matrix<rows,columns>& operator/=(const double& d); Vector<rows> operator*(const Vector<columns>& v) const; // FIXME it doesn't like this // friend Matrix<rows,columns> operator*<rows,columns>(const double& d, // const Matrix<rows,columns>& m); friend Matrix<rows,columns> OuterProduct<rows,columns>(const Vector<rows>& v1, const Vector<columns>& v2); const double& elem(const int i, const int j) const {return m_elem[i][j];} double& elem(const int i, const int j) {return m_elem[i][j];} Vector<columns> row(const int i) const; void setRow(const int i, const Vector<columns>& v); Vector<rows> column(const int i) const; void setColumn(const int i, const Vector<rows>& v); Matrix<rows,columns>& zero(); Matrix<columns,rows> transpose() const; // The following are only defined for square matrices. Trying // to use them with non-square matrices will result in various // compiler/linker errors. // FIXME is there some way to do this with partial specialization, // without having to rewrite all the operator functions? Matrix<rows,columns>& identity(); Matrix<rows,columns>& diagonal(const Vector<rows>& v) {return *this = DiagonalMatrix(v);} double trace() const {return Trace(*this);} double determinant() const {return Determinant(*this);} Matrix<columns,rows> inverse() const {return Inverse(*this);} friend Matrix<rows> DiagonalMatrix<rows>(const Vector<rows>& v); friend double Trace<rows>(const Matrix<rows>& m); friend double Determinant<rows>(const Matrix<rows>& m); friend Matrix<rows> Inverse<rows>(const Matrix<rows>& m); //TODO rotate() and string functions, Atlas and Tcross functions from stage/math private: double m_elem[rows][columns]; }; Matrix<3> SkewSymmetric(const Vector<3>& v); }} // namespace WF::Math #endif // WFMATH_MATRIX_H 0707010000004D000081A4000000000000000000000001656C867F000021AB000000000000000000000000000000000000003E00000000wfmath-1701611135.403a8bd/src/wfmath/unused/oldmatrix_funcs.h// -*-C++-*- // matrix_funcs.h (Matrix<> template functions) // // The WorldForge Project // Copyright (C) 2001 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Ron Steinke // Created: 2001-12-7 #ifndef WFMATH_MATRIX_FUNCS_H #define WFMATH_MATRIX_FUNCS_H #include <wfmath/matrix.h> #include <wfmath/error.h> namespace WF { namespace Math { template<const int rows, const int columns> inline Matrix<rows,columns>::Matrix(const Matrix<rows,columns>& m) { for(int i = 0; i < rows; ++i) for(int j = 0; j < columns; ++j) m_elem[i][j] = m.m_elem[i][j]; } template<const int rows, const int columns> inline bool Matrix<rows,columns>::operator==(const Matrix<rows,columns>& m) const { for(int i = 0; i < rows; ++i) for(int j = 0; j < columns; ++j) if(m_elem[i][j] != m.m_elem[i][j]) return false; return true; } template<const int rows, const int columns> bool Matrix<rows,columns>::operator< (const Matrix<rows,columns>& m) const { for(int i = 0; i < rows; ++i) { for(int j = 0; j < columns; ++j) { if(m_elem[i][j] < m.m_elem[i][j]) return true; if(m_elem[i][j] > m.m_elem[i][j]) return false; } } return false; } template<const int rows, const int columns> inline Matrix<rows,columns> Matrix<rows,columns>::operator+(const Matrix<rows,columns>& m) const { Matrix<rows,columns> out; for(int i = 0; i < rows; ++i) for(int j = 0; j < columns; ++j) out.m_elem[i][j] = this->m_elem[i][j] + m.m_elem[i][j]; return out; } template<const int rows, const int columns> inline Matrix<rows,columns> Matrix<rows,columns>::operator-(const Matrix<rows,columns>& m) const { Matrix<rows,columns> out; for(int i = 0; i < rows; ++i) for(int j = 0; j < columns; ++j) out.m_elem[i][j] = m_elem[i][j] - m.m_elem[i][j]; return out; } template<const int rows, const int columns> template<const int i> inline Matrix<rows,i> Matrix<rows,columns>::operator*(const Matrix<columns, i>& m) const { Matrix<columns, i> out; for(int j = 0; j < rows; ++j) { for(int k = 0; k < i; ++k) { out.m_elem[j][k] = 0; for(int l = 0; l < columns; ++l) out.m_elem[j][k] += m_elem[j][l] * m.m_elem[l][k]; } } return out; } template<const int rows, const int columns> Matrix<rows,columns> Matrix<rows,columns>::operator*(const double& d) const { Matrix<rows,columns> out; for(int i = 0; i < rows; ++i) for(int j = 0; j < columns; ++j) out.m_elem[i][j] = m_elem[i][j] * d; return out; } template<const int rows, const int columns> Matrix<rows,columns> operator*(const double& d, const Matrix<rows,columns>& m) { Matrix<rows,columns> out; for(int i = 0; i < rows; ++i) for(int j = 0; j < columns; ++j) out.m_elem[i][j] = m.m_elem[i][j] * d; return out; } template<const int rows, const int columns> Matrix<rows,columns> Matrix<rows,columns>::operator/(const double& d) const { Matrix<rows,columns> out; for(int i = 0; i < rows; ++i) for(int j = 0; j < columns; ++j) out.m_elem[i][j] = m_elem[i][j] / d; return out; } template<const int rows, const int columns> inline Matrix<rows,columns> Matrix<rows,columns>::operator-() const // Unary minus { Matrix<rows,columns> out; for(int i = 0; i < rows; ++i) for(int j = 0; j < columns; ++j) out.m_elem[i][j] = -m_elem[i][j]; return out; } template<const int rows, const int columns> inline Matrix<rows,columns>& Matrix<rows,columns>::operator+=(const Matrix<rows,columns>& m) { for(int i = 0; i < rows; ++i) for(int j = 0; j < columns; ++j) m_elem[i][j] += m.m_elem[i][j]; return *this; } template<const int rows, const int columns> inline Matrix<rows,columns>& Matrix<rows,columns>::operator-=(const Matrix<rows,columns>& m) { for(int i = 0; i < rows; ++i) for(int j = 0; j < columns; ++j) m_elem[i][j] -= m.m_elem[i][j]; return *this; } template<const int rows, const int columns> Matrix<rows,columns>& Matrix<rows,columns>::operator*=(const double& d) { for(int i = 0; i < rows; ++i) for(int j = 0; j < columns; ++j) m_elem[i][j] *= d; return *this; } template<const int rows, const int columns> Matrix<rows,columns>& Matrix<rows,columns>::operator/=(const double& d) { for(int i = 0; i < rows; ++i) for(int j = 0; j < columns; ++j) m_elem[i][j] /= d; return *this; } template<const int rows, const int columns> inline Vector<rows> Matrix<rows,columns>::operator*(const Vector<columns>& v) const { Vector<rows> out; for(int i = 0; i < rows; ++i) { out[i] = 0; for(int j = 0; j < columns; ++j) out[i] += m_elem[i][j] * v[j]; } return out; } template<const int rows, const int columns> inline Matrix<rows,columns> OuterProduct(const Vector<rows>& v1, const Vector<columns>& v2) { Matrix<rows,columns> out; for(int i = 0; i < rows; ++i) for(int j = 0; j < columns; ++j) out.m_elem[i][j] = v1[i] * v2[j]; } template<const int rows, const int columns> inline Vector<columns> Matrix<rows,columns>::row(const int i) const { Vector<columns> out; for(int j = 0; j < columns; ++j) out[j] = m_elem[i][j]; return out; } template<const int rows, const int columns> void Matrix<rows,columns>::setRow(const int i, const Vector<columns>& v) { for(int j = 0; j < columns; ++j) m_elem[i][j] = v[j]; } template<const int rows, const int columns> inline Vector<rows> Matrix<rows,columns>::column(const int i) const { Vector<columns> out; for(int j = 0; j < rows; ++j) out[j] = m_elem[j][i]; return out; } template<const int rows, const int columns> void Matrix<rows,columns>::setColumn(const int i, const Vector<rows>& v) { for(int j = 0; j < rows; ++j) m_elem[j][i] = v[j]; } template<const int rows, const int columns> inline Matrix<rows,columns>& Matrix<rows,columns>::zero() { for(int i = 0; i < rows; ++i) for(int j = 0; j < columns; ++j) m_elem[i][j] = 0; return *this; } template<const int rows, const int columns> inline Matrix<columns,rows> Matrix<rows,columns>::transpose() const { Matrix<columns,rows> m; for(int i = 0; i < rows; ++i) for(int j = 0; j < columns; ++j) m.m_elem[j][i] = m_elem[i][j]; return m; } template<const int rows, const int columns> inline Matrix<rows,columns>& Matrix<rows,columns>::identity() { Vector<rows> v; for(int i = 0; i < rows; ++i) v[i] = 1; this->diagonal(v); return *this; } template<const int size> inline Matrix<size> DiagonalMatrix(const Vector<size>& v) { Matrix<size> out; out.zero(); for(int i = 0; i < size; ++i) out.m_elem[i][i] = v[i]; return out; } template<const int size> inline double Trace(const Matrix<size>& m) { double out = 0; for(int i = 0; i < size; ++i) out += m.m_elem[i][i]; return out; } double _MatrixDeterminantImpl(const int size, double* m); template<const int size> inline double Determinant(const Matrix<size>& m) { double mtmp[size*size]; // Scratch space for(int i = 0; i < size; ++i) for(int j = 0; j < size; ++j) mtmp[i*size+j] = m.elem(i, j); return _MatrixDeterminantImpl(size, mtmp); } int _MatrixInverseImpl(const int size, double* in, double* out); template<const int size> inline Matrix<size> Inverse(const Matrix<size>& m) { double in[size*size], out[size*size]; // Scratch space for(int i = 0; i < size; ++i) { for(int j = 0; j < size; ++j) { in[i*size+j] = m.elem(i, j); out[i*size+j] = (i == j) ? 1 : 0; } } if(_MatrixInverseImpl(size, in, out) != 0) throw DegenerateMatrix<size>(m); Matrix<size> mout; for(int i = 0; i < size; ++i) for(int j = 0; j < size; ++j) mout.elem(i, j) = out[i*size+j]; return mout; } }} // namespace WF::Math #endif // WFMATH_MATRIX_FUNCS_H 0707010000004E000081A4000000000000000000000001656C867F0000087F000000000000000000000000000000000000003F00000000wfmath-1701611135.403a8bd/src/wfmath/unused/oldmatrix_test.cpp// -*-C++-*- // matrix_test.cpp (Matrix<> test functions) // // The WorldForge Project // Copyright (C) 2001 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Ron Steinke // Created: 2001-12-7 #include "vector.h" #include "vector_funcs.h" #include "matrix.h" #include "matrix_funcs.h" #include "const.h" #include <assert.h> #include "stream_funcs.h" #include <iostream> using namespace WF::Math; //TODO tests for non-square matrices template<const int size> void test_matrix(const Matrix<size>& m) { cout << "Testing matrix: " << m << std::endl; cout << "Transpose is: " << m.transpose() << std::endl; Matrix<size> minv = m.inverse(); double mdet = m.determinant(), minvdet = minv.determinant(); cout << "Inverse is: " << minv << std::endl; assert(fabs(mdet * minvdet - 1) < WFMATH_EPSILON); Matrix<size> nothing; nothing.identity(); nothing -= m * minv; cout << "This should be zero: " << nothing << std::endl; for(int i = 0; i < size; ++i) for(int j = 0; j < size; ++j) assert(fabs(nothing.elem(i, j)) < WFMATH_EPSILON); } int main() { Matrix<2> m2; Matrix<3> m3; m2.identity(); m2.elem(1, 0) = 1; test_matrix(m2); m3.identity(); m3.elem(1, 0) = 1; m3.elem(0, 2) = WFMATH_CONST_SQRT2; m3.elem(2, 0) = WFMATH_CONST_SQRT3; test_matrix(m3); return 0; } 0707010000004F000081A4000000000000000000000001656C867F00001989000000000000000000000000000000000000003000000000wfmath-1701611135.403a8bd/src/wfmath/vector.cpp// vector.cpp (Vector<> implementation) // // The WorldForge Project // Copyright (C) 2001 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Ron Steinke // Created: 2001-12-7 // Extensive amounts of this material come from the Vector2D // and Vector3D classes from stage/math, written by Bryce W. // Harrington, Kosh, and Jari Sundell (Rakshasa). #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "vector_funcs.h" #include "basis.h" #include "point.h" #include "quaternion.h" namespace WFMath { template<> CoordType Vector<2>::sloppyMag() const { CoordType ax = std::fabs(m_elem[0]), ay = std::fabs(m_elem[1]); const CoordType p = numeric_constants<CoordType>::sqrt2() - 1; // Don't need float add, all terms > 0 if(ax > ay) return ax + p * ay; else if (ay > 0) return ay + p * ax; else return 0; } template<> CoordType Vector<3>::sloppyMag() const { CoordType ax = std::fabs(m_elem[0]), ay = std::fabs(m_elem[1]), az = std::fabs(m_elem[2]); const CoordType p = numeric_constants<CoordType>::sqrt2() - 1; const CoordType q = numeric_constants<CoordType>::sqrt3() + 1 - 2 * numeric_constants<CoordType>::sqrt2(); // Don't need FloatAdd, only term < 0 is q, it's very small, // and amin1 * amin2 / amax < amax. if(ax > ay && ax > az) return ax + p * (ay + az) + q * ay * az / ax; else if (ay > az) return ay + p * (ax + az) + q * ax * az / ay; else if (az > 0) return az + p * (ax + ay) + q * ax * ay / az; else return 0; } template<> Vector<3>& Vector<3>::rotate(const Vector<3>& axis, CoordType theta) { CoordType axis_sqr_mag = axis.sqrMag(); assert(axis_sqr_mag != 0); Vector<3> perp_part = *this - axis * Dot(*this, axis) / axis_sqr_mag; Vector<3> rot90 = Cross(axis, perp_part) / std::sqrt(axis_sqr_mag); *this += perp_part * (std::cos(theta) - 1) + rot90 * std::sin(theta); return *this; } template<> Vector<3>& Vector<3>::rotate(const Quaternion& q) { *this = (2 * q.scalar() * q.scalar() - 1) * *this + 2 * q.vector() * Dot(q.vector(), *this) + 2 * q.scalar() * Cross(q.vector(), *this); return *this; } CoordType Cross(const Vector<2>& v1, const Vector<2>& v2) { CoordType ans = v1[0] * v2[1] - v2[0] * v1[1]; return (ans >= v1._scaleEpsilon(v2)) ? ans : 0; } Vector<3> Cross(const Vector<3>& v1, const Vector<3>& v2) { Vector<3> ans; ans.setValid(v1.isValid() && v2.isValid()); ans[0] = v1[1] * v2[2] - v2[1] * v1[2]; ans[1] = v1[2] * v2[0] - v2[2] * v1[0]; ans[2] = v1[0] * v2[1] - v2[0] * v1[1]; double delta = v1._scaleEpsilon(v2); for(int i = 0; i < 3; ++i) if(std::fabs(ans[i]) < delta) ans[i] = 0; return ans; } template<> Vector<2>& Vector<2>::polar(CoordType r, CoordType theta) { CoordType d[2] = {r, theta}; _PolarToCart(d, m_elem); m_valid = true; return *this; } template<> void Vector<2>::asPolar(CoordType& r, CoordType& theta) const { CoordType d[2]; _CartToPolar(m_elem, d); r = d[0]; theta = d[1]; } template<> Vector<3>& Vector<3>::polar(CoordType r, CoordType theta, CoordType z) { CoordType d[2] = {r, theta}; _PolarToCart(d, m_elem); m_elem[2] = z; m_valid = true; return *this; } template<> void Vector<3>::asPolar(CoordType& r, CoordType& theta, CoordType& z) const { CoordType d[2]; _CartToPolar(m_elem, d); r = d[0]; theta = d[1]; z = m_elem[2]; } template<> Vector<3>& Vector<3>::spherical(CoordType r, CoordType theta, CoordType phi) { CoordType d[3] = {r, theta, phi}; _SphericalToCart(d, m_elem); m_valid = true; return *this; } template<> void Vector<3>::asSpherical(CoordType& r, CoordType& theta, CoordType& phi) const { CoordType d[3]; _CartToSpherical(m_elem, d); r = d[0]; theta = d[1]; phi = d[2]; } template class Vector<3>; static_assert(std::is_standard_layout<Vector<3>>::value, "Vector should be standard layout."); static_assert(std::is_trivially_copyable<Vector<3>>::value, "Vector should be trivially copyable."); template class Vector<2>; static_assert(std::is_standard_layout<Vector<2>>::value, "Vector should be standard layout."); static_assert(std::is_trivially_copyable<Vector<2>>::value, "Vector should be trivially copyable."); template Vector<3>& operator-=(Vector<3>& v1, const Vector<3>& v2); template Vector<2>& operator-=(Vector<2>& v1, const Vector<2>& v2); template Vector<3>& operator+=(Vector<3>& v1, const Vector<3>& v2); template Vector<2>& operator+=(Vector<2>& v1, const Vector<2>& v2); template Vector<3>& operator*=(Vector<3>& v1, CoordType d); template Vector<2>& operator*=(Vector<2>& v1, CoordType d); template Vector<3>& operator/=(Vector<3>& v1, CoordType d); template Vector<2>& operator/=(Vector<2>& v1, CoordType d); template CoordType Dot<3>(const Vector<3> &, const Vector<3> &); template CoordType Dot<2>(const Vector<2> &, const Vector<2> &); template CoordType Angle<3>(const Vector<3> &, const Vector<3> &); template Vector<3> operator-<3>(const Vector<3> &); template Vector<3> operator*<3>(CoordType, const Vector<3> &); template Vector<2> operator*<2>(CoordType, const Vector<2> &); template Vector<3> operator*<3>(const Vector<3> &, CoordType); template Vector<2> operator*<2>(const Vector<2> &, CoordType); template Vector<3> operator/<3>(const Vector<3> &, CoordType); template Vector<2> operator/<2>(const Vector<2> &, CoordType); template Vector<3> operator+<3>(const Vector<3> &, const Vector<3> &); template Vector<2> operator+<2>(const Vector<2> &, const Vector<2> &); template Vector<3> operator-<3>(const Vector<3> &, const Vector<3> &); template Vector<2> operator-<2>(const Vector<2> &, const Vector<2> &); } 07070100000050000081A4000000000000000000000001656C867F00003EFC000000000000000000000000000000000000002E00000000wfmath-1701611135.403a8bd/src/wfmath/vector.h// vector.h (Vector<> class definition) // // The WorldForge Project // Copyright (C) 2001 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Ron Steinke // Created: 2001-12-7 // Extensive amounts of this material come from the Vector2D // and Vector3D classes from stage/math, written by Bryce W. // Harrington, Kosh, and Jari Sundell (Rakshasa). #ifndef WFMATH_VECTOR_H #define WFMATH_VECTOR_H #include <wfmath/const.h> #include <iosfwd> #include <cmath> namespace WFMath { template<int dim> Vector<dim>& operator+=(Vector<dim>& v1, const Vector<dim>& v2); template<int dim> Vector<dim>& operator-=(Vector<dim>& v1, const Vector<dim>& v2); template<int dim> Vector<dim>& operator*=(Vector<dim>& v, CoordType d); template<int dim> Vector<dim>& operator/=(Vector<dim>& v, CoordType d); template<int dim> Vector<dim> operator+(const Vector<dim>& v1, const Vector<dim>& v2); template<int dim> Vector<dim> operator-(const Vector<dim>& v1, const Vector<dim>& v2); template<int dim> Vector<dim> operator-(const Vector<dim>& v); // Unary minus template<int dim> Vector<dim> operator*(CoordType d, const Vector<dim>& v); template<int dim> Vector<dim> operator*(const Vector<dim>& v, CoordType d); template<int dim> Vector<dim> operator/(const Vector<dim>& v, CoordType d); template<int dim> CoordType Dot(const Vector<dim>& v1, const Vector<dim>& v2); template<int dim> CoordType Angle(const Vector<dim>& v, const Vector<dim>& u); // The following are defined in rotmatrix_funcs.h /// returns m * v template<int dim> // m * v Vector<dim> Prod(const RotMatrix<dim>& m, const Vector<dim>& v); /// returns m^-1 * v template<int dim> // m^-1 * v Vector<dim> InvProd(const RotMatrix<dim>& m, const Vector<dim>& v); /// returns v * m /** * This is the function to use to rotate a Vector v using a Matrix m **/ template<int dim> // v * m Vector<dim> Prod(const Vector<dim>& v, const RotMatrix<dim>& m); /// return v * m^-1 template<int dim> // v * m^-1 Vector<dim> ProdInv(const Vector<dim>& v, const RotMatrix<dim>& m); /// template<int dim> Vector<dim> operator*(const RotMatrix<dim>& m, const Vector<dim>& v); /// template<int dim> Vector<dim> operator*(const Vector<dim>& v, const RotMatrix<dim>& m); template<int dim> Vector<dim> operator-(const Point<dim>& c1, const Point<dim>& c2); template<int dim> Point<dim> operator+(const Point<dim>& c, const Vector<dim>& v); template<int dim> Point<dim> operator-(const Point<dim>& c, const Vector<dim>& v); template<int dim> Point<dim> operator+(const Vector<dim>& v, const Point<dim>& c); template<int dim> Point<dim>& operator+=(Point<dim>& p, const Vector<dim>& v); template<int dim> Point<dim>& operator-=(Point<dim>& p, const Vector<dim>& v); template<int dim> std::ostream& operator<<(std::ostream& os, const Vector<dim>& v); template<int dim> std::istream& operator>>(std::istream& is, Vector<dim>& v); template<typename Shape> class ZeroPrimitive; /// A dim dimensional vector /** * This class implements the 'generic' subset of the interface in * the fake class Shape. **/ template<int dim = 3> class Vector { friend class ZeroPrimitive<Vector<dim> >; public: /// Construct an uninitialized vector Vector() : m_elem{}, m_valid(false) { } /// Construct a copy of a vector Vector(const Vector&) = default; /// Construct a vector from an object passed by Atlas explicit Vector(const AtlasInType& a); /// Construct a vector from a point. explicit Vector(const Point<dim>& point); /** * @brief Provides a global instance preset to zero. */ static const Vector<dim>& ZERO(); friend std::ostream& operator<< <dim>(std::ostream& os, const Vector& v); friend std::istream& operator>> <dim>(std::istream& is, Vector& v); /// Create an Atlas object from the vector AtlasOutType toAtlas() const; /// Set the vector's value to that given by an Atlas object void fromAtlas(const AtlasInType& a); Vector& operator=(const Vector& v) = default; bool isEqualTo(const Vector& v, CoordType epsilon = numeric_constants<CoordType>::epsilon()) const; bool operator==(const Vector& v) const {return isEqualTo(v);} bool operator!=(const Vector& v) const {return !isEqualTo(v);} bool isValid() const {return m_valid;} /// make isValid() return true if you've initialized the vector by hand void setValid(bool valid = true) {m_valid = valid;} /// Zero the components of a vector Vector& zero(); // Math operators /// Add the second vector to the first friend Vector& operator+=<dim>(Vector& v1, const Vector& v2); /// Subtract the second vector from the first friend Vector& operator-=<dim>(Vector& v1, const Vector& v2); /// Multiply the magnitude of v by d friend Vector& operator*=<dim>(Vector& v, CoordType d); /// Divide the magnitude of v by d friend Vector& operator/=<dim>(Vector& v, CoordType d); /// Take the sum of two vectors friend Vector operator+<dim>(const Vector& v1, const Vector& v2); /// Take the difference of two vectors friend Vector operator-<dim>(const Vector& v1, const Vector& v2); /// Reverse the direction of a vector friend Vector operator-<dim>(const Vector& v); // Unary minus /// Multiply a vector by a scalar friend Vector operator*<dim>(CoordType d, const Vector& v); /// Multiply a vector by a scalar friend Vector operator*<dim>(const Vector& v, CoordType d); /// Divide a vector by a scalar friend Vector operator/<dim>(const Vector& v, CoordType d); // documented outside the class definition friend Vector Prod<dim>(const RotMatrix<dim>& m, const Vector& v); friend Vector InvProd<dim>(const RotMatrix<dim>& m, const Vector& v); /// Get the i'th element of the vector CoordType operator[](const int i) const {return m_elem[i];} /// Get the i'th element of the vector CoordType& operator[](const int i) {return m_elem[i];} /// Find the vector which gives the offset between two points friend Vector operator-<dim>(const Point<dim>& c1, const Point<dim>& c2); /// Find the point at the offset v from the point c friend Point<dim> operator+<dim>(const Point<dim>& c, const Vector& v); /// Find the point at the offset -v from the point c friend Point<dim> operator-<dim>(const Point<dim>& c, const Vector& v); /// Find the point at the offset v from the point c friend Point<dim> operator+<dim>(const Vector& v, const Point<dim>& c); /// Shift a point by a vector friend Point<dim>& operator+=<dim>(Point<dim>& p, const Vector& rhs); /// Shift a point by a vector, in the opposite direction friend Point<dim>& operator-=<dim>(Point<dim>& p, const Vector& rhs); friend CoordType Cross(const Vector<2>& v1, const Vector<2>& v2); friend Vector<3> Cross(const Vector<3>& v1, const Vector<3>& v2); /// The dot product of two vectors friend CoordType Dot<dim>(const Vector& v1, const Vector& v2); /// The angle between two vectors friend CoordType Angle<dim>(const Vector& v, const Vector& u); /// The squared magnitude of a vector CoordType sqrMag() const; /// The magnitude of a vector CoordType mag() const {return std::sqrt(sqrMag());} /// Normalize a vector Vector& normalize(CoordType norm = 1.0) {CoordType themag = mag(); return (*this *= norm / themag);} /// An approximation to the magnitude of a vector /** * The sloppyMag() function gives a value between * the true magnitude and sloppyMagMax multiplied by the * true magnitude. sloppyNorm() uses sloppyMag() to normalize * the vector. This is currently only implemented for * dim = {1, 2, 3}. For all current implementations, * sloppyMagMax is greater than or equal to one. * The constant sloppyMagMaxSqrt is provided for those * who want to most closely approximate the true magnitude, * without caring whether it's too low or too high. **/ CoordType sloppyMag() const; /// Approximately normalize a vector /** * Normalize a vector using sloppyMag() instead of the true magnitude. * The new length of the vector will be between norm/sloppyMagMax() * and norm. **/ Vector& sloppyNorm(CoordType norm = 1.0); // Can't seem to implement these as constants, implementing // inline lookup functions instead. /// The maximum ratio of the return value of sloppyMag() to the true magnitude static CoordType sloppyMagMax(); /// The square root of sloppyMagMax() /** * This is provided for people who want to obtain maximum accuracy from * sloppyMag(), without caring whether the answer is high or low. * The result sloppyMag()/sloppyMagMaxSqrt() will be within sloppyMagMaxSqrt() * of the true magnitude. **/ static CoordType sloppyMagMaxSqrt(); /// Rotate the vector in the (axis1, axis2) plane by the angle theta Vector& rotate(int axis1, int axis2, CoordType theta); /// Rotate the vector in the (v1, v2) plane by the angle theta /** * This throws CollinearVectors if v1 and v2 are parallel. **/ Vector& rotate(const Vector& v1, const Vector& v2, CoordType theta); /// Rotate the vector using a matrix Vector& rotate(const RotMatrix<dim>&); // mirror image functions /// Reflect a vector in the direction of the i'th axis Vector& mirror(const int i) { m_elem[i] *= -1; return *this;} /// Reflect a vector in the direction specified by v Vector& mirror(const Vector& v) {return operator-=(*this, 2 * v * Dot(v, *this) / v.sqrMag());} /// Reflect a vector in all directions simultaneously. /** * This is a nice way to implement the parity operation if dim is odd. **/ Vector& mirror() {return operator*=(*this, -1);} // Specialized 2D/3D stuff starts here // The following functions are defined only for // two dimensional (rotate(CoordType), Vector<>(CoordType, CoordType)) // and three dimensional (the rest of them) vectors. // Attempting to call these on any other vector will // result in a linker error. /// 2D only: construct a vector from (x, y) coordinates Vector(CoordType x, CoordType y); /// 3D only: construct a vector from (x, y, z) coordinates Vector(CoordType x, CoordType y, CoordType z); /// 2D only: rotate a vector by an angle theta Vector& rotate(CoordType theta); /// 3D only: rotate a vector about the x axis by an angle theta Vector& rotateX(CoordType theta); /// 3D only: rotate a vector about the y axis by an angle theta Vector& rotateY(CoordType theta); /// 3D only: rotate a vector about the z axis by an angle theta Vector& rotateZ(CoordType theta); /// 3D only: rotate a vector about the i'th axis by an angle theta Vector& rotate(const Vector& axis, CoordType theta); /// 3D only: rotate a vector using a Quaternion Vector& rotate(const Quaternion& q); // Label the first three components of the vector as (x,y,z) for // 2D/3D convienience /// Access the first component of a vector CoordType x() const {return m_elem[0];} /// Access the first component of a vector CoordType& x() {return m_elem[0];} /// Access the second component of a vector CoordType y() const {return m_elem[1];} /// Access the second component of a vector CoordType& y() {return m_elem[1];} /// Access the third component of a vector CoordType z() const; /// Access the third component of a vector CoordType& z(); /// Flip the x component of a vector Vector& mirrorX() {return mirror(0);} /// Flip the y component of a vector Vector& mirrorY() {return mirror(1);} /// Flip the z component of a vector Vector& mirrorZ(); /// 2D only: construct a vector from polar coordinates Vector& polar(CoordType r, CoordType theta); /// 2D only: convert a vector to polar coordinates void asPolar(CoordType& r, CoordType& theta) const; /// 3D only: construct a vector from polar coordinates Vector& polar(CoordType r, CoordType theta, CoordType z); /// 3D only: convert a vector to polar coordinates void asPolar(CoordType& r, CoordType& theta, CoordType& z) const; /// 3D only: construct a vector from shperical coordinates Vector& spherical(CoordType r, CoordType theta, CoordType phi); /// 3D only: convert a vector to shperical coordinates void asSpherical(CoordType& r, CoordType& theta, CoordType& phi) const; const CoordType* elements() const {return m_elem;} private: double _scaleEpsilon(const Vector& v, CoordType epsilon = numeric_constants<CoordType>::epsilon()) const {return _ScaleEpsilon(m_elem, v.m_elem, dim, epsilon);} CoordType m_elem[dim]; bool m_valid; }; template<> inline CoordType Vector<3>::z() const { return m_elem[2]; } template<> inline CoordType& Vector<3>::z() { return m_elem[2]; } template<> inline Vector<3>& Vector<3>::mirrorZ() { return mirror(2); } /// 2D only: get the z component of the cross product of two vectors CoordType Cross(const Vector<2>& v1, const Vector<2>& v2); /// 3D only: get the cross product of two vectors Vector<3> Cross(const Vector<3>& v1, const Vector<3>& v2); /// Check if two vectors are parallel /** * Returns true if the vectors are parallel. For parallel * vectors, same_dir is set to true if they point the same * direction, and false if they point opposite directions **/ template<int dim> bool Parallel(const Vector<dim>& v1, const Vector<dim>& v2, bool& same_dir); /// Check if two vectors are parallel /** * Convienience wrapper if you don't care about same_dir **/ template<int dim> bool Parallel(const Vector<dim>& v1, const Vector<dim>& v2); /// Check if two vectors are perpendicular template<int dim> bool Perpendicular(const Vector<dim>& v1, const Vector<dim>& v2); template <int dim> inline Vector<dim> operator+(const Vector<dim>& v1, const Vector<dim>& v2) { Vector<dim> ans(v1); ans += v2; return ans; } template <int dim> inline Vector<dim> operator-(const Vector<dim>& v1, const Vector<dim>& v2) { Vector<dim> ans(v1); ans -= v2; return ans; } template <int dim> inline Vector<dim> operator*(const Vector<dim>& v, CoordType d) { Vector<dim> ans(v); ans *= d; return ans; } template<int dim> inline Vector<dim> operator*(CoordType d, const Vector<dim>& v) { Vector<dim> ans(v); ans *= d; return ans; } template <int dim> inline Vector<dim> operator/(const Vector<dim>& v, CoordType d) { Vector<dim> ans(v); ans /= d; return ans; } template<int dim> inline bool Parallel(const Vector<dim>& v1, const Vector<dim>& v2, bool& same_dir) { CoordType dot = Dot(v1, v2); same_dir = (dot > 0); return Equal(dot * dot, v1.sqrMag() * v2.sqrMag()); } template<int dim> inline bool Parallel(const Vector<dim>& v1, const Vector<dim>& v2) { bool same_dir; return Parallel(v1, v2, same_dir); } template<> inline CoordType Vector<1>::sloppyMagMax() { return 1.f; } template<> inline CoordType Vector<2>::sloppyMagMax() { return 1.082392200292393968799446410733f; } template<> inline CoordType Vector<3>::sloppyMagMax() { return 1.145934719303161490541433900265f; } template<> inline CoordType Vector<1>::sloppyMagMaxSqrt() { return 1.f; } template<> inline CoordType Vector<2>::sloppyMagMaxSqrt() { return 1.040380795811030899095785063701f; } template<> inline CoordType Vector<3>::sloppyMagMaxSqrt() { return 1.070483404496847625250328653179f; } } // namespace WFMath #endif // WFMATH_VECTOR_H 07070100000051000081A4000000000000000000000001656C867F00001E48000000000000000000000000000000000000003400000000wfmath-1701611135.403a8bd/src/wfmath/vector_funcs.h// vector_funcs.h (Vector<> template functions) // // The WorldForge Project // Copyright (C) 2001 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Ron Steinke // Created: 2001-12-7 // Extensive amounts of this material come from the Vector2D // and Vector3D classes from stage/math, written by Bryce W. // Harrington, Kosh, and Jari Sundell (Rakshasa). #ifndef WFMATH_VECTOR_FUNCS_H #define WFMATH_VECTOR_FUNCS_H #include <wfmath/vector.h> #include <wfmath/rotmatrix.h> #include <wfmath/zero.h> #include <limits> #include <cassert> namespace WFMath { template<int dim> Vector<dim>::Vector(const Point<dim>& p) : m_valid(p.isValid()) { for(int i = 0; i < dim; ++i) { m_elem[i] = p.elements()[i]; } } template<int dim> const Vector<dim>& Vector<dim>::ZERO() { static ZeroPrimitive<Vector<dim> > zeroVector(dim); return zeroVector.getShape(); } template<int dim> bool Vector<dim>::isEqualTo(const Vector<dim>& v, CoordType epsilon) const { //If anyone is invalid they are never equal if (!v.m_valid || !m_valid) { return false; } CoordType delta = _ScaleEpsilon(m_elem, v.m_elem, dim, epsilon); for(int i = 0; i < dim; ++i) { if(std::fabs(m_elem[i] - v.m_elem[i]) > delta) { return false; } } return true; } template <int dim> Vector<dim>& operator+=(Vector<dim>& v1, const Vector<dim>& v2) { v1.m_valid = v1.m_valid && v2.m_valid; for(int i = 0; i < dim; ++i) { v1.m_elem[i] += v2.m_elem[i]; } return v1; } template <int dim> Vector<dim>& operator-=(Vector<dim>& v1, const Vector<dim>& v2) { v1.m_valid = v1.m_valid && v2.m_valid; for(int i = 0; i < dim; ++i) { v1.m_elem[i] -= v2.m_elem[i]; } return v1; } template <int dim> Vector<dim>& operator*=(Vector<dim>& v, CoordType d) { for(int i = 0; i < dim; ++i) { v.m_elem[i] *= d; } return v; } template <int dim> Vector<dim>& operator/=(Vector<dim>& v, CoordType d) { for(int i = 0; i < dim; ++i) { v.m_elem[i] /= d; } return v; } template <int dim> Vector<dim> operator-(const Vector<dim>& v) { Vector<dim> ans; ans.m_valid = v.m_valid; for(int i = 0; i < dim; ++i) { ans.m_elem[i] = -v.m_elem[i]; } return ans; } template<int dim> Vector<dim>& Vector<dim>::sloppyNorm(CoordType norm) { CoordType mag = sloppyMag(); assert("need nonzero length vector" && mag > norm / std::numeric_limits<CoordType>::max()); return (*this *= norm / mag); } template<int dim> Vector<dim>& Vector<dim>::zero() { m_valid = true; for(int i = 0; i < dim; ++i) { m_elem[i] = 0; } return *this; } template<int dim> CoordType Angle(const Vector<dim>& v, const Vector<dim>& u) { // Adding numbers with large magnitude differences can cause // a loss of precision, but Dot() checks for this now CoordType dp = FloatClamp(Dot(u, v) / std::sqrt(u.sqrMag() * v.sqrMag()), -1.0, 1.0); CoordType angle = std::acos(dp); return angle; } template<int dim> Vector<dim>& Vector<dim>::rotate(int axis1, int axis2, CoordType theta) { assert(axis1 >= 0 && axis2 >= 0 && axis1 < dim && axis2 < dim && axis1 != axis2); CoordType tmp1 = m_elem[axis1], tmp2 = m_elem[axis2]; CoordType stheta = std::sin(theta), ctheta = std::cos(theta); m_elem[axis1] = tmp1 * ctheta - tmp2 * stheta; m_elem[axis2] = tmp2 * ctheta + tmp1 * stheta; return *this; } template<int dim> Vector<dim>& Vector<dim>::rotate(const Vector<dim>& v1, const Vector<dim>& v2, CoordType theta) { RotMatrix<dim> m; return operator=(Prod(*this, m.rotation(v1, v2, theta))); } template<int dim> Vector<dim>& Vector<dim>::rotate(const RotMatrix<dim>& m) { return *this = Prod(*this, m); } template<> Vector<3>& Vector<3>::rotate(const Vector<3>& axis, CoordType theta); template<> Vector<3>& Vector<3>::rotate(const Quaternion& q); template<int dim> CoordType Dot(const Vector<dim>& v1, const Vector<dim>& v2) { double delta = _ScaleEpsilon(v1.m_elem, v2.m_elem, dim); CoordType ans = 0; for(int i = 0; i < dim; ++i) { ans += v1.m_elem[i] * v2.m_elem[i]; } return (std::fabs(ans) >= delta) ? ans : 0; } template<int dim> CoordType Vector<dim>::sqrMag() const { CoordType ans = 0; for(int i = 0; i < dim; ++i) { // all terms > 0, no loss of precision through cancelation ans += m_elem[i] * m_elem[i]; } return ans; } template<int dim> bool Perpendicular(const Vector<dim>& v1, const Vector<dim>& v2) { CoordType max1 = 0, max2 = 0; for(int i = 0; i < dim; ++i) { CoordType val1 = std::fabs(v1[i]), val2 = std::fabs(v2[i]); if(val1 > max1) { max1 = val1; } if(val2 > max2) { max2 = val2; } } // Need to scale by both, since Dot(v1, v2) goes like the product of the magnitudes int exp1, exp2; (void) std::frexp(max1, &exp1); (void) std::frexp(max2, &exp2); return std::fabs(Dot(v1, v2)) < std::ldexp(numeric_constants<CoordType>::epsilon(), exp1 + exp2); } // Note for people trying to compute the above numbers // more accurately: // The worst value for dim == 2 occurs when the ratio of the components // of the vector is sqrt(2) - 1. The value above is equal to sqrt(4 - 2 * sqrt(2)). // The worst value for dim == 3 occurs when the two smaller components // are equal, and their ratio with the large component is the // (unique, real) solution to the equation q x^3 + (q-1) x + p == 0, // where p = sqrt(2) - 1, and q = sqrt(3) + 1 - 2 * sqrt(2). // Running the script bc_sloppy_mag_3 provided with the WFMath source // will calculate the above number. template<> Vector<2>& Vector<2>::polar(CoordType r, CoordType theta); template<> void Vector<2>::asPolar(CoordType& r, CoordType& theta) const; template<> Vector<3>& Vector<3>::polar(CoordType r, CoordType theta, CoordType z); template<> void Vector<3>::asPolar(CoordType& r, CoordType& theta, CoordType& z) const; template<> Vector<3>& Vector<3>::spherical(CoordType r, CoordType theta, CoordType phi); template<> void Vector<3>::asSpherical(CoordType& r, CoordType& theta, CoordType& phi) const; template<> CoordType Vector<2>::sloppyMag() const; template<> CoordType Vector<3>::sloppyMag() const; template<> CoordType Vector<1>::sloppyMag() const {return std::fabs(m_elem[0]);} template<> Vector<2>::Vector(CoordType x, CoordType y) : m_valid(true) {m_elem[0] = x; m_elem[1] = y;} template<> Vector<3>::Vector(CoordType x, CoordType y, CoordType z) : m_valid(true) {m_elem[0] = x; m_elem[1] = y; m_elem[2] = z;} template<> Vector<2>& Vector<2>::rotate(CoordType theta) {return rotate(0, 1, theta);} template<> Vector<3>& Vector<3>::rotateX(CoordType theta) {return rotate(1, 2, theta);} template<> Vector<3>& Vector<3>::rotateY(CoordType theta) {return rotate(2, 0, theta);} template<> Vector<3>& Vector<3>::rotateZ(CoordType theta) {return rotate(0, 1, theta);} } // namespace WFMath #endif // WFMATH_VECTOR_FUNCS_H 07070100000052000081A4000000000000000000000001656C867F00000928000000000000000000000000000000000000002E00000000wfmath-1701611135.403a8bd/src/wfmath/wfmath.h// -*-C++-*- // wfmath.h (General include file for the WFMath library) // // The WorldForge Project // Copyright (C) 2001 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Ron Steinke // Created: 2001-12-7 #ifndef WFMATH_WFMATH_H #define WFMATH_WFMATH_H // Simple stuff #include <wfmath/error.h> #include <wfmath/const.h> // Basic types #include <wfmath/vector.h> #include <wfmath/rotmatrix.h> #include <wfmath/point.h> #include <wfmath/quaternion.h> // Shape types #include <wfmath/axisbox.h> #include <wfmath/ball.h> #include <wfmath/segment.h> #include <wfmath/rotbox.h> #include <wfmath/polygon.h> // Shape intersection functions #include <wfmath/intersect.h> // Probability and statistics #include <wfmath/probability.h> #include <wfmath/timestamp.h> #include <wfmath/randgen.h> #include <wfmath/shuffle.h> // iostreams and strings #include <wfmath/stream.h> #include <wfmath/int_to_string.h> // Don't include atlasconv.h, which includes <Atlas/Message/Object.h> // There is, however, no linker dependency on atlas in the library, // so it is quite safe to use WFMath without atlas, as long as you // don't include this header // This file doesn't include basis.h, which only contains declarations // for some functions which are used in vector.cpp and point.cpp // Any header file "foo_funcs.h" is automatically included in "foo.h", // so those files are not listed here. Similarly, "intersect_decls.h" // is included in "intersect.h" (among other places). #endif // WFMATH_WFMATH_H 07070100000053000081A4000000000000000000000001656C867F000008DB000000000000000000000000000000000000003500000000wfmath-1701611135.403a8bd/src/wfmath/wrapped_array.h // Copright (C) 1999 // $Revision$ // $Date$ // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA, // or download the License terms from prep.ai.mit.edu/pub/gnu/COPYING-2.0. // // Contact: // -------- // Bernd Gaertner // Institut f. Informatik // ETH Zuerich // ETH-Zentrum // CH-8092 Zuerich, Switzerland // http://www.inf.ethz.ch/personal/gaertner // #ifndef WFMATH_WRAPPED_ARRAY_H #define WFMATH_WRAPPED_ARRAY_H namespace WFMath { namespace _miniball { template <int d> class Wrapped_array { private: double coord [d]{}; public: // default Wrapped_array() = default; // copy from Wrapped_array Wrapped_array (const Wrapped_array& p) = default; // copy from double* Wrapped_array (const double* p) { for (int i=0; i<d; ++i) coord[i] = p[i]; } // assignment Wrapped_array& operator = (const Wrapped_array& p) = default; // coordinate access double& operator [] (int i) { return coord[i]; } const double& operator [] (int i) const { return coord[i]; } const double* begin() const { return coord; } const double* end() const { return coord+d; } }; }} // namespace WFMath::_miniball #endif // WFMATH_WRAPPED_ARRAY_H 07070100000054000081A4000000000000000000000001656C867F0000077D000000000000000000000000000000000000002C00000000wfmath-1701611135.403a8bd/src/wfmath/zero.h// The WorldForge Project // Copyright (C) 2009 The WorldForge Project // // Author: Erik Hjortsberg <erik@worlforge.org, (C) 2009 // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. #ifndef WFMATH_ZERO_H #define WFMATH_ZERO_H namespace WFMath { /** @brief Utility class for providing zero primitives. This class will only work with simple structures such as Vector or Point which provide a m_elem structure. In order for it to access the m_elem structure it must be declared as a friend class of the class it will provide an instance of. @author Erik Hjortsberg <erik@worldforge.org> */ template<typename Shape> class ZeroPrimitive { public: /** @brief Ctor. An instance of Shape with zero values will be created at construction time. @param dim The dimensions of the shape. */ explicit ZeroPrimitive(int dim) : m_shape() { for (int i = 0; i < dim; ++i) { m_shape.m_elem[i] = 0; } m_shape.m_valid = true; } /** @brief Gets the zeroed shape. */ const Shape& getShape() const { return m_shape; } private: /** @brief The interal zeroed shape. */ Shape m_shape; }; } #endif //WFMATH_ZERO_H 07070100000055000041ED000000000000000000000003656C867F00000000000000000000000000000000000000000000002000000000wfmath-1701611135.403a8bd/tests07070100000056000081A4000000000000000000000001656C867F00000293000000000000000000000000000000000000002F00000000wfmath-1701611135.403a8bd/tests/CMakeLists.txt# Add test wf_add_test(ball_test.cpp) wf_add_test(const_test.cpp) wf_add_test(intstring_test.cpp) wf_add_test(line_test.cpp) wf_add_test(point_test.cpp) wf_add_test(polygon_test.cpp) wf_add_test(probability_test.cpp) wf_add_test(quaternion_test.cpp) wf_add_test(randgen_test.cpp) wf_add_test(rotmatrix_test.cpp) wf_add_test(shape_test.cpp) wf_add_test(timestamp_test.cpp) wf_add_test(vector_test.cpp) if (Atlas_FOUND) link_directories(${Atlas_LIBRARY_DIR}) wf_add_test(atlas/atlas_0_7_test.cpp) target_link_libraries(atlas_0_7_test ${Atlas_LIBRARIES}) target_include_directories(atlas_0_7_test PUBLIC ${Atlas_INCLUDE_DIR}) endif (Atlas_FOUND)07070100000057000041ED000000000000000000000002656C867F00000000000000000000000000000000000000000000002600000000wfmath-1701611135.403a8bd/tests/atlas07070100000058000081A4000000000000000000000001656C867F00000668000000000000000000000000000000000000003900000000wfmath-1701611135.403a8bd/tests/atlas/atlas_0_4_test.cpp// atlas_tests.cpp (WFMath/Atlas Message conversion test code) // // The WorldForge Project // Copyright (C) 2001 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Ron Steinke // Created: 2001-12-12 #include<Atlas/Message/Object.h> #include "atlasconv.h" using namespace WFMath; template<class C> void atlas_test(const C& c) { // cout << c << std::endl; Atlas::Message::Object a = c.toAtlas(); C out(a); // cout << out << std::endl; // Only match to string precision assert(Equal(c, out, FloatMax(WFMATH_EPSILON,1e-5))); } int main() { Point<3> p(1, 0, Sqrt2); atlas_test(p); Vector<3> v(1, -1, 4); atlas_test(v); Quaternion q(v, 0.7); atlas_test(q); AxisBox<3> b1(Point<3>().setToOrigin(), p), b2(p, p + v); atlas_test(b1); atlas_test(b2); return 0; } 07070100000059000081A4000000000000000000000001656C867F00000962000000000000000000000000000000000000003900000000wfmath-1701611135.403a8bd/tests/atlas/atlas_0_7_test.cpp// atlas_tests.cpp (WFMath/Atlas Message conversion test code) // // The WorldForge Project // Copyright (C) 2001 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Ron Steinke // Created: 2001-12-12 #include <Atlas/Message/Element.h> #include "wfmath/atlasconv.h" #include "wfmath/stream.h" #include <cassert> using namespace WFMath; template<class C> void atlas_test(const C& c) { std::cout << c << std::endl; Atlas::Message::Element a = c.toAtlas(); C out(a); assert(out.isValid()); std::cout << out << std::endl; // Only match to string precision assert(Equal(c, out, FloatMax(numeric_constants<CoordType>::epsilon(),1e-5))); } int main() { Point<3> p(1, 0, numeric_constants<CoordType>::sqrt2()); atlas_test(p); Vector<3> v(1, -1, 4); atlas_test(v); Quaternion q(v, 0.7); atlas_test(q); AxisBox<3> b1(Point<3>().setToOrigin(), p), b2(p, p + v); atlas_test(b1); atlas_test(b2); Ball<3> ball(Point<3>(1, 2, 3), 10); atlas_test(ball); Polygon<2> poly; poly.addCorner(0, WFMath::Point<2>(0, 0)); poly.addCorner(1, WFMath::Point<2>(10, 0)); poly.addCorner(2, WFMath::Point<2>(10, 10)); atlas_test(poly); Line<2> line; line.addCorner(0, WFMath::Point<2>(0, 0)); line.addCorner(1, WFMath::Point<2>(10, 0)); atlas_test(line); Line<3> line2; line2.addCorner(0, WFMath::Point<3>(0, 0, 0)); line2.addCorner(1, WFMath::Point<3>(10, 0, 5)); atlas_test(line2); RotBox<2> rotbox(Point<2>(1, 2), Vector<2>(10, 20), RotMatrix<2>().identity()); atlas_test(rotbox); return 0; } 0707010000005A000081A4000000000000000000000001656C867F0000052B000000000000000000000000000000000000002E00000000wfmath-1701611135.403a8bd/tests/ball_test.cpp// vector_test.cpp (Vector<> test functions) // // The WorldForge Project // Copyright (C) 2001 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Alistair Riddoch // Created: 2011-01-26 #ifdef NDEBUG #undef NDEBUG #endif #ifndef DEBUG #define DEBUG #endif #include "wfmath/ball.h" #include <cassert> using namespace WFMath; int main() { Ball<2> b1(Point<2>(0,0), 1); assert(b1.isValid()); Ball<2> b2(Point<2>(0,0), -1); assert(!b2.isValid()); return 0; } 0707010000005B000081A4000000000000000000000001656C867F0000065F000000000000000000000000000000000000002F00000000wfmath-1701611135.403a8bd/tests/const_test.cpp// const_test.cpp (Equal() test functions) // // The WorldForge Project // Copyright (C) 2002 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Ron Steinke // Created: 2002-1-28 #ifdef NDEBUG #undef NDEBUG #endif #ifndef DEBUG #define DEBUG #endif #include "wfmath/const.h" #include <cassert> using namespace WFMath; // TestEqual() directly stolen from Numbers.cpp in Willow (thanks, Jesse!) static void TestEqual() { assert( Equal(1.0001, 1.0, 1.0e-3)); assert(!Equal(1.0001, 1.0, 1.0e-5)); assert( Equal(0.00010000, 0.00010002, 1.0e-3)); assert(!Equal(0.00010000, 0.00010002, 1.0e-6)); assert( Equal(1000100.0, 1000000.0, 1.0e-3)); assert(!Equal(1000100.0, 1000000.0, 1.0e-6)); } int main() { TestEqual(); return 0; } 0707010000005C000081A4000000000000000000000001656C867F00000762000000000000000000000000000000000000002F00000000wfmath-1701611135.403a8bd/tests/general_test.h// general_test.h (generic class interface test functions) // // The WorldForge Project // Copyright (C) 2001 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Ron Steinke // Created: 2001-1-6 #ifndef WFMATH_GENERAL_TEST_H #define WFMATH_GENERAL_TEST_H #include "wfmath/const.h" #include "wfmath/stream.h" #include <string> #include <iostream> #include <cstdlib> #include <cassert> namespace WFMath { template<class C> void test_general(const C& c) { C c1, c2(c); // Generic and copy constructors c1 = c; // operator=() assert(Equal(c1, c2)); assert(c1 == c2); assert(!(c1 != c2)); std::string s = ToString(c); // Uses operator<<() implicitly C c3; try { FromString(c3, s); // Uses operator>>() implicitly } catch(const ParseError&) { std::cerr << "Couldn't parse generated string: " << s << std::endl; abort(); } // We lose precision in string conversion assert(Equal(c3, c, FloatMax(numeric_constants<CoordType>::epsilon(), 1e-5F))); } } // namespace WFMath #endif // WFMATH_GENERAL_TEST_H 0707010000005D000081A4000000000000000000000001656C867F000006CD000000000000000000000000000000000000003300000000wfmath-1701611135.403a8bd/tests/intstring_test.cpp// intstring_test.cpp (IntToString() test functions) // // The WorldForge Project // Copyright (C) 2002 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Ron Steinke // Created: 2002-1-28 #ifdef NDEBUG #undef NDEBUG #endif #ifndef DEBUG #define DEBUG #endif #include "wfmath/int_to_string.h" #include "wfmath/randgen.h" #include <climits> #include <cstdlib> #include <cassert> using namespace WFMath; static void TestConvert() { for(unsigned i = 0; i < 100; ++i) { unsigned long val = MTRand::instance.randInt(); assert(strtoul(IntToString(val).c_str(), 0, 0) == val); // This assignment changes the value, but we just want a // random number, so we don't care. Large unsigned ints will // provide us negative numbers for testing. long val2 = (long) val; assert(atol(IntToString(val2).c_str()) == val2); } } int main() { TestConvert(); return 0; } 0707010000005E000081A4000000000000000000000001656C867F00000B8A000000000000000000000000000000000000002E00000000wfmath-1701611135.403a8bd/tests/line_test.cpp// line_test.cpp (Line<> test functions) // // The WorldForge Project // Copyright (C) 2001 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Ron Steinke // Created: 2012-01-26 #ifdef NDEBUG #undef NDEBUG #endif #ifndef DEBUG #define DEBUG #endif #include "wfmath/const.h" #include "wfmath/vector.h" #include "wfmath/point.h" #include "wfmath/axisbox.h" #include "wfmath/ball.h" #include "wfmath/stream.h" #include "wfmath/line.h" #include "general_test.h" #include "shape_test.h" #include <vector> #include <list> #include <cassert> using namespace WFMath; template<int dim> void test_line(const Line<dim>& p) { std::cout << "Testing line: " << p << std::endl; // test_general(p); // test_shape(p); assert(p == p); // FIXME more tests } void test_modify() { Line<2> line; line.addCorner(0, Point<2>(2, 2)); line.addCorner(0, Point<2>(0, 0)); assert(line.getCorner(0) == Point<2>(0, 0)); line.moveCorner(0, Point<2>(1, 1)); assert(line.getCorner(0) == Point<2>(1, 1)); } int main() { Line<2> line2_1; assert(!line2_1.isValid()); line2_1.addCorner(0, Point<2>(0, 0)); line2_1.addCorner(0, Point<2>(4, 0)); line2_1.addCorner(0, Point<2>(4, -4)); line2_1.addCorner(0, Point<2>(0, -4)); assert(line2_1.isValid()); test_line(line2_1); assert(line2_1 == line2_1); Line<2> line2_2; assert(!line2_2.isValid()); line2_2.addCorner(0, Point<2>(0, 0)); line2_2.addCorner(0, Point<2>(4, -4)); line2_2.addCorner(0, Point<2>(4, 0)); line2_2.addCorner(0, Point<2>(0, -4)); assert(line2_2.isValid()); // Check in-equality assert(line2_1 != line2_2); // Check assignment line2_2 = line2_1; // Check equality assert(line2_1 == line2_2); Line<2> line2_3; assert(!line2_3.isValid()); assert(line2_3 != line2_1); line2_3 = line2_1; assert(line2_3 == line2_1); // Check bounding box calculation assert(Equal(line2_1.boundingBox(), AxisBox<2>(Point<2>(0, -4), Point<2>(4, 0)))); Line<2> line2_4(line2_1); assert(line2_1 == line2_4); Line<3> line3; test_line(line3); test_modify(); return 0; } 0707010000005F000081A4000000000000000000000001656C867F00000BED000000000000000000000000000000000000002F00000000wfmath-1701611135.403a8bd/tests/point_test.cpp// point_test.cpp (Point<> test functions) // // The WorldForge Project // Copyright (C) 2001 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Ron Steinke // Created: 2001-12-12 #ifdef NDEBUG #undef NDEBUG #endif #ifndef DEBUG #define DEBUG #endif #include "wfmath/const.h" #include "wfmath/vector.h" #include "wfmath/point.h" #include "wfmath/axisbox.h" #include "wfmath/ball.h" #include "wfmath/stream.h" #include "general_test.h" #include "shape_test.h" #include <vector> #include <list> using namespace WFMath; template<int dim> void test_point(const Point<dim>& p) { std::cout << "Testing point: " << p << std::endl; test_general(p); test_shape(p); std::vector<Point<dim> > pvec; std::list<CoordType> clist; assert(!Barycenter(pvec).isValid()); assert(!Barycenter(pvec, clist).isValid()); pvec.push_back(p); assert(p == Barycenter(pvec)); clist.push_back(5); assert(p == Barycenter(pvec, clist)); // Barycenter fails if sum of weights is 0 pvec.push_back(p); assert(Barycenter(pvec).isValid()); clist.push_back(-5); assert(!Barycenter(pvec, clist).isValid()); assert(p == p + (p - p)); //Check that an invalid point isn't equal to a valid point, even if the values are equal Point<dim> invalid_point_1; Point<dim> invalid_point_2; for (size_t i = 0; i < dim; ++i) { invalid_point_1[i] = 0.0; invalid_point_2[i] = 0.0; } assert(invalid_point_1 != Point<dim>::ZERO()); //Two invalid points are never equal assert(invalid_point_1 != invalid_point_2); // FIXME more tests } int main() { Point<2> p{}; assert(!p.isValid()); test_point(Point<2>(1, -1)); test_point(Point<3>(1, -1, numeric_constants<CoordType>::sqrt2())); Point<2> zero2 = Point<2>::ZERO(); assert(zero2.x() == 0 && zero2.y() == 0); Point<3> zero3 = Point<3>::ZERO(); assert(zero3.x() == 0 && zero3.y() == 0 && zero3.z() == 0); assert(Point<3>(1,2,3).isEqualTo(Point<3>(1,2,3))); assert(!Point<3>(1,2,3).isEqualTo(Point<3>(3,2,1))); assert(!Point<3>(1,2,3).isEqualTo(Point<3>())); assert(!Point<3>().isEqualTo(Point<3>(3,2,1))); assert(!Point<3>().isEqualTo(Point<3>())); //invalid points are never equal return 0; } 07070100000060000081A4000000000000000000000001656C867F000016C8000000000000000000000000000000000000003100000000wfmath-1701611135.403a8bd/tests/polygon_test.cpp// polygon_test.cpp (Polygon<> test functions) // // The WorldForge Project // Copyright (C) 2002 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Ron Steinke // Created: 2002-1-20 #ifdef NDEBUG #undef NDEBUG #endif #ifndef DEBUG #define DEBUG #endif #include "wfmath/const.h" #include "wfmath/vector.h" #include "wfmath/rotmatrix.h" #include "wfmath/point.h" #include "wfmath/polygon.h" #include "wfmath/polygon_intersect.h" #include "wfmath/stream.h" #include <vector> #include "general_test.h" #include "shape_test.h" using namespace WFMath; template<int dim> void test_polygon(const Polygon<dim>& p) { std::cout << "Testing " << p << std::endl; test_general(p); test_shape(p); // FIXME more tests // Just check that these compile Point<dim> point; point.setToOrigin(); AxisBox<dim> a(point, point, true); Vector<dim> vec; vec.zero(); RotMatrix<dim> mat; mat.identity(); RotBox<dim> r(point, vec, mat); Intersect(p, a, false); Intersect(p, r, false); } /** * Test intersection between a square polygon and axis boxes at each of its four sides. */ void test_intersect() { Polygon<2> p; p.addCorner(0, Point<2>(0, 0)); p.addCorner(0, Point<2>(4, 0)); p.addCorner(0, Point<2>(4, -4)); p.addCorner(0, Point<2>(0, -4)); p.isValid(); AxisBox<2> a1(Point<2>(-1, -1), Point<2>(1, -3)); std::cout << "Testing intersection of " << p << " and " << a1 << std::endl; assert(Intersect(p, a1, false)); AxisBox<2> a2(Point<2>(1, -5), Point<2>(2, -3)); std::cout << "Testing intersection of " << p << " and " << a2 << std::endl; assert(Intersect(p, a2, false)); AxisBox<2> a3(Point<2>(5, -1), Point<2>(3, -3)); std::cout << "Testing intersection of " << p << " and " << a3 << std::endl; assert(Intersect(p, a3, false)); AxisBox<2> a4(Point<2>(1, 1), Point<2>(2, -1)); std::cout << "Testing intersection of " << p << " and " << a4 << std::endl; assert(Intersect(p, a4, false)); RotBox<2> r1(Point<2>(-1, -1), Vector<2>(2, -2), RotMatrix<2>().identity()); std::cout << "Testing intersection of " << p << " and " << r1 << std::endl; assert(Intersect(p, r1, false)); RotBox<2> r2(Point<2>(1, -5), Vector<2>(1, 2), RotMatrix<2>().identity()); std::cout << "Testing intersection of " << p << " and " << r2 << std::endl; assert(Intersect(p, r2, false)); RotBox<2> r3(Point<2>(5, -1), Vector<2>(-2, -2), RotMatrix<2>().identity()); std::cout << "Testing intersection of " << p << " and " << r3 << std::endl; assert(Intersect(p, r3, false)); RotBox<2> r4(Point<2>(1, 1), Vector<2>(1, -2), RotMatrix<2>().identity()); std::cout << "Testing intersection of " << p << " and " << r4 << std::endl; assert(Intersect(p, r4, false)); } /** * Test contains between a square polygon and axis boxes at each of its four sides. */ void test_contains() { Polygon<2> p; p.addCorner(0, Point<2>(0, 0)); p.addCorner(0, Point<2>(4, 0)); p.addCorner(0, Point<2>(4, -4)); p.addCorner(0, Point<2>(0, -4)); p.isValid(); AxisBox<2> a1(Point<2>(0.1f, -3.9f), Point<2>(0.2f, -3.8f)); std::cout << "Testing " << p << " contains " << a1 << std::endl; assert(Contains(p, a1, false)); AxisBox<2> a2(Point<2>(3.8f, -3.9f), Point<2>(3.9f, -3.8f)); std::cout << "Testing " << p << " contains " << a2 << std::endl; assert(Contains(p, a2, false)); AxisBox<2> a3(Point<2>(0.1f, -0.2f), Point<2>(0.2f, -0.1f)); std::cout << "Testing " << p << " contains " << a3 << std::endl; assert(Contains(p, a3, false)); AxisBox<2> a4(Point<2>(3.8f, -0.2f), Point<2>(3.9f, -0.1f)); std::cout << "Testing " << p << " contains " << a4 << std::endl; assert(Contains(p, a4, false)); RotBox<2> r1(Point<2>(0.1f, -3.9f), Vector<2>(0.1f, 0.1f), RotMatrix<2>().identity()); std::cout << "Testing " << p << " contains " << r1 << std::endl; assert(Contains(p, r1, false)); RotBox<2> r2(Point<2>(3.8f, -3.9f), Vector<2>(0.1f, 0.1f), RotMatrix<2>().identity()); std::cout << "Testing " << p << " contains " << r2 << std::endl; assert(Contains(p, r2, false)); RotBox<2> r3(Point<2>(0.1f, -0.2f), Vector<2>(0.1f, 0.1f), RotMatrix<2>().identity()); std::cout << "Testing " << p << " contains " << r3 << std::endl; assert(Contains(p, r3, false)); RotBox<2> r4(Point<2>(3.8f, -0.2f), Vector<2>(0.1f, 0.1f), RotMatrix<2>().identity()); std::cout << "Testing " << p << " contains " << r4 << std::endl; assert(Contains(p, r4, false)); } int main() { bool succ; Polygon<2> p2; succ = p2.addCorner(0, Point<2>(1, -1)); assert(succ); succ = p2.addCorner(0, Point<2>(2, -1)); assert(succ); succ = p2.addCorner(0, Point<2>(1, -3)); assert(succ); test_polygon(p2); Polygon<3> p3; succ = p3.addCorner(0, Point<3>(1, -1, 5)); assert(succ); succ = p3.addCorner(0, Point<3>(2, -1, std::sqrt(3.0f/2))); assert(succ); succ = p3.addCorner(0, Point<3>(1, -3, 2.0f/3)); assert(succ); test_polygon(p3); test_intersect(); test_contains(); return 0; } 07070100000061000081A4000000000000000000000001656C867F000010FB000000000000000000000000000000000000003500000000wfmath-1701611135.403a8bd/tests/probability_test.cpp// probability_test.cpp (probability and statistics test functions) // // The WorldForge Project // Copyright (C) 2001 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Ron Steinke // Created: 2002-1-24 #ifdef NDEBUG #undef NDEBUG #endif #ifndef DEBUG #define DEBUG #endif #include "wfmath/const.h" #include "wfmath/probability.h" #include "wfmath/shuffle.h" #include <iostream> #include <vector> #include <cassert> using namespace WFMath; const double fudge = 3000; const double use_epsilon = fudge * std::numeric_limits<double>::epsilon(); void test_probability(double mean, double std_dev, double step) { assert(step > 0); assert(mean > 0); double one_minus_gauss_sum = 0.5, poisson_sum = 0; bool gauss_done = false, poisson_done = false, past_poisson_peak = false; // double my_fudge = 1; for(unsigned int num_step = 0; !gauss_done || !poisson_done; ++num_step) { // std::cout << "Step " << num_step << std::endl; if(!gauss_done) { double val = Gaussian(mean, std_dev, mean + step * num_step); // std::cout << "val = " << val << std::endl; double cond = GaussianConditional(mean, std_dev, mean + step * num_step); // std::cout << "cond = " << cond << std::endl; double cond_conj = GaussianConditional(mean, std_dev, mean - step * num_step); // std::cout << "cond_conj = " << cond_conj << std::endl; if(val > fudge * std::numeric_limits<double>::min()) { if(cond_conj != 0) { // double first_frac = val / cond, second_frac = val / cond_conj; // double sum = first_frac + second_frac; // std::cout << first_frac << ',' << second_frac << ',' << sum - 1 << std::endl; // assert(Equal(sum, 1, use_epsilon)); // while(!Equal(sum, 1, my_fudge * std::numeric_limits<double>::epsilon())) // my_fudge *= 1.1; } if(num_step != 0) { // std::cout << "one_minus_gauss_sum = " << one_minus_gauss_sum << std::endl; assert(Equal(val, one_minus_gauss_sum * cond, fudge * step / mean)); one_minus_gauss_sum = val / cond - val * step; assert(one_minus_gauss_sum > -use_epsilon); // Avoid cumulative roundoff errors } } else gauss_done = true; } if(!poisson_done) { double val = Poisson(mean / step, num_step); // std::cout << "val = " << val << std::endl; double cond = PoissonConditional(mean / step, num_step); // std::cout << "cond = " << cond << std::endl; // std::cout << "poisson_sum = " << poisson_sum << std::endl; assert(val <= 1 + use_epsilon); assert(cond <= 1 + use_epsilon); assert(Equal(val + poisson_sum * cond, cond, use_epsilon)); poisson_sum += val; assert(poisson_sum <= 1 + use_epsilon); if(val > fudge * std::numeric_limits<double>::min() && past_poisson_peak) poisson_done = true; else if(val > std::numeric_limits<double>::epsilon()) past_poisson_peak = true; } } // std::cout << "my_fudge = " << my_fudge << std::endl; } // just a simple test, to make sure it's not really broken void test_shuffle() { const int nums[] = {0, 4, 1, -5, 7, 3}; unsigned num_nums = sizeof(nums)/sizeof(nums[0]); std::vector<int> foo(nums, nums + num_nums); Shuffle(foo); // for(unsigned i = 0; i < foo.size(); ++i) // std::cerr << foo[i] << ' '; // std::cerr << std::endl; } int main() { test_probability(2.0, 0.5, 0.001); test_probability(0.3, 2.0, 0.001); return 0; } 07070100000062000081A4000000000000000000000001656C867F00000E5D000000000000000000000000000000000000003400000000wfmath-1701611135.403a8bd/tests/quaternion_test.cpp// quaternion_test.cpp (Quaternion test functions) // // The WorldForge Project // Copyright (C) 2001 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Ron Steinke // Created: 2002-1-20 #ifdef NDEBUG #undef NDEBUG #endif #ifndef DEBUG #define DEBUG #endif #include "wfmath/const.h" #include "wfmath/vector.h" #include "wfmath/rotmatrix_funcs.h" #include "wfmath/quaternion.h" #include "wfmath/stream.h" #include <vector> #include "general_test.h" #include <cmath> using namespace WFMath; void test_quaternion(const Quaternion& q) { std::cout << "Testing " << q << std::endl; test_general(q); Quaternion q2; q2.identity(); std::cout << "q = " << q << std::endl; std::cout << "q2 = " << q2 << std::endl; std::cout << "q * q2= " << q * q2 << std::endl; std::cout << "q2 * q = " << q2 * q << std::endl; assert(q == q * q2); assert(q == q2 * q); assert(q == q / q2); q2 /= q; std::cout << "q = " << q << std::endl; std::cout << "q2 = " << q2 << std::endl; assert(q * q2 == Quaternion().identity()); q2 *= q; std::cout << "q2 = " << q2 << std::endl; assert(q2 == Quaternion().identity()); Quaternion qi((Quaternion::Identity())); std::cout << "qi = " << qi << std::endl; assert(qi == Quaternion().identity()); Quaternion q3(0, 5.0f/12); RotMatrix<3> m(q); // Check orthogonality of created matrix for(int i = 0; i < 3; ++i) { for(int j = i; j < 3; ++j) { CoordType dot_sum = 0; for(int k = 0; k < 3; ++k) dot_sum += m.elem(i, k) * m.elem(j, k); // std::cout << '(' << i << ',' << j << ") dot_sum == " << dot_sum << std::endl; assert(Equal(dot_sum, (i == j) ? 1 : 0)); } } Quaternion q4; assert(q4.fromRotMatrix(m)); // std::cout << m << std::endl << q4 << std::endl; assert(q4 == q); //FIXME 2->1 Quaternion->RotMatrix<3> mapping Vector<3> v(1, 2, 3), v2(v); v.rotate(q); v.rotate(q2 / q); assert(v2 == v); // std::cout << v << std::endl << v2 << std::endl; v.rotate(q); v2 = ProdInv(v2, m); // std::cout << v << std::endl << v2 << std::endl; assert(v == v2); CoordType s(q.scalar()); assert(Equal(s * s + q.vector().sqrMag(), 1)); Quaternion q_other(1, 2, 3, 4); v.rotate(q).rotate(q_other); v2.rotate(q * q_other); assert(v == v2); //Check that an invalid quaternion isn't equal to a valid quaternion Quaternion invalid_1; Quaternion invalid_2; assert(invalid_1 != Quaternion::Identity()); //Two invalid points are never equal assert(invalid_1 != invalid_2); const Quaternion& identity = Quaternion::IDENTITY(); assert(identity.isValid()); assert(identity.scalar() == 1.0f); assert(identity.vector() == WFMath::Vector<3>::ZERO()); } int main() { Quaternion q(Vector<3>(1, 3, -std::sqrt(0.7f)), .3f); test_quaternion(q); return 0; } 07070100000063000081A4000000000000000000000001656C867F00000966000000000000000000000000000000000000003100000000wfmath-1701611135.403a8bd/tests/randgen_test.cpp// randgen.cpp (time and random number implementation) // // The WorldForge Project // Copyright (C) 2002 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Alistair Riddoch // Created: 2011-2-14 #include <assert.h> #include "wfmath/randgen.h" #include <cstdio> #include <iostream> #ifdef HAVE_CONFIG_H #include "config.h" #endif using WFMath::MTRand; bool test_known_sequence() { static WFMath::MTRand::uint32 expected_results[] = { 2221777491u, 2873750246u, 4067173416u, 794519497u, 3287624630u, 3357287912u, 1212880927u, 2464917741u, 949382604u, 1898004827u }; WFMath::MTRand rng; bool result = true; rng.seed(23); for (int i = 0; i < 10; ++i) { WFMath::MTRand::uint32 rnd = rng.randInt(); if (rnd != expected_results[i]) { std::cerr << "Mismatch between MTRand and known result sequuence\n" << rnd << " != " << expected_results[i] << std::endl; result = false; } assert(rnd == expected_results[i]); } return result; } bool test_generator_instances() { MTRand one(23); printf("%.16f %.16f\n", one.rand(), one.rand()); float oneres = static_cast<float>(one.rand()); MTRand two(23); printf("%.16f %.16f\n", two.rand<float>(), two.rand<float>()); float twores = two.rand<float>(); printf("%.16f %.16f\n", oneres, twores); return oneres == twores; } int main() { return !(test_known_sequence() && test_generator_instances()); } 07070100000064000081A4000000000000000000000001656C867F00000CAD000000000000000000000000000000000000003300000000wfmath-1701611135.403a8bd/tests/rotmatrix_test.cpp// rotmatrix_test.cpp (RotMatrix<> test functions) // // The WorldForge Project // Copyright (C) 2001 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Ron Steinke // Created: 2001-12-7 #ifdef NDEBUG #undef NDEBUG #endif #ifndef DEBUG #define DEBUG #endif #include "wfmath/const.h" #include "wfmath/vector.h" #include "wfmath/rotmatrix.h" #include "wfmath/stream.h" #include "general_test.h" #include <cmath> using namespace WFMath; template<int dim> void test_rotmatrix(const RotMatrix<dim>& m) { std::cout << "Testing RotMatrix: " << m << std::endl; test_general(m); RotMatrix<dim> minv = m.inverse(); // cout << "Inverse is: " << minv << std::endl; RotMatrix<dim> ident; ident.identity(); RotMatrix<dim> try_ident; try_ident = ProdInv(m, m); // cout << "This should be the identity: " << try_ident << std::endl; for(int i = 0; i < dim; ++i) for(int j = 0; j < dim; ++j) assert(Equal(ident.elem(i, j), try_ident.elem(i, j))); try_ident = Prod(m, minv); // cout << "This should be the identity: " << try_ident << std::endl; for(int i = 0; i < dim; ++i) for(int j = 0; j < dim; ++j) assert(Equal(ident.elem(i, j), try_ident.elem(i, j))); std::string s_mat = ToString(m); RotMatrix<dim> str_m; FromString(str_m, s_mat); // cout << "After conversion through a string, the matrix is " << str_m << std::endl; // cout << "Element differences after conversion are: "; for(int i = 0; i < dim; ++i) { for(int j = 0; j < dim; ++j) { CoordType diff = m.elem(i, j) - str_m.elem(i, j); // cout << diff; assert(std::fabs(diff) < FloatMax(numeric_constants<CoordType>::epsilon(), 1e-6f)); // if(i < dim - 1 || j < dim - 1) // cout << ", "; } } // cout << std::endl; RotMatrix<dim> conv_ident = Prod(str_m, str_m.inverse()); // cout << "Converted M * M^T identity check: " << conv_ident; // cout << std::endl; for(int i = 0; i < dim; ++i) for(int j = 0; j < dim; ++j) assert(Equal(conv_ident.elem(i, j), (i == j) ? 1 : 0)); // FIXME much more } int main() { RotMatrix<2> m2; RotMatrix<3> m3; m2.rotation(numeric_constants<CoordType>::pi() / 6); m3.rotation(Vector<3>(1, 0, numeric_constants<CoordType>::sqrt2()), numeric_constants<CoordType>::pi() / 5); test_rotmatrix(m2); test_rotmatrix(m3); // FIXME toEuler(), fromEuler() return 0; } 07070100000065000081A4000000000000000000000001656C867F00001412000000000000000000000000000000000000002F00000000wfmath-1701611135.403a8bd/tests/shape_test.cpp// shape_test.cpp (basic shape test functions) // // The WorldForge Project // Copyright (C) 2001 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Ron Steinke // Created: 2001-12-12 #ifdef NDEBUG #undef NDEBUG #endif #ifndef DEBUG #define DEBUG #endif #include "wfmath/const.h" #include "wfmath/vector.h" #include "wfmath/rotmatrix.h" #include "wfmath/point.h" #include "wfmath/axisbox.h" #include "wfmath/ball.h" #include "wfmath/segment.h" #include "wfmath/rotbox.h" #include "wfmath/intersect.h" #include "wfmath/stream.h" #include <vector> #include "general_test.h" #include "shape_test.h" #include <cmath> using namespace WFMath; template<int dim> void test_shape(const Point<dim>& p1, const Point<dim>& p2) { CoordType sqr_dist = SquaredDistance(p1, p2); AxisBox<dim> box(p1, p2), tmp; std::cout << "Testing " << box << std::endl; test_general(box); test_shape_no_rotate(box); tmp = Union(box, box); assert(tmp == box); assert(Intersection(box, box, tmp)); assert(tmp == box); std::vector<AxisBox<dim> > boxvec; boxvec.push_back(box); assert(box == BoundingBox(boxvec)); assert(Intersect(box, p1, false)); assert(!Intersect(box, p1, true)); assert(Intersect(box, box, false)); assert(Intersect(box, box, true)); assert(Contains(box, box, false)); assert(!Contains(box, box, true)); Ball<dim> ball(p1, 1); std::cout << "Testing " << ball << std::endl; test_general(ball); test_shape(ball); assert(Intersect(ball, p1, false)); assert(Intersect(ball, p1, true)); assert(Intersect(ball, box, false)); assert(Intersect(ball, box, true)); assert(Contains(ball, box, false) == (sqr_dist <= 1)); assert(Contains(ball, box, true) == (sqr_dist < 1)); assert(!Contains(box, ball, false)); assert(!Contains(box, ball, true)); assert(Intersect(ball, ball, false)); assert(Intersect(ball, ball, true)); assert(Contains(ball, ball, false)); assert(!Contains(ball, ball, true)); Segment<dim> seg(p1, p2); std::cout << "Testing " << seg << std::endl; test_general(seg); test_shape(seg); assert(Intersect(seg, p1, false)); assert(!Intersect(seg, p1, true)); assert(Intersect(seg, box, false)); assert(Intersect(seg, box, true)); assert(!Contains(seg, box, false)); assert(!Contains(seg, box, true)); assert(Contains(box, seg, false)); assert(!Contains(box, seg, true)); assert(Intersect(seg, ball, false)); assert(Intersect(seg, ball, true)); assert(!Contains(seg, ball, false)); assert(!Contains(seg, ball, true)); assert(Contains(ball, seg, false) == (sqr_dist <= 1)); assert(Contains(ball, seg, true) == (sqr_dist < 1)); assert(Intersect(seg, seg, false)); assert(Intersect(seg, seg, true)); assert(Contains(seg, seg, false)); assert(!Contains(seg, seg, true)); RotBox<dim> rbox( p1, p2 - p1, RotMatrix<dim>().rotation(0, 1, numeric_constants<CoordType>::pi() / 6)); std::cout << "Testing " << rbox << std::endl; test_general(rbox); test_shape(rbox); assert(Intersect(rbox, p1, false)); assert(!Intersect(rbox, p1, true)); assert(Intersect(rbox, box, false)); assert(Intersect(rbox, box, true)); assert(!Contains(rbox, box, false)); assert(!Contains(rbox, box, true)); assert(!Contains(box, rbox, false)); assert(!Contains(box, rbox, true)); assert(Intersect(rbox, ball, false)); assert(Intersect(rbox, ball, true)); assert(!Contains(rbox, ball, false)); assert(!Contains(rbox, ball, true)); assert(Contains(ball, rbox, false) == (sqr_dist <= 1)); assert(Contains(ball, rbox, true) == (sqr_dist < 1)); assert(Intersect(rbox, seg, false)); // The next function may either succeed or fail, depending on the points passed. Intersect(rbox, seg, true); assert(!Contains(rbox, seg, false)); assert(!Contains(rbox, seg, true)); assert(!Contains(seg, rbox, false)); assert(!Contains(seg, rbox, true)); assert(Intersect(rbox, rbox, false)); assert(Intersect(rbox, rbox, true)); assert(Contains(rbox, rbox, false)); assert(!Contains(rbox, rbox, true)); // FIXME more tests } int main() { test_shape(Point<2>(1, -1), Point<2>().setToOrigin()); test_shape(Point<3>(1, -1, numeric_constants<CoordType>::sqrt2()), Point<3>().setToOrigin()); return 0; } 07070100000066000081A4000000000000000000000001656C867F000009E3000000000000000000000000000000000000002D00000000wfmath-1701611135.403a8bd/tests/shape_test.h// shape_test.h (generic shape interface test functions) // // The WorldForge Project // Copyright (C) 2001 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Ron Steinke // Created: 2001-1-6 #ifndef WFMATH_SHAPE_TEST_H #define WFMATH_SHAPE_TEST_H #include "wfmath/const.h" #include "wfmath/vector.h" #include "wfmath/rotmatrix.h" #include "wfmath/point.h" #include "wfmath/axisbox.h" #include "wfmath/ball.h" #include "wfmath/intersect.h" #include "wfmath/stream.h" #include <cassert> namespace WFMath { template<int dim, template<int> class Shape> void test_shape_no_rotate(const Shape<dim>& s) { Shape<dim> s2 = s; size_t corners = s2.numCorners(); Point<dim> p = s2.getCenter(); Vector<dim> v; v.zero(); v[0] = 1; s2.shift(v); for(size_t i = 0; i < corners; ++i) { s2.moveCornerTo(p, i); p = s2.getCorner(i); } s2.moveCenterTo(p); assert(s2 == s); AxisBox<dim> box = s.boundingBox(); assert(Contains(box, s, false)); Ball<dim> ball1 = s.boundingSphere(), ball2 = s.boundingSphereSloppy(); // cout << ball1 << std::endl << ball2 << std::endl; assert(Contains(ball1, s, false)); assert(Contains(ball2, ball1, false)); } template<int dim, template<int> class Shape> void test_shape(const Shape<dim>& s) { test_shape_no_rotate(s); Shape<dim> s2 = s; RotMatrix<dim> m; Point<dim> p; size_t corners = s2.numCorners(); if(dim >= 2) m.rotation(0, 1, numeric_constants<CoordType>::pi() / 6); else m.identity(); for(size_t i = 0; i < corners; ++i) { s2.rotateCorner(m, i); p = s2.getCorner(i); } s2.rotatePoint(m, p); s2.rotateCenter(m); } } // namespace WFMath #endif // WFMATH_SHAPE_TEST_H 07070100000067000081A4000000000000000000000001656C867F000004CA000000000000000000000000000000000000003300000000wfmath-1701611135.403a8bd/tests/timestamp_test.cpp#ifdef NDEBUG #undef NDEBUG #endif #ifndef DEBUG #define DEBUG #endif #include <wfmath/timestamp.h> #include <stdlib.h> #include <iostream> using namespace WFMath; using std::cout; using std::endl; int main() { TimeStamp tsa; if (tsa.isValid()) { cout << "default constructor returned valid" << endl; return EXIT_FAILURE; } tsa += TimeDiff(50); if (tsa.isValid()) { cout << "invalid stamp += valid time diff returned valid" << endl; return EXIT_FAILURE; } tsa = TimeStamp::now(); if (!tsa.isValid()) return EXIT_FAILURE; tsa += TimeDiff(); if (tsa.isValid()) { cout << "valid time += invalid diff returned valid" << endl; return EXIT_FAILURE; } TimeDiff tda(1000); if (!tda.isValid()) { cout << "construct diff from literal msecs is broken" << endl; return EXIT_FAILURE; } tsa = TimeStamp::now(); TimeStamp tsb = tsa; if (tsa != tsb) { cout << "equality of stamps is broken" << endl; return EXIT_FAILURE; // equality is broken } tsb += tda; if (tsa >= tsb) return EXIT_FAILURE; // compare is broken return EXIT_SUCCESS; } 07070100000068000081A4000000000000000000000001656C867F00000FA3000000000000000000000000000000000000003000000000wfmath-1701611135.403a8bd/tests/vector_test.cpp// vector_test.cpp (Vector<> test functions) // // The WorldForge Project // Copyright (C) 2001 The WorldForge Project // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // For information about WorldForge and its authors, please contact // the Worldforge Web Site at http://www.worldforge.org. // Author: Ron Steinke // Created: 2001-12-7 #ifdef NDEBUG #undef NDEBUG #endif #ifndef DEBUG #define DEBUG #endif #include "wfmath/const.h" #include "wfmath/vector.h" #include "wfmath/rotmatrix.h" #include "wfmath/stream.h" #include "general_test.h" #include <cmath> using namespace WFMath; template<int dim> void test_vector(const Vector<dim>& v) { std::cout << "Testing vector: " << v << std::endl; test_general(v); CoordType sqr_mag = v.sqrMag(); assert(Equal(std::sqrt(sqr_mag), v.mag())); assert(Equal(sqr_mag, Dot(v, v))); Vector<dim> v1, v2; v1.zero(); v1[0] = 1; for(int i = 0; i < dim; ++i) v2[i] = 1; const int steps = 8; Vector<dim> vcopy = v; for(int j = 0; j < dim; ++j) { for(int i = 0; i < steps; ++i) { vcopy.rotate(v1, v2, 2 * numeric_constants<CoordType>::pi() / steps); // std::cout << vcopy << std::endl; assert(Equal(sqr_mag, vcopy.sqrMag())); } for(int i = 0; i < dim; ++i) assert(Equal(v[i], vcopy[i])); v2 -= v1 / 2; // operator-=(), operator/() int k = (j < dim - 1) ? j + 1 : 0; v1.rotate(j, k, numeric_constants<CoordType>::pi() / 2); } v2 *= 2; // operator*=() for(int i = 0; i < dim; ++i) assert(Equal(v2[i], 1.0)); // operator+(), operator-(), operator*() (pre and post), operator/() CoordType check = Dot((v1 + v2) * 5 - v2 / 4, 2 * v2); assert(Equal((10.0 + dim * 38.0 / 4.0), check)); Vector<dim> v3 = v; v3 += v; v3 *= 2; v3 -= 2 * v; v3 /= 2; assert(v == v3); for(int i = 0; i < dim; ++i) assert(v[i] == v3[i]); // const and non-const operator[]() CoordType check_mag = v.sloppyMag() / v.mag(); assert(1 - numeric_constants<CoordType>::epsilon() < check_mag); assert(check_mag < Vector<dim>::sloppyMagMax() + numeric_constants<CoordType>::epsilon()); //Check that an invalid vector isn't equal to a valid vector, even if the values are equal Vector<dim> invalid_1; Vector<dim> invalid_2; for (size_t i = 0; i < dim; ++i) { invalid_1[i] = 0.0; invalid_2[i] = 0.0; } assert(invalid_1 != Vector<dim>::ZERO()); //Two invalid points are never equal assert(invalid_1 != invalid_2); // Still need Dot(), Angle(), normalize(), mirror() } int main() { Vector<2> v2(1, -1); Vector<3> v3(1, -1, numeric_constants<CoordType>::sqrt2()); test_vector(v2); test_vector(v3); Vector<2> zero2 = Vector<2>::ZERO(); assert(zero2.x() == 0 && zero2.y() == 0); Vector<3> zero3 = Vector<3>::ZERO(); assert(zero3.x() == 0 && zero3.y() == 0 && zero3.z() == 0); assert(v2.sloppyMag() / v2.mag() < Vector<2>::sloppyMagMax()); assert(v3.sloppyMag() / v3.mag() < Vector<3>::sloppyMagMax()); v2.sloppyNorm(1); v3.sloppyNorm(1); assert((Vector<3>(1, 0, 0).rotate(Cross(Vector<3>(1, 0, 0), Vector<3>(0, 1, 0)), numeric_constants<CoordType>::pi() / 2) - Vector<3>(0, 1, 0)).sqrMag() < numeric_constants<CoordType>::epsilon() * numeric_constants<CoordType>::epsilon()); // Need 2D+3D stuff return 0; } 07070100000069000041ED000000000000000000000004656C867F00000000000000000000000000000000000000000000002000000000wfmath-1701611135.403a8bd/tools0707010000006A000081A4000000000000000000000001656C867F000002C1000000000000000000000000000000000000003000000000wfmath-1701611135.403a8bd/tools/Config.cmake.in# Find @PROJECT_NAME@ includes and library # # This module defines # @PROJECT_NAME@_INCLUDE_DIR - the @PROJECT_NAME@ include directories # @PROJECT_NAME@_LIBRARIES - link these to use the @PROJECT_NAME@ # @PROJECT_NAME@_LIBRARY_DIR - the location of the libraries # # A target "@PROJECT_NAME@::@PROJECT_NAME@" is also provided. set(@PROJECT_NAME@_VERSION @VERSION@) set(@PROJECT_NAME@_LIBRARIES @PROJECT_NAME@) @PACKAGE_INIT@ set_and_check(@PROJECT_NAME@_INCLUDE_DIR "@PACKAGE_CMAKE_INSTALL_INCLUDEDIR@") set_and_check(@PROJECT_NAME@_LIBRARY_DIR "@PACKAGE_CMAKE_INSTALL_LIBDIR@") include("${CMAKE_CURRENT_LIST_DIR}/@PROJECT_NAME@Targets.cmake") check_required_components(@PROJECT_NAME@)0707010000006B000041ED000000000000000000000003656C867F00000000000000000000000000000000000000000000002600000000wfmath-1701611135.403a8bd/tools/conan0707010000006C000081A4000000000000000000000001656C867F000006CE000000000000000000000000000000000000003300000000wfmath-1701611135.403a8bd/tools/conan/conanfile.pyimport os from conan import ConanFile from conan.tools.cmake import CMake, cmake_layout, CMakeToolchain, CMakeDeps from conan.tools.files import copy, update_conandata, collect_libs from conan.tools.scm import Git from conans.errors import ConanException class WfmathConan(ConanFile): name = "wfmath" version = "1.0.3" license = "GPL-2.0+" author = "Erik Ogenvik <erik@ogenvik.org>" homepage = "https://www.worldforge.org" url = "https://github.com/worldforge/wfmath" description = "A math library for the Worldforge system." topics = ("mmorpg", "worldforge") settings = "os", "compiler", "build_type", "arch" options = {"shared": [False, True], "fPIC": [True, False]} default_options = {"shared": False, "fPIC": True} generators = "CMakeToolchain" user = "worldforge" package_type = "library" def export(self): git = Git(self, self.recipe_folder) try: scm_url, scm_commit = git.get_url_and_commit() update_conandata(self, {"sources": {"commit": scm_commit, "url": scm_url}}) except ConanException: pass def export_sources(self): folder = os.path.join(self.recipe_folder, "../..") copy(self, "*", folder, self.export_sources_folder, excludes=["build"]) def config_options(self): if self.settings.os == "Windows": del self.options.fPIC def layout(self): self.folders.root = "../.." cmake_layout(self) def build(self): cmake = CMake(self) cmake.configure() cmake.build() def package(self): cmake = CMake(self) cmake.install() def package_info(self): self.cpp_info.libs = collect_libs(self) 0707010000006D000041ED000000000000000000000002656C867F00000000000000000000000000000000000000000000003300000000wfmath-1701611135.403a8bd/tools/conan/test_package0707010000006E000081A4000000000000000000000001656C867F000000F7000000000000000000000000000000000000004200000000wfmath-1701611135.403a8bd/tools/conan/test_package/CMakeLists.txtcmake_minimum_required(VERSION 2.8.12) project(PackageTest CXX) set(CMAKE_CXX_STANDARD 14) set(CMAKE_CXX_STANDARD_REQUIRED on) find_package(wfmath CONFIG REQUIRED) add_executable(example example.cpp) target_link_libraries(example wfmath::wfmath)0707010000006F000081A4000000000000000000000001656C867F0000027E000000000000000000000000000000000000004000000000wfmath-1701611135.403a8bd/tools/conan/test_package/conanfile.pyimport os from conan import ConanFile from conan.tools.cmake import CMake, cmake_layout from conan.tools.build import can_run class TestConan(ConanFile): settings = "os", "compiler", "build_type", "arch" generators = "CMakeDeps", "CMakeToolchain" def requirements(self): self.requires(self.tested_reference_str) def build(self): cmake = CMake(self) cmake.configure() cmake.build() def layout(self): cmake_layout(self) def test(self): if can_run(self): cmd = os.path.join(self.cpp.build.bindir, "example") self.run(cmd, env="conanrun") 07070100000070000081A4000000000000000000000001656C867F00000071000000000000000000000000000000000000003F00000000wfmath-1701611135.403a8bd/tools/conan/test_package/example.cpp#include <iostream> #include <wfmath/point.h> int main() { WFMath::Point<3> p = WFMath::Point<3>::ZERO(); } 07070100000071000041ED000000000000000000000002656C867F00000000000000000000000000000000000000000000002800000000wfmath-1701611135.403a8bd/tools/support07070100000072000081A4000000000000000000000001656C867F0000B7B0000000000000000000000000000000000000003600000000wfmath-1701611135.403a8bd/tools/support/ChangeLog-CVS2012-01-18 Al Riddoch <alriddoch@googlemail.com> * Release 0.3.12, interface version 6 2012-01-18 Al Riddoch <alriddoch@googlemail.com> * Fix a number of portability bugs. Make a bunch of performance improvements, mostly be avoiding converting between double and float. Switch to using standard C++ library for math functions, as the way templates work makes getting the right float type way more efficient. Fix some bad namespacing which broke on some compilers. 2011-02-12 Al Riddoch <alriddoch@googlemail.com> * Release 0.3.11, interface version 5 2011-02-12 Al Riddoch <alriddoch@googlemail.com> * Inline all Atlas related methods in atlasconv.h to avoid linking issues. Explicitly instantiate all templates and avoid including headers full of big functions in client apps. Make all public templates default to 3 dimensions. Clean out assertions which might cause runtime crashes, or lead to instability in non-debug builds. Fix a number of bugs with intersection and barycenter functions. 2009-12-29 Al Riddoch <alriddoch@googlemail.com> * Release 0.3.10 2009-12-29 Al Riddoch <alriddoch@googlemail.com> * wfmath/int_to_string.cpp: Reduce the scope of some const variables. * wfmath/vector.cpp: Add some template specialisations. 2009-08-04 Al Riddoch <alriddoch@googlemail.com> * wfmath/axisbox.h: Add writable accessors to the axisbox corner points. 2009-06-18 Al Riddoch <alriddoch@googlemail.com> * wfmath/point.h, wfmath/point_funcs.h, wfmath/vector.h, wfmath/vector_funcs.h: Fix copy constructors to take a reference, and don't inline the heavy loop. 2009-01-26 Al Riddoch <alriddoch@googlemail.com> * Release 0.3.9 * NEWS: Update date on release news item. 2009-01-12 Al Riddoch <alriddoch@googlemail.com> * wfmath/axisbox.cpp, wfmath/axisbox.h: Fix a missing include. 2009-01-12 Al Riddoch <alriddoch@googlemail.com> * wfmath/atlasconv.h: Move the inlined constructor from Atlas data here to keep it out of the library compiled code. * wfmath/axisbox.cpp, wfmath/axisbox.h: Don't include all the code as inlined by default, and instead force instantiation of the templates in the library. * wfmath/const.h: Fill out the set for forward declarations. * wfmath/intersect_decls.h, wfmath/axisbox.h: Remove the now redundant forward declarations. * wfmath/point.cpp: Include axisbox_funcs.h as it contains Point functions which require AxisBox. 2009-01-11 Al Riddoch <alriddoch@googlemail.com> * wfmath/zero.h: Add a new line to the end of zero.h. * configure.ac: Check for fabsf. * wfmath/atlasconv.h: Move inlined constructors into this file to ensure code that requires Atlas-C++ isn't linked by the main library. * wfmath/const.cpp: Add a special float implementation of Equal to use more efficient underlying mechanism. * wfmath/const.h: Add forward declarations for major classes. * wfmath/point.cpp, wfmath/vector.cpp: Add specialisations of some previously inlined code to reduce dependency mess. Force instantation of templates so code is included in the library for things that should not be inlined. * wfmath/point.h, wfmath/vector.h: Remove forward declarations and unnecessary includes. Strip out asserts as including cassert interferes with application code. Remove some messy inlined code and clean up the declaraions of 3D only methods. Don't force inclusaion of the _funcs.h headers which contains most of the implementation. * wfmath/point_funcs.h, wfmath/vector_funcs.h: Clean up formatting and scoping. Remove inline from a number of methods. * wfmath/quaternion.cpp: Use CoordType, not float. * wfmath/rotbox.h: Include quaternion.h as required. * wfmath/rotmatrix.h: Remove asserts as they interfere with application code. * wfmath/rotmatrix_funcs.h: Add cassert include back here as required. 2009-01-05 Erik Hjortsberg <erik@worldforge.org> * wfmath/atlasconv.h: Provide proper templated parsing methods for all current terrain mods and shapes. * wfmath/zero.h: Add a helper class for holding zero values of points and vectors. * wfmath/ball.h, wfmath/polygon.h, wfmath/rotbox.h: Add toAtlas and fromAtlas methods, implemented in atlasconv.h. Also add contstructor which takes Atlas data. * wfmath/atlas_0_6_test.cpp: Added tests for parsing shapes from Atlas. 2008-11-15 Al Riddoch <alriddoch@googlemail.com> * Release 0.3.8 * NEWS: Update date on release news item. * configure.ac: Increment version number. 2008-11-10 Al Riddoch <alriddoch@googlemail.com> * wfmath/intstring_test.cpp, wfmath/probability_test.cpp: Force debug mode before including <cassert>. 2008-11-10 Al Riddoch <alriddoch@googlemail.com> * wfmath/quaternion_test.cpp, wfmath/rotmatrix_test.cpp, wfmath/shape_test.cpp, wfmath/vector_test.cpp: Force debug mode before include <cassert>. 2008-11-09 Al Riddoch <alriddoch@googlemail.com> * wfmath/polygon_intersect.h: Convery the warning about unfinished functionality to a big FIXME section. 2008-11-09 Al Riddoch <alriddoch@googlemail.com> * wfmath/intersect.h: Add another set of parentheses to make things clearer. 2008-11-07 Al Riddoch <alriddoch@googlemail.com> * wfmath/intersect.h: Move parentheses to a more appropriate place. 2008-11-04 Anders Petersson <demitar@worldforge.org> * configure.ac: Added AC_PROG_CXX to prevent a circular dependency in AC_CHECK_HEADERS(sstream strstream, ...) 2007-11-25 Al Riddoch <alriddoch@googlemail.com> * wfmath.spec.in: Create new sub package for generated documentation. 2007-11-25 Al Riddoch <alriddoch@googlemail.com> * configure.ac: Add support for cross compiling, and fix up the comments. 2007-11-25 Al Riddoch <alriddoch@googlemail.com> * Release 0.3.7 2007-11-25 Al Riddoch <alriddoch@googlemail.com> * NEWS: Update date on release news item. * acinclude.m4: Include the latest version of the pkgconfig macro. * configure.ac: Increment version number, and use latest pkgconfig check syntax. * AUTHORS, wfmath.spec.in: Update contact email addresses, * atlas/Makefile.am: Remove Atlas-C++ 0.4 test programs. 2007-11-24 Al Riddoch <alriddoch@zepler.org> * wfmath.spec.in: Split static libraries out into their own package. 2007-11-20 Al Riddoch <alriddoch@zepler.org> * wfmath/atlasconv.h: Initialise age when setting up Quaternion from Atlas data. 2007-07-20 Al Riddoch <alriddoch@zepler.org> * NEWS: Update date on release news item. * Release 0.3.6 2007-07-18 Al Riddoch <alriddoch@zepler.org> * configure.ac: Increment version number to 0.3.6 2007-07-18 Al Riddoch <alriddoch@zepler.org> * wfmath/axisbox.h, wfmath/axisbox_funcs.h, wfmath/ball.h, wfmath/ball_funcs.h, wfmath/point.h, wfmath/point_funcs.h: Tighten up template specicialisations to deal with stricter rules in gcc 4.2. 2007-02-13 Al Riddoch <alriddoch@zepler.org> * wfmath/polygon_intersect.cpp, wfmath/polygon_intersect.h, wfmath/rotmatrix_funcs.h: When an assert is used to detect a bad condition in a function, ensure that in a production build where asserts are disabled, the function still returns a sane value, to avoid compiler warnings. 2006-08-18 Al Riddoch <alriddoch@zepler.org> * NEWS: Update date on release news item. * Release 0.3.5 2006-08-18 Al Riddoch <alriddoch@zepler.org> * autogen.sh: Get rid of non-functional --enable-compile-warnings flag, and enable debug by default when invoking configure from autogen. 2006-08-17 Al Riddoch <alriddoch@zepler.org> * wfmath/Makefile.am: Remove useless AM_CXXFLAGS. * configure.ac: Straighten out interface version numbers, remove unused substitutions, and add debug compiler flag support. Increment version for release. * NEWS: Add provisional news item for release. 2006-08-17 Al Riddoch <alriddoch@zepler.org> * wfmath/point.h, wfmath/point_funcs.h, wfmath/quaternion.cpp, wfmath/quaternion.h, wfmath/vector.h, wfmath/vector_funcs.h: Re-order and reimplement some of the operators, so they are more efficient and in some cases cleaner. * wfmath/quaternion_test.cpp: Output values for the results of test calculations to make them easier to debug when they fail. 2006-08-16 Al Riddoch <alriddoch@zepler.org> * wfmath/intstring_test.cpp: Switch to using atol instead of atoi to ensure longs work on platforms where long is bigger than int. 2006-08-04 Al Riddoch <alriddoch@zepler.org> * wfmath/quaternion.cpp: If a quaternion is initialised with values which would make it normalise with division by zero, or be initialised with NaN, mark as invalid and return. * autogen.sh: Remove references to long removed mainainer mode. 2005-12-02 James Turner <james@worldforge.org> * Add X-Code 2.0 project file (ProjectBuilder project will be deleted shortly). 2005-09-22 Al Riddoch <alriddoch@zepler.org> * wfmath/atlasconv.h: If a quaternion is initialised with values which would make it normalise with division by zero, mark as invalid and return. 2005-06-11 Al Riddoch <alriddoch@zepler.org> * wfmath.spec.in: Minor changes to spec. * NEWS: Update NEWS. * Release 0.3.4 2005-04-30 Al Riddoch <alriddoch@zepler.org> * wfmath/Makefile.am: Don't force compilation with -O2. There are good reasons not to. * configure.ac: Update autoconf usage. * acinclude.m4: Remove unused AM_PATH_ATLAS, and add required pkg-config macro. 2005-04-12 Al Riddoch <alriddoch@zepler.org> * configure.ac: Fix a bug in initialising the version to a non-literal. * doc/Doxyfile.in: Use VERSION instead of WFMATH_VERSION as intended by autoconf. 2005-04-11 Al Riddoch <alriddoch@zepler.org> * configure.ac: Increment version to 0.3.4 for release, and clean up a bit. 2004-12-31 Al Riddoch <alriddoch@zepler.org> * wfmath.spec.in: Update spec with License URL Package Vendor and Distribution tags. Sunday, October 10th, 2004 Ron Steinke <rsteinke@w-link.net> * Changed CXXFLAGS to AM_CXXFLAGS in the atlas Makefile.am to fix a configure warning. * Change a comma operator in an assert() to && to fix a compile warning. Saturday, October 9th, 2004 Ron Steinke <rsteinke@w-link.net> * Added missing 'inline' keywords in int_to_string.h. 2004-07-19 Al Riddoch <alriddoch@zepler.org> * Minor update to the rpm spec. No need to re-spin the release. Wednesday, July 19th, 2004 Ron Steinke <rsteinke@w-link.net> * 0.3.3 release. Wednesday, June 30th, 2004 Ron Steinke <rsteinke@w-link.net> * Erik Hjortsberg's gcc 3.4 compile fixes, part 2. Wednesday, June 30th, 2004 Ron Steinke <rsteinke@w-link.net> * Erik Hjortsberg's gcc 3.4 compile fixes. 2004-06-06 Al Riddoch <alriddoch@zepler.org> * Fix devel dependencies in rpm spec. 2004-06-03 James Turner <james@worldforge.org> * XCode project updates Saturday, March 6th, 2004 Al Riddoch <alriddoch@zepler.org> * wfmath/atlasconv.h: Add typedefs so the tests still work with the 0.4 series. Wednesday, March 3rd, 2004 James Turner <james@worldforge.org> * Made atlasconv.h use the new Atlas::Message public typdefs, instead of the current Element typedefs, which are becoming private. * ProjectBuilder updates for X-Code Wednesday, February 18th, 2004 Ron Steinke <rsteinke@w-link.net> * Fixed 'no newline at end of file' warning for timestamp_test.cpp. Sunday, February 15th, 2004 Ron Steinke <rsteinke@w-link.net> * Changed the Atlas forward declaration workaround to return a reference to Atlas::Message::Element instead of a copy. Thursday, February 5th, 2004 Ron Steinke <rsteinke@w-link.net> * Got the fooCorner() fix right. * 0.3.2 release! for the last time! Wednesday, February 4th, 2004 Ron Steinke <rsteinke@w-link.net> * Added wfmath.spec to EXTRA_DIST to ease rpm building. * 0.3.2 release! (no, really! this time I mean it!) Wednesday, February 4th, 2004 Ron Steinke <rsteinke@w-link.net> * Added a missing word to some descriptive text in wfmath.spec. * 0.3.2 release! Friday, January 30th, 2004 Ron Steinke <rsteinke@w-link.net> * Changed the fooCorner() functions in Ball from {assert(false);} to {assert(false); abort();}, per Al's comments, so they fail properly if used when NDEBUG is defined. Thursday, January 29th, 2004 Ron Steinke <rsteinke@w-link.net> * Updated the AUTHORS file. Thursday, January 29th, 2004 Ron Steinke <rsteinke@w-link.net> * Bumped version to 0.3.2, in preparation for a release tommorow. Thursday, January 29th, James Turner <james@worldforge.org> * Add a test for the timestamp/timediff code (not exhaustive by any means) Thursday, January 29th, 2004 Ron Steinke <rsteinke@w-link.net> * Fixed the TimeDiff constructor from milliseconds to set the is_valid flag (thanks James!). Tuesday, January 27th, 2004 Ron Steinke <rsteinke@w-link.net> * Changed the Shuffle() function to use the new random number API instead of the old one, and use std::vector<>::size_type instead of unsigned for greater portability. Added a basic test to make sure it builds and runs. Sunday, January 18th, 2004 Ron Steinke <rsteinke@w-link.net> * Made the Quaternion costructor from a Vector<3> (for a rotation around that axis) 'explicit'. Sunday, January 18th, 2004 Ron Steinke <rsteinke@w-link.net> * Added round-off age checks to the functions where Quaternion and RotMatrix<3> rotate each other. * Added rotate() convienience wrappers to RotMatrix, Quaternion and Vector for cases where rotation is just multiplication. Sunday, January 18th, 2004 Ron Steinke <rsteinke@w-link.net> * wfmath/point.h, wfmath/axisbox.h, wfmath/axisbox_funcs.h, wfmath/segment.h, wfmath/segment_funcs.h, wfmath/ball.h, wfmath/rotbox.h, wfmath/rotbox_funcs.h, wfmath/polygon.h, wfmath/polygon_funcs.h, wfmath/polygon.cpp: Added Quaternion-based rotation functions and toParentCoords(), toLocalCoords() to all shapes, in parallel to those functions previously added to Point. * wfmath/rotmatrix*, wfmath/quaternion*: Added functions to let RotMatrix<3> and Quaternion rotate each other. RotMatrix<3>::rotate(Quaternion) was needed for Quaternion-based rotation of RotBox<3>. Sunday, January 18th, 2004 Ron Steinke <rsteinke@w-link.net> * wfmath/MersenneTwister.h, wfmath/const.h, wfmath/miniball_funcs.h: Replace ANSI C headers #include <foo.h> with #include <cfoo>. * wfmath/stream.h: Removed commented-out sstream #include. * wfmath/timestamp.*: Moved winsock.h #include into the .cpp file, moved timeval class declaration for win32 inside the TimeStamp class. Sunday, January 11th, 2004 Ron Steinke <rsteinke@w-link.net> * wfmath/timestamp.h: Pull winsock #include outside of WFMath namespace. Sunday, December 21st, 2003 Ron Steinke <rsteinke@w-link.net> * wfmath/timestamp.h: Pull in winsock2.h instead of winsock.h under win32. Friday, December 19th, 2003 Al Riddoch <alriddoch@zepler.org> * Remove Serial from rpm spec as it is not required, and messes up deps. Saturday, December 6th, 2003 Ron Steinke <rsteinke@w-link.net> * wfmath/polygon_intersect.cpp: Got rid of the only new/delete calls in the whole library, as the object in question could just as well be declared on the stack. Saturday, December 6th, 2003 Ron Steinke <rsteinke@w-link.net> * wfmath/timestamp.cpp: Added James' patch to make valgrind happy. Thursday, November 27th, 2003 Ron Steinke <rsteinke@w-link.net> * Only one of the Point/Quaterion and Point/Matrix coordinate transformation functions can or needs to have a default rotation argument. Thursday, November 27th, 2003 Ron Steinke <rsteinke@w-link.net> * The inverse of a Quaternion is q.inverse(), not -q. Thursday, November 27th, 2003 Ron Steinke <rsteinke@w-link.net> * Added local/parent coordinate transformation functions and quaternion based 3D rotations to Point, still need to add these to the rest of the shape classes. Sunday, October 26th, 2003 Ron Steinke <rsteinke@w-link.net> * wfmath/quaternion.cpp, wfmath/atlasconv.h: Set validity of vector component of Quaternion in three other places we'd missed. * wfmath/rotmatrix*, wfmath/quaternion*: Added roundoff aging code. As we do many floating point calculations, RotMatrix and Quaternion will tend to drift from their respective normalizations due to roundoff error. The new code adds an m_age, which keeps track of how many computations ago they were normalized, and automatically renomalizes them after a given number of computations. Because we know that they're still close to being normalized, the renormalization code is linearized, so it's not too horrible as a speed hit. Sunday, October 26th, 2003 Al Riddoch <alriddoch@zepler.org> * wfmath/quaternion.cpp: Ensure vector component is valid when constructing a valid quaternion. Sunday, September 21st, 2003 Ron Steinke <rsteinke@w-link.net> * Some cleanups to int_to_string.cpp * Added some macros to const.h for future normalization-aging checks in RotMatrix and Quaterion. * 0.3.1 release Monday, August 25nd, 2003 Ron Steinke <rsteinke@w-link.net> * Moved hash() function out of MersenneTwister.h to randgen.cpp, to get time_t and clock_t out of the header. Friday, August 22nd, 2003 Ron Steinke <rsteinke@w-link.net> * Forgot to make deprecated IRand(), Drand() (which now wrap Mersenne Twister) inline. Now fixed. Tuesday, August 19th, 2003 Al Riddoch <alriddoch@zepler.org> * Remove obsolete file wfmath.m4. Tuesday, August 19th, 2003 Al Riddoch <alriddoch@zepler.org> * Updated spec. Sunday, August 17th, 2003 Ron Steinke <rsteinke@w-link.net> * Moved config.h include after timestamp.h include in timestamp.cpp, since it's only the unistd.h include that's causing the FreeBSD problem. Sunday, August 17th, 2003 Al Riddoch <alriddoch@zepler.org> * wfmath/timestamp.cpp: Moved include of timestamp.h to workaround problem on FreeBSD. * Makefile.am: Remove obsolete .pbxproj from DIST list. Saturday, August 16th, 2003 James Turner <james@worldforge.org> * Update ProjectBuilder files. Move along, nothing to see here, unless you're on OS-X. If you are, please let me know if these are useful. Thursday, August 14th, 2003 Ron Steinke <rsteinke@w-link.net> * Fixed typos in a #error message in atlasconv.h. * Changed atlas/Makefile.am to build the tests with 0.3. * 0.3.0 release! Friday, August 8th, 2003 Ron Steinke <rsteinke@w-link.net> * Changed to using Mersenne Twister for random number generation. Anyone who wants the old interface should #define WFMATH_USE_OLD_RAND. * Dropped old, deprecated intersect interface version. This version of the API was used briefly in stage at one point, and that was at least a year ago. Friday, August 8th, 2003 Ron Steinke <rsteinke@w-link.net> * Forgot to change to 0.3 in wfmath/Makefile.am, fixed that. * Got rid of support for old 'list of lists' encoding for AxisBox in atlasconv.h. Also got rid of a bunch of push_back() calls by predeclaring the size of Atlas::Message::Foo::ListType instances. Friday, August 8th, 2003 Ron Steinke <rsteinke@w-link.net> * Updated version number to 0.3 in preparation for doing a release next week. * Got rid of wfmath-config, we won't support it in 0.3. * Added instring_test, which tests both IntToString() and IRand(). * Got rid of operator<() in all classes except for those in timestamp.*. It was only there 'so we could use wfmath classes as keys in std::map'. However, since equality isn't transitive (a == b && b == c does not imply a == c), this has some problems. If you really want a map of spatial objects, you probably want something like stage's OctTree instead. * Fixed IRand() to deal with the fact that UINT_MAX is often larger than RAND_MAX. * Added a few inline IntToString() cases to make sure short and int get cast to the appropriate (signed or unsigned) version of long. * Added int_to_string.h to wfmath.h. Monday, August 4th, 2003 Ron Steinke <rsteinke@w-link.net> * Added IntToString() utility function, because I'm tired of writing the same code in a dozen different applications. Tuesday, July 22nd, 2003 Ron Steinke <rsteinke@w-link.net> * More poly-atlas tweaks. Forgot to inline some wrapper functions, had to add a template AtlasInType constructor to take advantange of the fact that the Atlas::Message::Foo constructor is overloaded (needed that to build Eris). Tuesday, July 22nd, 2003 Ron Steinke <rsteinke@w-link.net> * Changes to support both Atlas-C++ 0.4 and 0.6 with atlasconv.h * Changed needless 'const CoordType' for pass-by-value in some Quaternion function calls to 'CoordType' Tuesday, July 22nd, 2003 Ron Steinke <rsteinke@w-link.net> * Fixed a couple more m_valid bugs. Monday, July 21st, 2003 Al Riddoch <alriddoch@zepler.org> * wfmath/atlasconv.h: Use AsNum() rather than AsFloat() so that integers don't cause exceptions. * wfmath/quaternion.h: Fix operator=() so it copies m_valid to the assignee. Thursday, July 3rd, 2003 Al Riddoch <alriddoch@zepler.org> * Update rpm spec to be cleaner, and make the technical sections more generic. Friday, June 27th, 2003 Ron Steinke <rsteinke@w-link.net> * Did a Quaternion-specific implementation of rotation(from, to) instead of just calling the RotMatrix version and converting. Also changed RotMatrix<2>::rotation(from, to) not to throw ColinearVectors in the case where the inputs are antiparallel, since in 2d there's only one possible plane of rotation and we can give a canonical answer. Tuesday, June 24th, 2003 Ron Steinke <rsteinke@w-link.net> * Fixed a bug in RotMatrix::rotation(from, to), added a Quaternion wrapper for the same function Tuesday, June 3rd, 2003 Ron Steinke <rsteinke@w-link.net> * Instantiated Intersect(), Contains() functions and stream operators for dim=2,3 in .cpp files * Made most template functions inline, bumped the interface number in case this broke compatibility Tuesday, May 27th, 2003 Ron Steinke <rsteinke@w-link.net> * Added elements() const accessors to the underlying arrays in Vector and Point. Sunday, May 4th, 2003 Ron Steinke <rsteinke@w-link.net> * Toned down chuck's more explicit message for the failure of the configure check for Atlas. Anyone who doesn't know what Atlas is isn't going to care about the Atlas::Message::Object encoding code stubs, and it's best not to make them think they need to download another library if they don't have to. Thursday, May 1st, 2003 Ron Steinke <rsteinke@w-link.net> * Changed configure.in to configure.ac, since it now contains code which is incompatible with autoconf 2.13 Thursday, April 24th, 2003 Al Riddoch <alriddoch@zepler.org> * Add news item, and fix rpm spec. * Release 0.2.11, API 0.2, interface version 1. Wednesday, April 23rd, 2003 Al Riddoch <alriddoch@zepler.org> * Update spec file, and set the interface version ready for release. Wednesday, April 23rd, 2003 James Turner <james@worldforge.org> * Updated configure.in to use pkg-config to detect Atlas-C++, removing the need for AM_PATH_ATLAS in one more place. * Wrapped the sstream / strstream include tests in an AC_LANG(C++) section, which they need in order to detect correctly, at least on OS-X. Tuesday, April 22nd, 2003 James Turner <james@worldforge.org> * Added the ProjectBuilder files to EXTRA_DIST in anticipation of a new stable release. Tuesday, April 22nd, 2003 Ron Steinke <rsteinke@w-link.net> * Added trivial RotMatrix<>::parity() function. Thursday, April 17th, 2003 James Turner <james@worldforge.org> * Add support for the Atlas tests to the ProjectBuilder files (you'll need to update the reference to Atlas.framework to whereever you built it). Again, all the tests pass. Wednesday, April 16th, 2003 James Turner <james@worldforge.org> * Updated the ProjectBuilder files, including targets for some of the test cases, which all pass with flying colours. Friday, January 31, 2003 Al Riddoch <alriddoch@zepler.org> * Convert to using pkg-config Saturday, January 11, 2003 James Turner <james@worldforge.org> * Changed 'libtool' to 'libtoolize' in autogen.sh so an autoXXXX build works under Mac OS-X. * Added project builder files to produce a WFMath framework If you use this or have any comments, please let me know. Monday, November 4, 2002 Ron Steinke <rsteinke@w-link.net> * Added isValid() member functions to TimeStamp, TimeDiff (the flags were already there) * Improved TimeStamp, TimeDiff documentation Saturday, November 2, 2002 Ron Steinke <rsteinke@w-link.net> * Added documentation. With the exception of those associated with Polygon, all API functions should now be documented. Saturday, November 2, 2002 Al Riddoch <alriddoch@zepler.org> * Add rpm spec. Friday, November 1, 2002 Ron Steinke <rsteinke@w-link.net> * Added Doxyfile.in to CVS, did some work towards docs Wednesday, October 30, 2002 Michael Koch <konqueror@gmx.de> * Added manpage for wfmath-config. Wednesday, October 23, 2002 Ron Steinke <rsteinke@w-link.net> * Portability fix. Apparently debian on sparc uses int instead of long for the usec field of struct timeval. Monday, October 10, 2002 Ron Steinke <rsteinke@w-link.net> * Changed operator==() for quaternions to regard two quaternions as equal iff they produce the same 3x3 rotation matrix. This means q == -q is true. * Added a Shuffle() function which randomizes the order of elements contained in a std::vector. * Doc updates * Bumped version number to 0.2.10 Monday, September 2, 2002 Ron Steinke <rsteinke@w-link.net> * Bumped version number to 0.2.9 Friday, August 2, 2002 Ron Steinke <rsteinke@w-link.net> * Fixed a bug involving the machine dependence of the behavior of % for negative numbers Monday, July 22, 2002 Ron Steinke <rsteinke@w-link.net> * Wraped a declaration of a variable which is only used in an assert() in #ifndef NDEBUG Saturday, June 23, 2002 Ron Steinke <rsteinke@w-link.net> * Added timestamp class from Eris * Added random number generators (really wrappers for rand()) * Added Quaternion::inverse() Saturday, May 11, 2002 Ron Steinke <rsteinke@w-link.net> * Bumped version number to 0.2.8, due to the sign convention changes Friday, May 10, 2002 Ron Steinke <rsteinke@w-link.net> * Added an isValid() flag to all classes. Point and Vector also have a setValid() function, since you can assign values directly to the array elements. * Switched _Poly2Orient to use the Point and Vector isValid() flags, rather than having its own flags. Friday, May 10, 2002 Ron Steinke <rsteinke@w-link.net> * Switched sign convention for quaternions to match the more sensible convention used by cyphesis. This fixes a bug with wfmath and cyphesis miscommunicating about orientations over the network, but introduces a similar problem with older versions of wfmath. Everyone is urged to upgrade wfmath. Friday, April 26, 2002 Ron Steinke <rsteinke@w-link.net> * Added WFMATH_DEPRECATE_OLD_INTERSECT flag to build without the old intersect API. Fixed wfmath to build with the old API removed. Friday, April 26, 2002 Ron Steinke <rsteinke@w-link.net> * Bumped version number for 0.2.7 release Sunday, April 21, 2002 Ron Steinke <rsteinke@w-link.net> * Changed format sent by AxisBox<>::toAtlas() for better network optimization Wednesday, April 9, 2002 Ron Steinke <rsteinke@w-link.net> * The eris-support-on-msvc changes now work Wednesday, April 9, 2002 Ron Steinke <rsteinke@w-link.net> * Hopefully have enough of wfmath working on msvc now to support eris Tuesday, April 9, 2002 Ron Steinke <rsteinke@w-link.net> * (Continued work on MSVC++ workarounds).7 Tuesday, April 9, 2002 Ron Steinke <rsteinke@w-link.net> * (Continued work on MSVC++ workarounds).6 Tuesday, April 9, 2002 Ron Steinke <rsteinke@w-link.net> * (Continued work on MSVC++ workarounds).5 Tuesday, April 9, 2002 Ron Steinke <rsteinke@w-link.net> * (Continued work on MSVC++ workarounds).4 Tuesday, April 9, 2002 Ron Steinke <rsteinke@w-link.net> * (Continued work on MSVC++ workarounds).3 Tuesday, April 9, 2002 Ron Steinke <rsteinke@w-link.net> * (Continued work on MSVC++ workarounds).2 Tuesday, April 9, 2002 Ron Steinke <rsteinke@w-link.net> * Continued work on MSVC++ workarounds Tuesday, April 9, 2002 Ron Steinke <rsteinke@w-link.net> * Started adding workarounds to compile with MSVC++ * Started adding doxygen docs Friday, March 24, 2002 Ron Steinke <rsteinke@w-link.net> * Tweaked the syntax of the new Parallel() function slightly Thursday, March 23, 2002 Ron Steinke <rsteinke@w-link.net> * Finished Intersect(Polygon, Polygon). Now I've just got to test all those intersection functions * Added Parallel() and Perpendicular() functions to compare the orientation of two vectors * Incremented version number to 0.2.6 Tuesday, March 23, 2002 Ron Steinke <rsteinke@w-link.net> * Fixed bug with declaring the default value of the "proper" argument of the intersection functions twice * Moved the function definitions for intersection-oriented members of _Poly2Orient from polygon_funcs.h into polygon_intersect.h * Wrote definitions for Contains(Polygon, AxisBox), Contains(Polygon, RotBox), and Contains(Polygon, Polygon). Got most of Intersect(Polygon, Polygon) done, except for the case where the two planes containing the polygons intersect in a line (the standard case in 3d) Thursday, March 21, 2002 Ron Steinke <rsteinke@w-link.net> * Fixed Polygon<> intersection functions with AxisBox<> and RotBox<> in polygon_intersect.h * Replaced separate Intersect() and IntersectProper() functions with a "bool proper" argument to Intersect(), did the same for Contains(). For backwards compatibility, make the "proper" argument default to false, and wrote generic IntersectProper() and ContainsProper() templates to call Intersect() and Contains() with proper = true (keep them? deprecate them? which API is better?). Tuesday, March 12, 2002 Ron Steinke <rsteinke@w-link.net> * Added a default value of 1.0 for the norm in Vector::normalize() * Added a virtual destructor to the exception defined in atlasconv.h * Fixed a terminate-the-loop-proberly bug in probability.cpp (replaced DBL_MIN by DBL_EPSILON) * Got test functions to compile with gcc-3.0 Saturday, March 9, 2002 Dan Tomalesky <grim@xynesis.com> * Added acinclude.m4 for atlas so people without atlas can still autogen.sh and configure will give warning instead of getting bizarre macro missing error for atlas when atlas is not installed Thursday, March 7, 2002 Ron Steinke <rsteinke@w-link.net> * Fixed error in configure check for sstream vs. strstream Wednesday, March 6, 2002 Ron Steinke <rsteinke@w-link.net> * Merged in Grimicus' patch to add wfmath-config Wednesday, March 6, 2002 Ron Steinke <rsteinke@w-link.net> * Redid sstream vs. strstream compatibility code Wednesday, March 6, 2002 Ron Steinke <rsteinke@w-link.net> * Got rid of stupid "set fail bit" on parse errors for operator>>(), it now throws instead * Added configure check for sstream vs. strstream, compatibility code Monday, March 04, 2002 Al Riddoch <alriddoch@zepler.org> * wfmath/error.h: Added destructor with throw(); to exception class. * wfmath/polygon.h: Removed trailing comma from enumeration. * wfmath/polygon.h, wfmath/stream.h: Fixed std:: namespace issues, and made typenames explicit. Wednesday, February 27, 2002 Ron Steinke <rsteinke@w-link.net> * Commented out horribly broken intersection functions with AxisBox and RotBox in polygon_intersect.h Wednesday, February 27, 2002 Ron Steinke <rsteinke@w-link.net> * Autogen.sh cleanups Tuesday, February 26, 2002 Ron Steinke <rsteinke@w-link.net> * Bump version number to 0.2.5, so we can have an official version needed by the stage patches. Monday, February 25, 2002 Ron Steinke <rsteinke@w-link.net> * Added rotation() functions to RotMatrix<3> and Quaternion which take a single Vector<3> as argument (as opposed to a vector for the rotation axis and an angle), and determine the rotation angle from the length of the vector. This is nice for things like the rotation generated by (angular velocity) * dT, since it handles the zero-length axis case cleanly, and avoids an extra call to sqrt(). * Fixed an error in atlasconv.h, where specializations of AxisBox<>::fromAtlas() to particular dimensions weren't marked as inline Friday, February 22, 2002 Ron Steinke <rsteinke@w-link.net> * Broke the Polygon<> intersection functions out of polygon_funcs.h and polygon.cpp into the separate files polygon_intersect.h and polygon_intersect.cpp * Moved the implementations of the boundingBox() and boundingSphere() functions in Point out of point_funcs.h into axisbox_funcs.h and ball_funcs.h. This lets me remove the include dependence of Point on AxisBox and Ball. * Fixed up list of files included in wfmath.h. It now includes everything but atlasconv.h, which is intentionally excluded. Wednesday, February 20, 2002 Ron Steinke <rsteinke@w-link.net> * Fixed RotBox to match the new sense of RotMatrix<> rotation, still need to look at its interaction with Polygon<> to get that right * Wrote Intersect(RotBox, AxisBox) for 2d, 3d * Removed a needless <iostream> dependency from atlasconv.h * Bump version number to 0.2.4 Sunday, February 17, 2002 Ron Steinke <rsteinke@w-link.net> * Some doc fixes * Added a #warning about using the Polygon<> Intersect() and Contains() functions Thursday, February 14, 2002 Ron Steinke <rsteinke@w-link.net> * Missed a change in rotation sense in Vector<3>::rotate(const Quaterion&), fixed now Thursday, February 14, 2002 Ron Steinke <rsteinke@w-link.net> * Added comments to many assert()'s * Switched the sense of rotation in RotMatrix<> and Quaternion to be compatible with OpenGL and the rest of Worldforge. Also used this as an excuse to scrap all the Euler angle stuff, since: 1) with different axis conventions floating around, it's very confusing, and 2) I have yet to see someone try to use it in the case where it is the correct solution Tuesday, February 12, 2002 Ron Steinke <rsteinke@w-link.net> * Changed Point<>:origin() to Point<>::setToOrigin() * Added assert() checks on array indices passed to many functions Tuesday, February 12, 2002 Ron Steinke <rsteinke@w-link.net> * Added Equal() template to call foo->isEqualTo(). * Replaced "const CoordType&" with CoordType everywhere it was used. * Got rid of scaleEpsilon member function in Point<> in favor of calling _ScaleEpsilon directly, minimized use of _scaleEpsilon member function in Vector<> * Improved efficiency of some member functions in Segment<> * Got rid of <iostream> in wrapped_array.h, got rid of MINIBALL_NO_STD_NAMESPACE test on whether to include <list> or <list.h> and <cassert> or <assert.h> (since we're including them as <list> and <assert.h> elsewhere), got rid of miniball_config.h Friday, February 1, 2002 Ron Steinke <rsteinke@w-link.net> * Changed IsFloatEqual() to Equal(), removed FloatAdd() and FloatSubtract(), vastly improved precision checks for round-off error. The intersection functions still need to be audited to make sure they're handling it right. * API change, increment version to 0.2.3 Monday, January 28, 2002 Ron Steinke <rsteinke@w-link.net> * Cleanups to const.h, const.cpp suggested by Jesse Jones in the code review, and associated repurcussions to the rest of the codebase. Friday, January 25, 2002 Ron Steinke <rsteinke@w-link.net> * Some efficiency improvements and generalizations to the backend of the probability functions * Wrote Polygon<3> intersections with AxisBox<3> and RotBox<3> Thursday, January 24, 2002 Ron Steinke <rsteinke@w-link.net> * Karsten's Makefile.am fixes for srcdir != builddir * New probability distribution functions, Gaussian and Poisson distributions * Increment version to 0.2.2 Tuesday, January 22, 2002 Ron Steinke <rsteinke@w-link.net> * Changed namespace from WF::Math to WFMath * Changed fromAtlas() to throw an exception instead of returning bool, added constructors from Atlas::Message::Object to appropriate types * Incremented version number to 0.2.1, since there were API changes and other people are starting to care about dependencies on this library; there'll probably be a lot of 0.2 versions Tuesday, January 22, 2002 Ron Steinke <rsteinke@w-link.net> * Changed the atlas functions for Quaternion and AxisBox<> to conform to atlas specs, got rid of atlas functions which still used string conversion * Fixed Contains(Polygon<2>, Segment<2>) and Contains(Polygon<2>, Polygon<2>) for endpoint intersection; commented out Intersect(RotBox<>, AxisBox<>) and IntersectProper(RotBox<>, AxisBox<>) because I'm pretty sure the algorithm's wrong * Added another rotation() function to RotMatrix<>, this one constructs the rotation necessary to rotate one vector into another * Got versioning on library build working correctly * Changed version to 0.2.0, implementation of remaining Polygon<> intersection routines delayed until a later version Sunday, January 20, 2002 Ron Steinke <rsteinke@w-link.net> * Wrote all the Polygon<2> intersection functions, and about half of the general Polygon<> intersection functions; a few of the 2d functions still need more work * Changed intersect_test back to shape_test; decided one test program was sufficient for all of AxisBox<>, Ball<>, Segment<>, and RotBox<> * Wrote test code for Polygon<> to call the generic tests; added the generic tests to shape_test; wrote fairly complete test code for Quaternion * Changed from FromAtlas() and ToAtlas() functions to fromAtlas() and toAtlas() member functions; changed Vector<> and Point<> from sending string objects to atlas to sending lists, so we're more compatible with the getPos() and getVelocity() methods of Atlas::Objects::Entity::RootEntityData * Upped version number to 0.1.9. The library now implements the functionality in stage/math, plus the mathematical parts of coal and eris. Will go to 0.2 when the polygon intersect functions are done, and the unit tests are more complete Tuesday, January 15, 2002 Ron Steinke <rsteinke@w-link.net> * Cleaned up Euler angle stuff in RotMatrix<> and Quaternion, changed everything to z-y-z convention * Moved template specialization declarations from vector.h to vector_funcs.h * Made Vector<> and Point<> mathematical operators all friends instead of members, to allow friendship for mathematical operators which take mixed types Friday, January 11, 2002 Ron Steinke <rsteinke@w-link.net> * Added Quaternion class, based on code from eris * Renamed matrix.h, matrix_funcs.h, matrix.cpp, matrix_test.cpp to rotmatrix.h, rotmatrix_funcs.h, rotmatrix.cpp, rotmatrix_test.cpp; this matches the name of the class, and it's best to have the matrix.h slot available in case we need it later. Need to do this now before everyone starts using the library Wednesday, January 9, 2002 Ron Steinke <rsteinke@w-link.net> * Added BoundingBox(), BoundingSphere() functions for a container of points. The BoundingSphere() function uses the (GPL'd) miniball code of Bernd Gaertner <http://www.inf.ethz.ch/personal/gaertner> * Moved the implementations of operator<<() and operator>>() for Polygon<2> out of stream.h and into stream.cpp, fixing a linker error for any file which included stream.h (oops). Wednesday, January 9, 2002 Ron Steinke <rsteinke@w-link.net> * Started on Polygon<> class * Wrote some test functions for the generic part of the class interface (operator=(), isEqualTo(), etc.) and the generic shape interface (getCorner(), boundingBox(), etc.) * Added Midpoint() function in point.h * Cleaned up operator<() to check !IsFloatEqual() when comparing variables of type CoordType * Added autogen.sh Friday, January 4, 2002 Ron Steinke <rsteinke@w-link.net> * Got atlas_test working Thursday, January 3, 2002 Ron Steinke <rsteinke@w-link.net> * Changed Barycenter() to take a container of Point<> instead of an array, added BoundingBox() for a container of AxisBox<> * Optimized special cases in AxisBox::getCorner() and RotBox::getCorner(), got rid of AxisBox::lowCorner() and AxisBox::highCorner() * Extended RotMatrix<> to allow for mirror image flips in addition to rotations, added mirror() functions to both RotMatrix<> and Vector<> * Removed foolish const from return value of RotMatrix<>::rotation() * Wrote better member accessors for most shapes (there's no reason not to have direct access to the members in anything but AxisBox<>) * Inlined some of the simpler class member functions * Moved atlasconv.h from atlas/ into wfmath/, since we don't need Atlas to install it, just to build the test code Monday, December 31, 2001 Ron Steinke <rsteinke@w-link.net> * Added boundingSphere(), boundingSphereSloppy() to all the shapes * Wrote FloatMin(), FloatMax(), and FloatClamp(). This let me remove std::min() and std::max(), and with them the dependency on <algorithm> * Cleaned up the inclusion of outside headers * Replaced double with CoordType everywhere, with the exception of the precision/tolerance/epsilon arguments of float comparison functions and the intenals of IsFloatEqual() * Switched CoordType from double to float. This puts the library precision at about 3e-6 (on my machine), close to the precision of the strings being passed by ToAtlas() and FromAtlas() * Replaced fromStream() with operator>>(), using fail() flag to indicate a bad parse * Upped the version number from 0.0.1 to 0.1.0, as the shape API appears to be settling down, and it sure doesn't feel like 0.0 anymore Monday, December 31, 2001 Ron Steinke <rsteinke@w-link.net> * Cleaned up string and stream stuff, classes only need to include <iosfwd>, everything else is in stream.h/stream.cpp, removed stringconv.h/stringconv.cpp Sunday, December 30, 2001 Ron Steinke <rsteinke@w-link.net> * Finished the RotBox<> intersection functions * Cleaned up use of namespaces in *.cpp files * Added to the test code * Miscelaneous bug fixes Saturday, December 29, 2001 Ron Steinke <rsteinke@w-link.net> * Fixed an error in the README Saturday, December 29, 2001 Ron Steinke <rsteinke@w-link.net> * Wrote some documentation, cleaned up the little that was already there. Saturday, December 29, 2001 Ron Steinke <rsteinke@w-link.net> * Removed some unnecessary template specifications, changed Vector<len> to Vector<dim> and RotMatrix<size> to RotMatrix<dim> for cross class consistency in the name of the template parameter * Removed the base Shape<> class, leaving a bunch of simple classes for basic shapes which possess a common interface * Changed test code to use toString() method directly rather than through operator<<() * Changed ToAtlas() and FromAtlas() to use toString() and fromString(), eliminating the need for a separately compiled atlas conversion library * Added the shape interface functions to Point<> * Replaced the symlinks to COPYING and INSTALL files added by automake with the files themselves. This should hopefully let me get them into CVS. * More work on intersection functions Tuesday, December 18, 2001 Ron Steinke <rsteinke@w-link.net> * Some cleanup on RotMatrix<>::setVals() backend, Atlas conversion functions * Added Ball<>, Segment<>, RotBox<> classes (not all RotBox<> intersection functions written yet) Monday, December 17, 2001 Ron Steinke <rsteinke@w-link.net> * Wrote Shape<> base class * Wrote AxisBox<> class * Cleaned up header file naming convention, so foo_funcs.h is always the function templates for the class in foo.h Friday, December 14, 2001 Ron Steinke <rsteinke@w-link.net> * .cvsignore fixes * Rearranged the ordering of function declarations in the classes in an attempt at a cross-class standard, added some bits I'd missed * Added polar, spherical coordinate conversions to Point<> and Vector<> Thursday, December 13, 2001 Ron Steinke <rsteinke@w-link.net> * Added setVals() method to Matrix<> * Added operator>> for Vector<>, Matrix<>, Point<> to give string read capability, added stream_funcs.cpp * Added toString() and fromString() for Vector<>, Matrix<>, Point<>, changed operator<< to use toString(), removed operator>> Wednesday, December 12, 2001 Ron Steinke <rsteinke@w-link.net> * Created atlas_funcs.cpp, wrote GetAtlasDoubleList() and SetAtlasDoubleList() to handle most of the Atlas interface work * Got a test for Atlas into configure.in * First CVS upload ` * Copied the CoalCoord class in as Point<>, moved CoordType and IsFloatEqual() into const.h, const.cpp * Added FloatAdd() and FloatSubtract() to handle numbers whose sum/difference is (nearly) zero * Modified Vector<> and Matrix<> to use CoordType Tuesday, December 11, 2001 Ron Steinke <rsteinke@w-link.net> * Got test functions working with RotMatrix<> * Created atlas_funcs.h to hold Atlas interface code, wrote ToAtlas() and FromAtlas() for Vector<> and Matrix<> Monday, December 10, 2001 Ron Steinke <rsteinke@w-link.net> * After coversation with Rakshasa about how matrices are actually being used in stage, replaced Matrix<> with RotMatrix<> Friday, December 7, 2001 Ron Steinke <rsteinke@w-link.net> * Created some tests in matrix_test * Added GPL information to all the source files Thursday, December 6, 2001 Ron Steinke <rsteinke@w-link.net> * Added more tests to vector_test * Implemented sloppyMag and associated functions for Vector<2>, Vector<3> * Added a script, bc_sloppy_mag_3, to calculate some constants for the Vector<3> implementation of sloppyMag * Got rid of RowVector<> and ColumnVector<> classes, added rowSet() and columnSet() to Matrix<> Wednesday, December 5, 2001 Ron Steinke <rsteinke@w-link.net> * First ChangeLog entry * Autoconf is working, and the Vector<> and Matrix<> class compile * Got the README, AUTHORS, and TODO files written * Changed #include "foo.h" to #include <wfmath/foo.h> in the header files * Added const.h * Created vector_test.cpp, matrix_test.cpp, started work on vector_test 07070100000073000081ED000000000000000000000001656C867F000006E0000000000000000000000000000000000000003E00000000wfmath-1701611135.403a8bd/tools/support/generate-ChangeLog.sh#!/bin/bash #A script for combining the legacy ChangeLog found in ChangeLog-CVS with one output from git. The script will only run if the current ChangeLog contains exactly one line. #This makes it possible to do a new "make dist" from an existing source distribution (as the ChangeLog would then be complete.). top_srcdir=$1 distdir=$2 commitid=$3 if [[ x${distdir} = "x" ]] || [[ x${top_srcdir} = "x" ]] || [[ x${commitid} = "x" ]]; then echo "This script will generate an aggregated ChangeLog by combining the legacy ChangeLog-CVS file with the output from git log. It therefore needs to be run in a git source directory." echo "Params: <source directory path> <distribution directory path> <SHA1 of first git commit>" exit 1 fi #Only do the aggregation if the ChangeLog file is exactly one line. If not the aggregation has already been done. if [[ $(wc -l < "${distdir}/ChangeLog") = "0" ]]; then echo "Generating ChangeLog by appending the old CVS ChangeLog to the one generated from git. This requires that you create the dist in the git repository." cd "${top_srcdir}" || exit chmod u+w "${distdir}/ChangeLog" && git log "${commitid}"..HEAD --stat --name-only --date=short --abbrev-commit > "${distdir}"/ChangeLog && echo "" >> "${distdir}/ChangeLog" && cat "${top_srcdir}/tools/support/ChangeLog-CVS" >> "${distdir}/ChangeLog" #Put a notice in the legacy ChangeLog-CVS file, thus bringing the size of the dist down a bit. chmod u+w "${distdir}/tools/support/ChangeLog-CVS" && echo "This file was needed for generating the proper ChangeLog as an aggregate of the code held in git and older code in CVS. It's now empty, but needs to be included in the source distribution to not upset automake." > "${distdir}/tools/support/ChangeLog-CVS" fi 07070100000074000081ED000000000000000000000001656C867F00000914000000000000000000000000000000000000003F00000000wfmath-1701611135.403a8bd/tools/support/generate_abi_report.sh#!/bin/bash if [ $# -ne 1 ] then echo "Performs an ABI check against an older version, using the ABI_compliance_checker tool." echo "You must have the ABI_compliance_checker installed to use this script. Get it from http://ispras.linuxbase.org/index.php/ABI_compliance_checker" echo "This script must be run from the Git source directory." echo "Usage: `basename $0` <older_version>" echo "<older_version> is the name of an older tag (or commit) which this script will check out from Git" exit -1 fi command -v git >/dev/null 2>&1 || { echo "Git command not available." > $1; exit 0; } command -v abi-compliance-checker >/dev/null 2>&1 || { echo "abi-compliance-checker command not available; get it from http://ispras.linuxbase.org/index.php/ABI_compliance_checker." > $1; exit 0; } SOURCE_DIR=$PWD #Figure out the name of the lib by looking in "configure" LIBRARY_NAME=`grep PACKAGE_NAME= $SOURCE_DIR/configure | sed -e s/PACKAGE_NAME=\'//g | sed -e s/\'//g` ABI_REPORT_DIR=$PWD/abi_report #Disable warnings to counteract -Werror (older code might cause warnings with newer compilers, and fail through -Werror). export CXXFLAGS="$CXXFLAGS -w" OLD_VERSION=$1 OLD_SOURCE_DIR=$ABI_REPORT_DIR/${OLD_VERSION}_source OLD_BUILD_DIR=$ABI_REPORT_DIR/${OLD_VERSION}_build OLD_INSTALL_DIR=$ABI_REPORT_DIR/${OLD_VERSION}_install MASTER_BUILD_DIR=$ABI_REPORT_DIR/master_build MASTER_INSTALL_DIR=$ABI_REPORT_DIR/master_install mkdir -p $ABI_REPORT_DIR mkdir -p $OLD_SOURCE_DIR mkdir -p $OLD_BUILD_DIR mkdir -p $MASTER_BUILD_DIR #Check out the older version into a separate tree git archive $OLD_VERSION | tar -x -C $OLD_SOURCE_DIR if [ $? != 0 ] then echo "Could not check out '$OLD_VERSION'. Make sure that this is something that's available in Git." exit -1 fi echo "Building master version" cd $MASTER_BUILD_DIR && $SOURCE_DIR/configure --prefix $MASTER_INSTALL_DIR && make install echo "Building older version" cd $OLD_SOURCE_DIR && NOCONFIGURE=1 ./autogen.sh && cd $OLD_BUILD_DIR && $OLD_SOURCE_DIR/configure --prefix $OLD_INSTALL_DIR && make install if [ $? != 0 ] then echo "Error when building old version." exit -1 fi cd $ABI_REPORT_DIR echo "Performing ABI compliance check" abi-compliance-checker -l $LIBRARY_NAME -v1 $OLD_VERSION -v2 master -old $OLD_INSTALL_DIR -new $MASTER_INSTALL_DIR 07070100000075000081A4000000000000000000000001656C867F000000F5000000000000000000000000000000000000002D00000000wfmath-1701611135.403a8bd/tools/wfmath.pc.inprefix=@CMAKE_INSTALL_PREFIX@ exec_prefix=${prefix} libdir=${exec_prefix}/@CMAKE_INSTALL_LIBDIR@ includedir=${prefix}/include Name: @PROJECT_NAME@ Description: @DESCRIPTION@ Version: @VERSION@ Libs: -L${libdir} -lwfmath Cflags: -I${includedir} 07070100000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000B00000000TRAILER!!!1361 blocks
Locations
Projects
Search
Status Monitor
Help
OpenBuildService.org
Documentation
API Documentation
Code of Conduct
Contact
Support
@OBShq
Terms
openSUSE Build Service is sponsored by
The Open Build Service is an
openSUSE project
.
Sign Up
Log In
Places
Places
All Projects
Status Monitor