repo_id
stringlengths
19
138
file_path
stringlengths
32
200
content
stringlengths
1
12.9M
__index_level_0__
int64
0
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/tf2/CMakeLists.txt
cmake_minimum_required(VERSION 3.5) project(tf2 CXX) set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_FLAGS "-fPIC -DNDEBUG -O3 -pipe -Wall") # set (CMAKE_INSTALL_PREFIX ${CMAKE_SOURCE_DIR}/build/install CACHE STRING "" FORCE) # set (UNIT_TEST_INSTALL_PREFIX ${CMAKE_INSTALL_PREFIX}/tests CACHE STRING "" FORCE) # set(CMAKE_CXX_FLAGS "-std=c++11 -pthread -fPIE -fPIC -Wno-deprecated -pipe -W -Werror -Wall -g -O2" CACHE STRING "" FORCE) find_package(Boost REQUIRED COMPONENTS system thread) include_directories( include ${Boost_INCLUDE_DIR} # for signals2 is header only ) option(BUILD_TESTS "Build the tests" ON) # export user definitions #CPP Libraries add_library(tf2 SHARED src/cache.cpp src/buffer_core.cpp src/static_cache.cpp src/time.cpp ) target_link_libraries(tf2 ${Boost_LIBRARIES} ) # ${catkin_LIBRARIES} ${console_bridge_LIBRARIES}) install(TARGETS ${PROJECT_NAME} DESTINATION ${CMAKE_INSTALL_PREFIX}/lib ) install(DIRECTORY include DESTINATION ${CMAKE_INSTALL_PREFIX} ) install(FILES README.md DESTINATION ${CMAKE_INSTALL_PREFIX} ) if (BUILD_TESTS) include(cmake/GTest.cmake) fetch_googletest( ${PROJECT_SOURCE_DIR}/cmake ${PROJECT_BINARY_DIR}/googletest ) enable_testing() add_subdirectory(test) endif()
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/tf2/package.xml
<package> <name>tf2</name> <version>0.5.16</version> <description> tf2 is the second generation of the transform library, which lets the user keep track of multiple coordinate frames over time. tf2 maintains the relationship between coordinate frames in a tree structure buffered in time, and lets the user transform points, vectors, etc between any two coordinate frames at any desired point in time. </description> <author>Tully Foote</author> <author>Eitan Marder-Eppstein</author> <author>Wim Meeussen</author> <maintainer email="tfoote@osrfoundation.org">Tully Foote</maintainer> <license>BSD</license> <url type="website">http://www.ros.org/wiki/tf2</url> <buildtool_depend version_gte="0.5.68">catkin</buildtool_depend> <build_depend>libconsole-bridge-dev</build_depend> <build_depend>geometry_msgs</build_depend> <build_depend>rostime</build_depend> <build_depend>tf2_msgs</build_depend> <run_depend>libconsole-bridge-dev</run_depend> <run_depend>geometry_msgs</run_depend> <run_depend>rostime</run_depend> <run_depend>tf2_msgs</run_depend> </package>
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/tf2/3rd-tf2.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") cc_library( name = "tf2", hdrs = glob([ "include/geometry_msgs/**", "include/tf2_msgs/**", "include/tf2/**", ]), srcs = glob(["lib/*.so"]), strip_include_prefix = "include", visibility = ["//visibility:public"], )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/tf2/mainpage.dox
/** \mainpage \htmlinclude manifest.html \b tf2 is the second generation of the tf library. This library implements the interface defined by tf2::BufferCore. There is also a Python wrapper with the same API that class this library using CPython bindings. \section codeapi Code API The main interface is through the tf2::BufferCore interface. It uses the exceptions in exceptions.h and the Stamped datatype in transform_datatypes.h. \section conversions Conversion Interface tf2 offers a templated conversion interface for external libraries to specify conversions between tf2-specific data types and user-defined data types. Various templated functions in tf2_ros use the conversion interface to apply transformations from the tf server to these custom datatypes. The conversion interface is defined in tf2/convert.h. Some packages that implement this interface: - tf2_bullet - tf2_eigen - tf2_geometry_msgs - tf2_kdl - tf2_sensor_msgs More documentation for the conversion interface is available on the <A HREF="http://wiki.ros.org/tf2/Tutorials/Migration/DataConversions">ROS Wiki</A>. **/
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/tf2/cyberfile.xml
<package format="2"> <name>3rd-tf2</name> <version>local</version> <description> Apollo packaged tf2 Lib. </description> <maintainer email="apollo-support@baidu.com">Apollo</maintainer> <license>Apache License 2.0</license> <url type="website">https://www.apollo.auto/</url> <url type="repository">https://github.com/ApolloAuto/apollo</url> <url type="bugtracker">https://github.com/ApolloAuto/apollo/issues</url> <depend repo_name="boost">3rd-boost-dev</depend> <type>module</type> <src_path url="https://github.com/ApolloAuto/apollo">//third_party/tf2</src_path> </package>
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/tf2/README.md
# tf2-apollo ## Intro tf2-apollo was Apollo's clone of ROS tf2 for coordinate transforms. It seems that it was based on `ros/geometry2` tagged `0.5.16` ## How to build ``` mkdir build && cd build cmake .. -DBUILD_TESTS=OFF -DCMAKE_INSTALL_PREFIX=/usr/local/tf2 make -j$(nproc) sudo make install ``` ## gtest support for tf2-apollo In order not to build gtest into our docker image, gtest support for tf2 was implemented according to https://crascit.com/2015/07/25/cmake-gtest ## Reference - https://github.com/ros/geometry2 - http://wiki.ros.org/geometry2
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/tf2/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_binary") load("//tools/install:install.bzl", "install", "install_files", "install_src_files") package( default_visibility = ["//visibility:public"], ) cc_binary( name = "libtf2.so", srcs = [ "src/buffer_core.cpp", "src/cache.cpp", "src/static_cache.cpp", "src/time.cpp", ], deps = [ "@boost", ":tf2_headers", ], linkshared = True, ) cc_library( name = "tf2_headers", hdrs = glob([ "include/geometry_msgs/**", "include/tf2_msgs/**", "include/tf2/**", ]), strip_include_prefix = "include", ) cc_library( name = "tf2", srcs = [ ":libtf2.so", ], visibility = ["//visibility:public"], deps = [ "@boost", ":tf2_headers", ], ) install( name = "install", data_dest = "3rd-tf2", library_dest = "3rd-tf2/lib", targets = [ ":libtf2.so" ], data = [ ":cyberfile.xml", ":3rd-tf2.BUILD", ], ) install_src_files( name = "install_src", deps = [ ":install_tf2_src", ":install_tf2_hdrs", ], ) install_src_files( name = "install_tf2_src", src_dir = ["."], dest = "3rd-tf2/src", filter = "*", ) install_src_files( name = "install_tf2_hdrs", src_dir = ["include"], dest = "3rd-tf2/include", filter = "*", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/tf2/CHANGELOG.rst
^^^^^^^^^^^^^^^^^^^^^^^^^ Changelog for package tf2 ^^^^^^^^^^^^^^^^^^^^^^^^^ 0.5.16 (2017-07-14) ------------------- * remove explicit templating to standardize on overloading. But provide backwards compatibility with deprecation. * Merge pull request `#144 <https://github.com/ros/geometry2/issues/144>`_ from clearpathrobotics/dead_lock_fix Solve a bug that causes a deadlock in MessageFilter * Resolve 2 places where the error_msg would not be propogated. Fixes `#198 <https://github.com/ros/geometry2/issues/198>`_ * Remove generate_rand_vectors() from a number of tests. (`#227 <https://github.com/ros/geometry2/issues/227>`_) * fixing include directory order to support overlays (`#231 <https://github.com/ros/geometry2/issues/231>`_) * replaced dependencies on tf2_msgs_gencpp by exported dependencies * Document the lifetime of the returned reference for getFrameId getTimestamp * relax normalization tolerance. `#196 <https://github.com/ros/geometry2/issues/196>`_ was too strict for some use cases. (`#220 <https://github.com/ros/geometry2/issues/220>`_) * Solve a bug that causes a deadlock in MessageFilter * Contributors: Adel Fakih, Chris Lalancette, Christopher Wecht, Tully Foote, dhood 0.5.15 (2017-01-24) ------------------- 0.5.14 (2017-01-16) ------------------- * fixes `#194 <https://github.com/ros/geometry2/issues/194>`_ check for quaternion normalization before inserting into storage (`#196 <https://github.com/ros/geometry2/issues/196>`_) * check for quaternion normalization before inserting into storage * Add test to check for transform failure on invalid quaternion input * updating getAngleShortestPath() (`#187 <https://github.com/ros/geometry2/issues/187>`_) * Move internal cache functions into a namespace Fixes https://github.com/ros/geometry2/issues/175 * Link properly to convert.h * Landing page for tf2 describing the conversion interface * Fix comment on BufferCore::MAX_GRAPH_DEPTH. * Contributors: Jackie Kay, Phil Osteen, Tully Foote, alex, gavanderhoorn 0.5.13 (2016-03-04) ------------------- 0.5.12 (2015-08-05) ------------------- * add utilities to get yaw, pitch, roll and identity transform * provide more conversions between types The previous conversion always assumed that it was converting a non-message type to a non-message type. Now, one, both or none can be a message or a non-message. * Contributors: Vincent Rabaud 0.5.11 (2015-04-22) ------------------- 0.5.10 (2015-04-21) ------------------- * move lct_cache into function local memoryfor `#92 <https://github.com/ros/geometry_experimental/issues/92>`_ * Clean up range checking. Re: `#92 <https://github.com/ros/geometry_experimental/issues/92>`_ * Fixed chainToVector * release lock before possibly invoking user callbacks. Fixes `#91 <https://github.com/ros/geometry_experimental/issues/91>`_ * Contributors: Jackie Kay, Tully Foote 0.5.9 (2015-03-25) ------------------ * fixing edge case where two no frame id lookups matched in getLatestCommonTime * Contributors: Tully Foote 0.5.8 (2015-03-17) ------------------ * change from default argument to overload to avoid linking issue `#84 <https://github.com/ros/geometry_experimental/issues/84>`_ * remove useless Makefile files * Remove unused assignments in max/min functions * change _allFramesAsDot() -> _allFramesAsDot(double current_time) * Contributors: Jon Binney, Kei Okada, Tully Foote, Vincent Rabaud 0.5.7 (2014-12-23) ------------------ 0.5.6 (2014-09-18) ------------------ 0.5.5 (2014-06-23) ------------------ * convert to use console bridge from upstream debian package https://github.com/ros/rosdistro/issues/4633 * Fix format string * Contributors: Austin, Tully Foote 0.5.4 (2014-05-07) ------------------ * switch to boost signals2 following `ros/ros_comm#267 <https://github.com/ros/ros_comm/issues/267>`_, blocking `ros/geometry#23 <https://github.com/ros/geometry/issues/23>`_ * Contributors: Tully Foote 0.5.3 (2014-02-21) ------------------ 0.5.2 (2014-02-20) ------------------ 0.5.1 (2014-02-14) ------------------ 0.5.0 (2014-02-14) ------------------ 0.4.10 (2013-12-26) ------------------- * updated error message. fixes `#38 <https://github.com/ros/geometry_experimental/issues/38>`_ * tf2: add missing console bridge include directories (fix `#48 <https://github.com/ros/geometry_experimental/issues/48>`_) * Fix const correctness of tf2::Vector3 rotate() method The method does not modify the class thus should be const. This has already been fixed in Bullet itself. * Contributors: Dirk Thomas, Timo Rohling, Tully Foote 0.4.9 (2013-11-06) ------------------ 0.4.8 (2013-11-06) ------------------ * moving python documentation to tf2_ros from tf2 to follow the code * removing legacy rospy dependency. implementation removed in 0.4.0 fixes `#27 <https://github.com/ros/geometry_experimental/issues/27>`_ 0.4.7 (2013-08-28) ------------------ * switching to use allFramesAsStringNoLock inside of getLatestCommonTime and walkToParent and locking in public API _getLatestCommonTime instead re `#23 <https://github.com/ros/geometry_experimental/issues/23>`_ * Fixes a crash in tf's view_frames related to dot code generation in allFramesAsDot 0.4.6 (2013-08-28) ------------------ * cleaner fix for `#19 <https://github.com/ros/geometry_experimental/issues/19>`_ * fix pointer initialization. Fixes `#19 <https://github.com/ros/geometry_experimental/issues/19>`_ * fixes `#18 <https://github.com/ros/geometry_experimental/issues/18>`_ for hydro * package.xml: corrected typo in description 0.4.5 (2013-07-11) ------------------ * adding _chainAsVector method for https://github.com/ros/geometry/issues/18 * adding _allFramesAsDot for backwards compatability https://github.com/ros/geometry/issues/18 0.4.4 (2013-07-09) ------------------ * making repo use CATKIN_ENABLE_TESTING correctly and switching rostest to be a test_depend with that change. * tf2: Fixes a warning on OS X, but generally safer Replaces the use of pointers with shared_ptrs, this allows the polymorphism and makes it so that the compiler doesn't yell at us about calling delete on a class with a public non-virtual destructor. * tf2: Fixes compiler warnings on OS X This exploited a gcc specific extension and is not C++ standard compliant. There used to be a "fix" for OS X which no longer applies. I think it is ok to use this as an int instead of a double, but another way to fix it would be to use a define. * tf2: Fixes linkedit errors on OS X 0.4.3 (2013-07-05) ------------------ 0.4.2 (2013-07-05) ------------------ * adding getCacheLength() to parallel old tf API * removing legacy static const variable MAX_EXTRAPOLATION_DISTANCE copied from tf unnecessesarily 0.4.1 (2013-07-05) ------------------ * adding old style callback notifications to BufferCore to enable backwards compatability of message filters * exposing dedicated thread logic in BufferCore and checking in Buffer * more methods to expose, and check for empty cache before getting latest timestamp * adding methods to enable backwards compatability for passing through to tf::Transformer 0.4.0 (2013-06-27) ------------------ * splitting rospy dependency into tf2_py so tf2 is pure c++ library. * switching to console_bridge from rosconsole * moving convert methods back into tf2 because it does not have any ros dependencies beyond ros::Time which is already a dependency of tf2 * Cleaning up unnecessary dependency on roscpp * Cleaning up packaging of tf2 including: removing unused nodehandle fixing overmatch on search and replace cleaning up a few dependencies and linking removing old backup of package.xml making diff minimally different from tf version of library * suppressing bullet LinearMath copy inside of tf2, so it will not collide, and should not be used externally. * Restoring test packages and bullet packages. reverting 3570e8c42f9b394ecbfd9db076b920b41300ad55 to get back more of the packages previously implemented reverting 04cf29d1b58c660fdc999ab83563a5d4b76ab331 to fix `#7 <https://github.com/ros/geometry_experimental/issues/7>`_ * fixing includes in unit tests * Make PythonLibs find_package python2 specific On systems with python 3 installed and default, find_package(PythonLibs) will find the python 3 paths and libraries. However, the c++ include structure seems to be different in python 3 and tf2 uses includes that are no longer present or deprecated. Until the includes are made to be python 3 compliant, we should specify that the version of python found must be python 2. 0.3.6 (2013-03-03) ------------------ 0.3.5 (2013-02-15 14:46) ------------------------ * 0.3.4 -> 0.3.5 0.3.4 (2013-02-15 13:14) ------------------------ * 0.3.3 -> 0.3.4 * moving LinearMath includes to include/tf2 0.3.3 (2013-02-15 11:30) ------------------------ * 0.3.2 -> 0.3.3 * fixing include installation of tf2 0.3.2 (2013-02-15 00:42) ------------------------ * 0.3.1 -> 0.3.2 * fixed missing include export & tf2_ros dependecy 0.3.1 (2013-02-14) ------------------ * 0.3.0 -> 0.3.1 * fixing PYTHON installation directory 0.3.0 (2013-02-13) ------------------ * switching to version 0.3.0 * adding setup.py to tf2 package * fixed tf2 exposing python functionality * removed line that was killing tf2_ros.so * fixing catkin message dependencies * removing packages with missing deps * adding missing package.xml * adding missing package.xml * adding missing package.xml * catkinizing geometry-experimental * removing bullet headers from use in header files * removing bullet headers from use in header files * merging my recent changes * setting child_frame_id overlooked in revision 6a0eec022be0 which fixed failing tests * allFramesAsString public and internal methods seperated. Public method is locked, private method is not * fixing another scoped lock * fixing one scoped lock * fixing test compilation * merge * Error message fix, ros-pkg5085 * Check if target equals to source before validation * When target_frame == source_frame, just returns an identity transform. * adding addition ros header includes for strictness * Fixed optimized lookups with compound transforms * Fixed problem in tf2 optimized branch. Quaternion multiplication order was incorrect * fix compilation on 32-bit * Josh fix: Final inverse transform composition (missed multiplying the sourcd->top vector by the target->top inverse orientation). b44877d2b054 * Josh change: fix first/last time case. 46bf33868e0d * fix transform accumulation to parent * fix parent lookup, now works on the real pr2's tree * move the message filter to tf2_ros * tf2::MessageFilter + tests. Still need to change it around to pass in a callback queue, since we're being triggered directly from the tf2 buffer * Don't add the request if the transform is already available. Add some new tests * working transformable callbacks with a simple (incomplete) test case * first pass at a transformable callback api, not tested yet * add interpolation cases * fix getLatestCommonTime -- no longer returns the latest of any of the times * Some more optimization -- allow findClosest to inline * another minor speedup * Minorly speed up canTransform by not requiring the full data lookup, and only looking up the parent * Add explicit operator= so that we can see the time in it on a profile graph. Also some minor cleanup * minor cleanup * add 3 more cases to the speed test * Remove use of btTransform at all from transform accumulation, since the conversion to/from is unnecessary, expensive, and can introduce floating point error * Don't use btTransform as an intermediate when accumulating transforms, as constructing them takes quite a bit of time * Completely remove lookupLists(). canTransform() now uses the same walking code as lookupTransform(). Also fixed a bug in the static transform publisher test * Genericise the walk-to-top-parent code in lookupTransform so that it will be able to be used by canTransform as well (minus the cost of actually computing the transform) * remove id lookup that wasn't doing anything * Some more optimization: * Reduce # of TransformStorage copies made in TimeCache::getData() * Remove use of lookupLists from getLatestCommonTime * lookupTransform() no longer uses lookupLists unless it's called with Time(0). Removes lots of object construction/destruction due to removal of pushing back on the lists * Remove CompactFrameID in favor of a typedef * these mode checks are no longer necessary * Fix crash when testing extrapolation on the forward transforms * Update cache unit tests to work with the changes TransformStorage. Also make sure that BT_USE_DOUBLE_PRECISION is set for tf2. * remove exposure of time_cache.h from buffer_core.h * Removed the mutex from TimeCache, as it's unnecessary (BufferCore needs to have its own mutex locked anyway), and this speeds things up by about 20% Also fixed a number of thread-safety problems * Optimize test_extrapolation a bit, 25% speedup of lookupTransform * use a hash map for looking up frame numbers, speeds up lookupTransform by ~8% * Cache vectors used for looking up transforms. Speeds up lookupTransform by another 10% * speed up lookupTransform by another 25% * speed up lookupTransform by another 2x. also reduces the memory footprint of the cache significantly * sped up lookupTransform by another 2x * First add of a simple speed test Sped up lookupTransform 2x * roscpp dependency explicit, instead of relying on implicit * static transform tested and working * tests passing and all throw catches removed too\! * validating frame_ids up front for lookup exceptions * working with single base class vector * tests passing for static storage * making method private for clarity * static cache implementation and test * cleaning up API doc typos * sphinx docs for Buffer * new dox mainpage * update tf2 manifest * commenting out twist * Changed cache_time to cache_time_ to follow C++ style guide, also initialized it to actually get things to work * no more rand in cache tests * Changing tf2_py.cpp to use underscores instead of camelCase * removing all old converter functions from transform_datatypes.h * removing last references to transform_datatypes.h in tf2 * transform conversions internalized * removing unused datatypes * copying bullet transform headers into tf2 and breaking bullet dependency * merge * removing dependency on tf * removing include of old tf from tf2 * update doc * merge * kdl unittest passing * Spaces instead of tabs in YAML grrrr * Adding quotes for parent * canTransform advanced ported * Hopefully fixing YAML syntax * new version of view_frames in new tf2_tools package * testing new argument validation and catching bug * Python support for debugging * merge * adding validation of frame_ids in queries with warnings and exceptions where appropriate * Exposing ability to get frames as a string * A compiling version of YAML debugging interface for BufferCore * placeholder for tf debug * fixing tf:: to tf2:: ns issues and stripping slashes on set in tf2 for backwards compatiabily * Adding a python version of the BufferClient * moving test to new package * merging * working unit test for BufferCore::lookupTransform * removing unused method test and converting NO_PARENT test to new API * Adding some comments * Moving the python bindings for tf2 to the tf2 package from the tf2_py package * buffercore tests upgraded * porting tf_unittest while running incrmentally instead of block copy * BufferCore::clear ported forward * successfully changed lookupTransform advanced to new version * switching to new implementation of lookupTransform tests still passing * compiling lookupTransform new version * removing tf_prefix from BufferCore. BuferCore is independent of any frame_ids. tf_prefix should be implemented at the ROS API level. * initializing tf_prefix * adding missing initialization * suppressing warnings * more tests ported * removing tests for apis not ported forward * setTransform tests ported * old tests in new package passing due to backwards dependency. now for the fun, port all 1500 lines :-) * setTransform working in new framework as well as old * porting more methods * more compatability * bringing in helper functions for buffer_core from tf.h/cpp * rethrowing to new exceptions * converting Storage to geometry_msgs::TransformStamped * removing deprecated useage * cleaning up includes * moving all implementations into cpp file * switching test to new class from old one * Compiling version of the buffer client * moving listener to tf_cpp * removing listener, it should be in another package * most of listener * add cantransform implementation * removing deprecated API usage * initial import of listener header * move implementation into library * 2 tests of buffer * moving executables back into bin * compiling again with new design * rename tfcore to buffercore * almost compiling version of template code * compiling tf2_core simple test * add test to start compiling * copying in tf_unittest for tf_core testing template * prototype of tf2_core implemented using old tf. * first version of template functions * remove timeouts * properly naming tf2_core.h from tf_core.h * working cache test with tf2 lib * first unit test passing, not yet ported * tf_core api * tf2 v2 * aborting port * moving across time cache tf and datatypes headers * copying exceptions from tf * switching to tf2 from tf_core *
0
apollo_public_repos/apollo/third_party/tf2
apollo_public_repos/apollo/third_party/tf2/test/CMakeLists.txt
ADD_DEFINITIONS(-fno-access-control -DUNIT_TEST=1) add_executable(cache_unittest cache_unittest.cpp) target_link_libraries(cache_unittest gtest_main tf2 ) # install(TARGETS cache_unittest # DESTINATION ${UNIT_TEST_INSTALL_PREFIX}) # add_executable(simple_tf2_core simple_tf2_core.cpp) target_link_libraries(simple_tf2_core gtest_main tf2 ) # install(TARGETS simple_tf2_core # DESTINATION ${UNIT_TEST_INSTALL_PREFIX}) add_executable(tf2_speed_test speed_test.cpp) target_link_libraries(tf2_speed_test gtest_main tf2 ) # # install(TARGETS tf2_speed_test # DESTINATION ${UNIT_TEST_INSTALL_PREFIX}) # add_executable(tf2_static_cache_test static_cache_test.cpp) target_link_libraries(tf2_static_cache_test gtest_main tf2 ) # install(TARGETS tf2_static_cache_test # DESTINATION ${UNIT_TEST_INSTALL_PREFIX}) # add_executable(tf2_speed_2_test speed_2_test.cpp) target_link_libraries(tf2_speed_2_test gtest_main tf2 ) # install(TARGETS tf2_speed_2_test # DESTINATION ${UNIT_TEST_INSTALL_PREFIX})
0
apollo_public_repos/apollo/third_party/tf2
apollo_public_repos/apollo/third_party/tf2/test/static_cache_test.cpp
/* * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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. */ #include <gtest/gtest.h> #include <tf2/time_cache.h> #include <sys/time.h> #include <stdexcept> #include <geometry_msgs/transform_stamped.h> #include <cmath> using namespace tf2; void setIdentity(TransformStorage& stor) { stor.translation_.setValue(0.0, 0.0, 0.0); stor.rotation_.setValue(0.0, 0.0, 0.0, 1.0); } TEST(StaticCache, Repeatability) { unsigned int runs = 100; tf2::StaticCache cache; TransformStorage stor; setIdentity(stor); for ( uint64_t i = 1; i < runs ; i++ ) { stor.frame_id_ = CompactFrameID(i); stor.stamp_ = tf2::Time(i); cache.insertData(stor); cache.getData(tf2::Time(i), stor); EXPECT_EQ(stor.frame_id_, i); EXPECT_EQ(stor.stamp_, tf2::Time(i)); } } TEST(StaticCache, DuplicateEntries) { tf2::StaticCache cache; TransformStorage stor; setIdentity(stor); stor.frame_id_ = CompactFrameID(3); stor.stamp_ = tf2::Time(1); cache.insertData(stor); cache.insertData(stor); cache.getData(tf2::Time(1), stor); //printf(" stor is %f\n", stor.transform.translation.x); EXPECT_TRUE(!std::isnan(stor.translation_.x())); EXPECT_TRUE(!std::isnan(stor.translation_.y())); EXPECT_TRUE(!std::isnan(stor.translation_.z())); EXPECT_TRUE(!std::isnan(stor.rotation_.x())); EXPECT_TRUE(!std::isnan(stor.rotation_.y())); EXPECT_TRUE(!std::isnan(stor.rotation_.z())); EXPECT_TRUE(!std::isnan(stor.rotation_.w())); } int main(int argc, char **argv){ testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
0
apollo_public_repos/apollo/third_party/tf2
apollo_public_repos/apollo/third_party/tf2/test/cache_unittest.cpp
/* * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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. */ #include <gtest/gtest.h> #include <tf2/time_cache.h> #include <sys/time.h> #include "tf2/LinearMath/Quaternion.h" #include <stdexcept> // #include <geometry_msgs/TransformStamped.h> #include "geometry_msgs/transform_stamped.h" #include <cmath> std::vector<double> values; unsigned int step = 0; void seed_rand() { values.clear(); for (unsigned int i = 0; i < 1000; i++) { int pseudo_rand = std::floor(i * M_PI); values.push_back(( pseudo_rand % 100)/50.0 - 1.0); //printf("Seeding with %f\n", values.back()); } }; double get_rand() { if (values.size() == 0) throw std::runtime_error("you need to call seed_rand first"); if (step >= values.size()) step = 0; else step++; return values[step]; } using namespace tf2; void setIdentity(TransformStorage& stor) { stor.translation_.setValue(0.0, 0.0, 0.0); stor.rotation_.setValue(0.0, 0.0, 0.0, 1.0); } TEST(TimeCache, Repeatability) { unsigned int runs = 100; tf2::TimeCache cache; TransformStorage stor; setIdentity(stor); for ( uint64_t i = 1; i < runs ; i++ ) { stor.frame_id_ = i; stor.stamp_ = tf2::Time(i); cache.insertData(stor); } for ( uint64_t i = 1; i < runs ; i++ ) { cache.getData(tf2::Time(i), stor); EXPECT_EQ(stor.frame_id_, i); EXPECT_EQ(stor.stamp_, tf2::Time(i)); } } TEST(TimeCache, RepeatabilityReverseInsertOrder) { unsigned int runs = 100; tf2::TimeCache cache; TransformStorage stor; setIdentity(stor); for ( int i = runs -1; i >= 0 ; i-- ) { stor.frame_id_ = i; stor.stamp_ = tf2::Time(i); cache.insertData(stor); } for ( uint64_t i = 1; i < runs ; i++ ) { cache.getData(tf2::Time(i), stor); EXPECT_EQ(stor.frame_id_, i); EXPECT_EQ(stor.stamp_, tf2::Time(i)); } } #if 0 // jfaust: this doesn't seem to actually be testing random insertion? TEST(TimeCache, RepeatabilityRandomInsertOrder) { seed_rand(); tf2::TimeCache cache; double my_vals[] = {13,2,5,4,9,7,3,11,15,14,12,1,6,10,0,8}; std::vector<double> values (my_vals, my_vals + sizeof(my_vals)/sizeof(double)); unsigned int runs = values.size(); TransformStorage stor; setIdentity(stor); for ( uint64_t i = 0; i <runs ; i++ ) { values[i] = 10.0 * get_rand(); std::stringstream ss; ss << values[i]; stor.header.frame_id = ss.str(); stor.frame_id_ = i; stor.stamp_ = ros::Time().fromNSec(i); cache.insertData(stor); } for ( uint64_t i = 1; i < runs ; i++ ) { cache.getData(ros::Time().fromNSec(i), stor); EXPECT_EQ(stor.frame_id_, i); EXPECT_EQ(stor.stamp_, ros::Time().fromNSec(i)); std::stringstream ss; ss << values[i]; EXPECT_EQ(stor.header.frame_id, ss.str()); } } #endif TEST(TimeCache, ZeroAtFront) { uint64_t runs = 100; tf2::TimeCache cache; TransformStorage stor; setIdentity(stor); for ( uint64_t i = 1; i < runs ; i++ ) { stor.frame_id_ = i; stor.stamp_ = tf2::Time(i); cache.insertData(stor); } stor.frame_id_ = runs; stor.stamp_ = tf2::Time(runs); cache.insertData(stor); for ( uint64_t i = 1; i < runs ; i++ ) { cache.getData(tf2::Time(i), stor); EXPECT_EQ(stor.frame_id_, i); EXPECT_EQ(stor.stamp_, tf2::Time(i)); } cache.getData(0, stor); EXPECT_EQ(stor.frame_id_, runs); EXPECT_EQ(stor.stamp_, tf2::Time(runs)); stor.frame_id_ = runs; stor.stamp_ = tf2::Time(runs + 1); cache.insertData(stor); //Make sure we get a different value now that a new values is added at the front cache.getData(0, stor); EXPECT_EQ(stor.frame_id_, runs); EXPECT_EQ(stor.stamp_, tf2::Time(runs + 1)); } TEST(TimeCache, CartesianInterpolation) { uint64_t runs = 100; double epsilon = 2e-6; seed_rand(); tf2::TimeCache cache; std::vector<double> xvalues(2); std::vector<double> yvalues(2); std::vector<double> zvalues(2); uint64_t offset = 200; TransformStorage stor; setIdentity(stor); for ( uint64_t i = 1; i < runs ; i++ ) { for (uint64_t step = 0; step < 2 ; step++) { xvalues[step] = 10.0 * get_rand(); yvalues[step] = 10.0 * get_rand(); zvalues[step] = 10.0 * get_rand(); stor.translation_.setValue(xvalues[step], yvalues[step], zvalues[step]); stor.frame_id_ = 2; stor.stamp_ = tf2::Time(step * 100 + offset); cache.insertData(stor); } for (int pos = 0; pos < 100 ; pos ++) { cache.getData(tf2::Time(offset + pos), stor); double x_out = stor.translation_.x(); double y_out = stor.translation_.y(); double z_out = stor.translation_.z(); // printf("pose %d, %f %f %f, expected %f %f %f\n", pos, x_out, y_out, z_out, // xvalues[0] + (xvalues[1] - xvalues[0]) * (double)pos/100., // yvalues[0] + (yvalues[1] - yvalues[0]) * (double)pos/100.0, // zvalues[0] + (xvalues[1] - zvalues[0]) * (double)pos/100.0); EXPECT_NEAR(xvalues[0] + (xvalues[1] - xvalues[0]) * (double)pos/100.0, x_out, epsilon); EXPECT_NEAR(yvalues[0] + (yvalues[1] - yvalues[0]) * (double)pos/100.0, y_out, epsilon); EXPECT_NEAR(zvalues[0] + (zvalues[1] - zvalues[0]) * (double)pos/100.0, z_out, epsilon); } cache.clearList(); } } /** \brief Make sure we dont' interpolate across reparented data */ TEST(TimeCache, ReparentingInterpolationProtection) { double epsilon = 1e-6; uint64_t offset = 555; seed_rand(); tf2::TimeCache cache; std::vector<double> xvalues(2); std::vector<double> yvalues(2); std::vector<double> zvalues(2); TransformStorage stor; setIdentity(stor); for (uint64_t step = 0; step < 2 ; step++) { xvalues[step] = 10.0 * get_rand(); yvalues[step] = 10.0 * get_rand(); zvalues[step] = 10.0 * get_rand(); stor.translation_.setValue(xvalues[step], yvalues[step], zvalues[step]); stor.frame_id_ = step + 4; stor.stamp_ = tf2::Time(step * 100 + offset); cache.insertData(stor); } for (int pos = 0; pos < 100 ; pos ++) { EXPECT_TRUE(cache.getData(tf2::Time(offset + pos), stor)); double x_out = stor.translation_.x(); double y_out = stor.translation_.y(); double z_out = stor.translation_.z(); EXPECT_NEAR(xvalues[0], x_out, epsilon); EXPECT_NEAR(yvalues[0], y_out, epsilon); EXPECT_NEAR(zvalues[0], z_out, epsilon); } } TEST(Bullet, Slerp) { uint64_t runs = 100; seed_rand(); tf2::Quaternion q1, q2; q1.setEuler(0,0,0); for (uint64_t i = 0 ; i < runs ; i++) { q2.setEuler(1.0 * get_rand(), 1.0 * get_rand(), 1.0 * get_rand()); tf2::Quaternion q3 = slerp(q1,q2,0.5); EXPECT_NEAR(q3.angle(q1), q2.angle(q3), 1e-5); } } TEST(TimeCache, AngularInterpolation) { uint64_t runs = 100; double epsilon = 1e-6; seed_rand(); tf2::TimeCache cache; std::vector<double> yawvalues(2); std::vector<double> pitchvalues(2); std::vector<double> rollvalues(2); uint64_t offset = 200; std::vector<tf2::Quaternion> quats(2); TransformStorage stor; setIdentity(stor); for ( uint64_t i = 1; i < runs ; i++ ) { for (uint64_t step = 0; step < 2 ; step++) { yawvalues[step] = 10.0 * get_rand() / 100.0; pitchvalues[step] = 0;//10.0 * get_rand(); rollvalues[step] = 0;//10.0 * get_rand(); quats[step].setRPY(yawvalues[step], pitchvalues[step], rollvalues[step]); stor.rotation_ = quats[step]; stor.frame_id_ = 3; stor.stamp_ = tf2::Time(offset + (step * 100)); //step = 0 or 1 cache.insertData(stor); } for (int pos = 0; pos < 100 ; pos ++) { EXPECT_TRUE(cache.getData(tf2::Time(offset + pos), stor)); //get the transform for the position tf2::Quaternion quat (stor.rotation_); //Generate a ground truth quaternion directly calling slerp tf2::Quaternion ground_truth = quats[0].slerp(quats[1], pos/100.0); //Make sure the transformed one and the direct call match EXPECT_NEAR(0, angle(ground_truth, quat), epsilon); } cache.clearList(); } } TEST(TimeCache, DuplicateEntries) { TimeCache cache; TransformStorage stor; setIdentity(stor); stor.frame_id_ = 3; stor.stamp_ = tf2::Time(1); cache.insertData(stor); cache.insertData(stor); cache.getData(tf2::Time(1), stor); //printf(" stor is %f\n", stor.translation_.x()); EXPECT_TRUE(!std::isnan(stor.translation_.x())); EXPECT_TRUE(!std::isnan(stor.translation_.y())); EXPECT_TRUE(!std::isnan(stor.translation_.z())); EXPECT_TRUE(!std::isnan(stor.rotation_.x())); EXPECT_TRUE(!std::isnan(stor.rotation_.y())); EXPECT_TRUE(!std::isnan(stor.rotation_.z())); EXPECT_TRUE(!std::isnan(stor.rotation_.w())); } int main(int argc, char **argv){ testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
0
apollo_public_repos/apollo/third_party/tf2
apollo_public_repos/apollo/third_party/tf2/test/speed_2_test.cpp
/* * Copyright (c) 2010, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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. */ #include <stdio.h> #include <tf2/buffer_core.h> #include "tf2/time.h" #include <boost/lexical_cast.hpp> #include <chrono> #include <thread> #include <mutex> #include <atomic> using std::chrono::system_clock; using std::chrono::steady_clock; using std::chrono::high_resolution_clock; uint64_t now_time() { high_resolution_clock::time_point now = high_resolution_clock::now(); auto nano_now = std::chrono::time_point_cast<std::chrono::nanoseconds>(now); auto epoch = nano_now.time_since_epoch(); uint64_t nano_time = std::chrono::duration_cast<std::chrono::nanoseconds>(epoch).count(); return nano_time; } tf2::BufferCore bc; std::atomic<bool> is_stop(false); void set_trans_form_1000() { for (uint64_t i = 0; i < 1000; ++i) { geometry_msgs::TransformStamped t; t.header.stamp = i; t.header.frame_id = "world"; t.child_frame_id = "novatel"; t.transform.translation.x = 1; t.transform.rotation.w = 1.0; bc.setTransform(t, "test"); } } std::mutex cout_mutex; std::atomic<uint64_t> total_cost_time(0); std::atomic<uint64_t> total_exec_cnt(0); void look_transform(int count, int look_idx = 0) { std::string frame_target = "world"; std::string frame_source = "velodyne64"; if (look_idx >= 1000) { look_idx = 999; } geometry_msgs::TransformStamped out_t; for (int i = 0; i < count; ++i) { uint64_t start = now_time(); out_t = bc.lookupTransform(frame_target, frame_source, look_idx); uint64_t end = now_time(); double dur = (double)end - (double)start; total_cost_time.fetch_add(dur); total_exec_cnt.fetch_add(1); } } std::atomic<uint64_t> can_total_cost(0); std::atomic<uint64_t> can_exec_cnt(0); void can_transform(int count, int look_idx = 0) { std::string frame_target = "world"; std::string frame_source = "velodyne64"; if (look_idx >= 1000) { look_idx = 999; } for (int i = 0; i < count; ++i) { uint64_t start = now_time(); bc.canTransform(frame_target, frame_source, look_idx); uint64_t end = now_time(); double dur = (double)end - (double)start; can_total_cost.fetch_add(dur); can_exec_cnt.fetch_add(1); } } int main(int argc, char **argv) { set_trans_form_1000(); geometry_msgs::TransformStamped t; t.header.stamp = 0; t.header.frame_id = "novatel"; t.child_frame_id = "velodyne64"; t.transform.translation.x = 1; t.transform.rotation.w = 1.0; bc.setTransform(t, "test", true); int th_nums = 1; int lookup_index = 0; // if (argc >= 2) { // th_nums = boost::lexical_cast<int>(argv[1]); // } // if (argc >= 3) { // lookup_index = boost::lexical_cast<int>(argv[2]); // } std::cout << "lookup max thread nums: " << th_nums << ", lookup index: " << lookup_index << std::endl; std::vector<std::thread> td_vec; std::vector<std::thread> can_tds; for (int i = 1; i <= th_nums; ++i) { total_cost_time = 0; total_exec_cnt = 0; can_total_cost = 0; can_exec_cnt = 0; for (int j = 1; j <= i; ++j) { td_vec.push_back(std::thread(look_transform, 100, lookup_index)); can_tds.push_back(std::thread(can_transform, 100, lookup_index)); } for (auto &td : td_vec) { td.join(); } for (auto &td : can_tds) { td.join(); } td_vec.clear(); can_tds.clear(); std::cout << "Thread Nums: " << i << ", lookup cnt: " << total_exec_cnt.load() << ", Total Time(ms): " << static_cast<double>(total_cost_time.load()) / 1e6 << ", Avg Time(ms): " << static_cast<double>(total_cost_time.load()) / 1e6 / total_exec_cnt.load() << std::endl; std::cout << "Thread Nums: " << i << ", can cnt: " << can_exec_cnt.load() << ", Total Time(ms): " << static_cast<double>(can_total_cost.load()) / 1e6 << ", Avg Time(ms): " << static_cast<double>(can_total_cost.load()) / 1e6 / can_exec_cnt.load() << std::endl; } }
0
apollo_public_repos/apollo/third_party/tf2
apollo_public_repos/apollo/third_party/tf2/test/simple_tf2_core.cpp
/* * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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. */ #include <gtest/gtest.h> #include <tf2/buffer_core.h> #include <sys/time.h> // #include <ros/ros.h> #include "tf2/LinearMath/Vector3.h" #include "tf2/exceptions.h" TEST(tf2, setTransformFail) { tf2::BufferCore tfc; geometry_msgs::TransformStamped st; EXPECT_FALSE(tfc.setTransform(st, "authority1")); } TEST(tf2, setTransformValid) { tf2::BufferCore tfc; geometry_msgs::TransformStamped st; st.header.frame_id = "foo"; st.header.stamp = tf2::Time(1e9); st.child_frame_id = "child"; st.transform.rotation.w = 1; EXPECT_TRUE(tfc.setTransform(st, "authority1")); } TEST(tf2, setTransformInvalidQuaternion) { tf2::BufferCore tfc; geometry_msgs::TransformStamped st; st.header.frame_id = "foo"; st.header.stamp = tf2::Time(1e9); st.child_frame_id = "child"; st.transform.rotation.w = 0; EXPECT_FALSE(tfc.setTransform(st, "authority1")); } TEST(tf2_lookupTransform, LookupException_Nothing_Exists) { tf2::BufferCore tfc; EXPECT_THROW(tfc.lookupTransform("a", "b", tf2::Time(1e9)), tf2::LookupException); } TEST(tf2_canTransform, Nothing_Exists) { tf2::BufferCore tfc; EXPECT_FALSE(tfc.canTransform("a", "b", tf2::Time(1e9))); std::string error_msg = std::string(); EXPECT_FALSE(tfc.canTransform("a", "b", tf2::Time(1e9), &error_msg)); ASSERT_STREQ(error_msg.c_str(), "canTransform: target_frame a does not exist. canTransform: source_frame b does not exist."); } TEST(tf2_lookupTransform, LookupException_One_Exists) { tf2::BufferCore tfc; geometry_msgs::TransformStamped st; st.header.frame_id = "foo"; st.header.stamp = tf2::Time(1e9); st.child_frame_id = "child"; st.transform.rotation.w = 1; EXPECT_TRUE(tfc.setTransform(st, "authority1")); EXPECT_THROW(tfc.lookupTransform("foo", "bar", tf2::Time(1e9)), tf2::LookupException); } TEST(tf2_canTransform, One_Exists) { tf2::BufferCore tfc; geometry_msgs::TransformStamped st; st.header.frame_id = "foo"; st.header.stamp = tf2::Time(1e9); st.child_frame_id = "child"; st.transform.rotation.w = 1; EXPECT_TRUE(tfc.setTransform(st, "authority1")); EXPECT_FALSE(tfc.canTransform("foo", "bar", tf2::Time(1e9))); } int main(int argc, char **argv){ testing::InitGoogleTest(&argc, argv); // ros::Time::init(); //needed for ros::TIme::now() return RUN_ALL_TESTS(); }
0
apollo_public_repos/apollo/third_party/tf2
apollo_public_repos/apollo/third_party/tf2/test/speed_test.cpp
/* * Copyright (c) 2010, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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. */ #include <stdio.h> #include <tf2/buffer_core.h> #include "tf2/time.h" #include <boost/lexical_cast.hpp> #include <chrono> using std::chrono::system_clock; using std::chrono::steady_clock; using std::chrono::high_resolution_clock; int main(int argc, char** argv) { int num_levels = 10; // if (argc > 1) // { // num_levels = boost::lexical_cast<uint32_t>(argv[1]); // } tf2::BufferCore bc; geometry_msgs::TransformStamped t; t.header.stamp = 1; t.header.frame_id = "root"; t.child_frame_id = "0"; t.transform.translation.x = 1; t.transform.rotation.w = 1.0; bc.setTransform(t, "me"); t.header.stamp = 2; bc.setTransform(t, "me"); for (uint32_t i = 1; i < num_levels/2; ++i) { for (uint32_t j = 1; j < 3; ++j) { std::stringstream parent_ss; parent_ss << (i - 1); std::stringstream child_ss; child_ss << i; t.header.stamp = tf2::Time(j); t.header.frame_id = parent_ss.str(); t.child_frame_id = child_ss.str(); bc.setTransform(t, "me"); } } t.header.frame_id = "root"; std::stringstream ss; ss << num_levels/2; t.header.stamp = 1; t.child_frame_id = ss.str(); bc.setTransform(t, "me"); t.header.stamp = 2; bc.setTransform(t, "me"); for (uint32_t i = num_levels/2 + 1; i < num_levels; ++i) { for (uint32_t j = 1; j < 3; ++j) { std::stringstream parent_ss; parent_ss << (i - 1); std::stringstream child_ss; child_ss << i; t.header.stamp = tf2::Time(j); t.header.frame_id = parent_ss.str(); t.child_frame_id = child_ss.str(); bc.setTransform(t, "me"); } } //logInfo_STREAM(bc.allFramesAsYAML()); std::string v_frame0 = boost::lexical_cast<std::string>(num_levels - 1); std::string v_frame1 = boost::lexical_cast<std::string>(num_levels/2 - 1); printf("%s to %s\n", v_frame0.c_str(), v_frame1.c_str()); geometry_msgs::TransformStamped out_t; const int count = 1000000; printf("Doing %d %d-level tests\n", count, num_levels); #if 01 { steady_clock::time_point start = steady_clock::now(); for (uint32_t i = 0; i < count; ++i) { out_t = bc.lookupTransform(v_frame1, v_frame0, 0); } steady_clock::time_point end = steady_clock::now(); double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count(); printf("lookupTransform at Time(0) took: %f (secs) for an average of: %.9f (secs)\n", dur, dur / (double)count); } #endif #if 01 { steady_clock::time_point start = steady_clock::now(); for (uint32_t i = 0; i < count; ++i) { out_t = bc.lookupTransform(v_frame1, v_frame0, tf2::Time(1)); } steady_clock::time_point end = steady_clock::now(); double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count(); printf("lookupTransform at Time(1) took: %f for an average of: %.9f\n", dur, dur / (double)count); } #endif #if 01 { steady_clock::time_point start = steady_clock::now(); for (uint32_t i = 0; i < count; ++i) { out_t = bc.lookupTransform(v_frame1, v_frame0, tf2::Time(1.5)); } steady_clock::time_point end = steady_clock::now(); double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count(); printf("lookupTransform at Time(1.5) took %f for an average of %.9f\n", dur, dur / (double)count); } #endif #if 01 { steady_clock::time_point start = steady_clock::now(); for (uint32_t i = 0; i < count; ++i) { out_t = bc.lookupTransform(v_frame1, v_frame0, tf2::Time(2)); } steady_clock::time_point end = steady_clock::now(); double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count(); printf("lookupTransform at Time(2) took %f for an average of %.9f\n", dur, dur / (double)count); } #endif #if 01 { steady_clock::time_point start = steady_clock::now(); for (uint32_t i = 0; i < count; ++i) { bc.canTransform(v_frame1, v_frame0, tf2::Time(0)); } steady_clock::time_point end = steady_clock::now(); double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count(); printf("canTransform at Time(0) took %f for an average of %.9f\n", dur, dur / (double)count); } #endif #if 01 { steady_clock::time_point start = steady_clock::now(); for (uint32_t i = 0; i < count; ++i) { bc.canTransform(v_frame1, v_frame0, tf2::Time(1)); } steady_clock::time_point end = steady_clock::now(); double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count(); printf("canTransform at Time(1) took %f for an average of %.9f\n", dur, dur / (double)count); } #endif #if 01 { steady_clock::time_point start = steady_clock::now(); for (uint32_t i = 0; i < count; ++i) { bc.canTransform(v_frame1, v_frame0, tf2::Time(1.5 * 1e9)); } steady_clock::time_point end = steady_clock::now(); double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count(); printf("canTransform at Time(1.5) took %f for an average of %.9f\n", dur, dur / (double)count); } #endif #if 01 { steady_clock::time_point start = steady_clock::now(); for (uint32_t i = 0; i < count; ++i) { bc.canTransform(v_frame1, v_frame0, tf2::Time(2)); } steady_clock::time_point end = steady_clock::now(); double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count(); printf("canTransform at Time(2) took %f for an average of %.9f\n", dur, dur / (double)count); } #endif }
0
apollo_public_repos/apollo/third_party/tf2
apollo_public_repos/apollo/third_party/tf2/cmake/GTest.cmake
# the following code to fetch googletest # is inspired by and adapted after https://crascit.com/2015/07/25/cmake-gtest/ # download and unpack googletest at configure time macro(fetch_googletest _download_module_path _download_root) set(GOOGLETEST_DOWNLOAD_ROOT ${_download_root}) configure_file( ${_download_module_path}/GTestDownload.cmake ${_download_root}/CMakeLists.txt @ONLY ) unset(GOOGLETEST_DOWNLOAD_ROOT) execute_process( COMMAND "${CMAKE_COMMAND}" -G "${CMAKE_GENERATOR}" . WORKING_DIRECTORY ${_download_root} ) execute_process( COMMAND "${CMAKE_COMMAND}" --build . WORKING_DIRECTORY ${_download_root} ) # adds the targers: gtest, gtest_main, gmock, gmock_main add_subdirectory( ${_download_root}/googletest-src ${_download_root}/googletest-build ) endmacro()
0
apollo_public_repos/apollo/third_party/tf2
apollo_public_repos/apollo/third_party/tf2/cmake/GTestDownload.cmake
# code copied from https://crascit.com/2015/07/25/cmake-gtest/ cmake_minimum_required(VERSION 3.5 FATAL_ERROR) project(GoogleTestDownload NONE) include(ExternalProject) ExternalProject_Add(googletest SOURCE_DIR "@GOOGLETEST_DOWNLOAD_ROOT@/googletest-src" BINARY_DIR "@GOOGLETEST_DOWNLOAD_ROOT@/googletest-build" GIT_REPOSITORY https://github.com/google/googletest.git GIT_TAG release-1.10.0 CONFIGURE_COMMAND "" BUILD_COMMAND "" INSTALL_COMMAND "" TEST_COMMAND "" )
0
apollo_public_repos/apollo/third_party/tf2/include
apollo_public_repos/apollo/third_party/tf2/include/tf2/time.h
/* * Copyright (c) 2013, Open Source Robotics Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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. */ #ifndef TF2_TIME_H #define TF2_TIME_H #include <stdint.h> #include <limits> namespace tf2 { typedef uint64_t Time; typedef uint64_t Duration; const uint64_t TIME_MAX = std::numeric_limits<uint64_t>::max(); double time_to_sec(Time t); } #endif
0
apollo_public_repos/apollo/third_party/tf2/include
apollo_public_repos/apollo/third_party/tf2/include/tf2/utils.h
// Copyright 2014 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef TF2_UTILS_H #define TF2_UTILS_H #include <tf2/LinearMath/Transform.h> #include <tf2/LinearMath/Quaternion.h> #include <tf2/impl/utils.h> namespace tf2 { /** Return the yaw, pitch, roll of anything that can be converted to a tf2::Quaternion * The conventions are the usual ROS ones defined in tf2/LineMath/Matrix3x3.h * \param a the object to get data from (it represents a rotation/quaternion) * \param yaw yaw * \param pitch pitch * \param roll roll */ template <class A> void getEulerYPR(const A& a, double& yaw, double& pitch, double& roll) { tf2::Quaternion q = impl::toQuaternion(a); impl::getEulerYPR(q, yaw, pitch, roll); } /** Return the yaw of anything that can be converted to a tf2::Quaternion * The conventions are the usual ROS ones defined in tf2/LineMath/Matrix3x3.h * This function is a specialization of getEulerYPR and is useful for its * wide-spread use in navigation * \param a the object to get data from (it represents a rotation/quaternion) * \param yaw yaw */ template <class A> double getYaw(const A& a) { tf2::Quaternion q = impl::toQuaternion(a); return impl::getYaw(q); } /** Return the identity for any type that can be converted to a tf2::Transform * \return an object of class A that is an identity transform */ template <class A> A getTransformIdentity() { tf2::Transform t; t.setIdentity(); A a; convert(t, a); return a; } } #endif //TF2_UTILS_H
0
apollo_public_repos/apollo/third_party/tf2/include
apollo_public_repos/apollo/third_party/tf2/include/tf2/transform_datatypes.h
/* * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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. */ /** \author Tully Foote */ #ifndef TF2_TRANSFORM_DATATYPES_H #define TF2_TRANSFORM_DATATYPES_H #include <string> #include "tf2/time.h" namespace tf2 { /** \brief The data type which will be cross compatable with geometry_msgs * This is the tf2 datatype equivilant of a MessageStamped */ template <typename T> class Stamped : public T{ public: Time stamp_; ///< The timestamp associated with this data std::string frame_id_; ///< The frame_id associated this data /** Default constructor */ Stamped() :frame_id_ ("NO_ID_STAMPED_DEFAULT_CONSTRUCTION"){}; //Default constructor used only for preallocation /** Full constructor */ Stamped(const T& input, const Time& timestamp, const std::string & frame_id) : T (input), stamp_ ( timestamp ), frame_id_ (frame_id){ } ; /** Copy Constructor */ Stamped(const Stamped<T>& s): T (s), stamp_(s.stamp_), frame_id_(s.frame_id_) {} /** Set the data element */ void setData(const T& input){*static_cast<T*>(this) = input;}; }; /** \brief Comparison Operator for Stamped datatypes */ template <typename T> bool operator==(const Stamped<T> &a, const Stamped<T> &b) { return a.frame_id_ == b.frame_id_ && a.stamp_ == b.stamp_ && static_cast<const T&>(a) == static_cast<const T&>(b); }; } #endif //TF2_TRANSFORM_DATATYPES_H
0
apollo_public_repos/apollo/third_party/tf2/include
apollo_public_repos/apollo/third_party/tf2/include/tf2/exceptions.h
/* * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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. */ /** \author Tully Foote */ #ifndef TF2_EXCEPTIONS_H #define TF2_EXCEPTIONS_H #include <stdexcept> namespace tf2{ /** \brief A base class for all tf2 exceptions * This inherits from ros::exception * which inherits from std::runtime_exception */ class TransformException: public std::runtime_error { public: TransformException(const std::string errorDescription) : std::runtime_error(errorDescription) { ; }; }; /** \brief An exception class to notify of no connection * * This is an exception class to be thrown in the case * that the Reference Frame tree is not connected between * the frames requested. */ class ConnectivityException:public TransformException { public: ConnectivityException(const std::string errorDescription) : tf2::TransformException(errorDescription) { ; }; }; /** \brief An exception class to notify of bad frame number * * This is an exception class to be thrown in the case that * a frame not in the graph has been attempted to be accessed. * The most common reason for this is that the frame is not * being published, or a parent frame was not set correctly * causing the tree to be broken. */ class LookupException: public TransformException { public: LookupException(const std::string errorDescription) : tf2::TransformException(errorDescription) { ; }; }; /** \brief An exception class to notify that the requested value would have required extrapolation beyond current limits. * */ class ExtrapolationException: public TransformException { public: ExtrapolationException(const std::string errorDescription) : tf2::TransformException(errorDescription) { ; }; }; /** \brief An exception class to notify that one of the arguments is invalid * * usually it's an uninitalized Quaternion (0,0,0,0) * */ class InvalidArgumentException: public TransformException { public: InvalidArgumentException(const std::string errorDescription) : tf2::TransformException(errorDescription) { ; }; }; /** \brief An exception class to notify that a timeout has occured * * */ class TimeoutException: public TransformException { public: TimeoutException(const std::string errorDescription) : tf2::TransformException(errorDescription) { ; }; }; } #endif //TF2_EXCEPTIONS_H
0
apollo_public_repos/apollo/third_party/tf2/include
apollo_public_repos/apollo/third_party/tf2/include/tf2/buffer_core.h
/* * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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. */ /** \author Tully Foote */ #ifndef TF2_BUFFER_CORE_H #define TF2_BUFFER_CORE_H #include "transform_storage.h" #include "tf2/time.h" #include <boost/signals2.hpp> #include <string> // #include "ros/duration.h" // #include "ros/time.h" //#include "geometry_msgs/TwistStamped.h" #include "geometry_msgs/transform_stamped.h" //////////////////////////backwards startup for porting //#include "tf/tf.h" #include <boost/unordered_map.hpp> #include <boost/thread/mutex.hpp> #include <boost/function.hpp> #include <boost/shared_ptr.hpp> namespace tf2 { typedef std::pair<Time, CompactFrameID> P_TimeAndFrameID; typedef uint32_t TransformableCallbackHandle; typedef uint64_t TransformableRequestHandle; class TimeCacheInterface; typedef boost::shared_ptr<TimeCacheInterface> TimeCacheInterfacePtr; enum TransformableResult { TransformAvailable, TransformFailure, }; /** \brief A Class which provides coordinate transforms between any two frames in a system. * * This class provides a simple interface to allow recording and lookup of * relationships between arbitrary frames of the system. * * libTF assumes that there is a tree of coordinate frame transforms which define the relationship between all coordinate frames. * For example your typical robot would have a transform from global to real world. And then from base to hand, and from base to head. * But Base to Hand really is composed of base to shoulder to elbow to wrist to hand. * libTF is designed to take care of all the intermediate steps for you. * * Internal Representation * libTF will store frames with the parameters necessary for generating the transform into that frame from it's parent and a reference to the parent frame. * Frames are designated using an std::string * 0 is a frame without a parent (the top of a tree) * The positions of frames over time must be pushed in. * * All function calls which pass frame ids can potentially throw the exception tf::LookupException */ class BufferCore { public: /************* Constants ***********************/ static const uint64_t DEFAULT_CACHE_TIME = 10 * 1e9; //!< The default amount of time to cache data in seconds (nanoseconds) static const uint32_t MAX_GRAPH_DEPTH = 1000UL; //!< Maximum graph search depth (deeper graphs will be assumed to have loops) /** Constructor * \param interpolating Whether to interpolate, if this is false the closest value will be returned * \param cache_time How long to keep a history of transforms in nanoseconds * */ BufferCore(Duration cache_time_ = Duration(DEFAULT_CACHE_TIME)); virtual ~BufferCore(void); /** \brief Clear all data */ void clear(); /** \brief Add transform information to the tf data structure * \param transform The transform to store * \param authority The source of the information for this transform * \param is_static Record this transform as a static transform. It will be good across all time. (This cannot be changed after the first call.) * \return True unless an error occured */ bool setTransform(const geometry_msgs::TransformStamped& transform, const std::string & authority, bool is_static = false); /*********** Accessors *************/ /** \brief Get the transform between two frames by frame ID. * \param target_frame The frame to which data should be transformed * \param source_frame The frame where the data originated * \param time The time at which the value of the transform is desired. (0 will get the latest) * \return The transform between the frames * * Possible exceptions tf2::LookupException, tf2::ConnectivityException, * tf2::ExtrapolationException, tf2::InvalidArgumentException */ geometry_msgs::TransformStamped lookupTransform(const std::string& target_frame, const std::string& source_frame, const Time& time) const; /** \brief Get the transform between two frames by frame ID assuming fixed frame. * \param target_frame The frame to which data should be transformed * \param target_time The time to which the data should be transformed. (0 will get the latest) * \param source_frame The frame where the data originated * \param source_time The time at which the source_frame should be evaluated. (0 will get the latest) * \param fixed_frame The frame in which to assume the transform is constant in time. * \return The transform between the frames * * Possible exceptions tf2::LookupException, tf2::ConnectivityException, * tf2::ExtrapolationException, tf2::InvalidArgumentException */ geometry_msgs::TransformStamped lookupTransform(const std::string& target_frame, const Time& target_time, const std::string& source_frame, const Time& source_time, const std::string& fixed_frame) const; /** \brief Lookup the twist of the tracking_frame with respect to the observation frame in the reference_frame using the reference point * \param tracking_frame The frame to track * \param observation_frame The frame from which to measure the twist * \param reference_frame The reference frame in which to express the twist * \param reference_point The reference point with which to express the twist * \param reference_point_frame The frame_id in which the reference point is expressed * \param time The time at which to get the velocity * \param duration The period over which to average * \return twist The twist output * * This will compute the average velocity on the interval * (time - duration/2, time+duration/2). If that is too close to the most * recent reading, in which case it will shift the interval up to * duration/2 to prevent extrapolation. * * Possible exceptions tf2::LookupException, tf2::ConnectivityException, * tf2::ExtrapolationException, tf2::InvalidArgumentException * * New in geometry 1.1 */ /* geometry_msgs::Twist lookupTwist(const std::string& tracking_frame, const std::string& observation_frame, const std::string& reference_frame, const tf::Point & reference_point, const std::string& reference_point_frame, const Time& time, const Duration& averaging_interval) const; */ /** \brief lookup the twist of the tracking frame with respect to the observational frame * * This is a simplified version of * lookupTwist with it assumed that the reference point is the * origin of the tracking frame, and the reference frame is the * observation frame. * * Possible exceptions tf2::LookupException, tf2::ConnectivityException, * tf2::ExtrapolationException, tf2::InvalidArgumentException * * New in geometry 1.1 */ /* geometry_msgs::Twist lookupTwist(const std::string& tracking_frame, const std::string& observation_frame, const Time& time, const Duration& averaging_interval) const; */ /** \brief Test if a transform is possible * \param target_frame The frame into which to transform * \param source_frame The frame from which to transform * \param time The time at which to transform * \param error_msg A pointer to a string which will be filled with why the transform failed, if not NULL * \return True if the transform is possible, false otherwise */ bool canTransform(const std::string& target_frame, const std::string& source_frame, const Time& time, std::string* error_msg = NULL) const; /** \brief Test if a transform is possible * \param target_frame The frame into which to transform * \param target_time The time into which to transform * \param source_frame The frame from which to transform * \param source_time The time from which to transform * \param fixed_frame The frame in which to treat the transform as constant in time * \param error_msg A pointer to a string which will be filled with why the transform failed, if not NULL * \return True if the transform is possible, false otherwise */ bool canTransform(const std::string& target_frame, const Time& target_time, const std::string& source_frame, const Time& source_time, const std::string& fixed_frame, std::string* error_msg = NULL) const; /** \brief A way to see what frames have been cached in yaml format * Useful for debugging tools */ std::string allFramesAsYAML(double current_time) const; /** Backwards compatibility for #84 */ std::string allFramesAsYAML() const; /** \brief A way to see what frames have been cached * Useful for debugging */ std::string allFramesAsString() const; typedef boost::function<void(TransformableRequestHandle request_handle, const std::string& target_frame, const std::string& source_frame, Time time, TransformableResult result)> TransformableCallback; /// \brief Internal use only TransformableCallbackHandle addTransformableCallback(const TransformableCallback& cb); /// \brief Internal use only void removeTransformableCallback(TransformableCallbackHandle handle); /// \brief Internal use only TransformableRequestHandle addTransformableRequest(TransformableCallbackHandle handle, const std::string& target_frame, const std::string& source_frame, Time time); /// \brief Internal use only void cancelTransformableRequest(TransformableRequestHandle handle); // Tell the buffer that there are multiple threads serviciing it. // This is useful for derived classes to know if they can block or not. void setUsingDedicatedThread(bool value) { using_dedicated_thread_ = value;}; // Get the state of using_dedicated_thread_ bool isUsingDedicatedThread() const { return using_dedicated_thread_;}; /* Backwards compatability section for tf::Transformer you should not use these */ /** * \brief Add a callback that happens when a new transform has arrived * * \param callback The callback, of the form void func(); * \return A boost::signals2::connection object that can be used to remove this * listener */ boost::signals2::connection _addTransformsChangedListener(boost::function<void(void)> callback); void _removeTransformsChangedListener(boost::signals2::connection c); /**@brief Check if a frame exists in the tree * @param frame_id_str The frame id in question */ bool _frameExists(const std::string& frame_id_str) const; /**@brief Fill the parent of a frame. * @param frame_id The frame id of the frame in question * @param parent The reference to the string to fill the parent * Returns true unless "NO_PARENT" */ bool _getParent(const std::string& frame_id, Time time, std::string& parent) const; /** \brief A way to get a std::vector of available frame ids */ void _getFrameStrings(std::vector<std::string>& ids) const; CompactFrameID _lookupFrameNumber(const std::string& frameid_str) const { return lookupFrameNumber(frameid_str); } CompactFrameID _lookupOrInsertFrameNumber(const std::string& frameid_str) { return lookupOrInsertFrameNumber(frameid_str); } int _getLatestCommonTime(CompactFrameID target_frame, CompactFrameID source_frame, Time& time, std::string* error_string) const { boost::mutex::scoped_lock lock(frame_mutex_); return getLatestCommonTime(target_frame, source_frame, time, error_string); } CompactFrameID _validateFrameId(const char* function_name_arg, const std::string& frame_id) const { return validateFrameId(function_name_arg, frame_id); } /**@brief Get the duration over which this transformer will cache */ Duration getCacheLength() { return cache_time_;} /** \brief Backwards compatabilityA way to see what frames have been cached * Useful for debugging */ std::string _allFramesAsDot(double current_time) const; std::string _allFramesAsDot() const; /** \brief Backwards compatabilityA way to see what frames are in a chain * Useful for debugging */ void _chainAsVector(const std::string & target_frame, Time target_time, const std::string & source_frame, Time source_time, const std::string & fixed_frame, std::vector<std::string>& output) const; private: /** \brief A way to see what frames have been cached * Useful for debugging. Use this call internally. */ std::string allFramesAsStringNoLock() const; /******************** Internal Storage ****************/ /** \brief The pointers to potential frames that the tree can be made of. * The frames will be dynamically allocated at run time when set the first time. */ typedef std::vector<TimeCacheInterfacePtr> V_TimeCacheInterface; V_TimeCacheInterface frames_; /** \brief A mutex to protect testing and allocating new frames on the above vector. */ mutable boost::mutex frame_mutex_; /** \brief A map from string frame ids to CompactFrameID */ typedef boost::unordered_map<std::string, CompactFrameID> M_StringToCompactFrameID; M_StringToCompactFrameID frameIDs_; /** \brief A map from CompactFrameID frame_id_numbers to string for debugging and output */ std::vector<std::string> frameIDs_reverse; /** \brief A map to lookup the most recent authority for a given frame */ std::map<CompactFrameID, std::string> frame_authority_; /// How long to cache transform history Duration cache_time_; typedef boost::unordered_map<TransformableCallbackHandle, TransformableCallback> M_TransformableCallback; M_TransformableCallback transformable_callbacks_; uint32_t transformable_callbacks_counter_; boost::mutex transformable_callbacks_mutex_; struct TransformableRequest { Time time; TransformableRequestHandle request_handle; TransformableCallbackHandle cb_handle; CompactFrameID target_id; CompactFrameID source_id; std::string target_string; std::string source_string; }; typedef std::vector<TransformableRequest> V_TransformableRequest; V_TransformableRequest transformable_requests_; boost::mutex transformable_requests_mutex_; uint64_t transformable_requests_counter_; struct RemoveRequestByCallback; struct RemoveRequestByID; // Backwards compatability for tf message_filter typedef boost::signals2::signal<void(void)> TransformsChangedSignal; /// Signal which is fired whenever new transform data has arrived, from the thread the data arrived in TransformsChangedSignal _transforms_changed_; /************************* Internal Functions ****************************/ /** \brief An accessor to get a frame, which will throw an exception if the frame is no there. * \param frame_number The frameID of the desired Reference Frame * * This is an internal function which will get the pointer to the frame associated with the frame id * Possible Exception: tf::LookupException */ TimeCacheInterfacePtr getFrame(CompactFrameID c_frame_id) const; TimeCacheInterfacePtr allocateFrame(CompactFrameID cfid, bool is_static); bool warnFrameId(const char* function_name_arg, const std::string& frame_id) const; CompactFrameID validateFrameId(const char* function_name_arg, const std::string& frame_id) const; /// String to number for frame lookup with dynamic allocation of new frames CompactFrameID lookupFrameNumber(const std::string& frameid_str) const; /// String to number for frame lookup with dynamic allocation of new frames CompactFrameID lookupOrInsertFrameNumber(const std::string& frameid_str); ///Number to string frame lookup may throw LookupException if number invalid const std::string& lookupFrameString(CompactFrameID frame_id_num) const; void createConnectivityErrorString(CompactFrameID source_frame, CompactFrameID target_frame, std::string* out) const; /**@brief Return the latest rostime which is common across the spanning set * zero if fails to cross */ int getLatestCommonTime(CompactFrameID target_frame, CompactFrameID source_frame, Time& time, std::string* error_string) const; template<typename F> int walkToTopParent(F& f, Time time, CompactFrameID target_id, CompactFrameID source_id, std::string* error_string) const; /**@brief Traverse the transform tree. If frame_chain is not NULL, store the traversed frame tree in vector frame_chain. * */ template<typename F> int walkToTopParent(F& f, Time time, CompactFrameID target_id, CompactFrameID source_id, std::string* error_string, std::vector<CompactFrameID> *frame_chain) const; void testTransformableRequests(); bool canTransformInternal(CompactFrameID target_id, CompactFrameID source_id, const Time& time, std::string* error_msg) const; bool canTransformNoLock(CompactFrameID target_id, CompactFrameID source_id, const Time& time, std::string* error_msg) const; //Whether it is safe to use canTransform with a timeout. (If another thread is not provided it will always timeout.) bool using_dedicated_thread_; }; }; #endif //TF2_CORE_H
0
apollo_public_repos/apollo/third_party/tf2/include
apollo_public_repos/apollo/third_party/tf2/include/tf2/time_cache.h
/* * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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. */ /** \author Tully Foote */ #ifndef TF2_TIME_CACHE_H #define TF2_TIME_CACHE_H #include "transform_storage.h" #include "tf2/time.h" #include <list> #include <sstream> // #include <ros/message_forward.h> // #include <ros/time.h> #include <boost/shared_ptr.hpp> // namespace geometry_msgs { // ROS_DECLARE_MESSAGE(TransformStamped); // } // namespace tf2 { typedef std::pair<Time, CompactFrameID> P_TimeAndFrameID; class TimeCacheInterface { public: /** \brief Access data from the cache */ virtual bool getData(Time time, TransformStorage & data_out, std::string* error_str = 0)=0; //returns false if data unavailable (should be thrown as lookup exception /** \brief Insert data into the cache */ virtual bool insertData(const TransformStorage& new_data)=0; /** @brief Clear the list of stored values */ virtual void clearList()=0; /** \brief Retrieve the parent at a specific time */ virtual CompactFrameID getParent(Time time, std::string* error_str) = 0; /** * \brief Get the latest time stored in this cache, and the parent associated with it. Returns parent = 0 if no data. */ virtual P_TimeAndFrameID getLatestTimeAndParent() = 0; /// Debugging information methods /** @brief Get the length of the stored list */ virtual unsigned int getListLength()=0; /** @brief Get the latest timestamp cached */ virtual Time getLatestTimestamp()=0; /** @brief Get the oldest timestamp cached */ virtual Time getOldestTimestamp()=0; }; typedef boost::shared_ptr<TimeCacheInterface> TimeCacheInterfacePtr; /** \brief A class to keep a sorted linked list in time * This builds and maintains a list of timestamped * data. And provides lookup functions to get * data out as a function of time. */ class TimeCache : public TimeCacheInterface { public: static const int MIN_INTERPOLATION_DISTANCE = 5; //!< Number of nano-seconds to not interpolate below. static const unsigned int MAX_LENGTH_LINKED_LIST = 1000000; //!< Maximum length of linked list, to make sure not to be able to use unlimited memory. static const int64_t DEFAULT_MAX_STORAGE_TIME = 1ULL * 1000000000LL; //!< default value of 10 seconds storage TimeCache(Duration max_storage_time = DEFAULT_MAX_STORAGE_TIME); /// Virtual methods virtual bool getData(Time time, TransformStorage & data_out, std::string* error_str = 0); virtual bool insertData(const TransformStorage& new_data); virtual void clearList(); virtual CompactFrameID getParent(Time time, std::string* error_str); virtual P_TimeAndFrameID getLatestTimeAndParent(); /// Debugging information methods virtual unsigned int getListLength(); virtual Time getLatestTimestamp(); virtual Time getOldestTimestamp(); private: typedef std::list<TransformStorage> L_TransformStorage; L_TransformStorage storage_; Duration max_storage_time_; /// A helper function for getData //Assumes storage is already locked for it inline uint8_t findClosest(TransformStorage*& one, TransformStorage*& two, Time target_time, std::string* error_str); inline void interpolate(const TransformStorage& one, const TransformStorage& two, Time time, TransformStorage& output); void pruneList(); }; class StaticCache : public TimeCacheInterface { public: /// Virtual methods virtual bool getData(Time time, TransformStorage & data_out, std::string* error_str = 0); //returns false if data unavailable (should be thrown as lookup exception virtual bool insertData(const TransformStorage& new_data); virtual void clearList(); virtual CompactFrameID getParent(Time time, std::string* error_str); virtual P_TimeAndFrameID getLatestTimeAndParent(); /// Debugging information methods virtual unsigned int getListLength(); virtual Time getLatestTimestamp(); virtual Time getOldestTimestamp(); private: TransformStorage storage_; }; } #endif // TF2_TIME_CACHE_H
0
apollo_public_repos/apollo/third_party/tf2/include
apollo_public_repos/apollo/third_party/tf2/include/tf2/convert.h
/* * Copyright (c) 2013, Open Source Robotics Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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. */ /** \author Tully Foote */ #ifndef TF2_CONVERT_H #define TF2_CONVERT_H #include <tf2/transform_datatypes.h> #include <tf2/exceptions.h> #include <geometry_msgs/transform_stamped.h> #include <tf2/impl/convert.h> #include <tf2/time.h> namespace tf2 { /**\brief The templated function expected to be able to do a transform * * This is the method which tf2 will use to try to apply a transform for any given datatype. * \param data_in The data to be transformed. * \param data_out A reference to the output data. Note this can point to data in and the method should be mutation safe. * \param transform The transform to apply to data_in to fill data_out. * * This method needs to be implemented by client library developers */ template <class T> void doTransform(const T& data_in, T& data_out, const geometry_msgs::TransformStamped& transform); /**\brief Get the timestamp from data * \param t The data input. * \return The timestamp associated with the data. The lifetime of the returned * reference is bound to the lifetime of the argument. */ template <class T> const Time& getTimestamp(const T& t); /**\brief Get the frame_id from data * \param t The data input. * \return The frame_id associated with the data. The lifetime of the returned * reference is bound to the lifetime of the argument. */ template <class T> const std::string& getFrameId(const T& t); /* An implementation for Stamped<P> datatypes */ template <class P> const Time& getTimestamp(const tf2::Stamped<P>& t) { return t.stamp_; } /* An implementation for Stamped<P> datatypes */ template <class P> const std::string& getFrameId(const tf2::Stamped<P>& t) { return t.frame_id_; } /** Function that converts from one type to a ROS message type. It has to be * implemented by each data type in tf2_* (except ROS messages) as it is * used in the "convert" function. * \param a an object of whatever type * \return the conversion as a ROS message */ template<typename A, typename B> B toMsg(const A& a); /** Function that converts from a ROS message type to another type. It has to be * implemented by each data type in tf2_* (except ROS messages) as it is used * in the "convert" function. * \param a a ROS message to convert from * \param b the object to convert to */ template<typename A, typename B> void fromMsg(const A&, B& b); /** Function that converts any type to any type (messages or not). * Matching toMsg and from Msg conversion functions need to exist. * If they don't exist or do not apply (for example, if your two * classes are ROS messages), just write a specialization of the function. * \param a an object to convert from * \param b the object to convert to */ template <class A, class B> void convert(const A& a, B& b) { //printf("In double type convert\n"); // impl::Converter<ros::message_traits::IsMessage<A>::value, ros::message_traits::IsMessage<B>::value>::convert(a, b); } template <class A> void convert(const A& a1, A& a2) { //printf("In single type convert\n"); if(&a1 != &a2) a2 = a1; } } #endif //TF2_CONVERT_H
0
apollo_public_repos/apollo/third_party/tf2/include
apollo_public_repos/apollo/third_party/tf2/include/tf2/transform_storage.h
/* * Copyright (c) 2010, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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. */ /** \author Tully Foote */ #ifndef TF2_TRANSFORM_STORAGE_H #define TF2_TRANSFORM_STORAGE_H #include <tf2/LinearMath/Vector3.h> #include <tf2/LinearMath/Quaternion.h> #include <geometry_msgs/transform_stamped.h> #include "tf2/time.h" // #include <ros/message_forward.h> // #include <ros/time.h> // #include <ros/types.h> // namespace geometry_msgs // { // ROS_DECLARE_MESSAGE(TransformStamped); // } namespace tf2 { typedef uint32_t CompactFrameID; /** \brief Storage for transforms and their parent */ class TransformStorage { public: TransformStorage(); TransformStorage(const geometry_msgs::TransformStamped& data, CompactFrameID frame_id, CompactFrameID child_frame_id); TransformStorage(const TransformStorage& rhs) { *this = rhs; } TransformStorage& operator=(const TransformStorage& rhs) { #if 01 rotation_ = rhs.rotation_; translation_ = rhs.translation_; stamp_ = rhs.stamp_; frame_id_ = rhs.frame_id_; child_frame_id_ = rhs.child_frame_id_; #endif return *this; } tf2::Quaternion rotation_; tf2::Vector3 translation_; Time stamp_; CompactFrameID frame_id_; CompactFrameID child_frame_id_; }; } #endif // TF2_TRANSFORM_STORAGE_H
0
apollo_public_repos/apollo/third_party/tf2/include/tf2
apollo_public_repos/apollo/third_party/tf2/include/tf2/impl/utils.h
// Copyright 2014 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef TF2_IMPL_UTILS_H #define TF2_IMPL_UTILS_H #include <tf2_geometry_msgs/tf2_geometry_msgs.h> #include <tf2/transform_datatypes.h> #include <tf2/LinearMath/Quaternion.h> namespace tf2 { namespace impl { /** Function needed for the generalization of toQuaternion * \param q a tf2::Quaternion * \return a copy of the same quaternion */ inline tf2::Quaternion toQuaternion(const tf2::Quaternion& q) { return q; } /** Function needed for the generalization of toQuaternion * \param q a geometry_msgs::Quaternion * \return a copy of the same quaternion as a tf2::Quaternion */ inline tf2::Quaternion toQuaternion(const geometry_msgs::Quaternion& q) { tf2::Quaternion res; fromMsg(q, res); return res; } /** Function needed for the generalization of toQuaternion * \param q a geometry_msgs::QuaternionStamped * \return a copy of the same quaternion as a tf2::Quaternion */ inline tf2::Quaternion toQuaternion(const geometry_msgs::QuaternionStamped& q) { tf2::Quaternion res; fromMsg(q.quaternion, res); return res; } /** Function needed for the generalization of toQuaternion * \param t some tf2::Stamped object * \return a copy of the same quaternion as a tf2::Quaternion */ template<typename T> tf2::Quaternion toQuaternion(const tf2::Stamped<T>& t) { geometry_msgs::QuaternionStamped q = toMsg(t); return toQuaternion(q); } /** Generic version of toQuaternion. It tries to convert the argument * to a geometry_msgs::Quaternion * \param t some object * \return a copy of the same quaternion as a tf2::Quaternion */ template<typename T> tf2::Quaternion toQuaternion(const T& t) { geometry_msgs::Quaternion q = toMsg(t); return toQuaternion(q); } /** The code below is blantantly copied from urdfdom_headers * only the normalization has been added. * It computes the Euler roll, pitch yaw from a tf2::Quaternion * It is equivalent to tf2::Matrix3x3(q).getEulerYPR(yaw, pitch, roll); * \param q a tf2::Quaternion * \param yaw the computed yaw * \param pitch the computed pitch * \param roll the computed roll */ inline void getEulerYPR(const tf2::Quaternion& q, double &yaw, double &pitch, double &roll) { double sqw; double sqx; double sqy; double sqz; sqx = q.x() * q.x(); sqy = q.y() * q.y(); sqz = q.z() * q.z(); sqw = q.w() * q.w(); // Cases derived from https://orbitalstation.wordpress.com/tag/quaternion/ double sarg = -2 * (q.x()*q.z() - q.w()*q.y()) / (sqx + sqy + sqz + sqw); /* normalization added from urdfom_headers */ if (sarg <= -0.99999) { pitch = -0.5*M_PI; roll = 0; yaw = -2 * atan2(q.y(), q.x()); } else if (sarg >= 0.99999) { pitch = 0.5*M_PI; roll = 0; yaw = 2 * atan2(q.y(), q.x()); } else { pitch = asin(sarg); roll = atan2(2 * (q.y()*q.z() + q.w()*q.x()), sqw - sqx - sqy + sqz); yaw = atan2(2 * (q.x()*q.y() + q.w()*q.z()), sqw + sqx - sqy - sqz); } }; /** The code below is a simplified version of getEulerRPY that only * returns the yaw. It is mostly useful in navigation where only yaw * matters * \param q a tf2::Quaternion * \return the computed yaw */ inline double getYaw(const tf2::Quaternion& q) { double yaw; double sqw; double sqx; double sqy; double sqz; sqx = q.x() * q.x(); sqy = q.y() * q.y(); sqz = q.z() * q.z(); sqw = q.w() * q.w(); // Cases derived from https://orbitalstation.wordpress.com/tag/quaternion/ double sarg = -2 * (q.x()*q.z() - q.w()*q.y()) / (sqx + sqy + sqz + sqw); /* normalization added from urdfom_headers */ if (sarg <= -0.99999) { yaw = -2 * atan2(q.y(), q.x()); } else if (sarg >= 0.99999) { yaw = 2 * atan2(q.y(), q.x()); } else { yaw = atan2(2 * (q.x()*q.y() + q.w()*q.z()), sqw + sqx - sqy - sqz); } return yaw; }; } } #endif //TF2_IMPL_UTILS_H
0
apollo_public_repos/apollo/third_party/tf2/include/tf2
apollo_public_repos/apollo/third_party/tf2/include/tf2/impl/convert.h
/* * Copyright (c) 2013, Open Source Robotics Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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. */ #ifndef TF2_IMPL_CONVERT_H #define TF2_IMPL_CONVERT_H namespace tf2 { namespace impl { template <bool IS_MESSAGE_A, bool IS_MESSAGE_B> class Converter { public: template<typename A, typename B> static void convert(const A& a, B& b); }; // The case where both A and B are messages should not happen: if you have two // messages that are interchangeable, well, that's against the ROS purpose: // only use one type. Worst comes to worst, specialize the original convert // function for your types. // if B == A, the templated version of convert with only one argument will be // used. // // //template <> //template <typename A, typename B> //inline void Converter<true, true>::convert(const A& a, B& b); template <> template <typename A, typename B> inline void Converter<true, false>::convert(const A& a, B& b) { fromMsg(a, b); } template <> template <typename A, typename B> inline void Converter<false, true>::convert(const A& a, B& b) { b = toMsg(a); } template <> template <typename A, typename B> inline void Converter<false, false>::convert(const A& a, B& b) { fromMsg(toMsg(a), b); } } } #endif //TF2_IMPL_CONVERT_H
0
apollo_public_repos/apollo/third_party/tf2/include/tf2
apollo_public_repos/apollo/third_party/tf2/include/tf2/LinearMath/MinMax.h
/* Copyright (c) 2003-2006 Gino van den Bergen / Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef GEN_MINMAX_H #define GEN_MINMAX_H template <class T> TF2SIMD_FORCE_INLINE const T& tf2Min(const T& a, const T& b) { return a < b ? a : b ; } template <class T> TF2SIMD_FORCE_INLINE const T& tf2Max(const T& a, const T& b) { return a > b ? a : b; } template <class T> TF2SIMD_FORCE_INLINE const T& GEN_clamped(const T& a, const T& lb, const T& ub) { return a < lb ? lb : (ub < a ? ub : a); } template <class T> TF2SIMD_FORCE_INLINE void tf2SetMin(T& a, const T& b) { if (b < a) { a = b; } } template <class T> TF2SIMD_FORCE_INLINE void tf2SetMax(T& a, const T& b) { if (a < b) { a = b; } } template <class T> TF2SIMD_FORCE_INLINE void GEN_clamp(T& a, const T& lb, const T& ub) { if (a < lb) { a = lb; } else if (ub < a) { a = ub; } } #endif
0
apollo_public_repos/apollo/third_party/tf2/include/tf2
apollo_public_repos/apollo/third_party/tf2/include/tf2/LinearMath/Matrix3x3.h
/* Copyright (c) 2003-2006 Gino van den Bergen / Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef TF2_MATRIX3x3_H #define TF2_MATRIX3x3_H #include "Vector3.h" #include "Quaternion.h" namespace tf2 { #define Matrix3x3Data Matrix3x3DoubleData /**@brief The Matrix3x3 class implements a 3x3 rotation matrix, to perform linear algebra in combination with Quaternion, Transform and Vector3. * Make sure to only include a pure orthogonal matrix without scaling. */ class Matrix3x3 { ///Data storage for the matrix, each vector is a row of the matrix Vector3 m_el[3]; public: /** @brief No initializaion constructor */ Matrix3x3 () {} // explicit Matrix3x3(const tf2Scalar *m) { setFromOpenGLSubMatrix(m); } /**@brief Constructor from Quaternion */ explicit Matrix3x3(const Quaternion& q) { setRotation(q); } /* template <typename tf2Scalar> Matrix3x3(const tf2Scalar& yaw, const tf2Scalar& pitch, const tf2Scalar& roll) { setEulerYPR(yaw, pitch, roll); } */ /** @brief Constructor with row major formatting */ Matrix3x3(const tf2Scalar& xx, const tf2Scalar& xy, const tf2Scalar& xz, const tf2Scalar& yx, const tf2Scalar& yy, const tf2Scalar& yz, const tf2Scalar& zx, const tf2Scalar& zy, const tf2Scalar& zz) { setValue(xx, xy, xz, yx, yy, yz, zx, zy, zz); } /** @brief Copy constructor */ TF2SIMD_FORCE_INLINE Matrix3x3 (const Matrix3x3& other) { m_el[0] = other.m_el[0]; m_el[1] = other.m_el[1]; m_el[2] = other.m_el[2]; } /** @brief Assignment Operator */ TF2SIMD_FORCE_INLINE Matrix3x3& operator=(const Matrix3x3& other) { m_el[0] = other.m_el[0]; m_el[1] = other.m_el[1]; m_el[2] = other.m_el[2]; return *this; } /** @brief Get a column of the matrix as a vector * @param i Column number 0 indexed */ TF2SIMD_FORCE_INLINE Vector3 getColumn(int i) const { return Vector3(m_el[0][i],m_el[1][i],m_el[2][i]); } /** @brief Get a row of the matrix as a vector * @param i Row number 0 indexed */ TF2SIMD_FORCE_INLINE const Vector3& getRow(int i) const { tf2FullAssert(0 <= i && i < 3); return m_el[i]; } /** @brief Get a mutable reference to a row of the matrix as a vector * @param i Row number 0 indexed */ TF2SIMD_FORCE_INLINE Vector3& operator[](int i) { tf2FullAssert(0 <= i && i < 3); return m_el[i]; } /** @brief Get a const reference to a row of the matrix as a vector * @param i Row number 0 indexed */ TF2SIMD_FORCE_INLINE const Vector3& operator[](int i) const { tf2FullAssert(0 <= i && i < 3); return m_el[i]; } /** @brief Multiply by the target matrix on the right * @param m Rotation matrix to be applied * Equivilant to this = this * m */ Matrix3x3& operator*=(const Matrix3x3& m); /** @brief Set from a carray of tf2Scalars * @param m A pointer to the beginning of an array of 9 tf2Scalars */ void setFromOpenGLSubMatrix(const tf2Scalar *m) { m_el[0].setValue(m[0],m[4],m[8]); m_el[1].setValue(m[1],m[5],m[9]); m_el[2].setValue(m[2],m[6],m[10]); } /** @brief Set the values of the matrix explicitly (row major) * @param xx Top left * @param xy Top Middle * @param xz Top Right * @param yx Middle Left * @param yy Middle Middle * @param yz Middle Right * @param zx Bottom Left * @param zy Bottom Middle * @param zz Bottom Right*/ void setValue(const tf2Scalar& xx, const tf2Scalar& xy, const tf2Scalar& xz, const tf2Scalar& yx, const tf2Scalar& yy, const tf2Scalar& yz, const tf2Scalar& zx, const tf2Scalar& zy, const tf2Scalar& zz) { m_el[0].setValue(xx,xy,xz); m_el[1].setValue(yx,yy,yz); m_el[2].setValue(zx,zy,zz); } /** @brief Set the matrix from a quaternion * @param q The Quaternion to match */ void setRotation(const Quaternion& q) { tf2Scalar d = q.length2(); tf2FullAssert(d != tf2Scalar(0.0)); tf2Scalar s = tf2Scalar(2.0) / d; tf2Scalar xs = q.x() * s, ys = q.y() * s, zs = q.z() * s; tf2Scalar wx = q.w() * xs, wy = q.w() * ys, wz = q.w() * zs; tf2Scalar xx = q.x() * xs, xy = q.x() * ys, xz = q.x() * zs; tf2Scalar yy = q.y() * ys, yz = q.y() * zs, zz = q.z() * zs; setValue(tf2Scalar(1.0) - (yy + zz), xy - wz, xz + wy, xy + wz, tf2Scalar(1.0) - (xx + zz), yz - wx, xz - wy, yz + wx, tf2Scalar(1.0) - (xx + yy)); } /** @brief Set the matrix from euler angles using YPR around ZYX respectively * @param yaw Yaw about Z axis * @param pitch Pitch about Y axis * @param roll Roll about X axis */ void setEulerZYX(const tf2Scalar& yaw, const tf2Scalar& pitch, const tf2Scalar& roll) __attribute__((deprecated)) { setEulerYPR(yaw, pitch, roll); } /** @brief Set the matrix from euler angles YPR around ZYX axes * @param eulerZ Yaw aboud Z axis * @param eulerY Pitch around Y axis * @param eulerX Roll about X axis * * These angles are used to produce a rotation matrix. The euler * angles are applied in ZYX order. I.e a vector is first rotated * about X then Y and then Z **/ void setEulerYPR(tf2Scalar eulerZ, tf2Scalar eulerY,tf2Scalar eulerX) { tf2Scalar ci ( tf2Cos(eulerX)); tf2Scalar cj ( tf2Cos(eulerY)); tf2Scalar ch ( tf2Cos(eulerZ)); tf2Scalar si ( tf2Sin(eulerX)); tf2Scalar sj ( tf2Sin(eulerY)); tf2Scalar sh ( tf2Sin(eulerZ)); tf2Scalar cc = ci * ch; tf2Scalar cs = ci * sh; tf2Scalar sc = si * ch; tf2Scalar ss = si * sh; setValue(cj * ch, sj * sc - cs, sj * cc + ss, cj * sh, sj * ss + cc, sj * cs - sc, -sj, cj * si, cj * ci); } /** @brief Set the matrix using RPY about XYZ fixed axes * @param roll Roll about X axis * @param pitch Pitch around Y axis * @param yaw Yaw aboud Z axis * **/ void setRPY(tf2Scalar roll, tf2Scalar pitch,tf2Scalar yaw) { setEulerYPR(yaw, pitch, roll); } /**@brief Set the matrix to the identity */ void setIdentity() { setValue(tf2Scalar(1.0), tf2Scalar(0.0), tf2Scalar(0.0), tf2Scalar(0.0), tf2Scalar(1.0), tf2Scalar(0.0), tf2Scalar(0.0), tf2Scalar(0.0), tf2Scalar(1.0)); } static const Matrix3x3& getIdentity() { static const Matrix3x3 identityMatrix(tf2Scalar(1.0), tf2Scalar(0.0), tf2Scalar(0.0), tf2Scalar(0.0), tf2Scalar(1.0), tf2Scalar(0.0), tf2Scalar(0.0), tf2Scalar(0.0), tf2Scalar(1.0)); return identityMatrix; } /**@brief Fill the values of the matrix into a 9 element array * @param m The array to be filled */ void getOpenGLSubMatrix(tf2Scalar *m) const { m[0] = tf2Scalar(m_el[0].x()); m[1] = tf2Scalar(m_el[1].x()); m[2] = tf2Scalar(m_el[2].x()); m[3] = tf2Scalar(0.0); m[4] = tf2Scalar(m_el[0].y()); m[5] = tf2Scalar(m_el[1].y()); m[6] = tf2Scalar(m_el[2].y()); m[7] = tf2Scalar(0.0); m[8] = tf2Scalar(m_el[0].z()); m[9] = tf2Scalar(m_el[1].z()); m[10] = tf2Scalar(m_el[2].z()); m[11] = tf2Scalar(0.0); } /**@brief Get the matrix represented as a quaternion * @param q The quaternion which will be set */ void getRotation(Quaternion& q) const { tf2Scalar trace = m_el[0].x() + m_el[1].y() + m_el[2].z(); tf2Scalar temp[4]; if (trace > tf2Scalar(0.0)) { tf2Scalar s = tf2Sqrt(trace + tf2Scalar(1.0)); temp[3]=(s * tf2Scalar(0.5)); s = tf2Scalar(0.5) / s; temp[0]=((m_el[2].y() - m_el[1].z()) * s); temp[1]=((m_el[0].z() - m_el[2].x()) * s); temp[2]=((m_el[1].x() - m_el[0].y()) * s); } else { int i = m_el[0].x() < m_el[1].y() ? (m_el[1].y() < m_el[2].z() ? 2 : 1) : (m_el[0].x() < m_el[2].z() ? 2 : 0); int j = (i + 1) % 3; int k = (i + 2) % 3; tf2Scalar s = tf2Sqrt(m_el[i][i] - m_el[j][j] - m_el[k][k] + tf2Scalar(1.0)); temp[i] = s * tf2Scalar(0.5); s = tf2Scalar(0.5) / s; temp[3] = (m_el[k][j] - m_el[j][k]) * s; temp[j] = (m_el[j][i] + m_el[i][j]) * s; temp[k] = (m_el[k][i] + m_el[i][k]) * s; } q.setValue(temp[0],temp[1],temp[2],temp[3]); } /**@brief Get the matrix represented as euler angles around ZYX * @param yaw Yaw around Z axis * @param pitch Pitch around Y axis * @param roll around X axis * @param solution_number Which solution of two possible solutions ( 1 or 2) are possible values*/ __attribute__((deprecated)) void getEulerZYX(tf2Scalar& yaw, tf2Scalar& pitch, tf2Scalar& roll, unsigned int solution_number = 1) const { getEulerYPR(yaw, pitch, roll, solution_number); }; /**@brief Get the matrix represented as euler angles around YXZ, roundtrip with setEulerYPR * @param yaw Yaw around Z axis * @param pitch Pitch around Y axis * @param roll around X axis */ void getEulerYPR(tf2Scalar& yaw, tf2Scalar& pitch, tf2Scalar& roll, unsigned int solution_number = 1) const { struct Euler { tf2Scalar yaw; tf2Scalar pitch; tf2Scalar roll; }; Euler euler_out; Euler euler_out2; //second solution //get the pointer to the raw data // Check that pitch is not at a singularity // Check that pitch is not at a singularity if (tf2Fabs(m_el[2].x()) >= 1) { euler_out.yaw = 0; euler_out2.yaw = 0; // From difference of angles formula tf2Scalar delta = tf2Atan2(m_el[2].y(),m_el[2].z()); if (m_el[2].x() < 0) //gimbal locked down { euler_out.pitch = TF2SIMD_PI / tf2Scalar(2.0); euler_out2.pitch = TF2SIMD_PI / tf2Scalar(2.0); euler_out.roll = delta; euler_out2.roll = delta; } else // gimbal locked up { euler_out.pitch = -TF2SIMD_PI / tf2Scalar(2.0); euler_out2.pitch = -TF2SIMD_PI / tf2Scalar(2.0); euler_out.roll = delta; euler_out2.roll = delta; } } else { euler_out.pitch = - tf2Asin(m_el[2].x()); euler_out2.pitch = TF2SIMD_PI - euler_out.pitch; euler_out.roll = tf2Atan2(m_el[2].y()/tf2Cos(euler_out.pitch), m_el[2].z()/tf2Cos(euler_out.pitch)); euler_out2.roll = tf2Atan2(m_el[2].y()/tf2Cos(euler_out2.pitch), m_el[2].z()/tf2Cos(euler_out2.pitch)); euler_out.yaw = tf2Atan2(m_el[1].x()/tf2Cos(euler_out.pitch), m_el[0].x()/tf2Cos(euler_out.pitch)); euler_out2.yaw = tf2Atan2(m_el[1].x()/tf2Cos(euler_out2.pitch), m_el[0].x()/tf2Cos(euler_out2.pitch)); } if (solution_number == 1) { yaw = euler_out.yaw; pitch = euler_out.pitch; roll = euler_out.roll; } else { yaw = euler_out2.yaw; pitch = euler_out2.pitch; roll = euler_out2.roll; } } /**@brief Get the matrix represented as roll pitch and yaw about fixed axes XYZ * @param roll around X axis * @param pitch Pitch around Y axis * @param yaw Yaw around Z axis * @param solution_number Which solution of two possible solutions ( 1 or 2) are possible values*/ void getRPY(tf2Scalar& roll, tf2Scalar& pitch, tf2Scalar& yaw, unsigned int solution_number = 1) const { getEulerYPR(yaw, pitch, roll, solution_number); } /**@brief Create a scaled copy of the matrix * @param s Scaling vector The elements of the vector will scale each column */ Matrix3x3 scaled(const Vector3& s) const { return Matrix3x3(m_el[0].x() * s.x(), m_el[0].y() * s.y(), m_el[0].z() * s.z(), m_el[1].x() * s.x(), m_el[1].y() * s.y(), m_el[1].z() * s.z(), m_el[2].x() * s.x(), m_el[2].y() * s.y(), m_el[2].z() * s.z()); } /**@brief Return the determinant of the matrix */ tf2Scalar determinant() const; /**@brief Return the adjoint of the matrix */ Matrix3x3 adjoint() const; /**@brief Return the matrix with all values non negative */ Matrix3x3 absolute() const; /**@brief Return the transpose of the matrix */ Matrix3x3 transpose() const; /**@brief Return the inverse of the matrix */ Matrix3x3 inverse() const; Matrix3x3 transposeTimes(const Matrix3x3& m) const; Matrix3x3 timesTranspose(const Matrix3x3& m) const; TF2SIMD_FORCE_INLINE tf2Scalar tdotx(const Vector3& v) const { return m_el[0].x() * v.x() + m_el[1].x() * v.y() + m_el[2].x() * v.z(); } TF2SIMD_FORCE_INLINE tf2Scalar tdoty(const Vector3& v) const { return m_el[0].y() * v.x() + m_el[1].y() * v.y() + m_el[2].y() * v.z(); } TF2SIMD_FORCE_INLINE tf2Scalar tdotz(const Vector3& v) const { return m_el[0].z() * v.x() + m_el[1].z() * v.y() + m_el[2].z() * v.z(); } /**@brief diagonalizes this matrix by the Jacobi method. * @param rot stores the rotation from the coordinate system in which the matrix is diagonal to the original * coordinate system, i.e., old_this = rot * new_this * rot^T. * @param threshold See iteration * @param iteration The iteration stops when all off-diagonal elements are less than the threshold multiplied * by the sum of the absolute values of the diagonal, or when maxSteps have been executed. * * Note that this matrix is assumed to be symmetric. */ void diagonalize(Matrix3x3& rot, tf2Scalar threshold, int maxSteps) { rot.setIdentity(); for (int step = maxSteps; step > 0; step--) { // find off-diagonal element [p][q] with largest magnitude int p = 0; int q = 1; int r = 2; tf2Scalar max = tf2Fabs(m_el[0][1]); tf2Scalar v = tf2Fabs(m_el[0][2]); if (v > max) { q = 2; r = 1; max = v; } v = tf2Fabs(m_el[1][2]); if (v > max) { p = 1; q = 2; r = 0; max = v; } tf2Scalar t = threshold * (tf2Fabs(m_el[0][0]) + tf2Fabs(m_el[1][1]) + tf2Fabs(m_el[2][2])); if (max <= t) { if (max <= TF2SIMD_EPSILON * t) { return; } step = 1; } // compute Jacobi rotation J which leads to a zero for element [p][q] tf2Scalar mpq = m_el[p][q]; tf2Scalar theta = (m_el[q][q] - m_el[p][p]) / (2 * mpq); tf2Scalar theta2 = theta * theta; tf2Scalar cos; tf2Scalar sin; if (theta2 * theta2 < tf2Scalar(10 / TF2SIMD_EPSILON)) { t = (theta >= 0) ? 1 / (theta + tf2Sqrt(1 + theta2)) : 1 / (theta - tf2Sqrt(1 + theta2)); cos = 1 / tf2Sqrt(1 + t * t); sin = cos * t; } else { // approximation for large theta-value, i.e., a nearly diagonal matrix t = 1 / (theta * (2 + tf2Scalar(0.5) / theta2)); cos = 1 - tf2Scalar(0.5) * t * t; sin = cos * t; } // apply rotation to matrix (this = J^T * this * J) m_el[p][q] = m_el[q][p] = 0; m_el[p][p] -= t * mpq; m_el[q][q] += t * mpq; tf2Scalar mrp = m_el[r][p]; tf2Scalar mrq = m_el[r][q]; m_el[r][p] = m_el[p][r] = cos * mrp - sin * mrq; m_el[r][q] = m_el[q][r] = cos * mrq + sin * mrp; // apply rotation to rot (rot = rot * J) for (int i = 0; i < 3; i++) { Vector3& row = rot[i]; mrp = row[p]; mrq = row[q]; row[p] = cos * mrp - sin * mrq; row[q] = cos * mrq + sin * mrp; } } } /**@brief Calculate the matrix cofactor * @param r1 The first row to use for calculating the cofactor * @param c1 The first column to use for calculating the cofactor * @param r1 The second row to use for calculating the cofactor * @param c1 The second column to use for calculating the cofactor * See http://en.wikipedia.org/wiki/Cofactor_(linear_algebra) for more details */ tf2Scalar cofac(int r1, int c1, int r2, int c2) const { return m_el[r1][c1] * m_el[r2][c2] - m_el[r1][c2] * m_el[r2][c1]; } void serialize(struct Matrix3x3Data& dataOut) const; void serializeFloat(struct Matrix3x3FloatData& dataOut) const; void deSerialize(const struct Matrix3x3Data& dataIn); void deSerializeFloat(const struct Matrix3x3FloatData& dataIn); void deSerializeDouble(const struct Matrix3x3DoubleData& dataIn); }; TF2SIMD_FORCE_INLINE Matrix3x3& Matrix3x3::operator*=(const Matrix3x3& m) { setValue(m.tdotx(m_el[0]), m.tdoty(m_el[0]), m.tdotz(m_el[0]), m.tdotx(m_el[1]), m.tdoty(m_el[1]), m.tdotz(m_el[1]), m.tdotx(m_el[2]), m.tdoty(m_el[2]), m.tdotz(m_el[2])); return *this; } TF2SIMD_FORCE_INLINE tf2Scalar Matrix3x3::determinant() const { return tf2Triple((*this)[0], (*this)[1], (*this)[2]); } TF2SIMD_FORCE_INLINE Matrix3x3 Matrix3x3::absolute() const { return Matrix3x3( tf2Fabs(m_el[0].x()), tf2Fabs(m_el[0].y()), tf2Fabs(m_el[0].z()), tf2Fabs(m_el[1].x()), tf2Fabs(m_el[1].y()), tf2Fabs(m_el[1].z()), tf2Fabs(m_el[2].x()), tf2Fabs(m_el[2].y()), tf2Fabs(m_el[2].z())); } TF2SIMD_FORCE_INLINE Matrix3x3 Matrix3x3::transpose() const { return Matrix3x3(m_el[0].x(), m_el[1].x(), m_el[2].x(), m_el[0].y(), m_el[1].y(), m_el[2].y(), m_el[0].z(), m_el[1].z(), m_el[2].z()); } TF2SIMD_FORCE_INLINE Matrix3x3 Matrix3x3::adjoint() const { return Matrix3x3(cofac(1, 1, 2, 2), cofac(0, 2, 2, 1), cofac(0, 1, 1, 2), cofac(1, 2, 2, 0), cofac(0, 0, 2, 2), cofac(0, 2, 1, 0), cofac(1, 0, 2, 1), cofac(0, 1, 2, 0), cofac(0, 0, 1, 1)); } TF2SIMD_FORCE_INLINE Matrix3x3 Matrix3x3::inverse() const { Vector3 co(cofac(1, 1, 2, 2), cofac(1, 2, 2, 0), cofac(1, 0, 2, 1)); tf2Scalar det = (*this)[0].dot(co); tf2FullAssert(det != tf2Scalar(0.0)); tf2Scalar s = tf2Scalar(1.0) / det; return Matrix3x3(co.x() * s, cofac(0, 2, 2, 1) * s, cofac(0, 1, 1, 2) * s, co.y() * s, cofac(0, 0, 2, 2) * s, cofac(0, 2, 1, 0) * s, co.z() * s, cofac(0, 1, 2, 0) * s, cofac(0, 0, 1, 1) * s); } TF2SIMD_FORCE_INLINE Matrix3x3 Matrix3x3::transposeTimes(const Matrix3x3& m) const { return Matrix3x3( m_el[0].x() * m[0].x() + m_el[1].x() * m[1].x() + m_el[2].x() * m[2].x(), m_el[0].x() * m[0].y() + m_el[1].x() * m[1].y() + m_el[2].x() * m[2].y(), m_el[0].x() * m[0].z() + m_el[1].x() * m[1].z() + m_el[2].x() * m[2].z(), m_el[0].y() * m[0].x() + m_el[1].y() * m[1].x() + m_el[2].y() * m[2].x(), m_el[0].y() * m[0].y() + m_el[1].y() * m[1].y() + m_el[2].y() * m[2].y(), m_el[0].y() * m[0].z() + m_el[1].y() * m[1].z() + m_el[2].y() * m[2].z(), m_el[0].z() * m[0].x() + m_el[1].z() * m[1].x() + m_el[2].z() * m[2].x(), m_el[0].z() * m[0].y() + m_el[1].z() * m[1].y() + m_el[2].z() * m[2].y(), m_el[0].z() * m[0].z() + m_el[1].z() * m[1].z() + m_el[2].z() * m[2].z()); } TF2SIMD_FORCE_INLINE Matrix3x3 Matrix3x3::timesTranspose(const Matrix3x3& m) const { return Matrix3x3( m_el[0].dot(m[0]), m_el[0].dot(m[1]), m_el[0].dot(m[2]), m_el[1].dot(m[0]), m_el[1].dot(m[1]), m_el[1].dot(m[2]), m_el[2].dot(m[0]), m_el[2].dot(m[1]), m_el[2].dot(m[2])); } TF2SIMD_FORCE_INLINE Vector3 operator*(const Matrix3x3& m, const Vector3& v) { return Vector3(m[0].dot(v), m[1].dot(v), m[2].dot(v)); } TF2SIMD_FORCE_INLINE Vector3 operator*(const Vector3& v, const Matrix3x3& m) { return Vector3(m.tdotx(v), m.tdoty(v), m.tdotz(v)); } TF2SIMD_FORCE_INLINE Matrix3x3 operator*(const Matrix3x3& m1, const Matrix3x3& m2) { return Matrix3x3( m2.tdotx( m1[0]), m2.tdoty( m1[0]), m2.tdotz( m1[0]), m2.tdotx( m1[1]), m2.tdoty( m1[1]), m2.tdotz( m1[1]), m2.tdotx( m1[2]), m2.tdoty( m1[2]), m2.tdotz( m1[2])); } /* TF2SIMD_FORCE_INLINE Matrix3x3 tf2MultTransposeLeft(const Matrix3x3& m1, const Matrix3x3& m2) { return Matrix3x3( m1[0][0] * m2[0][0] + m1[1][0] * m2[1][0] + m1[2][0] * m2[2][0], m1[0][0] * m2[0][1] + m1[1][0] * m2[1][1] + m1[2][0] * m2[2][1], m1[0][0] * m2[0][2] + m1[1][0] * m2[1][2] + m1[2][0] * m2[2][2], m1[0][1] * m2[0][0] + m1[1][1] * m2[1][0] + m1[2][1] * m2[2][0], m1[0][1] * m2[0][1] + m1[1][1] * m2[1][1] + m1[2][1] * m2[2][1], m1[0][1] * m2[0][2] + m1[1][1] * m2[1][2] + m1[2][1] * m2[2][2], m1[0][2] * m2[0][0] + m1[1][2] * m2[1][0] + m1[2][2] * m2[2][0], m1[0][2] * m2[0][1] + m1[1][2] * m2[1][1] + m1[2][2] * m2[2][1], m1[0][2] * m2[0][2] + m1[1][2] * m2[1][2] + m1[2][2] * m2[2][2]); } */ /**@brief Equality operator between two matrices * It will test all elements are equal. */ TF2SIMD_FORCE_INLINE bool operator==(const Matrix3x3& m1, const Matrix3x3& m2) { return ( m1[0][0] == m2[0][0] && m1[1][0] == m2[1][0] && m1[2][0] == m2[2][0] && m1[0][1] == m2[0][1] && m1[1][1] == m2[1][1] && m1[2][1] == m2[2][1] && m1[0][2] == m2[0][2] && m1[1][2] == m2[1][2] && m1[2][2] == m2[2][2] ); } ///for serialization struct Matrix3x3FloatData { Vector3FloatData m_el[3]; }; ///for serialization struct Matrix3x3DoubleData { Vector3DoubleData m_el[3]; }; TF2SIMD_FORCE_INLINE void Matrix3x3::serialize(struct Matrix3x3Data& dataOut) const { for (int i=0;i<3;i++) m_el[i].serialize(dataOut.m_el[i]); } TF2SIMD_FORCE_INLINE void Matrix3x3::serializeFloat(struct Matrix3x3FloatData& dataOut) const { for (int i=0;i<3;i++) m_el[i].serializeFloat(dataOut.m_el[i]); } TF2SIMD_FORCE_INLINE void Matrix3x3::deSerialize(const struct Matrix3x3Data& dataIn) { for (int i=0;i<3;i++) m_el[i].deSerialize(dataIn.m_el[i]); } TF2SIMD_FORCE_INLINE void Matrix3x3::deSerializeFloat(const struct Matrix3x3FloatData& dataIn) { for (int i=0;i<3;i++) m_el[i].deSerializeFloat(dataIn.m_el[i]); } TF2SIMD_FORCE_INLINE void Matrix3x3::deSerializeDouble(const struct Matrix3x3DoubleData& dataIn) { for (int i=0;i<3;i++) m_el[i].deSerializeDouble(dataIn.m_el[i]); } } #endif //TF2_MATRIX3x3_H
0
apollo_public_repos/apollo/third_party/tf2/include/tf2
apollo_public_repos/apollo/third_party/tf2/include/tf2/LinearMath/QuadWord.h
/* Copyright (c) 2003-2006 Gino van den Bergen / Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef TF2SIMD_QUADWORD_H #define TF2SIMD_QUADWORD_H #include "Scalar.h" #include "MinMax.h" #if defined (__CELLOS_LV2) && defined (__SPU__) #include <altivec.h> #endif namespace tf2 { /**@brief The QuadWord class is base class for Vector3 and Quaternion. * Some issues under PS3 Linux with IBM 2.1 SDK, gcc compiler prevent from using aligned quadword. */ #ifndef USE_LIBSPE2 ATTRIBUTE_ALIGNED16(class) QuadWord #else class QuadWord #endif { protected: #if defined (__SPU__) && defined (__CELLOS_LV2__) union { vec_float4 mVec128; tf2Scalar m_floats[4]; }; public: vec_float4 get128() const { return mVec128; } protected: #else //__CELLOS_LV2__ __SPU__ tf2Scalar m_floats[4]; #endif //__CELLOS_LV2__ __SPU__ public: /**@brief Return the x value */ TF2SIMD_FORCE_INLINE const tf2Scalar& getX() const { return m_floats[0]; } /**@brief Return the y value */ TF2SIMD_FORCE_INLINE const tf2Scalar& getY() const { return m_floats[1]; } /**@brief Return the z value */ TF2SIMD_FORCE_INLINE const tf2Scalar& getZ() const { return m_floats[2]; } /**@brief Set the x value */ TF2SIMD_FORCE_INLINE void setX(tf2Scalar x) { m_floats[0] = x;}; /**@brief Set the y value */ TF2SIMD_FORCE_INLINE void setY(tf2Scalar y) { m_floats[1] = y;}; /**@brief Set the z value */ TF2SIMD_FORCE_INLINE void setZ(tf2Scalar z) { m_floats[2] = z;}; /**@brief Set the w value */ TF2SIMD_FORCE_INLINE void setW(tf2Scalar w) { m_floats[3] = w;}; /**@brief Return the x value */ TF2SIMD_FORCE_INLINE const tf2Scalar& x() const { return m_floats[0]; } /**@brief Return the y value */ TF2SIMD_FORCE_INLINE const tf2Scalar& y() const { return m_floats[1]; } /**@brief Return the z value */ TF2SIMD_FORCE_INLINE const tf2Scalar& z() const { return m_floats[2]; } /**@brief Return the w value */ TF2SIMD_FORCE_INLINE const tf2Scalar& w() const { return m_floats[3]; } //TF2SIMD_FORCE_INLINE tf2Scalar& operator[](int i) { return (&m_floats[0])[i]; } //TF2SIMD_FORCE_INLINE const tf2Scalar& operator[](int i) const { return (&m_floats[0])[i]; } ///operator tf2Scalar*() replaces operator[], using implicit conversion. We added operator != and operator == to avoid pointer comparisons. TF2SIMD_FORCE_INLINE operator tf2Scalar *() { return &m_floats[0]; } TF2SIMD_FORCE_INLINE operator const tf2Scalar *() const { return &m_floats[0]; } TF2SIMD_FORCE_INLINE bool operator==(const QuadWord& other) const { return ((m_floats[3]==other.m_floats[3]) && (m_floats[2]==other.m_floats[2]) && (m_floats[1]==other.m_floats[1]) && (m_floats[0]==other.m_floats[0])); } TF2SIMD_FORCE_INLINE bool operator!=(const QuadWord& other) const { return !(*this == other); } /**@brief Set x,y,z and zero w * @param x Value of x * @param y Value of y * @param z Value of z */ TF2SIMD_FORCE_INLINE void setValue(const tf2Scalar& x, const tf2Scalar& y, const tf2Scalar& z) { m_floats[0]=x; m_floats[1]=y; m_floats[2]=z; m_floats[3] = 0.f; } /* void getValue(tf2Scalar *m) const { m[0] = m_floats[0]; m[1] = m_floats[1]; m[2] = m_floats[2]; } */ /**@brief Set the values * @param x Value of x * @param y Value of y * @param z Value of z * @param w Value of w */ TF2SIMD_FORCE_INLINE void setValue(const tf2Scalar& x, const tf2Scalar& y, const tf2Scalar& z,const tf2Scalar& w) { m_floats[0]=x; m_floats[1]=y; m_floats[2]=z; m_floats[3]=w; } /**@brief No initialization constructor */ TF2SIMD_FORCE_INLINE QuadWord() // :m_floats[0](tf2Scalar(0.)),m_floats[1](tf2Scalar(0.)),m_floats[2](tf2Scalar(0.)),m_floats[3](tf2Scalar(0.)) { } /**@brief Three argument constructor (zeros w) * @param x Value of x * @param y Value of y * @param z Value of z */ TF2SIMD_FORCE_INLINE QuadWord(const tf2Scalar& x, const tf2Scalar& y, const tf2Scalar& z) { m_floats[0] = x, m_floats[1] = y, m_floats[2] = z, m_floats[3] = 0.0f; } /**@brief Initializing constructor * @param x Value of x * @param y Value of y * @param z Value of z * @param w Value of w */ TF2SIMD_FORCE_INLINE QuadWord(const tf2Scalar& x, const tf2Scalar& y, const tf2Scalar& z,const tf2Scalar& w) { m_floats[0] = x, m_floats[1] = y, m_floats[2] = z, m_floats[3] = w; } /**@brief Set each element to the max of the current values and the values of another QuadWord * @param other The other QuadWord to compare with */ TF2SIMD_FORCE_INLINE void setMax(const QuadWord& other) { tf2SetMax(m_floats[0], other.m_floats[0]); tf2SetMax(m_floats[1], other.m_floats[1]); tf2SetMax(m_floats[2], other.m_floats[2]); tf2SetMax(m_floats[3], other.m_floats[3]); } /**@brief Set each element to the min of the current values and the values of another QuadWord * @param other The other QuadWord to compare with */ TF2SIMD_FORCE_INLINE void setMin(const QuadWord& other) { tf2SetMin(m_floats[0], other.m_floats[0]); tf2SetMin(m_floats[1], other.m_floats[1]); tf2SetMin(m_floats[2], other.m_floats[2]); tf2SetMin(m_floats[3], other.m_floats[3]); } }; } #endif //TF2SIMD_QUADWORD_H
0
apollo_public_repos/apollo/third_party/tf2/include/tf2
apollo_public_repos/apollo/third_party/tf2/include/tf2/LinearMath/Quaternion.h
/* Copyright (c) 2003-2006 Gino van den Bergen / Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef TF2_QUATERNION_H_ #define TF2_QUATERNION_H_ #include "Vector3.h" #include "QuadWord.h" namespace tf2 { /**@brief The Quaternion implements quaternion to perform linear algebra rotations in combination with Matrix3x3, Vector3 and Transform. */ class Quaternion : public QuadWord { public: /**@brief No initialization constructor */ Quaternion() {} // template <typename tf2Scalar> // explicit Quaternion(const tf2Scalar *v) : Tuple4<tf2Scalar>(v) {} /**@brief Constructor from scalars */ Quaternion(const tf2Scalar& x, const tf2Scalar& y, const tf2Scalar& z, const tf2Scalar& w) : QuadWord(x, y, z, w) {} /**@brief Axis angle Constructor * @param axis The axis which the rotation is around * @param angle The magnitude of the rotation around the angle (Radians) */ Quaternion(const Vector3& axis, const tf2Scalar& angle) { setRotation(axis, angle); } /**@brief Constructor from Euler angles * @param yaw Angle around Y unless TF2_EULER_DEFAULT_ZYX defined then Z * @param pitch Angle around X unless TF2_EULER_DEFAULT_ZYX defined then Y * @param roll Angle around Z unless TF2_EULER_DEFAULT_ZYX defined then X */ Quaternion(const tf2Scalar& yaw, const tf2Scalar& pitch, const tf2Scalar& roll) __attribute__((deprecated)) { #ifndef TF2_EULER_DEFAULT_ZYX setEuler(yaw, pitch, roll); #else setRPY(roll, pitch, yaw); #endif } /**@brief Set the rotation using axis angle notation * @param axis The axis around which to rotate * @param angle The magnitude of the rotation in Radians */ void setRotation(const Vector3& axis, const tf2Scalar& angle) { tf2Scalar d = axis.length(); tf2Assert(d != tf2Scalar(0.0)); tf2Scalar s = tf2Sin(angle * tf2Scalar(0.5)) / d; setValue(axis.x() * s, axis.y() * s, axis.z() * s, tf2Cos(angle * tf2Scalar(0.5))); } /**@brief Set the quaternion using Euler angles * @param yaw Angle around Y * @param pitch Angle around X * @param roll Angle around Z */ void setEuler(const tf2Scalar& yaw, const tf2Scalar& pitch, const tf2Scalar& roll) { tf2Scalar halfYaw = tf2Scalar(yaw) * tf2Scalar(0.5); tf2Scalar halfPitch = tf2Scalar(pitch) * tf2Scalar(0.5); tf2Scalar halfRoll = tf2Scalar(roll) * tf2Scalar(0.5); tf2Scalar cosYaw = tf2Cos(halfYaw); tf2Scalar sinYaw = tf2Sin(halfYaw); tf2Scalar cosPitch = tf2Cos(halfPitch); tf2Scalar sinPitch = tf2Sin(halfPitch); tf2Scalar cosRoll = tf2Cos(halfRoll); tf2Scalar sinRoll = tf2Sin(halfRoll); setValue(cosRoll * sinPitch * cosYaw + sinRoll * cosPitch * sinYaw, cosRoll * cosPitch * sinYaw - sinRoll * sinPitch * cosYaw, sinRoll * cosPitch * cosYaw - cosRoll * sinPitch * sinYaw, cosRoll * cosPitch * cosYaw + sinRoll * sinPitch * sinYaw); } /**@brief Set the quaternion using fixed axis RPY * @param roll Angle around X * @param pitch Angle around Y * @param yaw Angle around Z*/ void setRPY(const tf2Scalar& roll, const tf2Scalar& pitch, const tf2Scalar& yaw) { tf2Scalar halfYaw = tf2Scalar(yaw) * tf2Scalar(0.5); tf2Scalar halfPitch = tf2Scalar(pitch) * tf2Scalar(0.5); tf2Scalar halfRoll = tf2Scalar(roll) * tf2Scalar(0.5); tf2Scalar cosYaw = tf2Cos(halfYaw); tf2Scalar sinYaw = tf2Sin(halfYaw); tf2Scalar cosPitch = tf2Cos(halfPitch); tf2Scalar sinPitch = tf2Sin(halfPitch); tf2Scalar cosRoll = tf2Cos(halfRoll); tf2Scalar sinRoll = tf2Sin(halfRoll); setValue(sinRoll * cosPitch * cosYaw - cosRoll * sinPitch * sinYaw, //x cosRoll * sinPitch * cosYaw + sinRoll * cosPitch * sinYaw, //y cosRoll * cosPitch * sinYaw - sinRoll * sinPitch * cosYaw, //z cosRoll * cosPitch * cosYaw + sinRoll * sinPitch * sinYaw); //formerly yzx } /**@brief Set the quaternion using euler angles * @param yaw Angle around Z * @param pitch Angle around Y * @param roll Angle around X */ void setEulerZYX(const tf2Scalar& yaw, const tf2Scalar& pitch, const tf2Scalar& roll) __attribute__((deprecated)) { setRPY(roll, pitch, yaw); } /**@brief Add two quaternions * @param q The quaternion to add to this one */ TF2SIMD_FORCE_INLINE Quaternion& operator+=(const Quaternion& q) { m_floats[0] += q.x(); m_floats[1] += q.y(); m_floats[2] += q.z(); m_floats[3] += q.m_floats[3]; return *this; } /**@brief Sutf2ract out a quaternion * @param q The quaternion to sutf2ract from this one */ Quaternion& operator-=(const Quaternion& q) { m_floats[0] -= q.x(); m_floats[1] -= q.y(); m_floats[2] -= q.z(); m_floats[3] -= q.m_floats[3]; return *this; } /**@brief Scale this quaternion * @param s The scalar to scale by */ Quaternion& operator*=(const tf2Scalar& s) { m_floats[0] *= s; m_floats[1] *= s; m_floats[2] *= s; m_floats[3] *= s; return *this; } /**@brief Multiply this quaternion by q on the right * @param q The other quaternion * Equivilant to this = this * q */ Quaternion& operator*=(const Quaternion& q) { setValue(m_floats[3] * q.x() + m_floats[0] * q.m_floats[3] + m_floats[1] * q.z() - m_floats[2] * q.y(), m_floats[3] * q.y() + m_floats[1] * q.m_floats[3] + m_floats[2] * q.x() - m_floats[0] * q.z(), m_floats[3] * q.z() + m_floats[2] * q.m_floats[3] + m_floats[0] * q.y() - m_floats[1] * q.x(), m_floats[3] * q.m_floats[3] - m_floats[0] * q.x() - m_floats[1] * q.y() - m_floats[2] * q.z()); return *this; } /**@brief Return the dot product between this quaternion and another * @param q The other quaternion */ tf2Scalar dot(const Quaternion& q) const { return m_floats[0] * q.x() + m_floats[1] * q.y() + m_floats[2] * q.z() + m_floats[3] * q.m_floats[3]; } /**@brief Return the length squared of the quaternion */ tf2Scalar length2() const { return dot(*this); } /**@brief Return the length of the quaternion */ tf2Scalar length() const { return tf2Sqrt(length2()); } /**@brief Normalize the quaternion * Such that x^2 + y^2 + z^2 +w^2 = 1 */ Quaternion& normalize() { return *this /= length(); } /**@brief Return a scaled version of this quaternion * @param s The scale factor */ TF2SIMD_FORCE_INLINE Quaternion operator*(const tf2Scalar& s) const { return Quaternion(x() * s, y() * s, z() * s, m_floats[3] * s); } /**@brief Return an inversely scaled versionof this quaternion * @param s The inverse scale factor */ Quaternion operator/(const tf2Scalar& s) const { tf2Assert(s != tf2Scalar(0.0)); return *this * (tf2Scalar(1.0) / s); } /**@brief Inversely scale this quaternion * @param s The scale factor */ Quaternion& operator/=(const tf2Scalar& s) { tf2Assert(s != tf2Scalar(0.0)); return *this *= tf2Scalar(1.0) / s; } /**@brief Return a normalized version of this quaternion */ Quaternion normalized() const { return *this / length(); } /**@brief Return the ***half*** angle between this quaternion and the other * @param q The other quaternion */ tf2Scalar angle(const Quaternion& q) const { tf2Scalar s = tf2Sqrt(length2() * q.length2()); tf2Assert(s != tf2Scalar(0.0)); return tf2Acos(dot(q) / s); } /**@brief Return the angle between this quaternion and the other along the shortest path * @param q The other quaternion */ tf2Scalar angleShortestPath(const Quaternion& q) const { tf2Scalar s = tf2Sqrt(length2() * q.length2()); tf2Assert(s != tf2Scalar(0.0)); if (dot(q) < 0) // Take care of long angle case see http://en.wikipedia.org/wiki/Slerp return tf2Acos(dot(-q) / s) * tf2Scalar(2.0); else return tf2Acos(dot(q) / s) * tf2Scalar(2.0); } /**@brief Return the angle [0, 2Pi] of rotation represented by this quaternion */ tf2Scalar getAngle() const { tf2Scalar s = tf2Scalar(2.) * tf2Acos(m_floats[3]); return s; } /**@brief Return the angle [0, Pi] of rotation represented by this quaternion along the shortest path */ tf2Scalar getAngleShortestPath() const { tf2Scalar s; if (m_floats[3] >= 0) s = tf2Scalar(2.) * tf2Acos(m_floats[3]); else s = tf2Scalar(2.) * tf2Acos(-m_floats[3]); return s; } /**@brief Return the axis of the rotation represented by this quaternion */ Vector3 getAxis() const { tf2Scalar s_squared = tf2Scalar(1.) - tf2Pow(m_floats[3], tf2Scalar(2.)); if (s_squared < tf2Scalar(10.) * TF2SIMD_EPSILON) //Check for divide by zero return Vector3(1.0, 0.0, 0.0); // Arbitrary tf2Scalar s = tf2Sqrt(s_squared); return Vector3(m_floats[0] / s, m_floats[1] / s, m_floats[2] / s); } /**@brief Return the inverse of this quaternion */ Quaternion inverse() const { return Quaternion(-m_floats[0], -m_floats[1], -m_floats[2], m_floats[3]); } /**@brief Return the sum of this quaternion and the other * @param q2 The other quaternion */ TF2SIMD_FORCE_INLINE Quaternion operator+(const Quaternion& q2) const { const Quaternion& q1 = *this; return Quaternion(q1.x() + q2.x(), q1.y() + q2.y(), q1.z() + q2.z(), q1.m_floats[3] + q2.m_floats[3]); } /**@brief Return the difference between this quaternion and the other * @param q2 The other quaternion */ TF2SIMD_FORCE_INLINE Quaternion operator-(const Quaternion& q2) const { const Quaternion& q1 = *this; return Quaternion(q1.x() - q2.x(), q1.y() - q2.y(), q1.z() - q2.z(), q1.m_floats[3] - q2.m_floats[3]); } /**@brief Return the negative of this quaternion * This simply negates each element */ TF2SIMD_FORCE_INLINE Quaternion operator-() const { const Quaternion& q2 = *this; return Quaternion( - q2.x(), - q2.y(), - q2.z(), - q2.m_floats[3]); } /**@todo document this and it's use */ TF2SIMD_FORCE_INLINE Quaternion farthest( const Quaternion& qd) const { Quaternion diff,sum; diff = *this - qd; sum = *this + qd; if( diff.dot(diff) > sum.dot(sum) ) return qd; return (-qd); } /**@todo document this and it's use */ TF2SIMD_FORCE_INLINE Quaternion nearest( const Quaternion& qd) const { Quaternion diff,sum; diff = *this - qd; sum = *this + qd; if( diff.dot(diff) < sum.dot(sum) ) return qd; return (-qd); } /**@brief Return the quaternion which is the result of Spherical Linear Interpolation between this and the other quaternion * @param q The other quaternion to interpolate with * @param t The ratio between this and q to interpolate. If t = 0 the result is this, if t=1 the result is q. * Slerp interpolates assuming constant velocity. */ Quaternion slerp(const Quaternion& q, const tf2Scalar& t) const { tf2Scalar theta = angleShortestPath(q) / tf2Scalar(2.0); if (theta != tf2Scalar(0.0)) { tf2Scalar d = tf2Scalar(1.0) / tf2Sin(theta); tf2Scalar s0 = tf2Sin((tf2Scalar(1.0) - t) * theta); tf2Scalar s1 = tf2Sin(t * theta); if (dot(q) < 0) // Take care of long angle case see http://en.wikipedia.org/wiki/Slerp return Quaternion((m_floats[0] * s0 + -q.x() * s1) * d, (m_floats[1] * s0 + -q.y() * s1) * d, (m_floats[2] * s0 + -q.z() * s1) * d, (m_floats[3] * s0 + -q.m_floats[3] * s1) * d); else return Quaternion((m_floats[0] * s0 + q.x() * s1) * d, (m_floats[1] * s0 + q.y() * s1) * d, (m_floats[2] * s0 + q.z() * s1) * d, (m_floats[3] * s0 + q.m_floats[3] * s1) * d); } else { return *this; } } static const Quaternion& getIdentity() { static const Quaternion identityQuat(tf2Scalar(0.),tf2Scalar(0.),tf2Scalar(0.),tf2Scalar(1.)); return identityQuat; } TF2SIMD_FORCE_INLINE const tf2Scalar& getW() const { return m_floats[3]; } }; /**@brief Return the negative of a quaternion */ TF2SIMD_FORCE_INLINE Quaternion operator-(const Quaternion& q) { return Quaternion(-q.x(), -q.y(), -q.z(), -q.w()); } /**@brief Return the product of two quaternions */ TF2SIMD_FORCE_INLINE Quaternion operator*(const Quaternion& q1, const Quaternion& q2) { return Quaternion(q1.w() * q2.x() + q1.x() * q2.w() + q1.y() * q2.z() - q1.z() * q2.y(), q1.w() * q2.y() + q1.y() * q2.w() + q1.z() * q2.x() - q1.x() * q2.z(), q1.w() * q2.z() + q1.z() * q2.w() + q1.x() * q2.y() - q1.y() * q2.x(), q1.w() * q2.w() - q1.x() * q2.x() - q1.y() * q2.y() - q1.z() * q2.z()); } TF2SIMD_FORCE_INLINE Quaternion operator*(const Quaternion& q, const Vector3& w) { return Quaternion( q.w() * w.x() + q.y() * w.z() - q.z() * w.y(), q.w() * w.y() + q.z() * w.x() - q.x() * w.z(), q.w() * w.z() + q.x() * w.y() - q.y() * w.x(), -q.x() * w.x() - q.y() * w.y() - q.z() * w.z()); } TF2SIMD_FORCE_INLINE Quaternion operator*(const Vector3& w, const Quaternion& q) { return Quaternion( w.x() * q.w() + w.y() * q.z() - w.z() * q.y(), w.y() * q.w() + w.z() * q.x() - w.x() * q.z(), w.z() * q.w() + w.x() * q.y() - w.y() * q.x(), -w.x() * q.x() - w.y() * q.y() - w.z() * q.z()); } /**@brief Calculate the dot product between two quaternions */ TF2SIMD_FORCE_INLINE tf2Scalar dot(const Quaternion& q1, const Quaternion& q2) { return q1.dot(q2); } /**@brief Return the length of a quaternion */ TF2SIMD_FORCE_INLINE tf2Scalar length(const Quaternion& q) { return q.length(); } /**@brief Return the ***half*** angle between two quaternions*/ TF2SIMD_FORCE_INLINE tf2Scalar angle(const Quaternion& q1, const Quaternion& q2) { return q1.angle(q2); } /**@brief Return the shortest angle between two quaternions*/ TF2SIMD_FORCE_INLINE tf2Scalar angleShortestPath(const Quaternion& q1, const Quaternion& q2) { return q1.angleShortestPath(q2); } /**@brief Return the inverse of a quaternion*/ TF2SIMD_FORCE_INLINE Quaternion inverse(const Quaternion& q) { return q.inverse(); } /**@brief Return the result of spherical linear interpolation betwen two quaternions * @param q1 The first quaternion * @param q2 The second quaternion * @param t The ration between q1 and q2. t = 0 return q1, t=1 returns q2 * Slerp assumes constant velocity between positions. */ TF2SIMD_FORCE_INLINE Quaternion slerp(const Quaternion& q1, const Quaternion& q2, const tf2Scalar& t) { return q1.slerp(q2, t); } TF2SIMD_FORCE_INLINE Vector3 quatRotate(const Quaternion& rotation, const Vector3& v) { Quaternion q = rotation * v; q *= rotation.inverse(); return Vector3(q.getX(),q.getY(),q.getZ()); } TF2SIMD_FORCE_INLINE Quaternion shortestArcQuat(const Vector3& v0, const Vector3& v1) // Game Programming Gems 2.10. make sure v0,v1 are normalized { Vector3 c = v0.cross(v1); tf2Scalar d = v0.dot(v1); if (d < -1.0 + TF2SIMD_EPSILON) { Vector3 n,unused; tf2PlaneSpace1(v0,n,unused); return Quaternion(n.x(),n.y(),n.z(),0.0f); // just pick any vector that is orthogonal to v0 } tf2Scalar s = tf2Sqrt((1.0f + d) * 2.0f); tf2Scalar rs = 1.0f / s; return Quaternion(c.getX()*rs,c.getY()*rs,c.getZ()*rs,s * 0.5f); } TF2SIMD_FORCE_INLINE Quaternion shortestArcQuatNormalize2(Vector3& v0,Vector3& v1) { v0.normalize(); v1.normalize(); return shortestArcQuat(v0,v1); } } #endif
0
apollo_public_repos/apollo/third_party/tf2/include/tf2
apollo_public_repos/apollo/third_party/tf2/include/tf2/LinearMath/Scalar.h
/* Copyright (c) 2003-2009 Erwin Coumans http://bullet.googlecode.com This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef TF2_SCALAR_H #define TF2_SCALAR_H #ifdef TF2_MANAGED_CODE //Aligned data types not supported in managed code #pragma unmanaged #endif #include <math.h> #include <stdlib.h>//size_t for MSVC 6.0 #include <cstdlib> #include <cfloat> #include <float.h> #if defined(DEBUG) || defined (_DEBUG) #define TF2_DEBUG #endif #ifdef _WIN32 #if defined(__MINGW32__) || defined(__CYGWIN__) || (defined (_MSC_VER) && _MSC_VER < 1300) #define TF2SIMD_FORCE_INLINE inline #define ATTRIBUTE_ALIGNED16(a) a #define ATTRIBUTE_ALIGNED64(a) a #define ATTRIBUTE_ALIGNED128(a) a #else //#define TF2_HAS_ALIGNED_ALLOCATOR #pragma warning(disable : 4324) // disable padding warning // #pragma warning(disable:4530) // Disable the exception disable but used in MSCV Stl warning. // #pragma warning(disable:4996) //Turn off warnings about deprecated C routines // #pragma warning(disable:4786) // Disable the "debug name too long" warning #define TF2SIMD_FORCE_INLINE __forceinline #define ATTRIBUTE_ALIGNED16(a) __declspec(align(16)) a #define ATTRIBUTE_ALIGNED64(a) __declspec(align(64)) a #define ATTRIBUTE_ALIGNED128(a) __declspec (align(128)) a #ifdef _XBOX #define TF2_USE_VMX128 #include <ppcintrinsics.h> #define TF2_HAVE_NATIVE_FSEL #define tf2Fsel(a,b,c) __fsel((a),(b),(c)) #else #endif//_XBOX #endif //__MINGW32__ #include <assert.h> #ifdef TF2_DEBUG #define tf2Assert assert #else #define tf2Assert(x) #endif //tf2FullAssert is optional, slows down a lot #define tf2FullAssert(x) #define tf2Likely(_c) _c #define tf2Unlikely(_c) _c #else #if defined (__CELLOS_LV2__) #define TF2SIMD_FORCE_INLINE inline #define ATTRIBUTE_ALIGNED16(a) a __attribute__ ((aligned (16))) #define ATTRIBUTE_ALIGNED64(a) a __attribute__ ((aligned (64))) #define ATTRIBUTE_ALIGNED128(a) a __attribute__ ((aligned (128))) #ifndef assert #include <assert.h> #endif #ifdef TF2_DEBUG #define tf2Assert assert #else #define tf2Assert(x) #endif //tf2FullAssert is optional, slows down a lot #define tf2FullAssert(x) #define tf2Likely(_c) _c #define tf2Unlikely(_c) _c #else #ifdef USE_LIBSPE2 #define TF2SIMD_FORCE_INLINE __inline #define ATTRIBUTE_ALIGNED16(a) a __attribute__ ((aligned (16))) #define ATTRIBUTE_ALIGNED64(a) a __attribute__ ((aligned (64))) #define ATTRIBUTE_ALIGNED128(a) a __attribute__ ((aligned (128))) #ifndef assert #include <assert.h> #endif #ifdef TF2_DEBUG #define tf2Assert assert #else #define tf2Assert(x) #endif //tf2FullAssert is optional, slows down a lot #define tf2FullAssert(x) #define tf2Likely(_c) __builtin_expect((_c), 1) #define tf2Unlikely(_c) __builtin_expect((_c), 0) #else //non-windows systems #define TF2SIMD_FORCE_INLINE inline ///@todo: check out alignment methods for other platforms/compilers ///#define ATTRIBUTE_ALIGNED16(a) a __attribute__ ((aligned (16))) ///#define ATTRIBUTE_ALIGNED64(a) a __attribute__ ((aligned (64))) ///#define ATTRIBUTE_ALIGNED128(a) a __attribute__ ((aligned (128))) #define ATTRIBUTE_ALIGNED16(a) a #define ATTRIBUTE_ALIGNED64(a) a #define ATTRIBUTE_ALIGNED128(a) a #ifndef assert #include <assert.h> #endif #if defined(DEBUG) || defined (_DEBUG) #define tf2Assert assert #else #define tf2Assert(x) #endif //tf2FullAssert is optional, slows down a lot #define tf2FullAssert(x) #define tf2Likely(_c) _c #define tf2Unlikely(_c) _c #endif // LIBSPE2 #endif //__CELLOS_LV2__ #endif ///The tf2Scalar type abstracts floating point numbers, to easily switch between double and single floating point precision. typedef double tf2Scalar; //this number could be bigger in double precision #define TF2_LARGE_FLOAT 1e30 #define TF2_DECLARE_ALIGNED_ALLOCATOR() \ TF2SIMD_FORCE_INLINE void* operator new(size_t sizeInBytes) { return tf2AlignedAlloc(sizeInBytes,16); } \ TF2SIMD_FORCE_INLINE void operator delete(void* ptr) { tf2AlignedFree(ptr); } \ TF2SIMD_FORCE_INLINE void* operator new(size_t, void* ptr) { return ptr; } \ TF2SIMD_FORCE_INLINE void operator delete(void*, void*) { } \ TF2SIMD_FORCE_INLINE void* operator new[](size_t sizeInBytes) { return tf2AlignedAlloc(sizeInBytes,16); } \ TF2SIMD_FORCE_INLINE void operator delete[](void* ptr) { tf2AlignedFree(ptr); } \ TF2SIMD_FORCE_INLINE void* operator new[](size_t, void* ptr) { return ptr; } \ TF2SIMD_FORCE_INLINE void operator delete[](void*, void*) { } \ TF2SIMD_FORCE_INLINE tf2Scalar tf2Sqrt(tf2Scalar x) { return sqrt(x); } TF2SIMD_FORCE_INLINE tf2Scalar tf2Fabs(tf2Scalar x) { return fabs(x); } TF2SIMD_FORCE_INLINE tf2Scalar tf2Cos(tf2Scalar x) { return cos(x); } TF2SIMD_FORCE_INLINE tf2Scalar tf2Sin(tf2Scalar x) { return sin(x); } TF2SIMD_FORCE_INLINE tf2Scalar tf2Tan(tf2Scalar x) { return tan(x); } TF2SIMD_FORCE_INLINE tf2Scalar tf2Acos(tf2Scalar x) { if (x<tf2Scalar(-1)) x=tf2Scalar(-1); if (x>tf2Scalar(1)) x=tf2Scalar(1); return acos(x); } TF2SIMD_FORCE_INLINE tf2Scalar tf2Asin(tf2Scalar x) { if (x<tf2Scalar(-1)) x=tf2Scalar(-1); if (x>tf2Scalar(1)) x=tf2Scalar(1); return asin(x); } TF2SIMD_FORCE_INLINE tf2Scalar tf2Atan(tf2Scalar x) { return atan(x); } TF2SIMD_FORCE_INLINE tf2Scalar tf2Atan2(tf2Scalar x, tf2Scalar y) { return atan2(x, y); } TF2SIMD_FORCE_INLINE tf2Scalar tf2Exp(tf2Scalar x) { return exp(x); } TF2SIMD_FORCE_INLINE tf2Scalar tf2Log(tf2Scalar x) { return log(x); } TF2SIMD_FORCE_INLINE tf2Scalar tf2Pow(tf2Scalar x,tf2Scalar y) { return pow(x,y); } TF2SIMD_FORCE_INLINE tf2Scalar tf2Fmod(tf2Scalar x,tf2Scalar y) { return fmod(x,y); } #define TF2SIMD_2_PI tf2Scalar(6.283185307179586232) #define TF2SIMD_PI (TF2SIMD_2_PI * tf2Scalar(0.5)) #define TF2SIMD_HALF_PI (TF2SIMD_2_PI * tf2Scalar(0.25)) #define TF2SIMD_RADS_PER_DEG (TF2SIMD_2_PI / tf2Scalar(360.0)) #define TF2SIMD_DEGS_PER_RAD (tf2Scalar(360.0) / TF2SIMD_2_PI) #define TF2SIMDSQRT12 tf2Scalar(0.7071067811865475244008443621048490) #define tf2RecipSqrt(x) ((tf2Scalar)(tf2Scalar(1.0)/tf2Sqrt(tf2Scalar(x)))) /* reciprocal square root */ #define TF2SIMD_EPSILON DBL_EPSILON #define TF2SIMD_INFINITY DBL_MAX TF2SIMD_FORCE_INLINE tf2Scalar tf2Atan2Fast(tf2Scalar y, tf2Scalar x) { tf2Scalar coeff_1 = TF2SIMD_PI / 4.0f; tf2Scalar coeff_2 = 3.0f * coeff_1; tf2Scalar abs_y = tf2Fabs(y); tf2Scalar angle; if (x >= 0.0f) { tf2Scalar r = (x - abs_y) / (x + abs_y); angle = coeff_1 - coeff_1 * r; } else { tf2Scalar r = (x + abs_y) / (abs_y - x); angle = coeff_2 - coeff_1 * r; } return (y < 0.0f) ? -angle : angle; } TF2SIMD_FORCE_INLINE bool tf2FuzzyZero(tf2Scalar x) { return tf2Fabs(x) < TF2SIMD_EPSILON; } TF2SIMD_FORCE_INLINE bool tf2Equal(tf2Scalar a, tf2Scalar eps) { return (((a) <= eps) && !((a) < -eps)); } TF2SIMD_FORCE_INLINE bool tf2GreaterEqual (tf2Scalar a, tf2Scalar eps) { return (!((a) <= eps)); } TF2SIMD_FORCE_INLINE int tf2IsNegative(tf2Scalar x) { return x < tf2Scalar(0.0) ? 1 : 0; } TF2SIMD_FORCE_INLINE tf2Scalar tf2Radians(tf2Scalar x) { return x * TF2SIMD_RADS_PER_DEG; } TF2SIMD_FORCE_INLINE tf2Scalar tf2Degrees(tf2Scalar x) { return x * TF2SIMD_DEGS_PER_RAD; } #define TF2_DECLARE_HANDLE(name) typedef struct name##__ { int unused; } *name #ifndef tf2Fsel TF2SIMD_FORCE_INLINE tf2Scalar tf2Fsel(tf2Scalar a, tf2Scalar b, tf2Scalar c) { return a >= 0 ? b : c; } #endif #define tf2Fsels(a,b,c) (tf2Scalar)tf2Fsel(a,b,c) TF2SIMD_FORCE_INLINE bool tf2MachineIsLittleEndian() { long int i = 1; const char *p = (const char *) &i; if (p[0] == 1) // Lowest address contains the least significant byte return true; else return false; } ///tf2Select avoids branches, which makes performance much better for consoles like Playstation 3 and XBox 360 ///Thanks Phil Knight. See also http://www.cellperformance.com/articles/2006/04/more_techniques_for_eliminatin_1.html TF2SIMD_FORCE_INLINE unsigned tf2Select(unsigned condition, unsigned valueIfConditionNonZero, unsigned valueIfConditionZero) { // Set testNz to 0xFFFFFFFF if condition is nonzero, 0x00000000 if condition is zero // Rely on positive value or'ed with its negative having sign bit on // and zero value or'ed with its negative (which is still zero) having sign bit off // Use arithmetic shift right, shifting the sign bit through all 32 bits unsigned testNz = (unsigned)(((int)condition | -(int)condition) >> 31); unsigned testEqz = ~testNz; return ((valueIfConditionNonZero & testNz) | (valueIfConditionZero & testEqz)); } TF2SIMD_FORCE_INLINE int tf2Select(unsigned condition, int valueIfConditionNonZero, int valueIfConditionZero) { unsigned testNz = (unsigned)(((int)condition | -(int)condition) >> 31); unsigned testEqz = ~testNz; return static_cast<int>((valueIfConditionNonZero & testNz) | (valueIfConditionZero & testEqz)); } TF2SIMD_FORCE_INLINE float tf2Select(unsigned condition, float valueIfConditionNonZero, float valueIfConditionZero) { #ifdef TF2_HAVE_NATIVE_FSEL return (float)tf2Fsel((tf2Scalar)condition - tf2Scalar(1.0f), valueIfConditionNonZero, valueIfConditionZero); #else return (condition != 0) ? valueIfConditionNonZero : valueIfConditionZero; #endif } template<typename T> TF2SIMD_FORCE_INLINE void tf2Swap(T& a, T& b) { T tmp = a; a = b; b = tmp; } //PCK: endian swapping functions TF2SIMD_FORCE_INLINE unsigned tf2SwapEndian(unsigned val) { return (((val & 0xff000000) >> 24) | ((val & 0x00ff0000) >> 8) | ((val & 0x0000ff00) << 8) | ((val & 0x000000ff) << 24)); } TF2SIMD_FORCE_INLINE unsigned short tf2SwapEndian(unsigned short val) { return static_cast<unsigned short>(((val & 0xff00) >> 8) | ((val & 0x00ff) << 8)); } TF2SIMD_FORCE_INLINE unsigned tf2SwapEndian(int val) { return tf2SwapEndian((unsigned)val); } TF2SIMD_FORCE_INLINE unsigned short tf2SwapEndian(short val) { return tf2SwapEndian((unsigned short) val); } ///tf2SwapFloat uses using char pointers to swap the endianness ////tf2SwapFloat/tf2SwapDouble will NOT return a float, because the machine might 'correct' invalid floating point values ///Not all values of sign/exponent/mantissa are valid floating point numbers according to IEEE 754. ///When a floating point unit is faced with an invalid value, it may actually change the value, or worse, throw an exception. ///In most systems, running user mode code, you wouldn't get an exception, but instead the hardware/os/runtime will 'fix' the number for you. ///so instead of returning a float/double, we return integer/long long integer TF2SIMD_FORCE_INLINE unsigned int tf2SwapEndianFloat(float d) { unsigned int a = 0; unsigned char *dst = (unsigned char *)&a; unsigned char *src = (unsigned char *)&d; dst[0] = src[3]; dst[1] = src[2]; dst[2] = src[1]; dst[3] = src[0]; return a; } // unswap using char pointers TF2SIMD_FORCE_INLINE float tf2UnswapEndianFloat(unsigned int a) { float d = 0.0f; unsigned char *src = (unsigned char *)&a; unsigned char *dst = (unsigned char *)&d; dst[0] = src[3]; dst[1] = src[2]; dst[2] = src[1]; dst[3] = src[0]; return d; } // swap using char pointers TF2SIMD_FORCE_INLINE void tf2SwapEndianDouble(double d, unsigned char* dst) { unsigned char *src = (unsigned char *)&d; dst[0] = src[7]; dst[1] = src[6]; dst[2] = src[5]; dst[3] = src[4]; dst[4] = src[3]; dst[5] = src[2]; dst[6] = src[1]; dst[7] = src[0]; } // unswap using char pointers TF2SIMD_FORCE_INLINE double tf2UnswapEndianDouble(const unsigned char *src) { double d = 0.0; unsigned char *dst = (unsigned char *)&d; dst[0] = src[7]; dst[1] = src[6]; dst[2] = src[5]; dst[3] = src[4]; dst[4] = src[3]; dst[5] = src[2]; dst[6] = src[1]; dst[7] = src[0]; return d; } // returns normalized value in range [-TF2SIMD_PI, TF2SIMD_PI] TF2SIMD_FORCE_INLINE tf2Scalar tf2NormalizeAngle(tf2Scalar angleInRadians) { angleInRadians = tf2Fmod(angleInRadians, TF2SIMD_2_PI); if(angleInRadians < -TF2SIMD_PI) { return angleInRadians + TF2SIMD_2_PI; } else if(angleInRadians > TF2SIMD_PI) { return angleInRadians - TF2SIMD_2_PI; } else { return angleInRadians; } } ///rudimentary class to provide type info struct tf2TypedObject { tf2TypedObject(int objectType) :m_objectType(objectType) { } int m_objectType; inline int getObjectType() const { return m_objectType; } }; #endif //TF2SIMD___SCALAR_H
0
apollo_public_repos/apollo/third_party/tf2/include/tf2
apollo_public_repos/apollo/third_party/tf2/include/tf2/LinearMath/Transform.h
/* Copyright (c) 2003-2006 Gino van den Bergen / Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef tf2_Transform_H #define tf2_Transform_H #include "Matrix3x3.h" namespace tf2 { #define TransformData TransformDoubleData /**@brief The Transform class supports rigid transforms with only translation and rotation and no scaling/shear. *It can be used in combination with Vector3, Quaternion and Matrix3x3 linear algebra classes. */ class Transform { ///Storage for the rotation Matrix3x3 m_basis; ///Storage for the translation Vector3 m_origin; public: /**@brief No initialization constructor */ Transform() {} /**@brief Constructor from Quaternion (optional Vector3 ) * @param q Rotation from quaternion * @param c Translation from Vector (default 0,0,0) */ explicit TF2SIMD_FORCE_INLINE Transform(const Quaternion& q, const Vector3& c = Vector3(tf2Scalar(0), tf2Scalar(0), tf2Scalar(0))) : m_basis(q), m_origin(c) {} /**@brief Constructor from Matrix3x3 (optional Vector3) * @param b Rotation from Matrix * @param c Translation from Vector default (0,0,0)*/ explicit TF2SIMD_FORCE_INLINE Transform(const Matrix3x3& b, const Vector3& c = Vector3(tf2Scalar(0), tf2Scalar(0), tf2Scalar(0))) : m_basis(b), m_origin(c) {} /**@brief Copy constructor */ TF2SIMD_FORCE_INLINE Transform (const Transform& other) : m_basis(other.m_basis), m_origin(other.m_origin) { } /**@brief Assignment Operator */ TF2SIMD_FORCE_INLINE Transform& operator=(const Transform& other) { m_basis = other.m_basis; m_origin = other.m_origin; return *this; } /**@brief Set the current transform as the value of the product of two transforms * @param t1 Transform 1 * @param t2 Transform 2 * This = Transform1 * Transform2 */ TF2SIMD_FORCE_INLINE void mult(const Transform& t1, const Transform& t2) { m_basis = t1.m_basis * t2.m_basis; m_origin = t1(t2.m_origin); } /* void multInverseLeft(const Transform& t1, const Transform& t2) { Vector3 v = t2.m_origin - t1.m_origin; m_basis = tf2MultTransposeLeft(t1.m_basis, t2.m_basis); m_origin = v * t1.m_basis; } */ /**@brief Return the transform of the vector */ TF2SIMD_FORCE_INLINE Vector3 operator()(const Vector3& x) const { return Vector3(m_basis[0].dot(x) + m_origin.x(), m_basis[1].dot(x) + m_origin.y(), m_basis[2].dot(x) + m_origin.z()); } /**@brief Return the transform of the vector */ TF2SIMD_FORCE_INLINE Vector3 operator*(const Vector3& x) const { return (*this)(x); } /**@brief Return the transform of the Quaternion */ TF2SIMD_FORCE_INLINE Quaternion operator*(const Quaternion& q) const { return getRotation() * q; } /**@brief Return the basis matrix for the rotation */ TF2SIMD_FORCE_INLINE Matrix3x3& getBasis() { return m_basis; } /**@brief Return the basis matrix for the rotation */ TF2SIMD_FORCE_INLINE const Matrix3x3& getBasis() const { return m_basis; } /**@brief Return the origin vector translation */ TF2SIMD_FORCE_INLINE Vector3& getOrigin() { return m_origin; } /**@brief Return the origin vector translation */ TF2SIMD_FORCE_INLINE const Vector3& getOrigin() const { return m_origin; } /**@brief Return a quaternion representing the rotation */ Quaternion getRotation() const { Quaternion q; m_basis.getRotation(q); return q; } /**@brief Set from an array * @param m A pointer to a 15 element array (12 rotation(row major padded on the right by 1), and 3 translation */ void setFromOpenGLMatrix(const tf2Scalar *m) { m_basis.setFromOpenGLSubMatrix(m); m_origin.setValue(m[12],m[13],m[14]); } /**@brief Fill an array representation * @param m A pointer to a 15 element array (12 rotation(row major padded on the right by 1), and 3 translation */ void getOpenGLMatrix(tf2Scalar *m) const { m_basis.getOpenGLSubMatrix(m); m[12] = m_origin.x(); m[13] = m_origin.y(); m[14] = m_origin.z(); m[15] = tf2Scalar(1.0); } /**@brief Set the translational element * @param origin The vector to set the translation to */ TF2SIMD_FORCE_INLINE void setOrigin(const Vector3& origin) { m_origin = origin; } TF2SIMD_FORCE_INLINE Vector3 invXform(const Vector3& inVec) const; /**@brief Set the rotational element by Matrix3x3 */ TF2SIMD_FORCE_INLINE void setBasis(const Matrix3x3& basis) { m_basis = basis; } /**@brief Set the rotational element by Quaternion */ TF2SIMD_FORCE_INLINE void setRotation(const Quaternion& q) { m_basis.setRotation(q); } /**@brief Set this transformation to the identity */ void setIdentity() { m_basis.setIdentity(); m_origin.setValue(tf2Scalar(0.0), tf2Scalar(0.0), tf2Scalar(0.0)); } /**@brief Multiply this Transform by another(this = this * another) * @param t The other transform */ Transform& operator*=(const Transform& t) { m_origin += m_basis * t.m_origin; m_basis *= t.m_basis; return *this; } /**@brief Return the inverse of this transform */ Transform inverse() const { Matrix3x3 inv = m_basis.transpose(); return Transform(inv, inv * -m_origin); } /**@brief Return the inverse of this transform times the other transform * @param t The other transform * return this.inverse() * the other */ Transform inverseTimes(const Transform& t) const; /**@brief Return the product of this transform and the other */ Transform operator*(const Transform& t) const; /**@brief Return an identity transform */ static const Transform& getIdentity() { static const Transform identityTransform(Matrix3x3::getIdentity()); return identityTransform; } void serialize(struct TransformData& dataOut) const; void serializeFloat(struct TransformFloatData& dataOut) const; void deSerialize(const struct TransformData& dataIn); void deSerializeDouble(const struct TransformDoubleData& dataIn); void deSerializeFloat(const struct TransformFloatData& dataIn); }; TF2SIMD_FORCE_INLINE Vector3 Transform::invXform(const Vector3& inVec) const { Vector3 v = inVec - m_origin; return (m_basis.transpose() * v); } TF2SIMD_FORCE_INLINE Transform Transform::inverseTimes(const Transform& t) const { Vector3 v = t.getOrigin() - m_origin; return Transform(m_basis.transposeTimes(t.m_basis), v * m_basis); } TF2SIMD_FORCE_INLINE Transform Transform::operator*(const Transform& t) const { return Transform(m_basis * t.m_basis, (*this)(t.m_origin)); } /**@brief Test if two transforms have all elements equal */ TF2SIMD_FORCE_INLINE bool operator==(const Transform& t1, const Transform& t2) { return ( t1.getBasis() == t2.getBasis() && t1.getOrigin() == t2.getOrigin() ); } ///for serialization struct TransformFloatData { Matrix3x3FloatData m_basis; Vector3FloatData m_origin; }; struct TransformDoubleData { Matrix3x3DoubleData m_basis; Vector3DoubleData m_origin; }; TF2SIMD_FORCE_INLINE void Transform::serialize(TransformData& dataOut) const { m_basis.serialize(dataOut.m_basis); m_origin.serialize(dataOut.m_origin); } TF2SIMD_FORCE_INLINE void Transform::serializeFloat(TransformFloatData& dataOut) const { m_basis.serializeFloat(dataOut.m_basis); m_origin.serializeFloat(dataOut.m_origin); } TF2SIMD_FORCE_INLINE void Transform::deSerialize(const TransformData& dataIn) { m_basis.deSerialize(dataIn.m_basis); m_origin.deSerialize(dataIn.m_origin); } TF2SIMD_FORCE_INLINE void Transform::deSerializeFloat(const TransformFloatData& dataIn) { m_basis.deSerializeFloat(dataIn.m_basis); m_origin.deSerializeFloat(dataIn.m_origin); } TF2SIMD_FORCE_INLINE void Transform::deSerializeDouble(const TransformDoubleData& dataIn) { m_basis.deSerializeDouble(dataIn.m_basis); m_origin.deSerializeDouble(dataIn.m_origin); } } #endif
0
apollo_public_repos/apollo/third_party/tf2/include/tf2
apollo_public_repos/apollo/third_party/tf2/include/tf2/LinearMath/Vector3.h
/* Copyright (c) 2003-2006 Gino van den Bergen / Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef TF2_VECTOR3_H #define TF2_VECTOR3_H #include "Scalar.h" #include "MinMax.h" namespace tf2 { #define Vector3Data Vector3DoubleData #define Vector3DataName "Vector3DoubleData" /**@brief tf2::Vector3 can be used to represent 3D points and vectors. * It has an un-used w component to suit 16-byte alignment when tf2::Vector3 is stored in containers. This extra component can be used by derived classes (Quaternion?) or by user * Ideally, this class should be replaced by a platform optimized TF2SIMD version that keeps the data in registers */ ATTRIBUTE_ALIGNED16(class) Vector3 { public: #if defined (__SPU__) && defined (__CELLOS_LV2__) tf2Scalar m_floats[4]; public: TF2SIMD_FORCE_INLINE const vec_float4& get128() const { return *((const vec_float4*)&m_floats[0]); } public: #else //__CELLOS_LV2__ __SPU__ #ifdef TF2_USE_SSE // _WIN32 union { __m128 mVec128; tf2Scalar m_floats[4]; }; TF2SIMD_FORCE_INLINE __m128 get128() const { return mVec128; } TF2SIMD_FORCE_INLINE void set128(__m128 v128) { mVec128 = v128; } #else tf2Scalar m_floats[4]; #endif #endif //__CELLOS_LV2__ __SPU__ public: /**@brief No initialization constructor */ TF2SIMD_FORCE_INLINE Vector3() {} /**@brief Constructor from scalars * @param x X value * @param y Y value * @param z Z value */ TF2SIMD_FORCE_INLINE Vector3(const tf2Scalar& x, const tf2Scalar& y, const tf2Scalar& z) { m_floats[0] = x; m_floats[1] = y; m_floats[2] = z; m_floats[3] = tf2Scalar(0.); } /**@brief Add a vector to this one * @param The vector to add to this one */ TF2SIMD_FORCE_INLINE Vector3& operator+=(const Vector3& v) { m_floats[0] += v.m_floats[0]; m_floats[1] += v.m_floats[1];m_floats[2] += v.m_floats[2]; return *this; } /**@brief Sutf2ract a vector from this one * @param The vector to sutf2ract */ TF2SIMD_FORCE_INLINE Vector3& operator-=(const Vector3& v) { m_floats[0] -= v.m_floats[0]; m_floats[1] -= v.m_floats[1];m_floats[2] -= v.m_floats[2]; return *this; } /**@brief Scale the vector * @param s Scale factor */ TF2SIMD_FORCE_INLINE Vector3& operator*=(const tf2Scalar& s) { m_floats[0] *= s; m_floats[1] *= s;m_floats[2] *= s; return *this; } /**@brief Inversely scale the vector * @param s Scale factor to divide by */ TF2SIMD_FORCE_INLINE Vector3& operator/=(const tf2Scalar& s) { tf2FullAssert(s != tf2Scalar(0.0)); return *this *= tf2Scalar(1.0) / s; } /**@brief Return the dot product * @param v The other vector in the dot product */ TF2SIMD_FORCE_INLINE tf2Scalar dot(const Vector3& v) const { return m_floats[0] * v.m_floats[0] + m_floats[1] * v.m_floats[1] +m_floats[2] * v.m_floats[2]; } /**@brief Return the length of the vector squared */ TF2SIMD_FORCE_INLINE tf2Scalar length2() const { return dot(*this); } /**@brief Return the length of the vector */ TF2SIMD_FORCE_INLINE tf2Scalar length() const { return tf2Sqrt(length2()); } /**@brief Return the distance squared between the ends of this and another vector * This is symantically treating the vector like a point */ TF2SIMD_FORCE_INLINE tf2Scalar distance2(const Vector3& v) const; /**@brief Return the distance between the ends of this and another vector * This is symantically treating the vector like a point */ TF2SIMD_FORCE_INLINE tf2Scalar distance(const Vector3& v) const; /**@brief Normalize this vector * x^2 + y^2 + z^2 = 1 */ TF2SIMD_FORCE_INLINE Vector3& normalize() { return *this /= length(); } /**@brief Return a normalized version of this vector */ TF2SIMD_FORCE_INLINE Vector3 normalized() const; /**@brief Rotate this vector * @param wAxis The axis to rotate about * @param angle The angle to rotate by */ TF2SIMD_FORCE_INLINE Vector3 rotate( const Vector3& wAxis, const tf2Scalar angle ) const; /**@brief Return the angle between this and another vector * @param v The other vector */ TF2SIMD_FORCE_INLINE tf2Scalar angle(const Vector3& v) const { tf2Scalar s = tf2Sqrt(length2() * v.length2()); tf2FullAssert(s != tf2Scalar(0.0)); return tf2Acos(dot(v) / s); } /**@brief Return a vector will the absolute values of each element */ TF2SIMD_FORCE_INLINE Vector3 absolute() const { return Vector3( tf2Fabs(m_floats[0]), tf2Fabs(m_floats[1]), tf2Fabs(m_floats[2])); } /**@brief Return the cross product between this and another vector * @param v The other vector */ TF2SIMD_FORCE_INLINE Vector3 cross(const Vector3& v) const { return Vector3( m_floats[1] * v.m_floats[2] -m_floats[2] * v.m_floats[1], m_floats[2] * v.m_floats[0] - m_floats[0] * v.m_floats[2], m_floats[0] * v.m_floats[1] - m_floats[1] * v.m_floats[0]); } TF2SIMD_FORCE_INLINE tf2Scalar triple(const Vector3& v1, const Vector3& v2) const { return m_floats[0] * (v1.m_floats[1] * v2.m_floats[2] - v1.m_floats[2] * v2.m_floats[1]) + m_floats[1] * (v1.m_floats[2] * v2.m_floats[0] - v1.m_floats[0] * v2.m_floats[2]) + m_floats[2] * (v1.m_floats[0] * v2.m_floats[1] - v1.m_floats[1] * v2.m_floats[0]); } /**@brief Return the axis with the smallest value * Note return values are 0,1,2 for x, y, or z */ TF2SIMD_FORCE_INLINE int minAxis() const { return m_floats[0] < m_floats[1] ? (m_floats[0] <m_floats[2] ? 0 : 2) : (m_floats[1] <m_floats[2] ? 1 : 2); } /**@brief Return the axis with the largest value * Note return values are 0,1,2 for x, y, or z */ TF2SIMD_FORCE_INLINE int maxAxis() const { return m_floats[0] < m_floats[1] ? (m_floats[1] <m_floats[2] ? 2 : 1) : (m_floats[0] <m_floats[2] ? 2 : 0); } TF2SIMD_FORCE_INLINE int furthestAxis() const { return absolute().minAxis(); } TF2SIMD_FORCE_INLINE int closestAxis() const { return absolute().maxAxis(); } TF2SIMD_FORCE_INLINE void setInterpolate3(const Vector3& v0, const Vector3& v1, tf2Scalar rt) { tf2Scalar s = tf2Scalar(1.0) - rt; m_floats[0] = s * v0.m_floats[0] + rt * v1.m_floats[0]; m_floats[1] = s * v0.m_floats[1] + rt * v1.m_floats[1]; m_floats[2] = s * v0.m_floats[2] + rt * v1.m_floats[2]; //don't do the unused w component // m_co[3] = s * v0[3] + rt * v1[3]; } /**@brief Return the linear interpolation between this and another vector * @param v The other vector * @param t The ration of this to v (t = 0 => return this, t=1 => return other) */ TF2SIMD_FORCE_INLINE Vector3 lerp(const Vector3& v, const tf2Scalar& t) const { return Vector3(m_floats[0] + (v.m_floats[0] - m_floats[0]) * t, m_floats[1] + (v.m_floats[1] - m_floats[1]) * t, m_floats[2] + (v.m_floats[2] -m_floats[2]) * t); } /**@brief Elementwise multiply this vector by the other * @param v The other vector */ TF2SIMD_FORCE_INLINE Vector3& operator*=(const Vector3& v) { m_floats[0] *= v.m_floats[0]; m_floats[1] *= v.m_floats[1];m_floats[2] *= v.m_floats[2]; return *this; } /**@brief Return the x value */ TF2SIMD_FORCE_INLINE const tf2Scalar& getX() const { return m_floats[0]; } /**@brief Return the y value */ TF2SIMD_FORCE_INLINE const tf2Scalar& getY() const { return m_floats[1]; } /**@brief Return the z value */ TF2SIMD_FORCE_INLINE const tf2Scalar& getZ() const { return m_floats[2]; } /**@brief Set the x value */ TF2SIMD_FORCE_INLINE void setX(tf2Scalar x) { m_floats[0] = x;}; /**@brief Set the y value */ TF2SIMD_FORCE_INLINE void setY(tf2Scalar y) { m_floats[1] = y;}; /**@brief Set the z value */ TF2SIMD_FORCE_INLINE void setZ(tf2Scalar z) {m_floats[2] = z;}; /**@brief Set the w value */ TF2SIMD_FORCE_INLINE void setW(tf2Scalar w) { m_floats[3] = w;}; /**@brief Return the x value */ TF2SIMD_FORCE_INLINE const tf2Scalar& x() const { return m_floats[0]; } /**@brief Return the y value */ TF2SIMD_FORCE_INLINE const tf2Scalar& y() const { return m_floats[1]; } /**@brief Return the z value */ TF2SIMD_FORCE_INLINE const tf2Scalar& z() const { return m_floats[2]; } /**@brief Return the w value */ TF2SIMD_FORCE_INLINE const tf2Scalar& w() const { return m_floats[3]; } //TF2SIMD_FORCE_INLINE tf2Scalar& operator[](int i) { return (&m_floats[0])[i]; } //TF2SIMD_FORCE_INLINE const tf2Scalar& operator[](int i) const { return (&m_floats[0])[i]; } ///operator tf2Scalar*() replaces operator[], using implicit conversion. We added operator != and operator == to avoid pointer comparisons. TF2SIMD_FORCE_INLINE operator tf2Scalar *() { return &m_floats[0]; } TF2SIMD_FORCE_INLINE operator const tf2Scalar *() const { return &m_floats[0]; } TF2SIMD_FORCE_INLINE bool operator==(const Vector3& other) const { return ((m_floats[3]==other.m_floats[3]) && (m_floats[2]==other.m_floats[2]) && (m_floats[1]==other.m_floats[1]) && (m_floats[0]==other.m_floats[0])); } TF2SIMD_FORCE_INLINE bool operator!=(const Vector3& other) const { return !(*this == other); } /**@brief Set each element to the max of the current values and the values of another Vector3 * @param other The other Vector3 to compare with */ TF2SIMD_FORCE_INLINE void setMax(const Vector3& other) { tf2SetMax(m_floats[0], other.m_floats[0]); tf2SetMax(m_floats[1], other.m_floats[1]); tf2SetMax(m_floats[2], other.m_floats[2]); tf2SetMax(m_floats[3], other.w()); } /**@brief Set each element to the min of the current values and the values of another Vector3 * @param other The other Vector3 to compare with */ TF2SIMD_FORCE_INLINE void setMin(const Vector3& other) { tf2SetMin(m_floats[0], other.m_floats[0]); tf2SetMin(m_floats[1], other.m_floats[1]); tf2SetMin(m_floats[2], other.m_floats[2]); tf2SetMin(m_floats[3], other.w()); } TF2SIMD_FORCE_INLINE void setValue(const tf2Scalar& x, const tf2Scalar& y, const tf2Scalar& z) { m_floats[0]=x; m_floats[1]=y; m_floats[2]=z; m_floats[3] = tf2Scalar(0.); } void getSkewSymmetricMatrix(Vector3* v0,Vector3* v1,Vector3* v2) const { v0->setValue(0. ,-z() ,y()); v1->setValue(z() ,0. ,-x()); v2->setValue(-y() ,x() ,0.); } void setZero() { setValue(tf2Scalar(0.),tf2Scalar(0.),tf2Scalar(0.)); } TF2SIMD_FORCE_INLINE bool isZero() const { return m_floats[0] == tf2Scalar(0) && m_floats[1] == tf2Scalar(0) && m_floats[2] == tf2Scalar(0); } TF2SIMD_FORCE_INLINE bool fuzzyZero() const { return length2() < TF2SIMD_EPSILON; } TF2SIMD_FORCE_INLINE void serialize(struct Vector3Data& dataOut) const; TF2SIMD_FORCE_INLINE void deSerialize(const struct Vector3Data& dataIn); TF2SIMD_FORCE_INLINE void serializeFloat(struct Vector3FloatData& dataOut) const; TF2SIMD_FORCE_INLINE void deSerializeFloat(const struct Vector3FloatData& dataIn); TF2SIMD_FORCE_INLINE void serializeDouble(struct Vector3DoubleData& dataOut) const; TF2SIMD_FORCE_INLINE void deSerializeDouble(const struct Vector3DoubleData& dataIn); }; /**@brief Return the sum of two vectors (Point symantics)*/ TF2SIMD_FORCE_INLINE Vector3 operator+(const Vector3& v1, const Vector3& v2) { return Vector3(v1.m_floats[0] + v2.m_floats[0], v1.m_floats[1] + v2.m_floats[1], v1.m_floats[2] + v2.m_floats[2]); } /**@brief Return the elementwise product of two vectors */ TF2SIMD_FORCE_INLINE Vector3 operator*(const Vector3& v1, const Vector3& v2) { return Vector3(v1.m_floats[0] * v2.m_floats[0], v1.m_floats[1] * v2.m_floats[1], v1.m_floats[2] * v2.m_floats[2]); } /**@brief Return the difference between two vectors */ TF2SIMD_FORCE_INLINE Vector3 operator-(const Vector3& v1, const Vector3& v2) { return Vector3(v1.m_floats[0] - v2.m_floats[0], v1.m_floats[1] - v2.m_floats[1], v1.m_floats[2] - v2.m_floats[2]); } /**@brief Return the negative of the vector */ TF2SIMD_FORCE_INLINE Vector3 operator-(const Vector3& v) { return Vector3(-v.m_floats[0], -v.m_floats[1], -v.m_floats[2]); } /**@brief Return the vector scaled by s */ TF2SIMD_FORCE_INLINE Vector3 operator*(const Vector3& v, const tf2Scalar& s) { return Vector3(v.m_floats[0] * s, v.m_floats[1] * s, v.m_floats[2] * s); } /**@brief Return the vector scaled by s */ TF2SIMD_FORCE_INLINE Vector3 operator*(const tf2Scalar& s, const Vector3& v) { return v * s; } /**@brief Return the vector inversely scaled by s */ TF2SIMD_FORCE_INLINE Vector3 operator/(const Vector3& v, const tf2Scalar& s) { tf2FullAssert(s != tf2Scalar(0.0)); return v * (tf2Scalar(1.0) / s); } /**@brief Return the vector inversely scaled by s */ TF2SIMD_FORCE_INLINE Vector3 operator/(const Vector3& v1, const Vector3& v2) { return Vector3(v1.m_floats[0] / v2.m_floats[0],v1.m_floats[1] / v2.m_floats[1],v1.m_floats[2] / v2.m_floats[2]); } /**@brief Return the dot product between two vectors */ TF2SIMD_FORCE_INLINE tf2Scalar tf2Dot(const Vector3& v1, const Vector3& v2) { return v1.dot(v2); } /**@brief Return the distance squared between two vectors */ TF2SIMD_FORCE_INLINE tf2Scalar tf2Distance2(const Vector3& v1, const Vector3& v2) { return v1.distance2(v2); } /**@brief Return the distance between two vectors */ TF2SIMD_FORCE_INLINE tf2Scalar tf2Distance(const Vector3& v1, const Vector3& v2) { return v1.distance(v2); } /**@brief Return the angle between two vectors */ TF2SIMD_FORCE_INLINE tf2Scalar tf2Angle(const Vector3& v1, const Vector3& v2) { return v1.angle(v2); } /**@brief Return the cross product of two vectors */ TF2SIMD_FORCE_INLINE Vector3 tf2Cross(const Vector3& v1, const Vector3& v2) { return v1.cross(v2); } TF2SIMD_FORCE_INLINE tf2Scalar tf2Triple(const Vector3& v1, const Vector3& v2, const Vector3& v3) { return v1.triple(v2, v3); } /**@brief Return the linear interpolation between two vectors * @param v1 One vector * @param v2 The other vector * @param t The ration of this to v (t = 0 => return v1, t=1 => return v2) */ TF2SIMD_FORCE_INLINE Vector3 lerp(const Vector3& v1, const Vector3& v2, const tf2Scalar& t) { return v1.lerp(v2, t); } TF2SIMD_FORCE_INLINE tf2Scalar Vector3::distance2(const Vector3& v) const { return (v - *this).length2(); } TF2SIMD_FORCE_INLINE tf2Scalar Vector3::distance(const Vector3& v) const { return (v - *this).length(); } TF2SIMD_FORCE_INLINE Vector3 Vector3::normalized() const { return *this / length(); } TF2SIMD_FORCE_INLINE Vector3 Vector3::rotate( const Vector3& wAxis, const tf2Scalar angle ) const { // wAxis must be a unit lenght vector Vector3 o = wAxis * wAxis.dot( *this ); Vector3 x = *this - o; Vector3 y; y = wAxis.cross( *this ); return ( o + x * tf2Cos( angle ) + y * tf2Sin( angle ) ); } class tf2Vector4 : public Vector3 { public: TF2SIMD_FORCE_INLINE tf2Vector4() {} TF2SIMD_FORCE_INLINE tf2Vector4(const tf2Scalar& x, const tf2Scalar& y, const tf2Scalar& z,const tf2Scalar& w) : Vector3(x,y,z) { m_floats[3] = w; } TF2SIMD_FORCE_INLINE tf2Vector4 absolute4() const { return tf2Vector4( tf2Fabs(m_floats[0]), tf2Fabs(m_floats[1]), tf2Fabs(m_floats[2]), tf2Fabs(m_floats[3])); } tf2Scalar getW() const { return m_floats[3];} TF2SIMD_FORCE_INLINE int maxAxis4() const { int maxIndex = -1; tf2Scalar maxVal = tf2Scalar(-TF2_LARGE_FLOAT); if (m_floats[0] > maxVal) { maxIndex = 0; maxVal = m_floats[0]; } if (m_floats[1] > maxVal) { maxIndex = 1; maxVal = m_floats[1]; } if (m_floats[2] > maxVal) { maxIndex = 2; maxVal =m_floats[2]; } if (m_floats[3] > maxVal) { maxIndex = 3; } return maxIndex; } TF2SIMD_FORCE_INLINE int minAxis4() const { int minIndex = -1; tf2Scalar minVal = tf2Scalar(TF2_LARGE_FLOAT); if (m_floats[0] < minVal) { minIndex = 0; minVal = m_floats[0]; } if (m_floats[1] < minVal) { minIndex = 1; minVal = m_floats[1]; } if (m_floats[2] < minVal) { minIndex = 2; minVal =m_floats[2]; } if (m_floats[3] < minVal) { minIndex = 3; } return minIndex; } TF2SIMD_FORCE_INLINE int closestAxis4() const { return absolute4().maxAxis4(); } /**@brief Set x,y,z and zero w * @param x Value of x * @param y Value of y * @param z Value of z */ /* void getValue(tf2Scalar *m) const { m[0] = m_floats[0]; m[1] = m_floats[1]; m[2] =m_floats[2]; } */ /**@brief Set the values * @param x Value of x * @param y Value of y * @param z Value of z * @param w Value of w */ TF2SIMD_FORCE_INLINE void setValue(const tf2Scalar& x, const tf2Scalar& y, const tf2Scalar& z,const tf2Scalar& w) { m_floats[0]=x; m_floats[1]=y; m_floats[2]=z; m_floats[3]=w; } }; ///tf2SwapVector3Endian swaps vector endianness, useful for network and cross-platform serialization TF2SIMD_FORCE_INLINE void tf2SwapScalarEndian(const tf2Scalar& sourceVal, tf2Scalar& destVal) { unsigned char* dest = (unsigned char*) &destVal; unsigned char* src = (unsigned char*) &sourceVal; dest[0] = src[7]; dest[1] = src[6]; dest[2] = src[5]; dest[3] = src[4]; dest[4] = src[3]; dest[5] = src[2]; dest[6] = src[1]; dest[7] = src[0]; } ///tf2SwapVector3Endian swaps vector endianness, useful for network and cross-platform serialization TF2SIMD_FORCE_INLINE void tf2SwapVector3Endian(const Vector3& sourceVec, Vector3& destVec) { for (int i=0;i<4;i++) { tf2SwapScalarEndian(sourceVec[i],destVec[i]); } } ///tf2UnSwapVector3Endian swaps vector endianness, useful for network and cross-platform serialization TF2SIMD_FORCE_INLINE void tf2UnSwapVector3Endian(Vector3& vector) { Vector3 swappedVec; for (int i=0;i<4;i++) { tf2SwapScalarEndian(vector[i],swappedVec[i]); } vector = swappedVec; } TF2SIMD_FORCE_INLINE void tf2PlaneSpace1 (const Vector3& n, Vector3& p, Vector3& q) { if (tf2Fabs(n.z()) > TF2SIMDSQRT12) { // choose p in y-z plane tf2Scalar a = n[1]*n[1] + n[2]*n[2]; tf2Scalar k = tf2RecipSqrt (a); p.setValue(0,-n[2]*k,n[1]*k); // set q = n x p q.setValue(a*k,-n[0]*p[2],n[0]*p[1]); } else { // choose p in x-y plane tf2Scalar a = n.x()*n.x() + n.y()*n.y(); tf2Scalar k = tf2RecipSqrt (a); p.setValue(-n.y()*k,n.x()*k,0); // set q = n x p q.setValue(-n.z()*p.y(),n.z()*p.x(),a*k); } } struct Vector3FloatData { float m_floats[4]; }; struct Vector3DoubleData { double m_floats[4]; }; TF2SIMD_FORCE_INLINE void Vector3::serializeFloat(struct Vector3FloatData& dataOut) const { ///could also do a memcpy, check if it is worth it for (int i=0;i<4;i++) dataOut.m_floats[i] = float(m_floats[i]); } TF2SIMD_FORCE_INLINE void Vector3::deSerializeFloat(const struct Vector3FloatData& dataIn) { for (int i=0;i<4;i++) m_floats[i] = tf2Scalar(dataIn.m_floats[i]); } TF2SIMD_FORCE_INLINE void Vector3::serializeDouble(struct Vector3DoubleData& dataOut) const { ///could also do a memcpy, check if it is worth it for (int i=0;i<4;i++) dataOut.m_floats[i] = double(m_floats[i]); } TF2SIMD_FORCE_INLINE void Vector3::deSerializeDouble(const struct Vector3DoubleData& dataIn) { for (int i=0;i<4;i++) m_floats[i] = tf2Scalar(dataIn.m_floats[i]); } TF2SIMD_FORCE_INLINE void Vector3::serialize(struct Vector3Data& dataOut) const { ///could also do a memcpy, check if it is worth it for (int i=0;i<4;i++) dataOut.m_floats[i] = m_floats[i]; } TF2SIMD_FORCE_INLINE void Vector3::deSerialize(const struct Vector3Data& dataIn) { for (int i=0;i<4;i++) m_floats[i] = dataIn.m_floats[i]; } } #endif //TF2_VECTOR3_H
0
apollo_public_repos/apollo/third_party/tf2/include
apollo_public_repos/apollo/third_party/tf2/include/tf2_msgs/tf2_error.h
/* * Copyright (c) 2013, Open Source Robotics Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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. */ #ifndef TF2_MSGS_TF2_ERROR_H #define TF2_MSGS_TF2_ERROR_H namespace tf2_msgs { namespace TF2Error { const uint8_t NO_ERROR = 0; const uint8_t LOOKUP_ERROR = 1; const uint8_t CONNECTIVITY_ERROR = 2; const uint8_t EXTRAPOLATION_ERROR = 3; const uint8_t INVALID_ARGUMENT_ERROR = 4; const uint8_t TIMEOUT_ERROR = 5; const uint8_t TRANSFORM_ERROR = 6; } } #endif
0
apollo_public_repos/apollo/third_party/tf2/include
apollo_public_repos/apollo/third_party/tf2/include/geometry_msgs/transform_stamped.h
/* * Copyright (c) 2013, Open Source Robotics Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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. */ #ifndef GEOMETRY_MSGS_TRANSFORM_STAMPED_H #define GEOMETRY_MSGS_TRANSFORM_STAMPED_H #include <iostream> #include <stdint.h> namespace geometry_msgs { struct Header { uint32_t seq; uint64_t stamp; std::string frame_id; Header() : seq(0), stamp(0), frame_id("") {} }; struct Vector3 { double x; double y; double z; Vector3() : x(0.0), y(0.0), z(0.0) {} }; struct Quaternion { double x; double y; double z; double w; Quaternion(): x(0.0), y(0.0), z(0.0), w(0.0) {} }; struct Transform { Vector3 translation; Quaternion rotation; }; struct TransformStamped { Header header; std::string child_frame_id; Transform transform; }; } #endif
0
apollo_public_repos/apollo/third_party/tf2
apollo_public_repos/apollo/third_party/tf2/src/static_cache.cpp
/* * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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. */ /** \author Tully Foote */ #include "tf2/time_cache.h" #include "tf2/exceptions.h" #include "tf2/LinearMath/Transform.h" using namespace tf2; bool StaticCache::getData(Time time, TransformStorage & data_out, std::string* error_str) //returns false if data not available { data_out = storage_; data_out.stamp_ = time; (void)error_str; return true; }; bool StaticCache::insertData(const TransformStorage& new_data) { storage_ = new_data; return true; }; void StaticCache::clearList() { return; }; unsigned int StaticCache::getListLength() { return 1; }; CompactFrameID StaticCache::getParent(Time time, std::string* error_str) { (void)time; (void)error_str; return storage_.frame_id_; } P_TimeAndFrameID StaticCache::getLatestTimeAndParent() { return std::make_pair(Time(), storage_.frame_id_); } Time StaticCache::getLatestTimestamp() { return Time(); }; Time StaticCache::getOldestTimestamp() { return Time(); };
0
apollo_public_repos/apollo/third_party/tf2
apollo_public_repos/apollo/third_party/tf2/src/buffer_core.cpp
/* * Copyright (c) 2010, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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. */ /** \author Tully Foote */ #include "tf2/buffer_core.h" #include "tf2/exceptions.h" #include "tf2/time_cache.h" #include "tf2/time.h" // #include "tf2_msgs/TF2Error.h" #include <assert.h> #include <iostream> // #include <console_bridge/console.h> #include <boost/foreach.hpp> #include "tf2/LinearMath/Transform.h" #include "tf2_msgs/tf2_error.h" namespace tf2 { // Tolerance for acceptable quaternion normalization static double QUATERNION_NORMALIZATION_TOLERANCE = 10e-3; /** \brief convert Transform msg to Transform */ void transformMsgToTF2(const geometry_msgs::Transform& msg, tf2::Transform& tf2) { tf2 = tf2::Transform( tf2::Quaternion(msg.rotation.x, msg.rotation.y, msg.rotation.z, msg.rotation.w), tf2::Vector3(msg.translation.x, msg.translation.y, msg.translation.z)); } /** \brief convert Transform to Transform msg*/ void transformTF2ToMsg(const tf2::Transform& tf2, geometry_msgs::Transform& msg) { msg.translation.x = tf2.getOrigin().x(); msg.translation.y = tf2.getOrigin().y(); msg.translation.z = tf2.getOrigin().z(); msg.rotation.x = tf2.getRotation().x(); msg.rotation.y = tf2.getRotation().y(); msg.rotation.z = tf2.getRotation().z(); msg.rotation.w = tf2.getRotation().w(); } /** \brief convert Transform to Transform msg*/ void transformTF2ToMsg(const tf2::Transform& tf2, geometry_msgs::TransformStamped& msg, Time stamp, const std::string& frame_id, const std::string& child_frame_id) { transformTF2ToMsg(tf2, msg.transform); msg.header.stamp = stamp; msg.header.frame_id = frame_id; msg.child_frame_id = child_frame_id; } void transformTF2ToMsg(const tf2::Quaternion& orient, const tf2::Vector3& pos, geometry_msgs::Transform& msg) { msg.translation.x = pos.x(); msg.translation.y = pos.y(); msg.translation.z = pos.z(); msg.rotation.x = orient.x(); msg.rotation.y = orient.y(); msg.rotation.z = orient.z(); msg.rotation.w = orient.w(); } void transformTF2ToMsg(const tf2::Quaternion& orient, const tf2::Vector3& pos, geometry_msgs::TransformStamped& msg, Time stamp, const std::string& frame_id, const std::string& child_frame_id) { transformTF2ToMsg(orient, pos, msg.transform); msg.header.stamp = stamp; msg.header.frame_id = frame_id; msg.child_frame_id = child_frame_id; } void setIdentity(geometry_msgs::Transform& tx) { tx.translation.x = 0; tx.translation.y = 0; tx.translation.z = 0; tx.rotation.x = 0; tx.rotation.y = 0; tx.rotation.z = 0; tx.rotation.w = 1; } bool startsWithSlash(const std::string& frame_id) { if (frame_id.size() > 0) if (frame_id[0] == '/') return true; return false; } std::string stripSlash(const std::string& in) { std::string out = in; if (startsWithSlash(in)) out.erase(0, 1); return out; } bool BufferCore::warnFrameId(const char* function_name_arg, const std::string& frame_id) const { if (frame_id.size() == 0) { std::stringstream ss; ss << "Invalid argument passed to " << function_name_arg << " in tf2 frame_ids cannot be empty"; // logWarn("%s", ss.str().c_str()); return true; } if (startsWithSlash(frame_id)) { std::stringstream ss; ss << "Invalid argument \"" << frame_id << "\" passed to " << function_name_arg << " in tf2 frame_ids cannot start with a '/' like: "; // logWarn("%s", ss.str().c_str()); return true; } return false; } CompactFrameID BufferCore::validateFrameId(const char* function_name_arg, const std::string& frame_id) const { if (frame_id.empty()) { std::stringstream ss; ss << "Invalid argument passed to " << function_name_arg << " in tf2 frame_ids cannot be empty"; throw tf2::InvalidArgumentException(ss.str().c_str()); } if (startsWithSlash(frame_id)) { std::stringstream ss; ss << "Invalid argument \"" << frame_id << "\" passed to " << function_name_arg << " in tf2 frame_ids cannot start with a '/' like: "; throw tf2::InvalidArgumentException(ss.str().c_str()); } CompactFrameID id = lookupFrameNumber(frame_id); if (id == 0) { std::stringstream ss; ss << "\"" << frame_id << "\" passed to " << function_name_arg << " does not exist. "; throw tf2::LookupException(ss.str().c_str()); } return id; } BufferCore::BufferCore(Duration cache_time) : cache_time_(cache_time), transformable_callbacks_counter_(0), transformable_requests_counter_(0), using_dedicated_thread_(false) { frameIDs_["NO_PARENT"] = 0; frames_.push_back(TimeCacheInterfacePtr()); frameIDs_reverse.push_back("NO_PARENT"); } BufferCore::~BufferCore() {} void BufferCore::clear() { // old_tf_.clear(); boost::mutex::scoped_lock lock(frame_mutex_); if (frames_.size() > 1) { for (std::vector<TimeCacheInterfacePtr>::iterator cache_it = frames_.begin() + 1; cache_it != frames_.end(); ++cache_it) { if (*cache_it) (*cache_it)->clearList(); } } } bool BufferCore::setTransform( const geometry_msgs::TransformStamped& transform_in, const std::string& authority, bool is_static) { /////BACKEARDS COMPATABILITY /* tf::StampedTransform tf_transform; tf::transformStampedMsgToTF(transform_in, tf_transform); if (!old_tf_.setTransform(tf_transform, authority)) { printf("Warning old setTransform Failed but was not caught\n"); }*/ /////// New implementation geometry_msgs::TransformStamped stripped = transform_in; stripped.header.frame_id = stripSlash(stripped.header.frame_id); stripped.child_frame_id = stripSlash(stripped.child_frame_id); bool error_exists = false; if (stripped.child_frame_id == stripped.header.frame_id) { // logError( // "TF_SELF_TRANSFORM: Ignoring transform from authority \"%s\" with " // "frame_id and child_frame_id \"%s\" because they are the same", // authority.c_str(), stripped.child_frame_id.c_str()); error_exists = true; } if (stripped.child_frame_id == "") { // logError( // "TF_NO_CHILD_FRAME_ID: Ignoring transform from authority \"%s\" " // "because child_frame_id not set ", // authority.c_str()); error_exists = true; } if (stripped.header.frame_id == "") { // logError( // "TF_NO_FRAME_ID: Ignoring transform with child_frame_id \"%s\" from " // "authority \"%s\" because frame_id not set", // stripped.child_frame_id.c_str(), authority.c_str()); error_exists = true; } if (std::isnan(stripped.transform.translation.x) || std::isnan(stripped.transform.translation.y) || std::isnan(stripped.transform.translation.z) || std::isnan(stripped.transform.rotation.x) || std::isnan(stripped.transform.rotation.y) || std::isnan(stripped.transform.rotation.z) || std::isnan(stripped.transform.rotation.w)) { // logError( // "TF_NAN_INPUT: Ignoring transform for child_frame_id \"%s\" from " // "authority \"%s\" because of a nan value in the transform (%f %f %f) " // "(%f %f %f %f)", // stripped.child_frame_id.c_str(), authority.c_str(), // stripped.transform.translation.x, stripped.transform.translation.y, // stripped.transform.translation.z, stripped.transform.rotation.x, // stripped.transform.rotation.y, stripped.transform.rotation.z, // stripped.transform.rotation.w); error_exists = true; } bool valid = std::abs((stripped.transform.rotation.w * stripped.transform.rotation.w + stripped.transform.rotation.x * stripped.transform.rotation.x + stripped.transform.rotation.y * stripped.transform.rotation.y + stripped.transform.rotation.z * stripped.transform.rotation.z) - 1.0f) < QUATERNION_NORMALIZATION_TOLERANCE; if (!valid) { // logError( // "TF_DENORMALIZED_QUATERNION: Ignoring transform for child_frame_id " // "\"%s\" from authority \"%s\" because of an invalid quaternion in the " // "transform (%f %f %f %f)", // stripped.child_frame_id.c_str(), authority.c_str(), // stripped.transform.rotation.x, stripped.transform.rotation.y, // stripped.transform.rotation.z, stripped.transform.rotation.w); error_exists = true; } if (error_exists) return false; { boost::mutex::scoped_lock lock(frame_mutex_); CompactFrameID frame_number = lookupOrInsertFrameNumber(stripped.child_frame_id); TimeCacheInterfacePtr frame = getFrame(frame_number); if (frame == NULL) frame = allocateFrame(frame_number, is_static); if (frame->insertData(TransformStorage( stripped, lookupOrInsertFrameNumber(stripped.header.frame_id), frame_number))) { frame_authority_[frame_number] = authority; } else { // // logWarn( // "TF_OLD_DATA ignoring data from the past for frame %s at time %g " // "according to authority %s\nPossible reasons are listed at " // "http://wiki.ros.org/tf/Errors%%20explained", // stripped.child_frame_id.c_str(), time_to_sec(stripped.header.stamp), // authority.c_str()); return false; } } testTransformableRequests(); return true; } TimeCacheInterfacePtr BufferCore::allocateFrame(CompactFrameID cfid, bool is_static) { TimeCacheInterfacePtr frame_ptr = frames_[cfid]; if (is_static) { frames_[cfid] = TimeCacheInterfacePtr(new StaticCache()); } else { frames_[cfid] = TimeCacheInterfacePtr(new TimeCache(cache_time_)); } return frames_[cfid]; } enum WalkEnding { Identity, TargetParentOfSource, SourceParentOfTarget, FullPath, }; // TODO for Jade: Merge walkToTopParent functions; this is now a stub to // preserve ABI template <typename F> int BufferCore::walkToTopParent(F& f, Time time, CompactFrameID target_id, CompactFrameID source_id, std::string* error_string) const { return walkToTopParent(f, time, target_id, source_id, error_string, NULL); } template <typename F> int BufferCore::walkToTopParent( F& f, Time time, CompactFrameID target_id, CompactFrameID source_id, std::string* error_string, std::vector<CompactFrameID>* frame_chain) const { if (frame_chain) frame_chain->clear(); // Short circuit if zero length transform to allow lookups on non existant // links if (source_id == target_id) { f.finalize(Identity, time); return tf2_msgs::TF2Error::NO_ERROR; } // If getting the latest get the latest common time if (time == 0) { int retval = getLatestCommonTime(target_id, source_id, time, error_string); if (retval != tf2_msgs::TF2Error::NO_ERROR) { return retval; } } // Walk the tree to its root from the source frame, accumulating the transform CompactFrameID frame = source_id; CompactFrameID top_parent = frame; uint32_t depth = 0; std::string extrapolation_error_string; bool extrapolation_might_have_occurred = false; while (frame != 0) { TimeCacheInterfacePtr cache = getFrame(frame); if (frame_chain) frame_chain->push_back(frame); if (!cache) { // There will be no cache for the very root of the tree top_parent = frame; break; } CompactFrameID parent = f.gather(cache, time, &extrapolation_error_string); if (parent == 0) { // Just break out here... there may still be a path from source -> target top_parent = frame; extrapolation_might_have_occurred = true; break; } // Early out... target frame is a direct parent of the source frame if (frame == target_id) { f.finalize(TargetParentOfSource, time); return tf2_msgs::TF2Error::NO_ERROR; } f.accum(true); top_parent = frame; frame = parent; ++depth; if (depth > MAX_GRAPH_DEPTH) { if (error_string) { std::stringstream ss; ss << "The tf tree is invalid because it contains a loop." << std::endl << allFramesAsStringNoLock() << std::endl; *error_string = ss.str(); } return tf2_msgs::TF2Error::LOOKUP_ERROR; } } // Now walk to the top parent from the target frame, accumulating its // transform frame = target_id; depth = 0; std::vector<CompactFrameID> reverse_frame_chain; while (frame != top_parent) { TimeCacheInterfacePtr cache = getFrame(frame); if (frame_chain) reverse_frame_chain.push_back(frame); if (!cache) { break; } CompactFrameID parent = f.gather(cache, time, error_string); if (parent == 0) { if (error_string) { std::stringstream ss; ss << *error_string << ", when looking up transform from frame [" << lookupFrameString(source_id) << "] to frame [" << lookupFrameString(target_id) << "]"; *error_string = ss.str(); } return tf2_msgs::TF2Error::EXTRAPOLATION_ERROR; } // Early out... source frame is a direct parent of the target frame if (frame == source_id) { f.finalize(SourceParentOfTarget, time); if (frame_chain) { frame_chain->swap(reverse_frame_chain); } return tf2_msgs::TF2Error::NO_ERROR; } f.accum(false); frame = parent; ++depth; if (depth > MAX_GRAPH_DEPTH) { if (error_string) { std::stringstream ss; ss << "The tf tree is invalid because it contains a loop." << std::endl << allFramesAsStringNoLock() << std::endl; *error_string = ss.str(); } return tf2_msgs::TF2Error::LOOKUP_ERROR; } } if (frame != top_parent) { if (extrapolation_might_have_occurred) { if (error_string) { std::stringstream ss; ss << extrapolation_error_string << ", when looking up transform from frame [" << lookupFrameString(source_id) << "] to frame [" << lookupFrameString(target_id) << "]"; *error_string = ss.str(); } return tf2_msgs::TF2Error::EXTRAPOLATION_ERROR; } createConnectivityErrorString(source_id, target_id, error_string); return tf2_msgs::TF2Error::CONNECTIVITY_ERROR; } f.finalize(FullPath, time); if (frame_chain) { // Pruning: Compare the chains starting at the parent (end) until they // differ int m = static_cast<int>(reverse_frame_chain.size()) - 1; int n = static_cast<int>(frame_chain->size()) - 1; for (; m >= 0 && n >= 0; --m, --n) { if ((*frame_chain)[n] != reverse_frame_chain[m]) break; } // Erase all duplicate items from frame_chain if (n > 0) frame_chain->erase(frame_chain->begin() + (n - 1), frame_chain->end()); if (m < (int)reverse_frame_chain.size()) { for (int i = m; i >= 0; --i) { frame_chain->push_back(reverse_frame_chain[i]); } } } return tf2_msgs::TF2Error::NO_ERROR; } struct TransformAccum { TransformAccum() : source_to_top_quat(0.0, 0.0, 0.0, 1.0), source_to_top_vec(0.0, 0.0, 0.0), target_to_top_quat(0.0, 0.0, 0.0, 1.0), target_to_top_vec(0.0, 0.0, 0.0), result_quat(0.0, 0.0, 0.0, 1.0), result_vec(0.0, 0.0, 0.0) {} CompactFrameID gather(TimeCacheInterfacePtr cache, Time time, std::string* error_string) { if (!cache->getData(time, st, error_string)) { return 0; } return st.frame_id_; } void accum(bool source) { if (source) { source_to_top_vec = quatRotate(st.rotation_, source_to_top_vec) + st.translation_; source_to_top_quat = st.rotation_ * source_to_top_quat; } else { target_to_top_vec = quatRotate(st.rotation_, target_to_top_vec) + st.translation_; target_to_top_quat = st.rotation_ * target_to_top_quat; } } void finalize(WalkEnding end, Time _time) { switch (end) { case Identity: break; case TargetParentOfSource: result_vec = source_to_top_vec; result_quat = source_to_top_quat; break; case SourceParentOfTarget: { tf2::Quaternion inv_target_quat = target_to_top_quat.inverse(); tf2::Vector3 inv_target_vec = quatRotate(inv_target_quat, -target_to_top_vec); result_vec = inv_target_vec; result_quat = inv_target_quat; break; } case FullPath: { tf2::Quaternion inv_target_quat = target_to_top_quat.inverse(); tf2::Vector3 inv_target_vec = quatRotate(inv_target_quat, -target_to_top_vec); result_vec = quatRotate(inv_target_quat, source_to_top_vec) + inv_target_vec; result_quat = inv_target_quat * source_to_top_quat; } break; }; time = _time; } TransformStorage st; Time time; tf2::Quaternion source_to_top_quat; tf2::Vector3 source_to_top_vec; tf2::Quaternion target_to_top_quat; tf2::Vector3 target_to_top_vec; tf2::Quaternion result_quat; tf2::Vector3 result_vec; }; geometry_msgs::TransformStamped BufferCore::lookupTransform( const std::string& target_frame, const std::string& source_frame, const Time& time) const { boost::mutex::scoped_lock lock(frame_mutex_); if (target_frame == source_frame) { geometry_msgs::TransformStamped identity; identity.header.frame_id = target_frame; identity.child_frame_id = source_frame; identity.transform.rotation.w = 1; if (time == 0) { CompactFrameID target_id = lookupFrameNumber(target_frame); TimeCacheInterfacePtr cache = getFrame(target_id); if (cache) identity.header.stamp = cache->getLatestTimestamp(); else identity.header.stamp = time; } else identity.header.stamp = time; return identity; } // Identify case does not need to be validated above CompactFrameID target_id = validateFrameId("lookupTransform argument target_frame", target_frame); CompactFrameID source_id = validateFrameId("lookupTransform argument source_frame", source_frame); std::string error_string; TransformAccum accum; int retval = walkToTopParent(accum, time, target_id, source_id, &error_string); if (retval != tf2_msgs::TF2Error::NO_ERROR) { switch (retval) { case tf2_msgs::TF2Error::CONNECTIVITY_ERROR: throw ConnectivityException(error_string); break; case tf2_msgs::TF2Error::EXTRAPOLATION_ERROR: throw ExtrapolationException(error_string); break; case tf2_msgs::TF2Error::LOOKUP_ERROR: throw LookupException(error_string); break; default: // logError("Unknown error code: %d", retval); assert(0); } } geometry_msgs::TransformStamped output_transform; transformTF2ToMsg(accum.result_quat, accum.result_vec, output_transform, accum.time, target_frame, source_frame); return output_transform; } geometry_msgs::TransformStamped BufferCore::lookupTransform( const std::string& target_frame, const Time& target_time, const std::string& source_frame, const Time& source_time, const std::string& fixed_frame) const { validateFrameId("lookupTransform argument target_frame", target_frame); validateFrameId("lookupTransform argument source_frame", source_frame); validateFrameId("lookupTransform argument fixed_frame", fixed_frame); geometry_msgs::TransformStamped output; geometry_msgs::TransformStamped temp1 = lookupTransform(fixed_frame, source_frame, source_time); geometry_msgs::TransformStamped temp2 = lookupTransform(target_frame, fixed_frame, target_time); tf2::Transform tf1, tf2; transformMsgToTF2(temp1.transform, tf1); transformMsgToTF2(temp2.transform, tf2); transformTF2ToMsg(tf2 * tf1, output.transform); output.header.stamp = temp2.header.stamp; output.header.frame_id = target_frame; output.child_frame_id = source_frame; return output; } /* geometry_msgs::Twist BufferCore::lookupTwist(const std::string& tracking_frame, const std::string& observation_frame, constTime& time, const Duration& averaging_interval) const { try { geometry_msgs::Twist t; old_tf_.lookupTwist(tracking_frame, observation_frame, time, averaging_interval, t); return t; } catch (tf::LookupException& ex) { throw tf2::LookupException(ex.what()); } catch (tf::ConnectivityException& ex) { throw tf2::ConnectivityException(ex.what()); } catch (tf::ExtrapolationException& ex) { throw tf2::ExtrapolationException(ex.what()); } catch (tf::InvalidArgument& ex) { throw tf2::InvalidArgumentException(ex.what()); } } geometry_msgs::Twist BufferCore::lookupTwist(const std::string& tracking_frame, const std::string& observation_frame, const std::string& reference_frame, const tf2::Point & reference_point, const std::string& reference_point_frame, constTime& time, const Duration& averaging_interval) const { try{ geometry_msgs::Twist t; old_tf_.lookupTwist(tracking_frame, observation_frame, reference_frame, reference_point, reference_point_frame, time, averaging_interval, t); return t; } catch (tf::LookupException& ex) { throw tf2::LookupException(ex.what()); } catch (tf::ConnectivityException& ex) { throw tf2::ConnectivityException(ex.what()); } catch (tf::ExtrapolationException& ex) { throw tf2::ExtrapolationException(ex.what()); } catch (tf::InvalidArgument& ex) { throw tf2::InvalidArgumentException(ex.what()); } } */ struct CanTransformAccum { CompactFrameID gather(TimeCacheInterfacePtr cache, Time time, std::string* error_string) { return cache->getParent(time, error_string); } void accum(bool source) { (void) source;} void finalize(WalkEnding end, Time _time) { (void)end; (void) _time; } TransformStorage st; }; bool BufferCore::canTransformNoLock(CompactFrameID target_id, CompactFrameID source_id, const Time& time, std::string* error_msg) const { if (target_id == 0 || source_id == 0) { if (error_msg) { if (target_id == 0) { *error_msg += std::string("target_frame: " + lookupFrameString(target_id) + " does not exist."); } if (source_id == 0) { if (target_id == 0) { *error_msg += std::string(" "); } *error_msg += std::string("source_frame: " + lookupFrameString(source_id) + " " + lookupFrameString(source_id) + " does not exist."); } } return false; } if (target_id == source_id) { return true; } CanTransformAccum accum; if (walkToTopParent(accum, time, target_id, source_id, error_msg) == tf2_msgs::TF2Error::NO_ERROR) { return true; } return false; } bool BufferCore::canTransformInternal(CompactFrameID target_id, CompactFrameID source_id, const Time& time, std::string* error_msg) const { boost::mutex::scoped_lock lock(frame_mutex_); return canTransformNoLock(target_id, source_id, time, error_msg); } bool BufferCore::canTransform(const std::string& target_frame, const std::string& source_frame, const Time& time, std::string* error_msg) const { // Short circuit if target_frame == source_frame if (target_frame == source_frame) return true; if (warnFrameId("canTransform argument target_frame", target_frame)) return false; if (warnFrameId("canTransform argument source_frame", source_frame)) return false; boost::mutex::scoped_lock lock(frame_mutex_); CompactFrameID target_id = lookupFrameNumber(target_frame); CompactFrameID source_id = lookupFrameNumber(source_frame); if (target_id == 0 || source_id == 0) { if (error_msg) { if (target_id == 0) { *error_msg += std::string("canTransform: target_frame " + target_frame + " does not exist."); } if (source_id == 0) { if (target_id == 0) { *error_msg += std::string(" "); } *error_msg += std::string("canTransform: source_frame " + source_frame + " does not exist."); } } return false; } return canTransformNoLock(target_id, source_id, time, error_msg); } bool BufferCore::canTransform(const std::string& target_frame, const Time& target_time, const std::string& source_frame, const Time& source_time, const std::string& fixed_frame, std::string* error_msg) const { if (warnFrameId("canTransform argument target_frame", target_frame)) return false; if (warnFrameId("canTransform argument source_frame", source_frame)) return false; if (warnFrameId("canTransform argument fixed_frame", fixed_frame)) return false; boost::mutex::scoped_lock lock(frame_mutex_); CompactFrameID target_id = lookupFrameNumber(target_frame); CompactFrameID source_id = lookupFrameNumber(source_frame); CompactFrameID fixed_id = lookupFrameNumber(fixed_frame); if (target_id == 0 || source_id == 0 || fixed_id == 0) { if (error_msg) { if (target_id == 0) { *error_msg += std::string("canTransform: target_frame " + target_frame + " does not exist."); } if (source_id == 0) { if (target_id == 0) { *error_msg += std::string(" "); } *error_msg += std::string("canTransform: source_frame " + source_frame + " does not exist."); } if (source_id == 0) { if (target_id == 0 || source_id == 0) { *error_msg += std::string(" "); } *error_msg += std::string("fixed_frame: " + fixed_frame + "does not exist."); } } return false; } return canTransformNoLock(target_id, fixed_id, target_time, error_msg) && canTransformNoLock(fixed_id, source_id, source_time, error_msg); } tf2::TimeCacheInterfacePtr BufferCore::getFrame(CompactFrameID frame_id) const { if (frame_id >= frames_.size()) return TimeCacheInterfacePtr(); else { return frames_[frame_id]; } } CompactFrameID BufferCore::lookupFrameNumber( const std::string& frameid_str) const { CompactFrameID retval; M_StringToCompactFrameID::const_iterator map_it = frameIDs_.find(frameid_str); if (map_it == frameIDs_.end()) { retval = CompactFrameID(0); } else retval = map_it->second; return retval; } CompactFrameID BufferCore::lookupOrInsertFrameNumber( const std::string& frameid_str) { CompactFrameID retval = 0; M_StringToCompactFrameID::iterator map_it = frameIDs_.find(frameid_str); if (map_it == frameIDs_.end()) { retval = CompactFrameID(frames_.size()); frames_.push_back( TimeCacheInterfacePtr()); // Just a place holder for iteration frameIDs_[frameid_str] = retval; frameIDs_reverse.push_back(frameid_str); } else retval = frameIDs_[frameid_str]; return retval; } const std::string& BufferCore::lookupFrameString( CompactFrameID frame_id_num) const { if (frame_id_num >= frameIDs_reverse.size()) { std::stringstream ss; ss << "Reverse lookup of frame id " << frame_id_num << " failed!"; throw tf2::LookupException(ss.str()); } else return frameIDs_reverse[frame_id_num]; } void BufferCore::createConnectivityErrorString(CompactFrameID source_frame, CompactFrameID target_frame, std::string* out) const { if (!out) { return; } *out = std::string("Could not find a connection between '" + lookupFrameString(target_frame) + "' and '" + lookupFrameString(source_frame) + "' because they are not part of the same tree." + "Tf has two or more unconnected trees."); } std::string BufferCore::allFramesAsString() const { boost::mutex::scoped_lock lock(frame_mutex_); return this->allFramesAsStringNoLock(); } std::string BufferCore::allFramesAsStringNoLock() const { std::stringstream mstream; TransformStorage temp; // for (std::vector< TimeCache*>::iterator it = frames_.begin(); it != // frames_.end(); ++it) /// regular transforms for (unsigned int counter = 1; counter < frames_.size(); counter++) { TimeCacheInterfacePtr frame_ptr = getFrame(CompactFrameID(counter)); if (frame_ptr == NULL) continue; CompactFrameID frame_id_num; if (frame_ptr->getData(0, temp)) frame_id_num = temp.frame_id_; else { frame_id_num = 0; } mstream << "Frame " << frameIDs_reverse[counter] << " exists with parent " << frameIDs_reverse[frame_id_num] << "." << std::endl; } return mstream.str(); } struct TimeAndFrameIDFrameComparator { TimeAndFrameIDFrameComparator(CompactFrameID id) : id(id) {} bool operator()(const P_TimeAndFrameID& rhs) const { return rhs.second == id; } CompactFrameID id; }; int BufferCore::getLatestCommonTime(CompactFrameID target_id, CompactFrameID source_id, Time& time, std::string* error_string) const { // Error if one of the frames don't exist. if (source_id == 0 || target_id == 0) return tf2_msgs::TF2Error::LOOKUP_ERROR; if (source_id == target_id) { TimeCacheInterfacePtr cache = getFrame(source_id); // Set time to latest timestamp of frameid in case of target and source // frame id are the same if (cache) time = cache->getLatestTimestamp(); else time = 0; return tf2_msgs::TF2Error::NO_ERROR; } std::vector<P_TimeAndFrameID> lct_cache; // Walk the tree to its root from the source frame, accumulating the list of // parent/time as well as the latest time // in the target is a direct parent CompactFrameID frame = source_id; P_TimeAndFrameID temp; uint32_t depth = 0; Time common_time = TIME_MAX; while (frame != 0) { TimeCacheInterfacePtr cache = getFrame(frame); if (!cache) { // There will be no cache for the very root of the tree break; } P_TimeAndFrameID latest = cache->getLatestTimeAndParent(); if (latest.second == 0) { // Just break out here... there may still be a path from source -> target break; } if (latest.first != 0) { common_time = std::min(latest.first, common_time); } lct_cache.push_back(latest); frame = latest.second; // Early out... target frame is a direct parent of the source frame if (frame == target_id) { time = common_time; if (time == TIME_MAX) { time = 0; } return tf2_msgs::TF2Error::NO_ERROR; } ++depth; if (depth > MAX_GRAPH_DEPTH) { if (error_string) { std::stringstream ss; ss << "The tf tree is invalid because it contains a loop." << std::endl << allFramesAsStringNoLock() << std::endl; *error_string = ss.str(); } return tf2_msgs::TF2Error::LOOKUP_ERROR; } } // Now walk to the top parent from the target frame, accumulating the latest // time and looking for a common parent frame = target_id; depth = 0; common_time = TIME_MAX; CompactFrameID common_parent = 0; while (true) { TimeCacheInterfacePtr cache = getFrame(frame); if (!cache) { break; } P_TimeAndFrameID latest = cache->getLatestTimeAndParent(); if (latest.second == 0) { break; } if (latest.first != 0) { common_time = std::min(latest.first, common_time); } std::vector<P_TimeAndFrameID>::iterator it = std::find_if(lct_cache.begin(), lct_cache.end(), TimeAndFrameIDFrameComparator(latest.second)); if (it != lct_cache.end()) // found a common parent { common_parent = it->second; break; } frame = latest.second; // Early out... source frame is a direct parent of the target frame if (frame == source_id) { time = common_time; if (time == TIME_MAX) { time = 0; } return tf2_msgs::TF2Error::NO_ERROR; } ++depth; if (depth > MAX_GRAPH_DEPTH) { if (error_string) { std::stringstream ss; ss << "The tf tree is invalid because it contains a loop." << std::endl << allFramesAsStringNoLock() << std::endl; *error_string = ss.str(); } return tf2_msgs::TF2Error::LOOKUP_ERROR; } } if (common_parent == 0) { createConnectivityErrorString(source_id, target_id, error_string); return tf2_msgs::TF2Error::CONNECTIVITY_ERROR; } // Loop through the source -> root list until we hit the common parent { std::vector<P_TimeAndFrameID>::iterator it = lct_cache.begin(); std::vector<P_TimeAndFrameID>::iterator end = lct_cache.end(); for (; it != end; ++it) { if (it->first != 0) { common_time = std::min(common_time, it->first); } if (it->second == common_parent) { break; } } } if (common_time == TIME_MAX) { common_time = 0; } time = common_time; return tf2_msgs::TF2Error::NO_ERROR; } std::string BufferCore::allFramesAsYAML(double current_time) const { std::stringstream mstream; boost::mutex::scoped_lock lock(frame_mutex_); TransformStorage temp; if (frames_.size() == 1) mstream << "[]"; mstream.precision(3); mstream.setf(std::ios::fixed, std::ios::floatfield); // for (std::vector< TimeCache*>::iterator it = frames_.begin(); it != // frames_.end(); ++it) for (unsigned int counter = 1; counter < frames_.size(); counter++) // one referenced for 0 is no frame { CompactFrameID cfid = CompactFrameID(counter); CompactFrameID frame_id_num; TimeCacheInterfacePtr cache = getFrame(cfid); if (!cache) { continue; } if (!cache->getData(0, temp)) { continue; } frame_id_num = temp.frame_id_; std::string authority = "no recorded authority"; std::map<CompactFrameID, std::string>::const_iterator it = frame_authority_.find(cfid); if (it != frame_authority_.end()) { authority = it->second; } double rate = cache->getListLength() / std::max(time_to_sec(cache->getLatestTimestamp() - cache->getOldestTimestamp()), 0.0001); mstream << std::fixed; // fixed point notation mstream.precision(3); // 3 decimal places mstream << frameIDs_reverse[cfid] << ": " << std::endl; mstream << " parent: '" << frameIDs_reverse[frame_id_num] << "'" << std::endl; mstream << " broadcaster: '" << authority << "'" << std::endl; mstream << " rate: " << rate << std::endl; mstream << " most_recent_transform: " << time_to_sec(cache->getLatestTimestamp()) << std::endl; mstream << " oldest_transform: " << time_to_sec(cache->getOldestTimestamp()) << std::endl; if (current_time > 0) { mstream << " transform_delay: " << current_time - time_to_sec(cache->getLatestTimestamp()) << std::endl; } mstream << " buffer_length: " << time_to_sec(cache->getLatestTimestamp() - cache->getOldestTimestamp()) << std::endl; } return mstream.str(); } std::string BufferCore::allFramesAsYAML() const { return this->allFramesAsYAML(0.0); } TransformableCallbackHandle BufferCore::addTransformableCallback( const TransformableCallback& cb) { boost::mutex::scoped_lock lock(transformable_callbacks_mutex_); TransformableCallbackHandle handle = ++transformable_callbacks_counter_; while (!transformable_callbacks_.insert(std::make_pair(handle, cb)).second) { handle = ++transformable_callbacks_counter_; } return handle; } struct BufferCore::RemoveRequestByCallback { RemoveRequestByCallback(TransformableCallbackHandle handle) : handle_(handle) {} bool operator()(const TransformableRequest& req) { return req.cb_handle == handle_; } TransformableCallbackHandle handle_; }; void BufferCore::removeTransformableCallback( TransformableCallbackHandle handle) { { boost::mutex::scoped_lock lock(transformable_callbacks_mutex_); transformable_callbacks_.erase(handle); } { boost::mutex::scoped_lock lock(transformable_requests_mutex_); V_TransformableRequest::iterator it = std::remove_if( transformable_requests_.begin(), transformable_requests_.end(), RemoveRequestByCallback(handle)); transformable_requests_.erase(it, transformable_requests_.end()); } } TransformableRequestHandle BufferCore::addTransformableRequest( TransformableCallbackHandle handle, const std::string& target_frame, const std::string& source_frame, Time time) { // shortcut if target == source if (target_frame == source_frame) { return 0; } TransformableRequest req; req.target_id = lookupFrameNumber(target_frame); req.source_id = lookupFrameNumber(source_frame); // First check if the request is already transformable. If it is, return // immediately if (canTransformInternal(req.target_id, req.source_id, time, 0)) { return 0; } // Might not be transformable at all, ever (if it's too far in the past) if (req.target_id && req.source_id) { Time latest_time; // TODO: This is incorrect, but better than nothing. Really we want the // latest time for // any of the frames getLatestCommonTime(req.target_id, req.source_id, latest_time, 0); if (latest_time != 0 && time + cache_time_ < latest_time) { return 0xffffffffffffffffULL; } } req.cb_handle = handle; req.time = time; req.request_handle = ++transformable_requests_counter_; if (req.request_handle == 0 || req.request_handle == 0xffffffffffffffffULL) { req.request_handle = 1; } if (req.target_id == 0) { req.target_string = target_frame; } if (req.source_id == 0) { req.source_string = source_frame; } boost::mutex::scoped_lock lock(transformable_requests_mutex_); transformable_requests_.push_back(req); return req.request_handle; } struct BufferCore::RemoveRequestByID { RemoveRequestByID(TransformableRequestHandle handle) : handle_(handle) {} bool operator()(const TransformableRequest& req) { return req.request_handle == handle_; } TransformableCallbackHandle handle_; }; void BufferCore::cancelTransformableRequest(TransformableRequestHandle handle) { boost::mutex::scoped_lock lock(transformable_requests_mutex_); V_TransformableRequest::iterator it = std::remove_if(transformable_requests_.begin(), transformable_requests_.end(), RemoveRequestByID(handle)); if (it != transformable_requests_.end()) { transformable_requests_.erase(it, transformable_requests_.end()); } } // backwards compability for tf methods boost::signals2::connection BufferCore::_addTransformsChangedListener( boost::function<void(void)> callback) { boost::mutex::scoped_lock lock(transformable_requests_mutex_); return _transforms_changed_.connect(callback); } void BufferCore::_removeTransformsChangedListener( boost::signals2::connection c) { boost::mutex::scoped_lock lock(transformable_requests_mutex_); c.disconnect(); } bool BufferCore::_frameExists(const std::string& frame_id_str) const { boost::mutex::scoped_lock lock(frame_mutex_); return frameIDs_.count(frame_id_str); } bool BufferCore::_getParent(const std::string& frame_id, Time time, std::string& parent) const { boost::mutex::scoped_lock lock(frame_mutex_); CompactFrameID frame_number = lookupFrameNumber(frame_id); TimeCacheInterfacePtr frame = getFrame(frame_number); if (!frame) return false; CompactFrameID parent_id = frame->getParent(time, NULL); if (parent_id == 0) return false; parent = lookupFrameString(parent_id); return true; }; void BufferCore::_getFrameStrings(std::vector<std::string>& vec) const { vec.clear(); boost::mutex::scoped_lock lock(frame_mutex_); TransformStorage temp; // for (std::vector< TimeCache*>::iterator it = frames_.begin(); it != // frames_.end(); ++it) for (unsigned int counter = 1; counter < frameIDs_reverse.size(); counter++) { vec.push_back(frameIDs_reverse[counter]); } return; } void BufferCore::testTransformableRequests() { boost::mutex::scoped_lock lock(transformable_requests_mutex_); V_TransformableRequest::iterator it = transformable_requests_.begin(); typedef boost::tuple<TransformableCallback&, TransformableRequestHandle, std::string, std::string, Time&, TransformableResult&> TransformableTuple; std::vector<TransformableTuple> transformables; for (; it != transformable_requests_.end();) { TransformableRequest& req = *it; // One or both of the frames may not have existed when the request was // originally made. if (req.target_id == 0) { req.target_id = lookupFrameNumber(req.target_string); } if (req.source_id == 0) { req.source_id = lookupFrameNumber(req.source_string); } Time latest_time; bool do_cb = false; TransformableResult result = TransformAvailable; // TODO: This is incorrect, but better than nothing. Really we want the // latest time for // any of the frames getLatestCommonTime(req.target_id, req.source_id, latest_time, 0); if (latest_time != 0 && req.time + cache_time_ < latest_time) { do_cb = true; result = TransformFailure; } else if (canTransformInternal(req.target_id, req.source_id, req.time, 0)) { do_cb = true; result = TransformAvailable; } if (do_cb) { { boost::mutex::scoped_lock lock2(transformable_callbacks_mutex_); M_TransformableCallback::iterator it = transformable_callbacks_.find(req.cb_handle); if (it != transformable_callbacks_.end()) { transformables.push_back( boost::make_tuple(boost::ref(it->second), req.request_handle, lookupFrameString(req.target_id), lookupFrameString(req.source_id), boost::ref(req.time), boost::ref(result))); } } if (transformable_requests_.size() > 1) { transformable_requests_[it - transformable_requests_.begin()] = transformable_requests_.back(); } transformable_requests_.erase(transformable_requests_.end() - 1); } else { ++it; } } // unlock before allowing possible user callbacks to avoid potential deadlock // (#91) lock.unlock(); BOOST_FOREACH (TransformableTuple tt, transformables) { tt.get<0>()(tt.get<1>(), tt.get<2>(), tt.get<3>(), tt.get<4>(), tt.get<5>()); } // Backwards compatability callback for tf _transforms_changed_(); } std::string BufferCore::_allFramesAsDot(double current_time) const { std::stringstream mstream; mstream << "digraph G {" << std::endl; boost::mutex::scoped_lock lock(frame_mutex_); TransformStorage temp; if (frames_.size() == 1) { mstream << "\"no tf data recieved\""; } mstream.precision(3); mstream.setf(std::ios::fixed, std::ios::floatfield); for (unsigned int counter = 1; counter < frames_.size(); counter++) // one referenced for 0 is no frame { unsigned int frame_id_num; TimeCacheInterfacePtr counter_frame = getFrame(counter); if (!counter_frame) { continue; } if (!counter_frame->getData(0, temp)) { continue; } else { frame_id_num = temp.frame_id_; } std::string authority = "no recorded authority"; std::map<unsigned int, std::string>::const_iterator it = frame_authority_.find(counter); if (it != frame_authority_.end()) authority = it->second; double rate = counter_frame->getListLength() / std::max(time_to_sec(counter_frame->getLatestTimestamp() - counter_frame->getOldestTimestamp()), 0.0001); mstream << std::fixed; // fixed point notation mstream.precision(3); // 3 decimal places mstream << "\"" << frameIDs_reverse[frame_id_num] << "\"" << " -> " << "\"" << frameIDs_reverse[counter] << "\"" << "[label=\"" //<< "Time: " << current_time.toSec() << "\\n" << "Broadcaster: " << authority << "\\n" << "Average rate: " << rate << " Hz\\n" << "Most recent transform: " << time_to_sec(counter_frame->getLatestTimestamp()) << " "; if (current_time > 0) mstream << "( " << current_time - time_to_sec(counter_frame->getLatestTimestamp()) << " sec old)"; mstream << "\\n" // << "(time: " << getFrame(counter)->getLatestTimestamp().toSec() << // ")\\n" // << "Oldest transform: " << (current_time - // getFrame(counter)->getOldestTimestamp()).toSec() << " sec old \\n" // << "(time: " << (getFrame(counter)->getOldestTimestamp()).toSec() // << ")\\n" << "Buffer length: " << time_to_sec(counter_frame->getLatestTimestamp() - counter_frame->getOldestTimestamp()) << " sec\\n" << "\"];" << std::endl; } for (unsigned int counter = 1; counter < frames_.size(); counter++) // one referenced for 0 is no frame { unsigned int frame_id_num; TimeCacheInterfacePtr counter_frame = getFrame(counter); if (!counter_frame) { if (current_time > 0) { mstream << "edge [style=invis];" << std::endl; mstream << " subgraph cluster_legend { style=bold; color=black; label " "=\"view_frames Result\";\n" << "\"Recorded at time: " << current_time << "\"[ shape=plaintext ] ;\n " << "}" << "->" << "\"" << frameIDs_reverse[counter] << "\";" << std::endl; } continue; } if (counter_frame->getData(0, temp)) { frame_id_num = temp.frame_id_; } else { frame_id_num = 0; } if (frameIDs_reverse[frame_id_num] == "NO_PARENT") { mstream << "edge [style=invis];" << std::endl; mstream << " subgraph cluster_legend { style=bold; color=black; label " "=\"view_frames Result\";\n"; if (current_time > 0) mstream << "\"Recorded at time: " << current_time << "\"[ shape=plaintext ] ;\n "; mstream << "}" << "->" << "\"" << frameIDs_reverse[counter] << "\";" << std::endl; } } mstream << "}"; return mstream.str(); } std::string BufferCore::_allFramesAsDot() const { return _allFramesAsDot(0.0); } void BufferCore::_chainAsVector(const std::string& target_frame, Time target_time, const std::string& source_frame, Time source_time, const std::string& fixed_frame, std::vector<std::string>& output) const { std::string error_string; output.clear(); // empty vector std::stringstream mstream; boost::mutex::scoped_lock lock(frame_mutex_); TransformAccum accum; // Get source frame/time using getFrame CompactFrameID source_id = lookupFrameNumber(source_frame); CompactFrameID fixed_id = lookupFrameNumber(fixed_frame); CompactFrameID target_id = lookupFrameNumber(target_frame); std::vector<CompactFrameID> source_frame_chain; int retval = walkToTopParent(accum, source_time, fixed_id, source_id, &error_string, &source_frame_chain); if (retval != tf2_msgs::TF2Error::NO_ERROR) { switch (retval) { case tf2_msgs::TF2Error::CONNECTIVITY_ERROR: throw ConnectivityException(error_string); case tf2_msgs::TF2Error::EXTRAPOLATION_ERROR: throw ExtrapolationException(error_string); case tf2_msgs::TF2Error::LOOKUP_ERROR: throw LookupException(error_string); default: // logError("Unknown error code: %d", retval); assert(0); } } if (source_time != target_time) { std::vector<CompactFrameID> target_frame_chain; retval = walkToTopParent(accum, target_time, target_id, fixed_id, &error_string, &target_frame_chain); if (retval != tf2_msgs::TF2Error::NO_ERROR) { switch (retval) { case tf2_msgs::TF2Error::CONNECTIVITY_ERROR: throw ConnectivityException(error_string); case tf2_msgs::TF2Error::EXTRAPOLATION_ERROR: throw ExtrapolationException(error_string); case tf2_msgs::TF2Error::LOOKUP_ERROR: throw LookupException(error_string); default: // logError("Unknown error code: %d", retval); assert(0); } } int m = target_frame_chain.size() - 1; int n = source_frame_chain.size() - 1; for (; m >= 0 && n >= 0; --m, --n) { if (source_frame_chain[n] != target_frame_chain[m]) break; } // Erase all duplicate items from frame_chain if (n > 0) source_frame_chain.erase(source_frame_chain.begin() + (n - 1), source_frame_chain.end()); int z = target_frame_chain.size(); if (m < z) { for (int i = 0; i <= m; ++i) { source_frame_chain.push_back(target_frame_chain[i]); } } } // Write each element of source_frame_chain as string for (unsigned int i = 0; i < source_frame_chain.size(); ++i) { output.push_back(lookupFrameString(source_frame_chain[i])); } } } // namespace tf2
0
apollo_public_repos/apollo/third_party/tf2
apollo_public_repos/apollo/third_party/tf2/src/cache.cpp
/* * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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. */ /** \author Tully Foote */ #include "tf2/time_cache.h" #include "tf2/exceptions.h" #include <tf2/LinearMath/Vector3.h> #include <tf2/LinearMath/Quaternion.h> #include <tf2/LinearMath/Transform.h> #include <assert.h> #include "geometry_msgs/transform_stamped.h" namespace tf2 { TransformStorage::TransformStorage() { } TransformStorage::TransformStorage(const geometry_msgs::TransformStamped& data, CompactFrameID frame_id, CompactFrameID child_frame_id) : stamp_(data.header.stamp) , frame_id_(frame_id) , child_frame_id_(child_frame_id) { const geometry_msgs::Quaternion& o = data.transform.rotation; rotation_ = tf2::Quaternion(o.x, o.y, o.z, o.w); const geometry_msgs::Vector3& v = data.transform.translation; translation_ = tf2::Vector3(v.x, v.y, v.z); } TimeCache::TimeCache(Duration max_storage_time) : max_storage_time_(max_storage_time) {} namespace cache { // Avoid ODR collisions https://github.com/ros/geometry2/issues/175 // hoisting these into separate functions causes an ~8% speedup. Removing calling them altogether adds another ~10% void createExtrapolationException1(Time t0, Time t1, std::string* error_str) { if (error_str) { std::stringstream ss; ss << "Lookup would require extrapolation at time " << t0 << ", but only time " << t1 << " is in the buffer"; *error_str = ss.str(); } } void createExtrapolationException2(Time t0, Time t1, std::string* error_str) { if (error_str) { std::stringstream ss; ss << "Lookup would require extrapolation into the future. Requested time " << t0 << " but the latest data is at time " << t1; *error_str = ss.str(); } } void createExtrapolationException3(Time t0, Time t1, std::string* error_str) { if (error_str) { std::stringstream ss; ss << "Lookup would require extrapolation into the past. Requested time " << t0 << " but the earliest data is at time " << t1; *error_str = ss.str(); } } } // namespace cache uint8_t TimeCache::findClosest(TransformStorage*& one, TransformStorage*& two, Time target_time, std::string* error_str) { //No values stored if (storage_.empty()) { return 0; } //If time == 0 return the latest if (target_time == 0) { one = &storage_.front(); return 1; } // One value stored if (++storage_.begin() == storage_.end()) { TransformStorage& ts = *storage_.begin(); if (ts.stamp_ == target_time) { one = &ts; return 1; } else { cache::createExtrapolationException1(target_time, ts.stamp_, error_str); return 0; } } Time latest_time = (*storage_.begin()).stamp_; Time earliest_time = (*(storage_.rbegin())).stamp_; if (target_time == latest_time) { one = &(*storage_.begin()); return 1; } else if (target_time == earliest_time) { one = &(*storage_.rbegin()); return 1; } // Catch cases that would require extrapolation else if (target_time > latest_time) { cache::createExtrapolationException2(target_time, latest_time, error_str); return 0; } else if (target_time < earliest_time) { cache::createExtrapolationException3(target_time, earliest_time, error_str); return 0; } //At least 2 values stored //Find the first value less than the target value L_TransformStorage::iterator storage_it = storage_.begin(); while(storage_it != storage_.end()) { if (storage_it->stamp_ <= target_time) break; ++storage_it; } if (storage_it == storage_.end()) { return 0; } if (storage_it == storage_.begin()) { one = &*(storage_it); //Older return 1; } //Finally the case were somewhere in the middle Guarenteed no extrapolation :-) one = &*(storage_it); //Older two = &*(--storage_it); //Newer return 2; } void TimeCache::interpolate(const TransformStorage& one, const TransformStorage& two, Time time, TransformStorage& output) { // Check for zero distance case if( two.stamp_ == one.stamp_ ) { output = two; return; } //Calculate the ratio // tf2Scalar ratio = (time.toSec() - one.stamp_.toSec()) / (two.stamp_.toSec() - one.stamp_.toSec()); tf2Scalar ratio = time_to_sec(time - one.stamp_) / time_to_sec(two.stamp_ - one.stamp_); //Interpolate translation output.translation_.setInterpolate3(one.translation_, two.translation_, ratio); //Interpolate rotation output.rotation_ = slerp( one.rotation_, two.rotation_, ratio); output.stamp_ = one.stamp_; output.frame_id_ = one.frame_id_; output.child_frame_id_ = one.child_frame_id_; } bool TimeCache::getData(Time time, TransformStorage & data_out, std::string* error_str) //returns false if data not available { TransformStorage* p_temp_1; TransformStorage* p_temp_2; int num_nodes = findClosest(p_temp_1, p_temp_2, time, error_str); if (num_nodes == 0) { return false; } else if (num_nodes == 1) { data_out = *p_temp_1; } else if (num_nodes == 2) { if( p_temp_1->frame_id_ == p_temp_2->frame_id_) { interpolate(*p_temp_1, *p_temp_2, time, data_out); } else { data_out = *p_temp_1; } } else { assert(0); } return true; } CompactFrameID TimeCache::getParent(Time time, std::string* error_str) { TransformStorage* p_temp_1; TransformStorage* p_temp_2; int num_nodes = findClosest(p_temp_1, p_temp_2, time, error_str); if (num_nodes == 0) { return 0; } return p_temp_1->frame_id_; } bool TimeCache::insertData(const TransformStorage& new_data) { L_TransformStorage::iterator storage_it = storage_.begin(); if(storage_it != storage_.end()) { if (storage_it->stamp_ > new_data.stamp_ + max_storage_time_) { return false; } } while(storage_it != storage_.end()) { if (storage_it->stamp_ <= new_data.stamp_) break; ++storage_it; } storage_.insert(storage_it, new_data); pruneList(); return true; } void TimeCache::clearList() { storage_.clear(); } unsigned int TimeCache::getListLength() { return storage_.size(); } P_TimeAndFrameID TimeCache::getLatestTimeAndParent() { if (storage_.empty()) { return std::make_pair(Time(), 0); } const TransformStorage& ts = storage_.front(); return std::make_pair(ts.stamp_, ts.frame_id_); } Time TimeCache::getLatestTimestamp() { if (storage_.empty()) return Time(); //empty list case return storage_.front().stamp_; } Time TimeCache::getOldestTimestamp() { if (storage_.empty()) return Time(); //empty list case return storage_.back().stamp_; } void TimeCache::pruneList() { Time latest_time = storage_.begin()->stamp_; while(!storage_.empty() && storage_.back().stamp_ + max_storage_time_ < latest_time) { storage_.pop_back(); } // std::cout << "max_storage_time:" << max_storage_time_ <<", time cache list size:" << storage_.size() << std::endl; } // namespace tf2 }
0
apollo_public_repos/apollo/third_party/tf2
apollo_public_repos/apollo/third_party/tf2/src/time.cpp
#include "tf2/time.h" namespace tf2 { double time_to_sec(Time t) { return static_cast<double>(t) / 1e9; } }
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/py/init.bzl
load("//third_party/py:python_configure.bzl", "python_configure") def init(): python_configure(name = "local_config_python")
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/py/BUILD.tpl
# Adapted with modifications from tensorflow/third_party/py/ load("@rules_cc//cc:defs.bzl", "cc_library") package(default_visibility = ["//visibility:public"]) # config_setting( # name="python3", # flag_values = {"@rules_python//python:python_version": "PY3"} # ) cc_library( name = "python_lib", deps = ["//_python3:_python3_lib"], ) cc_library( name = "python_headers", deps = ["//_python3:_python3_headers"], )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/py/cyberfile.xml
<package format="2"> <name>3rd-py</name> <version>local</version> <description> Apollo packaged py Lib. </description> <maintainer email="apollo-support@baidu.com">Apollo</maintainer> <license>Apache License 2.0</license> <url type="website">https://www.apollo.auto/</url> <url type="repository">https://github.com/ApolloAuto/apollo</url> <url type="bugtracker">https://github.com/ApolloAuto/apollo/issues</url> <type>third-wrapper</type> <src_path url="https://github.com/ApolloAuto/apollo">//third_party/py</src_path> </package>
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/py/python_configure.bzl
# Adapted with modifications from tensorflow/third_party/py/ """Repository rule for Python autoconfiguration. `python_configure` depends on the following environment variables: * `PYTHON_BIN_PATH`: location of python binary. * `PYTHON_LIB_PATH`: Location of python libraries. """ load("//tools:common.bzl", "basename") _BAZEL_SH = "BAZEL_SH" _PYTHON3_BIN_PATH = "PYTHON_BIN_PATH" _PYTHON3_LIB_PATH = "PYTHON_LIB_PATH" _HEADERS_HELP = ( "Are Python3 headers installed? Try installing python3-dev on " + "Debian-based systems. Try python3-devel on Redhat-based systems." ) def _tpl(repository_ctx, tpl, substitutions = {}, out = None): if not out: out = tpl repository_ctx.template( out, Label("//third_party/py:%s.tpl" % tpl), substitutions, ) def _fail(msg): """Output failure message when auto configuration fails.""" red = "\033[0;31m" no_color = "\033[0m" fail("%sPython Configuration Error:%s %s\n" % (red, no_color, msg)) def _execute( repository_ctx, cmdline, error_msg = None, error_details = None, empty_stdout_fine = False): """Executes an arbitrary shell command. Args: repository_ctx: the repository_ctx object cmdline: list of strings, the command to execute error_msg: string, a summary of the error if the command fails error_details: string, details about the error or steps to fix it empty_stdout_fine: bool, if True, an empty stdout result is fine, otherwise it's an error Return: the result of repository_ctx.execute(cmdline) """ result = repository_ctx.execute(cmdline) if result.stderr or not (empty_stdout_fine or result.stdout): _fail("\n".join([ error_msg.strip() if error_msg else "Repository command failed", result.stderr.strip(), error_details if error_details else "", ])) else: return result def _read_dir(repository_ctx, src_dir): """Returns a string with all files in a directory. Finds all files inside a directory, traversing subfolders and following symlinks. The returned string contains the full path of all files separated by line breaks. """ find_result = _execute( repository_ctx, ["find", src_dir, "-follow", "-type", "f"], empty_stdout_fine = True, ) return find_result.stdout def _genrule(src_dir, genrule_name, command, outs): """Returns a string with a genrule. Genrule executes the given command and produces the given outputs. """ return ("genrule(\n" + ' name = "' + genrule_name + '",\n' + " outs = [\n" + outs + "\n ],\n" + ' cmd = """\n' + command + '\n """,\n' + ")\n") def _normalize_path(path): """Returns a path with '/' and remove the trailing slash.""" path = path.replace("\\", "/") if path[-1] == "/": path = path[:-1] return path def _symlink_genrule_for_dir( repository_ctx, src_dir, dest_dir, genrule_name, src_files = [], dest_files = []): """Returns a genrule to symlink a set of files. If src_dir is passed, files will be read from the given directory; otherwise we assume files are in src_files and dest_files """ if src_dir != None: src_dir = _normalize_path(src_dir) dest_dir = _normalize_path(dest_dir) files = "\n".join( sorted(_read_dir(repository_ctx, src_dir).splitlines()), ) # Create a list with the src_dir stripped to use for outputs. dest_files = files.replace(src_dir, "").splitlines() src_files = files.splitlines() command = [] outs = [] for i in range(len(dest_files)): if dest_files[i] != "": # If we have only one file to link we do not want to use the dest_dir, as # $(@D) will include the full path to the file. dest = "$(@D)/" + dest_dir + dest_files[i] if len( dest_files, ) != 1 else "$(@D)/" + dest_files[i] cmd = "ln -s" command.append(cmd + ' "%s" "%s"' % (src_files[i], dest)) outs.append(' "' + dest_dir + dest_files[i] + '",') return _genrule( src_dir, genrule_name, " && ".join(command), "\n".join(outs), ) def _get_python_bin(repository_ctx, bin_path_key, default_bin_path): """Gets the python bin path.""" python_bin = repository_ctx.os.environ.get(bin_path_key, default_bin_path) if not repository_ctx.path(python_bin).exists: # It's a command, use 'which' to find its path. python_bin_path = repository_ctx.which(python_bin) else: # It's a path, use it as it is. python_bin_path = python_bin if python_bin_path != None: return str(python_bin_path) _fail("Cannot find python in PATH, please make sure " + "python is installed and add its directory in PATH, or --define " + "%s='/something/else'.\nPATH=%s" % (bin_path_key, repository_ctx.os.environ.get("PATH", ""))) def _get_bash_bin(repository_ctx): """Gets the bash bin path.""" bash_bin = repository_ctx.os.environ.get(_BAZEL_SH) if bash_bin != None: return bash_bin else: bash_bin_path = repository_ctx.which("bash") if bash_bin_path != None: return str(bash_bin_path) else: _fail( "Cannot find bash in PATH, please make sure " + "bash is installed and add its directory in PATH, or --define " + "%s='/path/to/bash'.\nPATH=%s" % (_BAZEL_SH, repository_ctx.os.environ.get("PATH", "")), ) def _get_python_lib(repository_ctx, python_bin, lib_path_key): """Gets the python lib path.""" python_lib = repository_ctx.os.environ.get(lib_path_key) if python_lib != None: return python_lib print_lib = ( "<<END\n" + "from __future__ import print_function\n" + "import site\n" + "import os\n" + "\n" + "try:\n" + " input = raw_input\n" + "except NameError:\n" + " pass\n" + "\n" + "python_paths = []\n" + "if os.getenv('PYTHONPATH') is not None:\n" + " python_paths = os.getenv('PYTHONPATH').split(':')\n" + "try:\n" + " library_paths = site.getsitepackages()\n" + "except AttributeError:\n" + " from distutils.sysconfig import get_python_lib\n" + " library_paths = [get_python_lib()]\n" + "all_paths = set(python_paths + library_paths)\n" + "paths = []\n" + "for path in all_paths:\n" + " if os.path.isdir(path):\n" + " paths.append(path)\n" + "if len(paths) >=1:\n" + " print(paths[0])\n" + "END" ) cmd = "%s - %s" % (python_bin, print_lib) result = repository_ctx.execute([_get_bash_bin(repository_ctx), "-c", cmd]) return result.stdout.strip("\n") def _check_python_lib(repository_ctx, python_lib): """Checks the python lib path.""" cmd = 'test -d "%s" -a -x "%s"' % (python_lib, python_lib) result = repository_ctx.execute([_get_bash_bin(repository_ctx), "-c", cmd]) if result.return_code == 1: _fail("Invalid python library path: %s" % python_lib) def _check_python_bin(repository_ctx, python_bin, bin_path_key): """Checks the python bin path.""" cmd = '[[ -x "%s" ]] && [[ ! -d "%s" ]]' % (python_bin, python_bin) result = repository_ctx.execute([_get_bash_bin(repository_ctx), "-c", cmd]) if result.return_code == 1: _fail("--define %s='%s' is not executable. Is it the python binary?" % (bin_path_key, python_bin)) def _get_python_include(repository_ctx, python_bin): """Gets the python include path.""" result = _execute( repository_ctx, [ python_bin, "-c", "from __future__ import print_function;" + "from distutils import sysconfig;" + "print(sysconfig.get_python_inc())", ], error_msg = "Problem getting python include path for {}.".format(python_bin), error_details = ( "Is the Python binary path set up right? " + "(See " + python_bin + ".) " + "Is distutils installed? " + _HEADERS_HELP ), ) include_path = result.stdout.splitlines()[0] _execute( repository_ctx, [ python_bin, "-c", "import os;" + "main_header = os.path.join('{}', 'Python.h');".format(include_path) + "assert os.path.exists(main_header), main_header + ' does not exist.'", ], error_msg = "Unable to find Python headers for {}".format(python_bin), error_details = _HEADERS_HELP, empty_stdout_fine = True, ) return include_path def _create_single_version_package( repository_ctx, variety_name, bin_path_key, default_bin_path, lib_path_key): """Creates the repository containing files set up to build with Python.""" python_bin = _get_python_bin(repository_ctx, bin_path_key, default_bin_path) _check_python_bin(repository_ctx, python_bin, bin_path_key) python_lib = _get_python_lib(repository_ctx, python_bin, lib_path_key) _check_python_lib(repository_ctx, python_lib) python_include = _get_python_include(repository_ctx, python_bin) python_include_rule = _symlink_genrule_for_dir( repository_ctx, python_include, "{}_include".format(variety_name), "{}_include".format(variety_name), ) python_solib = basename(python_include) _tpl( repository_ctx, "variety", { "%{PYTHON_INCLUDE_GENRULE}": python_include_rule, "%{VARIETY_NAME}": variety_name, "%{PYTHON_SO_NAME}": python_solib, }, out = "{}/BUILD".format(variety_name), ) def _python_autoconf_impl(repository_ctx): """Implementation of the python_autoconf repository rule.""" _create_single_version_package( repository_ctx, "_python3", _PYTHON3_BIN_PATH, "python3", _PYTHON3_LIB_PATH, ) _tpl(repository_ctx, "BUILD") python_configure = repository_rule( implementation = _python_autoconf_impl, environ = [ _BAZEL_SH, _PYTHON3_BIN_PATH, _PYTHON3_LIB_PATH, ], attrs = { "_build_tpl": attr.label( default = Label("//third_party/py:BUILD.tpl"), allow_single_file = True, ), "_variety_tpl": attr.label( default = Label("//third_party/py:variety.tpl"), allow_single_file = True, ), }, ) """Detects and configures the local Python. It is expected that the system have both a working Python 3 installation Add the following to your WORKSPACE FILE: ```python python_configure(name = "local_config_python") ``` Args: name: A unique name for this workspace rule. """
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/py/variety.tpl
package(default_visibility=["//visibility:public"]) cc_library( name="%{VARIETY_NAME}_lib", linkopts = ["-l%{PYTHON_SO_NAME}"], ) cc_library( name="%{VARIETY_NAME}_headers", hdrs=[":%{VARIETY_NAME}_include"], includes=["%{VARIETY_NAME}_include"], ) %{PYTHON_INCLUDE_GENRULE}
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/py/BUILD
load("//tools/install:install.bzl", "install", "install_files", "install_src_files") package( default_visibility = ["//visibility:public"], ) install( name = "install", data_dest = "3rd-py", data = [ ":cyberfile.xml", ], ) install_src_files( name = "install_src", src_dir = ["."], dest = "3rd-py/src", filter = "*", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/localization_msf/init.bzl
def init(): pass
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/localization_msf/cyberfile.xml
<package format="2"> <name>3rd-localization-msf</name> <version>local</version> <description> Apollo packaged localization-msf Lib. </description> <maintainer email="apollo-support@baidu.com">Apollo</maintainer> <license>Apache License 2.0</license> <url type="website">https://www.apollo.auto/</url> <url type="repository">https://github.com/ApolloAuto/apollo</url> <url type="bugtracker">https://github.com/ApolloAuto/apollo/issues</url> <type>third-wrapper</type> <src_path url="https://github.com/ApolloAuto/apollo">//third_party/localization_msf</src_path> </package>
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/localization_msf/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") load("//tools/install:install.bzl", "install", "install_files", "install_src_files") load("//tools/platform:build_defs.bzl", "if_aarch64", "if_x86_64") package(default_visibility = ["//visibility:public"]) licenses(["notice"]) cc_library( name = "localization_msf", srcs = if_x86_64([ "x86_64/lib/liblocalization_msf.so", ]) + if_aarch64([ "aarch64/lib/liblocalization_msf.so", ]), hdrs = if_x86_64(glob([ "x86_64/include/*.h", ])) + if_aarch64(glob([ "aarch64/include/*.h", ])), include_prefix = "localization_msf", linkopts = [ "-lm", ], strip_include_prefix = select({ "@platforms//cpu:x86_64": "x86_64/include", "@platforms//cpu:aarch64": "aarch64/include", }), ) install( name = "install", data_dest = "3rd-localization-msf", data = [ "cyberfile.xml", ], ) install_src_files( name = "install_src", src_dir = ["."], dest = "3rd-localization-msf/src", filter = "*", deps = [":install_src_lib"] ) install_src_files( name = "install_src_lib", src_dir = if_x86_64([ "x86_64/lib", ]) + if_aarch64([ "aarch64/lib", ]), dest = "3rd-localization-msf/lib", filter = "*", )
0
apollo_public_repos/apollo/third_party/localization_msf
apollo_public_repos/apollo/third_party/localization_msf/x86_64/meta.txt
1.0.4
0
apollo_public_repos/apollo/third_party/localization_msf/x86_64
apollo_public_repos/apollo/third_party/localization_msf/x86_64/include/euler_tf.h
#ifndef APOLLO_LOCALIZATION_EULER_TF_H #define APOLLO_LOCALIZATION_EULER_TF_H #include "sins_struct.h" namespace apollo { namespace localization { namespace msf { void quaternion_to_euler(const double quaternion[4], Attitude *att); void euler_to_quaternion(const double x_euler, const double y_euler, const double z_euler, double qbn[4]); void euler_to_dcm(const Attitude *att, double dcm[3][3]); void quaternion_to_dcm(const double *quaternion, double dcm[3][3]); } // namespace msf } // namespace localization } // namespace apollo #endif
0
apollo_public_repos/apollo/third_party/localization_msf/x86_64
apollo_public_repos/apollo/third_party/localization_msf/x86_64/include/sins_struct.h
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #pragma once #include <Eigen/Geometry> namespace apollo { namespace localization { namespace msf { typedef Eigen::Affine3d TransformD; /**@brief the imu data struct including time, accelerometer and gyro in body frame. */ struct ImuData { ImuData(): measurement_time(0.0), fb{0.0}, wibb{0.0} {} double measurement_time; // unix time double fb[3]; double wibb[3]; }; struct WheelspeedData { WheelspeedData(): time(0.0), front_right_speed(0.0), front_left_speed(0.0), rear_right_speed(0.0), rear_left_speed(0.0) {} double time; double front_right_speed; double front_left_speed; double rear_right_speed; double rear_left_speed; }; /**@brief the position struct including longitude, latitude and height. */ struct Position { Position(): longitude(0.0), latitude(0.0), height(0.0) {} double longitude; double latitude; double height; }; /**@brief the velocity struct in ENU navigation frame. */ struct Velocity { Velocity(): ve(0.0), vn(0.0), vu(0.0) {} double ve; double vn; double vu; }; /**@brief the attitude struct including pitch, roll and yaw. */ struct Attitude { Attitude(): pitch(0.0), roll(0.0), yaw(0.0) {} double pitch; double roll; double yaw; }; /**@brief the INS pva struct including time, sins position velocity attitude, attitude quaternion * and the sins alignment status. */ struct InsPva { InsPva (): time(0.0), qbn{1.0, 0.0, 0.0, 0.0}, init_and_alignment(false) {} double time; Position pos; Velocity vel; Attitude att; double qbn[4]; bool init_and_alignment; }; struct Pose { Pose(): x(0.0), y(0.0), z(0.0), qx(0.0), qy(0.0), qz(0.0), qw(1.0) {} double x; double y; double z; double qx; double qy; double qz; double qw; }; enum class SinsIntegUpdateType { SINS_UPDATE = 0, SINS_FILTER_TIME_UPDATE, FILTER_TIME_UPDATE, FILTER_MEASURE_UPDATE, ALL_UPDATE }; /**@brief the measure data source. */ enum class MeasureType { GNSS_POS_ONLY = 0, GNSS_POS_VEL, GNSS_POS_XY, ENU_VEL_ONLY, POINT_CLOUD_POS, ODOMETER_VEL_ONLY, VEHICLE_CONSTRAINT, GNSS_DOUBLE_ANT_YAW, ZUPT }; /**@brief the frame type. */ enum class FrameType { ENU = 0, //in this frame the position give x y and z from earth center ECEF, //in this frame the position give the longitude and latitude unit:rad UTM, //in this frame the position give x y and z in utm frame ODOMETER_BODY }; /**@brief the measure data give to the navigation kalman filter measure update. */ struct MeasureData { MeasureData(): time(0.0), gnss_mode(0), measure_type(MeasureType::GNSS_POS_ONLY), frame_type(FrameType::ENU), is_have_variance(false), variance{0.0} {} double time; Position gnss_pos; Velocity gnss_vel; Attitude gnss_att; int gnss_mode; //gnss positioning type MeasureType measure_type; FrameType frame_type; bool is_have_variance; double variance[10][10]; //the noise variance of the measurement }; /**@brief the parameter using in sins calculate. */ struct InertialParameter { double wien[3]; //the rate of the earth rotation on the navigation frame double wenn[3]; //the rate of the carrier rotation relate to earth on the navigation frame double rm; double rn; double g; }; } // namespace msf } // namespace localization } // namespace apollo
0
apollo_public_repos/apollo/third_party/localization_msf/x86_64
apollo_public_repos/apollo/third_party/localization_msf/x86_64/include/gnss_solver.h
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #pragma once #include "gnss_struct.h" #include "sins_struct.h" namespace apollo { namespace localization { namespace msf { class GnssPntSolver; class GnssSolver { public: GnssSolver(); ~GnssSolver(); //set before solve bool set_position_option(int option); int get_position_option(); void set_enable_external_prediction(bool b_enable); bool get_enable_external_prediction(); bool set_tropsphere_option(int option); bool set_ionosphere_option(int option); bool set_rtk_result_file(char* rtk_result_file); bool set_ambiguity_file(char* ambiguity_recorder_file); void enable_half_cycle_ar(const bool b_enable); bool get_enable_half_cycle_ar(); void enable_cycle_slip_fix(); //ephemeris bool save_gnss_ephemris(const GnssEphemerisMsg& gnss_orbit); //observation bool save_baser_observation(const EpochObservationMsg& baser_obs); int solve(EpochObservationMsg *rover_obs, apollo::localization::msf::GnssPntResultMsg *rover_pnt); bool motion_update_xyz(double time_sec, const double position[3], const double std_pos[3][3], const double velocity[3], const double std_vel[3][3]); bool motion_update(double time_sec, const double position[3], const double std_pos[3][3], const double velocity[3], const double std_vel[3][3], const double euler[3], const double lever_arm[3]); double get_leap_second(unsigned int gps_week_num, double gps_week_second_s); double get_ratio(); private: GnssPntSolver *solver_; }; } // namespace msf } // namespace localization } // namespace apollo
0
apollo_public_repos/apollo/third_party/localization_msf/x86_64
apollo_public_repos/apollo/third_party/localization_msf/x86_64/include/gnss_struct.h
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #pragma once typedef unsigned int uint32; typedef int int32; namespace apollo { namespace localization { namespace msf { enum GnssBandID { BAND_UNKNOWN = 0, GPS_L1 = 1, GPS_L2 = 2, GPS_L5 = 3, BDS_B1 = 4, BDS_B2 = 5, BDS_B3 = 6, GLO_G1 = 7, GLO_G2 = 8, GLO_G3 = 9, GAL_E1 = 10, GAL_E5a = 11, GAL_E5b = 12, GAL_E6 = 13 }; enum GnssTimeType { TIME_UNKNOWN = 0, GPS_TIME = 1, BDS_TIME = 2, GLO_TIME = 3, GAL_TIME = 4 }; enum GnssType { SYS_UNKNOWN = 0, GPS_SYS = 1, BDS_SYS = 2, GLO_SYS = 3, GAL_SYS = 4 }; enum PseudoType { CODE_UNKNOWN = 0, CORSE_CODE = 1, PRECISION_CODE = 2 }; enum PntType { PNT_INVALID = 0, PNT_SPP = 1, PNT_PHASE_TD = 2, PNT_CODE_DIFF = 3, PNT_RTK_FLOAT = 4, PNT_RTK_FIXED = 5 }; class BandObservation; class BandObservationMsg { public: BandObservationMsg(); ~BandObservationMsg(); void map(BandObservation *data); void unmap(); BandObservation* mutable_data(); const BandObservation& data() const; bool has_band_id() const; void clear_band_id(); ::apollo::localization::msf::GnssBandID band_id() const; void set_band_id(::apollo::localization::msf::GnssBandID value); bool has_frequency_value() const; void clear_frequency_value(); double frequency_value() const; void set_frequency_value(double value); bool has_pseudo_type() const; void clear_pseudo_type(); ::apollo::localization::msf::PseudoType pseudo_type() const; void set_pseudo_type(::apollo::localization::msf::PseudoType value); bool has_pseudo_range() const; void clear_pseudo_range(); double pseudo_range() const; void set_pseudo_range(double value); bool has_carrier_phase() const; void clear_carrier_phase(); double carrier_phase() const; void set_carrier_phase(double value); bool has_loss_lock_index() const; void clear_loss_lock_index(); uint32 loss_lock_index() const; void set_loss_lock_index(uint32 value); bool has_doppler() const; void clear_doppler(); double doppler() const; void set_doppler(double value); bool has_snr() const; void clear_snr(); float snr() const; void set_snr(float value); private: BandObservation *data_; bool is_mapped_; }; class SatelliteObservation; class SatelliteObservationMsg { public: SatelliteObservationMsg(); ~SatelliteObservationMsg(); void map(SatelliteObservation *data); void unmap(); SatelliteObservation* mutable_data(); const SatelliteObservation& data() const; bool has_sat_prn() const; void clear_sat_prn(); uint32 sat_prn() const; void set_sat_prn(uint32 value); bool has_sat_sys() const; void clear_sat_sys(); ::apollo::localization::msf::GnssType sat_sys() const; void set_sat_sys(::apollo::localization::msf::GnssType value); bool has_band_obs_num() const; void clear_band_obs_num(); uint32 band_obs_num() const; void set_band_obs_num(uint32 value); int band_obs_size() const; void clear_band_obs(); const ::apollo::localization::msf::BandObservationMsg& band_obs(int index); ::apollo::localization::msf::BandObservationMsg* mutable_band_obs(int index); ::apollo::localization::msf::BandObservationMsg* add_band_obs(); private: SatelliteObservation *data_; bool is_mapped_; BandObservationMsg *band_obervation_msg_; }; class EpochObservation; class EpochObservationMsg { public: EpochObservationMsg(); ~EpochObservationMsg(); void map(EpochObservation *data); void unmap(); EpochObservation* mutable_data(); const EpochObservation& data() const; bool has_receiver_id() const; void clear_receiver_id(); uint32 receiver_id() const; void set_receiver_id(uint32 value); bool has_gnss_time_type() const; void clear_gnss_time_type(); ::apollo::localization::msf::GnssTimeType gnss_time_type() const; void set_gnss_time_type(::apollo::localization::msf::GnssTimeType value); bool has_gnss_week() const; void clear_gnss_week(); uint32 gnss_week() const; void set_gnss_week(uint32 value); bool has_gnss_second_s() const; void clear_gnss_second_s(); double gnss_second_s() const; void set_gnss_second_s(double value); bool has_position_x() const; void clear_position_x(); double position_x() const; void set_position_x(double value); bool has_position_y() const; void clear_position_y(); double position_y() const; void set_position_y(double value); bool has_position_z() const; void clear_position_z(); double position_z() const; void set_position_z(double value); bool has_health_flag() const; void clear_health_flag(); uint32 health_flag() const; void set_health_flag(uint32 value); bool has_sat_obs_num() const; void clear_sat_obs_num(); uint32 sat_obs_num() const; void set_sat_obs_num(uint32 value); int sat_obs_size() const; void clear_sat_obs(); const ::apollo::localization::msf::SatelliteObservationMsg& sat_obs(int index); ::apollo::localization::msf::SatelliteObservationMsg* mutable_sat_obs(int index); ::apollo::localization::msf::SatelliteObservationMsg* add_sat_obs(); private: EpochObservation *data_; bool is_mapped_; SatelliteObservationMsg *satellite_observation_msg_; }; // ------------------------------------------------------------------- class KepplerOrbit; class KepplerOrbitMsg { public: KepplerOrbitMsg(); // explicit KepplerOrbitMsg(KepplerOrbit *data); ~KepplerOrbitMsg(); void map(KepplerOrbit *data); void unmap(); KepplerOrbit* mutable_data(); const KepplerOrbit& data() const; bool has_gnss_type() const; void clear_gnss_type(); ::apollo::localization::msf::GnssType gnss_type() const; void set_gnss_type(::apollo::localization::msf::GnssType value); bool has_sat_prn() const; void clear_sat_prn(); uint32 sat_prn() const; void set_sat_prn(uint32 value); bool has_gnss_time_type() const; void clear_gnss_time_type(); ::apollo::localization::msf::GnssTimeType gnss_time_type() const; void set_gnss_time_type(::apollo::localization::msf::GnssTimeType value); bool has_year() const; void clear_year(); uint32 year() const; void set_year(uint32 value); bool has_month() const; void clear_month(); uint32 month() const; void set_month(uint32 value); bool has_day() const; void clear_day(); uint32 day() const; void set_day(uint32 value); bool has_hour() const; void clear_hour(); uint32 hour() const; void set_hour(uint32 value); bool has_minute() const; void clear_minute(); uint32 minute() const; void set_minute(uint32 value); bool has_second_s() const; void clear_second_s(); double second_s() const; void set_second_s(double value); bool has_week_num() const; void clear_week_num(); uint32 week_num() const; void set_week_num(uint32 value); bool has_reserved() const; void clear_reserved(); double reserved() const; void set_reserved(double value); bool has_af0() const; void clear_af0(); double af0() const; void set_af0(double value); bool has_af1() const; void clear_af1(); double af1() const; void set_af1(double value); bool has_af2() const; void clear_af2(); double af2() const; void set_af2(double value); bool has_iode() const; void clear_iode(); double iode() const; void set_iode(double value); bool has_deltan() const; void clear_deltan(); double deltan() const; void set_deltan(double value); bool has_m0() const; void clear_m0(); double m0() const; void set_m0(double value); bool has_e() const; void clear_e(); double e() const; void set_e(double value); bool has_roota() const; void clear_roota(); double roota() const; void set_roota(double value); bool has_toe() const; void clear_toe(); double toe() const; void set_toe(double value); bool has_toc() const; void clear_toc(); double toc() const; void set_toc(double value); bool has_cic() const; void clear_cic(); double cic() const; void set_cic(double value); bool has_crc() const; void clear_crc(); double crc() const; void set_crc(double value); bool has_cis() const; void clear_cis(); double cis() const; void set_cis(double value); bool has_crs() const; void clear_crs(); double crs() const; void set_crs(double value); bool has_cuc() const; void clear_cuc(); double cuc() const; void set_cuc(double value); bool has_cus() const; void clear_cus(); double cus() const; void set_cus(double value); bool has_omega0() const; void clear_omega0(); double omega0() const; void set_omega0(double value); bool has_omega() const; void clear_omega(); double omega() const; void set_omega(double value); bool has_i0() const; void clear_i0(); double i0() const; void set_i0(double value); bool has_omegadot() const; void clear_omegadot(); double omegadot() const; void set_omegadot(double value); bool has_idot() const; void clear_idot(); double idot() const; void set_idot(double value); bool has_codesonl2channel() const; void clear_codesonl2channel(); double codesonl2channel() const; void set_codesonl2channel(double value); bool has_l2pdataflag() const; void clear_l2pdataflag(); uint32 l2pdataflag() const; void set_l2pdataflag(uint32 value); bool has_accuracy() const; void clear_accuracy(); uint32 accuracy() const; void set_accuracy(uint32 value); bool has_health() const; void clear_health(); uint32 health() const; void set_health(uint32 value); bool has_tgd() const; void clear_tgd(); double tgd() const; void set_tgd(double value); bool has_iodc() const; void clear_iodc(); double iodc() const; void set_iodc(double value); private: KepplerOrbit *data_; bool is_mapped_; }; // ------------------------------------------------------------------- class GlonassOrbit; class GlonassOrbitMsg { public: GlonassOrbitMsg(); // explicit GlonassOrbitMsg(GlonassOrbit *data); ~GlonassOrbitMsg(); void map(GlonassOrbit *data); void unmap(); GlonassOrbit* mutable_data(); const GlonassOrbit& data() const; bool has_gnss_type() const; void clear_gnss_type(); ::apollo::localization::msf::GnssType gnss_type() const; void set_gnss_type(::apollo::localization::msf::GnssType value); bool has_slot_prn() const; void clear_slot_prn(); uint32 slot_prn() const; void set_slot_prn(uint32 value); bool has_gnss_time_type() const; void clear_gnss_time_type(); ::apollo::localization::msf::GnssTimeType gnss_time_type() const; void set_gnss_time_type(::apollo::localization::msf::GnssTimeType value); bool has_toe() const; void clear_toe(); double toe() const; void set_toe(double value); bool has_year() const; void clear_year(); uint32 year() const; void set_year(uint32 value); bool has_month() const; void clear_month(); uint32 month() const; void set_month(uint32 value); bool has_day() const; void clear_day(); uint32 day() const; void set_day(uint32 value); bool has_hour() const; void clear_hour(); uint32 hour() const; void set_hour(uint32 value); bool has_minute() const; void clear_minute(); uint32 minute() const; void set_minute(uint32 value); bool has_second_s() const; void clear_second_s(); double second_s() const; void set_second_s(double value); bool has_frequency_no() const; void clear_frequency_no(); int32 frequency_no() const; void set_frequency_no(int32 value); bool has_week_num() const; void clear_week_num(); uint32 week_num() const; void set_week_num(uint32 value); bool has_week_second_s() const; void clear_week_second_s(); double week_second_s() const; void set_week_second_s(double value); bool has_tk() const; void clear_tk(); double tk() const; void set_tk(double value); bool has_clock_offset() const; void clear_clock_offset(); double clock_offset() const; void set_clock_offset(double value); bool has_clock_drift() const; void clear_clock_drift(); double clock_drift() const; void set_clock_drift(double value); bool has_health() const; void clear_health(); uint32 health() const; void set_health(uint32 value); bool has_position_x() const; void clear_position_x(); double position_x() const; void set_position_x(double value); bool has_position_y() const; void clear_position_y(); double position_y() const; void set_position_y(double value); bool has_position_z() const; void clear_position_z(); double position_z() const; void set_position_z(double value); bool has_velocity_x() const; void clear_velocity_x(); double velocity_x() const; void set_velocity_x(double value); bool has_velocity_y() const; void clear_velocity_y(); double velocity_y() const; void set_velocity_y(double value); bool has_velocity_z() const; void clear_velocity_z(); double velocity_z() const; void set_velocity_z(double value); bool has_accelerate_x() const; void clear_accelerate_x(); double accelerate_x() const; void set_accelerate_x(double value); bool has_accelerate_y() const; void clear_accelerate_y(); double accelerate_y() const; void set_accelerate_y(double value); bool has_accelerate_z() const; void clear_accelerate_z(); double accelerate_z() const; void set_accelerate_z(double value); bool has_infor_age() const; void clear_infor_age(); double infor_age() const; void set_infor_age(double value); private: GlonassOrbit *data_; bool is_mapped_; }; class GnssEphemeris; class GnssEphemerisMsg { public: GnssEphemerisMsg(); ~GnssEphemerisMsg(); void map(GnssEphemeris *data); void unmap(); GnssEphemeris* mutable_data(); const GnssEphemeris& data() const; bool has_gnss_type() const; void clear_gnss_type(); ::apollo::localization::msf::GnssType gnss_type() const; void set_gnss_type(::apollo::localization::msf::GnssType value); bool has_keppler_orbit() const; void clear_keppler_orbit(); const ::apollo::localization::msf::KepplerOrbitMsg& keppler_orbit(); ::apollo::localization::msf::KepplerOrbitMsg* mutable_keppler_orbit(); bool has_glonass_orbit() const; void clear_glonass_orbit(); const ::apollo::localization::msf::GlonassOrbitMsg& glonass_orbit(); ::apollo::localization::msf::GlonassOrbitMsg* mutable_glonass_orbit(); private: GnssEphemeris *data_; bool is_mapped_; KepplerOrbitMsg *keppler_orbit_msg_; GlonassOrbitMsg *glonass_orbit_msg_; }; class SatDirCosine; class SatDirCosineMsg { public: SatDirCosineMsg(); ~SatDirCosineMsg(); void map(SatDirCosine* data); void unmap(); SatDirCosine* mutable_data(); const SatDirCosine& data() const; bool has_sat_prn() const; void clear_sat_prn(); uint32 sat_prn() const; void set_sat_prn(uint32 value); bool has_sat_sys() const; void clear_sat_sys(); uint32 sat_sys() const; void set_sat_sys(uint32 value); bool has_cosine_x() const; void clear_cosine_x(); double cosine_x() const; void set_cosine_x(double value); bool has_cosine_y() const; void clear_cosine_y(); double cosine_y() const; void set_cosine_y(double value); bool has_cosine_z() const; void clear_cosine_z(); double cosine_z() const; void set_cosine_z(double value); private: SatDirCosine *data_; bool is_mapped_; }; class GnssPntResult; class GnssPntResultMsg { public: GnssPntResultMsg(); ~GnssPntResultMsg(); void map(GnssPntResult *data); void unmap(); GnssPntResult *mutable_data(); const GnssPntResult& data() const; bool has_receiver_id() const; void clear_receiver_id(); uint32 receiver_id() const; void set_receiver_id(uint32 value); bool has_time_type() const; void clear_time_type(); ::apollo::localization::msf::GnssTimeType time_type() const; void set_time_type(::apollo::localization::msf::GnssTimeType value); bool has_gnss_week() const; void clear_gnss_week(); uint32 gnss_week() const; void set_gnss_week(uint32 value); bool has_gnss_second_s() const; void clear_gnss_second_s(); double gnss_second_s() const; void set_gnss_second_s(double value); bool has_pnt_type() const; void clear_pnt_type(); ::apollo::localization::msf::PntType pnt_type() const; void set_pnt_type(::apollo::localization::msf::PntType value); bool has_pos_x_m() const; void clear_pos_x_m(); double pos_x_m() const; void set_pos_x_m(double value); bool has_pos_y_m() const; void clear_pos_y_m(); double pos_y_m() const; void set_pos_y_m(double value); bool has_pos_z_m() const; void clear_pos_z_m(); double pos_z_m() const; void set_pos_z_m(double value); bool has_std_pos_x_m() const; void clear_std_pos_x_m(); double std_pos_x_m() const; void set_std_pos_x_m(double value); bool has_std_pos_y_m() const; void clear_std_pos_y_m(); double std_pos_y_m() const; void set_std_pos_y_m(double value); bool has_std_pos_z_m() const; void clear_std_pos_z_m(); double std_pos_z_m() const; void set_std_pos_z_m(double value); bool has_vel_x_m() const; void clear_vel_x_m(); double vel_x_m() const; void set_vel_x_m(double value); bool has_vel_y_m() const; void clear_vel_y_m(); double vel_y_m() const; void set_vel_y_m(double value); bool has_vel_z_m() const; void clear_vel_z_m(); double vel_z_m() const; void set_vel_z_m(double value); bool has_std_vel_x_m() const; void clear_std_vel_x_m(); double std_vel_x_m() const; void set_std_vel_x_m(double value); bool has_std_vel_y_m() const; void clear_std_vel_y_m(); double std_vel_y_m() const; void set_std_vel_y_m(double value); bool has_std_vel_z_m() const; void clear_std_vel_z_m(); double std_vel_z_m() const; void set_std_vel_z_m(double value); bool has_sovled_sat_num() const; void clear_sovled_sat_num(); uint32 sovled_sat_num() const; void set_sovled_sat_num(uint32 value); int sat_dir_cosine_size() const; void clear_sat_dir_cosine(); const ::apollo::localization::msf::SatDirCosineMsg& sat_dir_cosine(int index); ::apollo::localization::msf::SatDirCosineMsg* mutable_sat_dir_cosine(int index); ::apollo::localization::msf::SatDirCosineMsg* add_sat_dir_cosine(); bool has_pdop() const; void clear_pdop(); double pdop() const; void set_pdop(double value); bool has_hdop() const; void clear_hdop(); double hdop() const; void set_hdop(double value); bool has_vdop() const; void clear_vdop(); double vdop() const; void set_vdop(double value); private: GnssPntResult *data_; bool is_mapped_; SatDirCosineMsg *sat_dir_cosine_msg_; }; } // namespace msf } // namespace localization } // namespace apollo
0
apollo_public_repos/apollo/third_party/localization_msf/x86_64
apollo_public_repos/apollo/third_party/localization_msf/x86_64/include/sins.h
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #pragma once #include "sins_struct.h" namespace apollo { namespace localization { namespace msf { class SinsImpl; class Sins { public: Sins(); ~Sins(); public: void Init(bool imu_can_self_align); void SetSinsAlignFromVel(bool flag); // void SetSinsStateCheck(bool flag); void SetResetSinsPoseStd(double std); void SetResetSinsMeasSpanTime(double time); void SetImuAntennaLeverArm(double x, double y, double z); void SetVelThresholdGetYaw(double threshold); void AddMeasurement(const MeasureData& measure_data); void AddImu(const ImuData& imu_data); void GetPose(InsPva *ins_pva, double pva_covariance[9][9]); bool IsSinsAligned(); void GetEarthParameter(InertialParameter *earth_param); void GetRemoveBiasImu(ImuData *imu_data); protected: SinsImpl* sins_impl_; }; } // namespace msf } // namespace localization } // namespace apollo
0
apollo_public_repos/apollo/third_party/localization_msf/x86_64
apollo_public_repos/apollo/third_party/localization_msf/x86_64/include/pose_forcast.h
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #pragma once #include "sins_struct.h" namespace apollo { namespace localization { namespace msf { class PoseForcastImpl; class PoseForcast { public: PoseForcast(); ~PoseForcast(); void SetMaxListNum(int n); void SetMaxAccelInput(double threshold); void SetMaxGyroInput(double threshold); void SetWheelExtrinsic(double x, double y, double z, double qx, double qy, double qz, double qw); void SetZoneId(int zone_id); double GetLastestImuTime(); void PushInspvaData(const InsPva &data); void PushImuData(const ImuData &data); void PushWheelSpeedData(const WheelspeedData &data); int GetBestForcastPose(double time, double init_time, const Pose &init_pose, Pose *forcast_pose); bool GetImuframeDeltaPose(const double& start_time, const double& end_time, TransformD& delta_pose); protected: PoseForcastImpl *pose_forcast_impl_; }; } } }
0
apollo_public_repos/apollo/third_party/localization_msf/x86_64
apollo_public_repos/apollo/third_party/localization_msf/x86_64/include/lidar_locator.h
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #pragma once namespace apollo { namespace localization { namespace msf { class LidarLocatorImpl; class LidarLocator { public: LidarLocator(); ~LidarLocator(); public: void Init(unsigned int filter_size_x, unsigned int filter_size_y, float resolution, unsigned int node_size_x, unsigned int node_size_y); void SetVelodyneExtrinsic(double x, double y, double z, double qx, double qy, double qz, double qw); // void SetVehicleHeight(double height); void SetValidThreshold(float valid_threashold); void SetImageAlignMode(int mode); void SetLocalizationMode(int mode); void SetDeltaYawLimit(double limit); void SetDeltaPitchRollLimit(double limit); public: // set map node data void SetMapNodeData(int width, int height, int level_num, const float *const*intensities, const float *const*intensities_var, const float *const*altitudes, const unsigned int *const*counts); void SetMapNodeLeftTopCorner(double x, double y); // set point cloud void SetPointCloudData(int size, const double* pt_xs, const double* pt_ys, const double* pt_zs, const unsigned char* intensities); // compute localization result int Compute(double pose_x, double pose_y, double pose_z, double pose_qx, double pose_qy, double pose_qz, double pose_qw, bool use_avx = false); public: /**@brief Get the current optimal pose result. */ void GetLocationPose(double *x, double *y, double *z, double *qx, double *qy, double *qz, double *qw); /**@brief Get the covariance of the current optimal location. */ void GetLocationCovariance(const double **data, int *width, int *height); void GetSSDDistribution(const double **data, int *width, int *height); double GetLocationScore() const; protected: LidarLocatorImpl* _lidar_locator; }; } // namespace msf } // namespace localization } // namespace apollo
0
apollo_public_repos/apollo/third_party/localization_msf/x86_64
apollo_public_repos/apollo/third_party/localization_msf/x86_64/include/sins_data_transfer.h
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #pragma once #include "sins_struct.h" #include "local_sins/navigation_struct.hpp" namespace apollo { namespace localization { namespace msf { typedef adu::localization::integrated_navigation::SinsImuData SinsImuData; class SinsDataTransfer { public: void Transfer(const MeasureData &data, adu::localization::integrated_navigation::MeasureData *out_data); void Transfer(const Position &data, adu::localization::integrated_navigation::Position *out_data); void Transfer(const Velocity &data, adu::localization::integrated_navigation::Velocity *out_data); void Transfer(const Attitude &data, adu::localization::integrated_navigation::Attitude *out_data); void Transfer(const MeasureType &data, adu::localization::integrated_navigation::MeasureType *out_data); void Transfer(const FrameType &data, adu::localization::integrated_navigation::FrameType *out_data); void Transfer(const WheelspeedData &data, adu::localization::integrated_navigation::WheelspeedData *out_data); void Transfer(const ImuData &data, SinsImuData *out_data); void Transfer(const SinsIntegUpdateType &data, adu::localization::integrated_navigation::SinsIntegUpdateType *out_data); void Transfer(const InsPva &data, adu::localization::integrated_navigation::InsPva *out_data); void Transfer(const adu::localization::integrated_navigation::Position &data, Position *out_data); void Transfer(const adu::localization::integrated_navigation::Velocity &data, Velocity *out_data); void Transfer(const adu::localization::integrated_navigation::Attitude &data, Attitude *out_data); void Transfer(const adu::localization::integrated_navigation::InsPva &data, InsPva *out_data); }; } // msf } // localization } // apollo
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/centerpoint_infer_op/init.bzl
"""Loads the centerpoint_infer_op library""" load("//third_party/centerpoint_infer_op:workspace.bzl", "repo") def init(): repo()
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/centerpoint_infer_op/cyberfile.xml
<package format="2"> <name>3rd-centerpoint-infer-op</name> <version>local</version> <description> Apollo packaged civetweb Lib. </description> <maintainer email="apollo-support@baidu.com">Apollo</maintainer> <license>Apache License 2.0</license> <url type="website">https://www.apollo.auto/</url> <url type="repository">https://github.com/ApolloAuto/apollo</url> <url type="bugtracker">https://github.com/ApolloAuto/apollo/issues</url> <type>third-wrapper</type> <src_path url="https://github.com/ApolloAuto/apollo">//third_party/centerpoint_infer_op</src_path> </package>
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/centerpoint_infer_op/workspace.bzl
"""Loads the paddlelite library""" # Sanitize a dependency so that it works correctly from code that includes # Apollo as a submodule. load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") def clean_dep(dep): return str(Label(dep)) def repo(): http_archive( name = "centerpoint_infer_op", sha256 = "b39430eafad6b8b9b7e216840845b01c24b66406fb94ce06df721c6a3d738054", strip_prefix = "centerpoint_infer_op", urls = [ "https://apollo-system.bj.bcebos.com/archive/v8.0_bev/centerpoint_infer_op.tar.gz", ], )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/centerpoint_infer_op/BUILD
load("//tools/install:install.bzl", "install", "install_files", "install_src_files") package( default_visibility = ["//visibility:public"], ) install( name = "install_lib", data = glob([ "lib*.so", ]), data_dest = "3rd-centerpoint-infer-op/lib", ) install( name = "install", data = [ ":cyberfile.xml", ], data_dest = "3rd-centerpoint-infer-op", deps = ["install_lib"], ) install_src_files( name = "install_src", dest = "3rd-centerpoint-infer-op/src", filter = "*", src_dir = ["."], )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/nlohmann_json/init.bzl
"""Loads the nlohmann_json library""" load("//third_party/nlohmann_json:workspace.bzl", "repo") def init(): repo()
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/nlohmann_json/json.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") # JSON for Modern C++ licenses(["notice"]) # 3-Clause BSD exports_files(["LICENSE.MIT"]) cc_library( name = "json", hdrs = glob([ "include/nlohmann/**/*.hpp", ]), includes = ["include"], visibility = ["//visibility:public"], alwayslink = 1, ) cc_library( name = "single_json", hdrs = glob(["single_include/**/*.hpp"]), strip_include_prefix = "single_include", visibility = ["//visibility:public"], alwayslink = 1, )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/nlohmann_json/cyberfile.xml
<package format="2"> <name>3rd-nlohmann-json</name> <version>local</version> <description> Apollo packaged nlohmann-json Lib. </description> <maintainer email="apollo-support@baidu.com">Apollo</maintainer> <license>Apache License 2.0</license> <url type="website">https://www.apollo.auto/</url> <url type="repository">https://github.com/ApolloAuto/apollo</url> <url type="bugtracker">https://github.com/ApolloAuto/apollo/issues</url> <type>third-wrapper</type> <src_path url="https://github.com/ApolloAuto/apollo">//third_party/nlohmann_json</src_path> </package>
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/nlohmann_json/workspace.bzl
"""Loads the nlohmann_json library""" load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") # Sanitize a dependency so that it works correctly from code that includes # Apollo as a submodule. def clean_dep(dep): return str(Label(dep)) def repo(): http_archive( name = "com_github_nlohmann_json", sha256 = "7d0edf65f2ac7390af5e5a0b323b31202a6c11d744a74b588dc30f5a8c9865ba", strip_prefix = "json-3.8.0", build_file = clean_dep("//third_party/nlohmann_json:json.BUILD"), urls = [ "https://apollo-system.cdn.bcebos.com/archive/6.0/v3.8.0.tar.gz", "https://github.com/nlohmann/json/archive/v3.8.0.tar.gz", ], )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/nlohmann_json/BUILD
load("//tools/install:install.bzl", "install", "install_files", "install_src_files") package( default_visibility = ["//visibility:public"], ) install( name = "install", data_dest = "3rd-nlohmann-json", data = [ ":cyberfile.xml", ], ) install_src_files( name = "install_src", src_dir = ["."], dest = "3rd-nlohmann-json/src", filter = "*", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/fastrtps/fastcdr.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") cc_library( name = "fastcdr", includes = [ ".", ], linkopts = [ "-L/usr/local/fast-rtps/lib", "-lfastcdr", ], visibility = ["//visibility:public"], )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/fastrtps/cyberfile.xml
<package format="2"> <name>3rd-fastrtps</name> <version>local</version> <description> Apollo packaged 3rd-fastrtps Lib. </description> <maintainer email="apollo-support@baidu.com">Apollo</maintainer> <license>Apache License 2.0</license> <url type="website">https://www.apollo.auto/</url> <url type="repository">https://github.com/ApolloAuto/apollo</url> <url type="bugtracker">https://github.com/ApolloAuto/apollo/issues</url> <type>third-binary</type> <src_path url="https://github.com/ApolloAuto/apollo">//third_party/fastrtps</src_path> </package>
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/fastrtps/fastrtps.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") cc_library( name = "fastrtps", includes = [ ".", ], linkopts = [ "-L/usr/local/fast-rtps/lib", "-lfastrtps", "-lfastcdr", ], visibility = ["//visibility:public"], )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/fastrtps/workspace.bzl
"""Load the fastrtps library""" # Sanitize a dependency so that it works correctly from code that includes # Apollo as a submodule. def clean_dep(dep): return str(Label(dep)) def repo(): native.new_local_repository( name = "fastcdr", build_file = clean_dep("//third_party/fastrtps:fastcdr.BUILD"), path = "/usr/local/fast-rtps/include", ) native.new_local_repository( name = "fastrtps", build_file = clean_dep("//third_party/fastrtps:fastrtps.BUILD"), path = "/usr/local/fast-rtps/include", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/fastrtps/BUILD
load("//tools/install:install.bzl", "install", "install_files", "install_src_files") package( default_visibility = ["//visibility:public"], ) install( name = "install", data_dest = "3rd-fastrtps", data = [ ":cyberfile.xml", ":3rd-fastrtps.BUILD", ], ) install_src_files( name = "install_src", src_dir = ["."], dest = "3rd-fastrtps/src", filter = "*", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/fastrtps/3rd-fastrtps.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") cc_library( name = "fastrtps", includes = [ "include", ], hdrs = glob(["include/**/*"]), linkopts = [ "-lfastrtps", "-lfastcdr", ], strip_include_prefix = "include", visibility = ["//visibility:public"], )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/boost/cyberfile.xml
<package format="2"> <name>3rd-boost</name> <version>local</version> <description> Apollo packaged boost Lib. </description> <maintainer email="apollo-support@baidu.com">Apollo</maintainer> <license>Apache License 2.0</license> <url type="website">https://www.apollo.auto/</url> <url type="repository">https://github.com/ApolloAuto/apollo</url> <url type="bugtracker">https://github.com/ApolloAuto/apollo/issues</url> <type>third-binary</type> <src_path url="https://github.com/ApolloAuto/apollo">//third_party/boost</src_path> </package>
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/boost/workspace.bzl
"""Loads the boost library""" # Sanitize a dependency so that it works correctly from code that includes # Apollo as a submodule. def clean_dep(dep): return str(Label(dep)) def repo(): native.new_local_repository( name = "boost", build_file = clean_dep("//third_party/boost:boost.BUILD"), path = "/opt/apollo/sysroot/include", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/boost/3rd-boost.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") licenses(["notice"]) package(default_visibility = ["//visibility:public"]) cc_library( name = "boost", includes = ["include"], hdrs = glob(["include/**/*"]), linkopts = [ "-lboost_filesystem", "-lboost_program_options", "-lboost_regex", "-lboost_system", "-lboost_thread", ], strip_include_prefix = "include", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/boost/BUILD
load("//tools/install:install.bzl", "install", "install_files", "install_src_files") package( default_visibility = ["//visibility:public"], ) install( name = "install", data_dest = "3rd-boost", data = [ ":cyberfile.xml", ":3rd-boost.BUILD", ], ) install_src_files( name = "install_src", src_dir = ["."], dest = "3rd-boost/src", filter = "*", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/boost/boost.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") licenses(["notice"]) package(default_visibility = ["//visibility:public"]) # TODO(all): May use rules_boost. cc_library( name = "boost", includes = ["."], linkopts = [ "-L/opt/apollo/sysroot/lib", "-lboost_filesystem", "-lboost_program_options", "-lboost_regex", "-lboost_system", "-lboost_thread", ], )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/eigen3/init.bzl
"""Loads the eigen3 library""" load("//third_party/eigen3:workspace.bzl", "repo") def init(): repo()
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/eigen3/cyberfile.xml
<package format="2"> <name>3rd-eigen3</name> <version>local</version> <description> Apollo packaged eigen3 Lib. </description> <maintainer email="apollo-support@baidu.com">Apollo</maintainer> <license>Apache License 2.0</license> <url type="website">https://www.apollo.auto/</url> <url type="repository">https://github.com/ApolloAuto/apollo</url> <url type="bugtracker">https://github.com/ApolloAuto/apollo/issues</url> <type>third-wrapper</type> <src_path url="https://github.com/ApolloAuto/apollo">//third_party/eigen3</src_path> </package>
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/eigen3/eigen.BUILD
# Copyright 2018 The Cartographer Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Description: # Eigen is a C++ template library for linear algebra: vectors, # matrices, and related algorithms. load("@rules_cc//cc:defs.bzl", "cc_library") licenses([ # Note: Eigen is an MPL2 library that includes GPL v3 and LGPL v2.1+ code. # We've taken special care to not reference any restricted code. "reciprocal", # MPL2 "notice", # Portions BSD ]) exports_files(["COPYING.MPL2"]) EIGEN_FILES = [ "Eigen/**", "unsupported/Eigen/CXX11/**", "unsupported/Eigen/FFT", "unsupported/Eigen/**", "unsupported/Eigen/KroneckerProduct", "unsupported/Eigen/src/FFT/**", "unsupported/Eigen/src/KroneckerProduct/**", "unsupported/Eigen/MatrixFunctions", "unsupported/Eigen/SpecialFunctions", "unsupported/Eigen/src/MatrixFunctions/**", "unsupported/Eigen/src/SpecialFunctions/**", ] # List of files picked up by glob but actually part of another target. EIGEN_EXCLUDE_FILES = [ "Eigen/src/Core/arch/AVX/PacketMathGoogleTest.cc", ] EIGEN_MPL2_HEADER_FILES = glob( EIGEN_FILES, exclude = EIGEN_EXCLUDE_FILES, ) cc_library( name = "eigen", hdrs = EIGEN_MPL2_HEADER_FILES, includes = ["."], visibility = ["//visibility:public"], )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/eigen3/workspace.bzl
"""Loads the eigen library""" load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") # Sanitize a dependency so that it works correctly from code that includes # Apollo as a submodule. def clean_dep(dep): return str(Label(dep)) def repo(): http_archive( name = "eigen", build_file = clean_dep("//third_party/eigen3:eigen.BUILD"), sha256 = "a8d87c8df67b0404e97bcef37faf3b140ba467bc060e2b883192165b319cea8d", strip_prefix = "eigen-git-mirror-3.3.7", urls = [ "https://apollo-system.cdn.bcebos.com/archive/6.0/3.3.7.tar.gz", "https://github.com/eigenteam/eigen-git-mirror/archive/3.3.7.tar.gz", ], ) #native.new_local_repository( # name = "eigen", # build_file = clean_dep("//third_party/eigen3:eigen.BUILD"), # path = "/usr/include/eigen3", #)
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/eigen3/BUILD
load("//tools/install:install.bzl", "install", "install_files", "install_src_files") package( default_visibility = ["//visibility:public"], ) install( name = "install", data_dest = "3rd-eigen3", data = [ ":cyberfile.xml", ], ) install_src_files( name = "install_src", src_dir = ["."], dest = "3rd-eigen3/src", filter = "*", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/ad_rss_lib/ad_rss_lib.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_binary") load("@apollo//tools/install:install.bzl", "install", "install_files", "install_src_files") install( name = "install", targets = [ ":libad_rss.so", ], library_dest = "3rd-ad-rss-lib/lib", deps = [ ":ad_rss_export_hdrs", ], ) install_files( name = "ad_rss_export_hdrs", dest = "3rd-ad-rss-lib/include/ad_rss", files = glob([ "include/ad_rss/**/*.hpp", "src/**/*.hpp", "include/generated/ad_rss/**/*.hpp" ]), strip_prefix = [ "include/ad_rss", "src", "include/generated/ad_rss", ] ) package( default_visibility = ["//visibility:public"], ) licenses(["notice"]) cc_binary( name = "libad_rss.so", srcs = [ "src/generated/physics/Acceleration.cpp", "src/generated/physics/CoordinateSystemAxis.cpp", "src/generated/physics/Distance.cpp", "src/generated/physics/DistanceSquared.cpp", "src/generated/physics/Duration.cpp", "src/generated/physics/DurationSquared.cpp", "src/generated/physics/ParametricValue.cpp", "src/generated/physics/Speed.cpp", "src/generated/physics/SpeedSquared.cpp", "src/generated/situation/LateralRelativePosition.cpp", "src/generated/situation/LongitudinalRelativePosition.cpp", "src/generated/situation/SituationType.cpp", "src/generated/state/LateralResponse.cpp", "src/generated/state/LongitudinalResponse.cpp", "src/generated/world/LaneDrivingDirection.cpp", "src/generated/world/LaneSegmentType.cpp", "src/generated/world/ObjectType.cpp", "src/core/RssCheck.cpp", "src/core/RssResponseResolving.cpp", "src/core/RssResponseTransformation.cpp", "src/core/RssSituationChecking.cpp", "src/core/RssSituationExtraction.cpp", "src/physics/Math.cpp", "src/situation/RSSFormulas.cpp", "src/situation/RssIntersectionChecker.cpp", "src/situation/RSSSituation.cpp", "src/world/RssSituationCoordinateSystemConversion.cpp", "src/world/RssObjectPositionExtractor.cpp", ] + glob(["src/**/*.hpp","include/**/*.hpp"]), copts = [ "-fPIC", "-std=c++11", "-Werror", "-Wall", "-Wextra", "-pedantic", "-Wconversion", "-Wsign-conversion", ], includes = [ "include", "include/generated", "src", "tests/test_support", ], linkshared = True, ) cc_library( name = "ad_rss", srcs = ["libad_rss.so"], hdrs = glob(["include/**/*.hpp"]), copts = [ "-fPIC", "-std=c++11", "-Werror", "-Wall", "-Wextra", "-pedantic", "-Wconversion", "-Wsign-conversion", ], includes = [ "include", "include/generated", "src", "tests/test_support", ], ) ################################################################################ # Install section ################################################################################ ################################################################################ # Doxygen documentation ################################################################################
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/ad_rss_lib/cyberfile.xml
<package format="2"> <name>3rd-ad-rss-lib</name> <version>local</version> <description> Apollo packaged 3rd-ad-rss-lib Lib. </description> <maintainer email="apollo-support@baidu.com">Apollo</maintainer> <license>Apache License 2.0</license> <url type="website">https://www.apollo.auto/</url> <url type="repository">https://github.com/ApolloAuto/apollo</url> <url type="bugtracker">https://github.com/ApolloAuto/apollo/issues</url> <type>third-binary</type> <src_path url="https://github.com/ApolloAuto/apollo">//third_party/ad_rss_lib</src_path> </package>
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/ad_rss_lib/3rd-ad-rss-lib.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_binary") package( default_visibility = ["//visibility:public"], ) licenses(["notice"]) cc_library( name = "ad_rss", srcs = ["lib/libad_rss.so"], hdrs = glob(["include/**/*.hpp"]), copts = [ "-fPIC", "-std=c++11", "-Werror", "-Wall", "-Wextra", "-pedantic", "-Wconversion", "-Wsign-conversion", ], includes = [ "include", ], strip_include_prefix = "include", deps = ["situation_hpp"], ) cc_library( name = "situation_hpp", hdrs = glob(["include/ad_rss/situation/**/*.hpp"]), strip_include_prefix = "include/ad_rss", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/ad_rss_lib/workspace.bzl
"""Loads the ad_rss_lib library""" load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") # Sanitize a dependency so that it works correctly from code that includes # Apollo as a submodule. def clean_dep(dep): return str(Label(dep)) def repo(): http_archive( name = "ad_rss_lib", build_file = clean_dep("//third_party/ad_rss_lib:ad_rss_lib.BUILD"), sha256 = "10c161733a06053f79120f389d2d28208c927eb65759799fb8d7142666b61b9f", strip_prefix = "ad-rss-lib-1.1.0", urls = [ "https://apollo-system.cdn.bcebos.com/archive/6.0/v1.1.0.tar.gz", "https://github.com/intel/ad-rss-lib/archive/v1.1.0.tar.gz", ], )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/ad_rss_lib/BUILD
load("//tools/install:install.bzl", "install", "install_files", "install_src_files") package( default_visibility = ["//visibility:public"], ) install( name = "install", data_dest = "3rd-ad-rss-lib", data = [ ":cyberfile.xml", ":3rd-ad-rss-lib.BUILD", ], deps =[ "@ad_rss_lib//:install", ], ) install_src_files( name = "install_src", src_dir = ["."], dest = "3rd-ad-rss-lib/src", filter = "*", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/libtorch/libtorch_gpu_rocm.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") package(default_visibility = ["//visibility:public"]) licenses(["notice"]) cc_library( name = "libtorch_gpu_rocm", includes = [ ".", "torch/csrc/api/include", ], linkopts = [ "-L/usr/local/libtorch_gpu/lib", "-lc10", "-lc10_hip", "-ltorch", "-ltorch_cpu", "-ltorch_hip", ], linkstatic = False, deps = [ "@local_config_rocm//rocm:hip", "@local_config_python//:python_headers", "@local_config_python//:python_lib", ], )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/libtorch/cyberfile-cpu.xml
<package format="2"> <name>3rd-libtorch-cpu</name> <version>local</version> <description> Apollo packaged libtorch-cpu Lib. </description> <maintainer email="apollo-support@baidu.com">Apollo</maintainer> <license>Apache License 2.0</license> <url type="website">https://www.apollo.auto/</url> <url type="repository">https://github.com/ApolloAuto/apollo</url> <url type="bugtracker">https://github.com/ApolloAuto/apollo/issues</url> <depend expose="False">3rd-py-dev</depend> <type>third-binary</type> <src_path url="https://github.com/ApolloAuto/apollo">//third_party/libtorch</src_path> </package>
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/libtorch/libtorch_gpu_cuda.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") package(default_visibility = ["//visibility:public"]) licenses(["notice"]) cc_library( name = "libtorch_gpu_cuda", includes = [ ".", "torch/csrc/api/include", ], linkopts = [ "-L/usr/local/libtorch_gpu/lib", "-lc10", "-lc10_cuda", "-ltorch", "-ltorch_cpu", "-ltorch_cuda", ], linkstatic = False, deps = [ "@local_config_cuda//cuda:cudart", "@local_config_python//:python_headers", "@local_config_python//:python_lib", ], )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/libtorch/3rd-libtorch-cpu.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") cc_library( name = "libtorch_cpu", hdrs = glob(["include/**/*"]), linkopts = [ "-lc10", "-ltorch", "-ltorch_cpu", ], linkstatic = False, deps = [ "@local_config_python//:python_headers", "@local_config_python//:python_lib", ":libtorch_cpu_headers" ], strip_include_prefix = "include", visibility = ["//visibility:public"], ) cc_library( name = "libtorch_cpu_headers", hdrs = glob(["include/torch/csrc/api/include/**/*"]), linkstatic = False, deps = [ "@local_config_python//:python_headers", "@local_config_python//:python_lib", ], strip_include_prefix = "include/torch/csrc/api/include", visibility = ["//visibility:public"], )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/libtorch/libtorch_cpu.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") package(default_visibility = ["//visibility:public"]) licenses(["notice"]) cc_library( name = "libtorch_cpu", includes = [ ".", "torch/csrc/api/include", ], linkopts = [ "-L/usr/local/libtorch_cpu/lib", "-lc10", "-ltorch", "-ltorch_cpu", ], linkstatic = False, deps = [ "@local_config_python//:python_headers", "@local_config_python//:python_lib", ], )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/libtorch/cyberfile-gpu.xml
<package format="2"> <name>3rd-libtorch-gpu</name> <version>local</version> <description> Apollo packaged libtorch-gpu Lib. </description> <maintainer email="apollo-support@baidu.com">Apollo</maintainer> <license>Apache License 2.0</license> <url type="website">https://www.apollo.auto/</url> <url type="repository">https://github.com/ApolloAuto/apollo</url> <url type="bugtracker">https://github.com/ApolloAuto/apollo/issues</url> <depend expose="False">3rd-py-dev</depend> <type>third-binary</type> <src_path url="https://github.com/ApolloAuto/apollo">//third_party/libtorch</src_path> </package>
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/libtorch/3rd-libtorch.BUILD
load("//tools/install:install.bzl", "install", "install_files", "install_src_files") load("@rules_cc//cc:defs.bzl", "cc_library") package( default_visibility = ["//visibility:public"], ) cc_library( name = "libtorch", deps = select({ "//tools/platform:use_gpu": [ "@libtorch_gpu", ], "//conditions:default": [ "@libtorch_cpu", ], }), )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/libtorch/3rd-libtorch-gpu.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") load("//third_party/gpus:common.bzl", "gpu_library", "if_cuda", "if_rocm") cc_library( name = "libtorch_gpu", hdrs = glob(["include/**/*"]), linkopts = [ "-lc10", "-ltorch", "-ltorch_cpu", "-lnvonnxparser", ] + if_cuda([ "-lc10_cuda", "-ltorch_cuda", ])+ if_rocm([ "-lc10_hip, "-ltorch_hip, ]), linkstatic = False, deps = if_cuda([ "@local_config_cuda//cuda:cudart", ])+ if_rocm([ "@local_config_rocm//rocm:hip", ])+ [ "@local_config_python//:python_headers", "@local_config_python//:python_lib", ":libtorch_gpu_headers" ], strip_include_prefix = "include", visibility = ["//visibility:public"], ) cc_library( name = "libtorch_gpu_headers", hdrs = glob(["include/torch/csrc/api/include/**/*"]), linkstatic = False, deps = [ "@local_config_cuda//cuda:cudart", "@local_config_python//:python_headers", "@local_config_python//:python_lib", ], strip_include_prefix = "include/torch/csrc/api/include", visibility = ["//visibility:public"], )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/libtorch/workspace.bzl
"""Loads the libtorch_gpu library""" # Sanitize a dependency so that it works correctly from code that includes # Apollo as a submodule. def clean_dep(dep): return str(Label(dep)) def repo_cpu(): native.new_local_repository( name = "libtorch_cpu", build_file = clean_dep("//third_party/libtorch:libtorch_cpu.BUILD"), path = "/usr/local/libtorch_cpu/include", ) def repo_gpu(): native.new_local_repository( name = "libtorch_gpu_rocm", build_file = clean_dep("//third_party/libtorch:libtorch_gpu_rocm.BUILD"), path = "/usr/local/libtorch_gpu/include", ) native.new_local_repository( name = "libtorch_gpu_cuda", build_file = clean_dep("//third_party/libtorch:libtorch_gpu_cuda.BUILD"), path = "/usr/local/libtorch_gpu/include", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/libtorch/BUILD
load("//tools/install:install.bzl", "install", "install_files", "install_src_files") load("@rules_cc//cc:defs.bzl", "cc_library") package( default_visibility = ["//visibility:public"], ) cc_library( name = "libtorch", deps = select({ "//tools/platform:use_gpu": [ "@libtorch_gpu", ], "//conditions:default": [ "@libtorch_cpu", ], }), ) install( name = "install", deps = [ ":install_cpu", ":install_gpu" ] ) install_src_files( name = "install_src", deps = [ ":install_cpu_src", ":install_gpu_src" ] ) install( name = "install_cpu", data_dest = "3rd-libtorch-cpu", data = [ ":cyberfile-cpu.xml", ":3rd-libtorch-cpu.BUILD", ":3rd-libtorch.BUILD", ], rename = { "3rd-libtorch-cpu/cyberfile-cpu.xml" : "cyberfile.xml", "3rd-libtorch-cpu/3rd-libtorch.BUILD" : "BUILD", }, ) install_src_files( name = "install_cpu_src", src_dir = ["."], dest = "3rd-libtorch-cpu/src", filter = "*", ) install( name = "install_gpu", data_dest = "3rd-libtorch-gpu", data = [ ":cyberfile-gpu.xml", ":3rd-libtorch-gpu.BUILD", ":3rd-libtorch.BUILD", ], rename = { "3rd-libtorch-gpu/cyberfile-gpu.xml" : "cyberfile.xml", "3rd-libtorch-gpu/3rd-libtorch.BUILD" : "BUILD", }, ) install_src_files( name = "install_gpu_src", src_dir = ["."], dest = "3rd-libtorch-gpu/src", filter = "*", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/fftw3/cyberfile.xml
<package format="2"> <name>3rd-fftw3</name> <version>local</version> <description> Apollo packaged fftw3 Lib. </description> <maintainer email="apollo-support@baidu.com">Apollo</maintainer> <license>Apache License 2.0</license> <url type="website">https://www.apollo.auto/</url> <url type="repository">https://github.com/ApolloAuto/apollo</url> <url type="bugtracker">https://github.com/ApolloAuto/apollo/issues</url> <type>third-binary</type> <src_path url="https://github.com/ApolloAuto/apollo">//third_party/fftw3</src_path> </package>
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/fftw3/3rd-fftw3.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") licenses(["notice"]) package(default_visibility = ["//visibility:public"]) cc_library( name = "fftw3", includes = ["include"], hdrs = glob(["include/fftw3*"]), linkopts = [ "-lfftw3", "-lm", ], strip_include_prefix = "include", ) cc_library( name = "fftw3_omp", includes = ["include"], linkopts = [ "-lgomp", "-pthread", "-ldl", ], deps = [ ":fftw3", ], strip_include_prefix = "include", ) cc_library( name = "fftw3_threads", includes = ["include"], linkopts = [ "-pthread", ], deps = [ ":fftw3", ], strip_include_prefix = "include", )
0
apollo_public_repos/apollo/third_party
apollo_public_repos/apollo/third_party/fftw3/fftw3.BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") licenses(["notice"]) package(default_visibility = ["//visibility:public"]) cc_library( name = "fftw3", includes = ["."], linkopts = [ "-lfftw3", "-lm", ], ) cc_library( name = "fftw3_omp", includes = ["."], linkopts = [ "-lgomp", "-pthread", "-ldl", ], deps = [ ":fftw3", ], ) cc_library( name = "fftw3_threads", includes = ["."], linkopts = [ "-pthread", ], deps = [ ":fftw3", ], ) # cc_library( # name = "fftw3l", # includes = ["."], # linkopts = [ # "-lfftw3l", # "-lm", # ], # ) # # cc_library( # name = "fftw3l_omp", # includes = ["."], # linkopts = [ # "-lgomp", # "-pthread", # "-ldl", # ], # deps = [ # ":fftw3l", # ], # ) # # cc_library( # name = "fftw3l_threads", # includes = ["."], # linkopts = [ # "-pthread", # ], # deps = [ # ":fftw3l", # ], # ) # # cc_library( # name = "fftw3f", # includes = ["."], # linkopts = [ # "-lfftw3f", # "-lm", # ], # ) # # cc_library( # name = "fftw3f_omp", # includes = ["."], # linkopts = [ # "-lgomp", # "-pthread", # "-ldl", # ], # deps = [ # ":fftw3f", # ], # ) # # cc_library( # name = "fftw3f_threads", # includes = ["."], # linkopts = [ # "-pthread", # ], # deps = [ # ":fftw3f", # ], # ) # # cc_library( # name = "fftw3q", # includes = ["."], # linkopts = [ # "-lfftw3q", # "-lm", # ], # ) # # cc_library( # name = "fftw3q_omp", # includes = ["."], # linkopts = [ # "-lgomp", # "-pthread", # "-ldl", # ], # deps = [ # ":fftw3q", # ], # ) # # cc_library( # name = "fftw3q_threads", # includes = ["."], # linkopts = [ # "-pthread", # ], # deps = [ # ":fftw3q", # ], # )
0