### Install Nanoflann using vcpkg Source: https://github.com/jlblancoc/nanoflann/blob/master/README.md This sequence of commands demonstrates how to install Nanoflann using the vcpkg dependency manager. It involves cloning the vcpkg repository, bootstrapping it, integrating it with the system, and finally installing the Nanoflann package. ```sh $ git clone https://github.com/Microsoft/vcpkg.git $ cd vcpkg $ ./bootstrap-vcpkg.sh $ ./vcpkg integrate install $ ./vcpkg install nanoflann ``` -------------------------------- ### CMakeLists.txt for nanoflann Examples Source: https://github.com/jlblancoc/nanoflann/blob/master/examples/examples_gui/nanoflann_gui_example_R3/CMakeLists.txt This CMakeLists.txt file configures the build for nanoflann examples. It finds nanoflann and mrpt-gui, creates executables for different search types (radius, k-NN, r-kNN), sets compile definitions and options for optimization, and links the necessary libraries. It also ensures the current directory is added to include paths. ```cmake cmake_minimum_required(VERSION 3.0) project(nanoflann_gui_example_R3) find_package(nanoflann REQUIRED) find_package(mrpt-gui REQUIRED) add_executable(nanoflann_gui_example_R3_radius nanoflann_gui_example_R3.cpp) add_executable(nanoflann_gui_example_R3_knn nanoflann_gui_example_R3.cpp) add_executable(nanoflann_gui_example_R3_rknn nanoflann_gui_example_R3.cpp) target_compile_definitions(nanoflann_gui_example_R3_radius PRIVATE USE_RADIUS_SEARCH) target_compile_definitions(nanoflann_gui_example_R3_knn PRIVATE USE_KNN_SEARCH) target_compile_definitions(nanoflann_gui_example_R3_rknn PRIVATE USE_RKNN_SEARCH) # optimized build: if (CMAKE_COMPILER_IS_GNUCXX) target_compile_options(nanoflann_gui_example_R3_radius PRIVATE -O2 -mtune=native) target_compile_options(nanoflann_gui_example_R3_knn PRIVATE -O2 -mtune=native) target_compile_options(nanoflann_gui_example_R3_rknn PRIVATE -O2 -mtune=native) endif() # Make sure the include path is used: target_link_libraries(nanoflann_gui_example_R3_radius nanoflann::nanoflann mrpt::gui) target_link_libraries(nanoflann_gui_example_R3_knn nanoflann::nanoflann mrpt::gui) target_link_libraries(nanoflann_gui_example_R3_rknn nanoflann::nanoflann mrpt::gui) target_include_directories(nanoflann_gui_example_R3_radius PRIVATE ".") target_include_directories(nanoflann_gui_example_R3_knn PRIVATE ".") target_include_directories(nanoflann_gui_example_R3_rknn PRIVATE ".") ``` -------------------------------- ### Export and Install Library Targets Source: https://github.com/jlblancoc/nanoflann/blob/master/CMakeLists.txt Exports the project targets and installs the necessary header files and configuration files to the system directories. ```cmake install(EXPORT nanoflannTargets NAMESPACE nanoflann:: DESTINATION "${INSTALL_CMAKE_DIR}") install( FILES "${nanoflann_SOURCE_DIR}/include/nanoflann.hpp" DESTINATION "${INSTALL_INCLUDE_DIR}" ) ``` -------------------------------- ### Install Nanoflann using Conan Source: https://github.com/jlblancoc/nanoflann/blob/master/README.md This command installs Nanoflann using the Conan package manager. It fetches pre-built binaries or builds from source if necessary. This is a convenient way to manage Nanoflann as a dependency. ```sh $ conan install --requires="nanoflann/[*]" --build=missing ``` -------------------------------- ### Configure nanoflann GUI Example Build with CMake Source: https://github.com/jlblancoc/nanoflann/blob/master/examples/examples_gui/nanoflann_gui_example_bearings/CMakeLists.txt This CMakeLists.txt file sets up the build environment for a C++ executable. It finds and links the nanoflann and mrpt-gui libraries, adds compilation optimizations for GCC/Clang, and defines the executable target. The primary dependencies are CMake version 3.0+, nanoflann, and mrpt-gui. ```cmake cmake_minimum_required(VERSION 3.0) project(nanoflann_gui_example_bearings) find_package(nanoflann REQUIRED) find_package(mrpt-gui REQUIRED) add_executable(${PROJECT_NAME} ${PROJECT_NAME}.cpp) # optimized build: if (CMAKE_COMPILER_IS_GNUCXX) target_compile_options(${PROJECT_NAME} PRIVATE -O2 -mtune=native) endif() # Make sure the include path is used: target_link_libraries(${PROJECT_NAME} nanoflann::nanoflann mrpt::gui) ``` -------------------------------- ### Configure CMake Testing and Installation Source: https://github.com/jlblancoc/nanoflann/blob/master/CMakeLists.txt This snippet demonstrates how to conditionally enable unit tests and configure essential package files like pkg-config and CMake config files for library distribution. ```cmake option(NANOFLANN_BUILD_TESTS "Build unit tests" ON) if(NANOFLANN_BUILD_TESTS) enable_testing() add_subdirectory(tests) endif() configure_file( "${nanoflann_SOURCE_DIR}/scripts/nanoflann.pc.in" "${nanoflann_BINARY_DIR}/nanoflann.pc" @ONLY IMMEDIATE ) ``` -------------------------------- ### Build Nanoflann Samples with CMake Source: https://github.com/jlblancoc/nanoflann/blob/master/tests/gtest-1.8.0/README.md Generates native build scripts for Nanoflann using CMake, specifically enabling the build of sample projects. This is useful for testing and examples. ```bash mkdir mybuild cd mybuild cmake -Dgtest_build_samples=ON ${GTEST_DIR} ``` -------------------------------- ### Conditional CMake Dependency Configuration Source: https://github.com/jlblancoc/nanoflann/blob/master/examples/CMakeLists.txt Demonstrates how to conditionally build examples based on the presence of optional dependencies such as Eigen3 or MRPT-GUI. This ensures that examples requiring external libraries are only built when those libraries are found on the system. ```cmake if(EIGEN3_FOUND) DefineExample(matrix_example) target_include_directories (matrix_example PRIVATE ${EIGEN3_INCLUDE_DIR}) endif() find_package(mrpt-gui QUIET) if (mrpt-gui_FOUND) add_subdirectory(examples_gui/nanoflann_gui_example_R3) add_subdirectory(examples_gui/nanoflann_gui_example_bearings) endif() ``` -------------------------------- ### Define CMake Macro for nanoflann Examples Source: https://github.com/jlblancoc/nanoflann/blob/master/examples/CMakeLists.txt This macro automates the creation of executable targets for nanoflann examples. It sets the target folder, links the nanoflann library, and ensures the necessary include directories are configured. ```cmake macro(DefineExample _NAME) add_executable(${_NAME} ${_NAME}.cpp) set_target_properties(${_NAME} PROPERTIES FOLDER "Examples") target_link_libraries(${_NAME} nanoflann::nanoflann) endmacro() ``` -------------------------------- ### Integrate Eigen Matrices with KDTreeEigenMatrixAdaptor Source: https://context7.com/jlblancoc/nanoflann/llms.txt Demonstrates how to use the KDTreeEigenMatrixAdaptor to perform nearest neighbor searches on Eigen matrices without duplicating memory. It shows the setup of the matrix, index construction using std::cref, and the execution of a KNN query. ```cpp #include #include #include using matrix_t = Eigen::Matrix; using my_kd_tree_t = nanoflann::KDTreeEigenMatrixAdaptor; const size_t N = 1000; const size_t D = 3; matrix_t mat(N, D); for (size_t i = 0; i < N; i++) { for (size_t d = 0; d < D; d++) { mat(i, d) = 10.0 * rand() / RAND_MAX; } } my_kd_tree_t mat_index( D, std::cref(mat), 10 ); std::vector query_pt = {5.0, 5.0, 5.0}; const size_t num_results = 3; std::vector ret_indexes(num_results); std::vector out_dists_sqr(num_results); nanoflann::KNNResultSet resultSet(num_results); resultSet.init(&ret_indexes[0], &out_dists_sqr[0]); mat_index.index_->findNeighbors(resultSet, &query_pt[0]); for (size_t i = 0; i < resultSet.size(); i++) { std::cout << "Point " << ret_indexes[i] << " dist^2=" << out_dists_sqr[i] << "\n"; } ``` -------------------------------- ### CMake Integration for Nanoflann Source: https://github.com/jlblancoc/nanoflann/blob/master/README.md This snippet demonstrates how to integrate Nanoflann into a CMake project. It shows how to find the installed Nanoflann package and link it to an executable. Ensure Nanoflann is installed or its include directory is correctly specified. ```cmake # Find nanoflannConfig.cmake: find_package(nanoflann) add_executable(my_project test.cpp) # Make sure the include path is used: target_link_libraries(my_project nanoflann::nanoflann) ``` -------------------------------- ### Define nanoflann interface library Source: https://github.com/jlblancoc/nanoflann/blob/master/CMakeLists.txt Configures the nanoflann target as an INTERFACE library, specifying required C++ features and include directories for both build and installation environments. ```cmake add_library(nanoflann INTERFACE) target_compile_features(nanoflann INTERFACE cxx_auto_type cxx_decltype cxx_deleted_functions ) target_include_directories(nanoflann INTERFACE $ $) ``` -------------------------------- ### Configure KDTreeSingleIndexAdaptorParams Source: https://context7.com/jlblancoc/nanoflann/llms.txt Demonstrates how to initialize KD-tree construction parameters including leaf size, build flags, and multi-threading settings. These parameters balance build performance against query efficiency for spatial indexing. ```cpp #include nanoflann::KDTreeSingleIndexAdaptorParams params(10, nanoflann::KDTreeSingleIndexAdaptorFlags::None, 1); nanoflann::KDTreeSingleIndexAdaptorParams skip_build_params(10, nanoflann::KDTreeSingleIndexAdaptorFlags::SkipInitialBuildIndex, 1); nanoflann::KDTreeSingleIndexAdaptorParams threaded_params(10, nanoflann::KDTreeSingleIndexAdaptorFlags::None, 0); my_kd_tree_t index(3, cloud, params); ``` -------------------------------- ### Build Nanoflann using Make Source: https://github.com/jlblancoc/nanoflann/blob/master/tests/gtest-1.8.0/README.md Builds the Nanoflann library and sample tests using a provided Makefile. Assumes GNU make is available and the environment is configured correctly. ```bash cd ${GTEST_DIR}/make make ./sample1_unittest ``` -------------------------------- ### Apply Compile-Time Definitions Source: https://context7.com/jlblancoc/nanoflann/llms.txt Shows how to use preprocessor macros to customize nanoflann behavior, such as enforcing specific matching logic, disabling multi-threading, or configuring memory alignment for SIMD optimization. ```cpp #define NANOFLANN_FIRST_MATCH #define NANOFLANN_NO_THREADS #define NANOFLANN_NODE_ALIGNMENT 32 #include ``` -------------------------------- ### Execute Low-Level Searches with Custom Result Sets Source: https://context7.com/jlblancoc/nanoflann/llms.txt Shows how to use KNNResultSet and RadiusResultSet for granular control over search behavior and result retrieval in nanoflann. ```cpp #include #include // KNN search const size_t num_results = 1; size_t ret_index; float out_dist_sqr; nanoflann::KNNResultSet resultSet(num_results); resultSet.init(&ret_index, &out_dist_sqr); const float query_pt[3] = {0.5f, 0.5f, 0.5f}; index.findNeighbors(resultSet, &query_pt[0]); // Radius search const float squared_radius = 1.0f; std::vector> indices_dists; nanoflann::RadiusResultSet rResultSet(squared_radius, indices_dists); index.findNeighbors(rResultSet, query_pt); ``` -------------------------------- ### Build Static KD-Tree with KDTreeSingleIndexAdaptor (C++) Source: https://context7.com/jlblancoc/nanoflann/llms.txt Demonstrates how to construct a static KD-tree using `KDTreeSingleIndexAdaptor`. This class is suitable for datasets that do not change after the tree is built. It requires specifying the distance metric, the data adaptor (e.g., `PointCloud`), and the dimensionality. The tree is built upon construction. ```cpp #include // Define the KD-tree type with L2 distance metric for 3D points using my_kd_tree_t = nanoflann::KDTreeSingleIndexAdaptor< nanoflann::L2_Simple_Adaptor>, PointCloud, 3 // dimensionality (compile-time), use -1 for runtime >; // Create and populate your point cloud PointCloud cloud; // ... populate cloud.pts ... // Construct the KD-tree with max leaf size of 10 my_kd_tree_t index( 3, // dimensionality cloud, // data source nanoflann::KDTreeSingleIndexAdaptorParams(10 /* max leaf */) ); // The index is automatically built on construction // To manually rebuild after data changes: // cloud.pts.resize(cloud.pts.size() * 2); // index.buildIndex(); ``` -------------------------------- ### Perform K-Nearest Neighbors Search (C++) Source: https://context7.com/jlblancoc/nanoflann/llms.txt Shows how to use the `knnSearch` method of a nanoflann KD-tree index to find the K nearest neighbors to a given query point. It returns the indices and squared distances of the found neighbors. The number of results may be less than K if the dataset contains fewer points. ```cpp #include #include #include // Query point const float query_pt[3] = {0.5f, 0.5f, 0.5f}; // Storage for results size_t num_results = 5; std::vector ret_index(num_results); std::vector out_dist_sqr(num_results); // Perform KNN search num_results = index.knnSearch( &query_pt[0], // query point num_results, // number of neighbors to find &ret_index[0], // output: indices of neighbors &out_dist_sqr[0] // output: squared distances ); // Handle case where fewer points exist than requested ret_index.resize(num_results); out_dist_sqr.resize(num_results); // Print results std::cout << "Found " << num_results << " neighbors:\n"; for (size_t i = 0; i < num_results; i++) { std::cout << " Point #" << ret_index[i] << " dist^2=" << out_dist_sqr[i] << "\n"; } // Output: // Found 5 neighbors: // Point #4231 dist^2=0.00234 // Point #892 dist^2=0.00567 // ... ``` -------------------------------- ### Perform Radius-Based Search with nanoflann Source: https://context7.com/jlblancoc/nanoflann/llms.txt Demonstrates how to find all points within a specified radius using the radiusSearch method. Note that for L2 metrics, the radius provided must be squared. ```cpp #include #include #include const float query_pt[3] = {0.5f, 0.5f, 0.5f}; const float search_radius = 0.1f; std::vector> matches; matches.reserve(100); const size_t nMatches = index.radiusSearch(&query_pt[0], search_radius, matches); std::cout << "Found " << nMatches << " points within radius:\n"; for (size_t i = 0; i < nMatches; i++) { std::cout << " Point #" << matches[i].first << " dist^2=" << matches[i].second << "\n"; } ``` -------------------------------- ### Create nanoflann Dataset Adaptor (C++) Source: https://context7.com/jlblancoc/nanoflann/llms.txt Defines a custom data structure (PointCloud) that implements the necessary methods for nanoflann to access point data. This adaptor allows nanoflann to work with user-defined data without duplication. It requires `kdtree_get_point_count()` and `kdtree_get_pt()`, with `kdtree_get_bbox()` being optional. ```cpp #include #include template struct PointCloud { struct Point { T x, y, z; }; std::vector pts; // Required: Return the number of data points inline size_t kdtree_get_point_count() const { return pts.size(); } // Required: Return the dim'th component of the idx'th point inline T kdtree_get_pt(const size_t idx, const size_t dim) const { if (dim == 0) return pts[idx].x; else if (dim == 1) return pts[idx].y; else return pts[idx].z; } // Optional: Return false for default bbox computation template bool kdtree_get_bbox(BBOX& /* bb */) const { return false; } }; // Usage PointCloud cloud; cloud.pts.resize(10000); for (size_t i = 0; i < 10000; i++) { cloud.pts[i].x = static_cast(rand()) / RAND_MAX; cloud.pts[i].y = static_cast(rand()) / RAND_MAX; cloud.pts[i].z = static_cast(rand()) / RAND_MAX; } ``` -------------------------------- ### Persist KD-Tree Index to Disk Source: https://context7.com/jlblancoc/nanoflann/llms.txt Shows how to save a built KD-tree index to a binary file and load it back later. Note that the index file does not contain the original data points, so the same data source must be provided when loading the index. ```cpp #include #include using my_kd_tree_t = nanoflann::KDTreeSingleIndexAdaptor< nanoflann::L2_Simple_Adaptor>, PointCloud, 3>; PointCloud cloud; { // Save my_kd_tree_t index(3, cloud, {10}); std::ofstream f("index.bin", std::ios::binary); index.saveIndex(f); } { // Load my_kd_tree_t index(3, cloud, nanoflann::KDTreeSingleIndexAdaptorParams(10, nanoflann::KDTreeSingleIndexAdaptorFlags::SkipInitialBuildIndex)); std::ifstream f("index.bin", std::ios::binary); index.loadIndex(f); } ``` -------------------------------- ### Compile and Run Google Test's Own Tests with CMake Source: https://github.com/jlblancoc/nanoflann/blob/master/tests/gtest-1.8.0/README.md Steps to set up a build environment for Google Test using CMake, specifically to compile and run Google Test's internal test suite. This includes enabling test building and specifying the Python executable if needed. ```bash mkdir mybuild cd mybuild cmake -Dgtest_build_tests=ON ${GTEST_DIR} If Python is not found: cmake -DPYTHON_EXECUTABLE=path/to/python -Dgtest_build_tests=ON ${GTEST_DIR} Build and run tests: make make test ``` -------------------------------- ### Compile Google Test as Shared Library (DLL) Source: https://github.com/jlblancoc/nanoflann/blob/master/tests/gtest-1.8.0/README.md Instructions for compiling Google Test as a shared library (DLL on Windows) and for compiling tests that link against this shared library. It involves specific compiler flags to enable shared library creation and linking. ```bash Compile gtest as shared library: -DGTEST_CREATE_SHARED_LIBRARY=1 Compile tests linking against gtest shared library: -DGTEST_LINKED_AS_SHARED_LIBRARY=1 ``` -------------------------------- ### Compile Google Test Library with g++ Source: https://github.com/jlblancoc/nanoflann/blob/master/tests/gtest-1.8.0/README.md Compiles the Google Test source file into a static library. Requires Google Test headers to be in the include paths and uses pthread for thread support. ```bash g++ -isystem ${GTEST_DIR}/include -I${GTEST_DIR} \ -pthread -c ${GTEST_DIR}/src/gtest-all.cc ar -rv libgtest.a gtest-all.o ``` -------------------------------- ### Compile and Link User Test with g++ Source: https://github.com/jlblancoc/nanoflann/blob/master/tests/gtest-1.8.0/README.md Compiles a user's test source file and links it against the Google Test library. Requires Google Test headers and the compiled gtest library. ```bash g++ -isystem ${GTEST_DIR}/include -pthread path/to/your_test.cc libgtest.a \ -o your_test ``` -------------------------------- ### Implement Dynamic KD-Tree Indexing Source: https://context7.com/jlblancoc/nanoflann/llms.txt Explains the use of KDTreeSingleIndexDynamicAdaptor to manage point clouds that change over time, allowing for point insertion and removal without full index rebuilds. ```cpp #include using my_kd_tree_t = nanoflann::KDTreeSingleIndexDynamicAdaptor< nanoflann::L2_Simple_Adaptor>, PointCloud, 3 >; PointCloud cloud; my_kd_tree_t index(3, cloud, {10}); // Add points in chunks index.addPoints(i, end); // Remove a point index.removePoint(5000); ``` -------------------------------- ### Configure Distance Metrics for KD-Tree Source: https://context7.com/jlblancoc/nanoflann/llms.txt Illustrates the various distance metric adaptors available in nanoflann, including L2, L1, SO2, and SO3. These adaptors are passed as template arguments to the KDTreeSingleIndexAdaptor to define how distance is calculated between points. ```cpp #include using tree_L2 = nanoflann::KDTreeSingleIndexAdaptor< nanoflann::L2_Adaptor>, PointCloud, 3>; using tree_L2_Simple = nanoflann::KDTreeSingleIndexAdaptor< nanoflann::L2_Simple_Adaptor>, PointCloud, 3>; using tree_L1 = nanoflann::KDTreeSingleIndexAdaptor< nanoflann::L1_Adaptor>, PointCloud, 3>; using tree_SO2 = nanoflann::KDTreeSingleIndexAdaptor< nanoflann::SO2_Adaptor>, PointCloud_Orient, 1>; using tree_SO3 = nanoflann::KDTreeSingleIndexAdaptor< nanoflann::SO3_Adaptor>, PointCloud_Quat, 4>; ``` -------------------------------- ### Configure CMake for nanoflann integration Source: https://github.com/jlblancoc/nanoflann/blob/master/examples/example_with_cmake/CMakeLists.txt This CMake configuration file sets up a project to use nanoflann. It finds the package, defines the executable, and links the necessary library and include directories. ```cmake cmake_minimum_required(VERSION 3.0) project(pointcloud_example) # Find nanoflannConfig.cmake: find_package(nanoflann REQUIRED) add_executable(${PROJECT_NAME} pointcloud_example.cpp) # Make sure the include path is used: target_link_libraries(${PROJECT_NAME} nanoflann::nanoflann) # for this example to find "../utils.h" target_include_directories(${PROJECT_NAME} PRIVATE ".") ``` -------------------------------- ### Build Nanoflann using CMake Source: https://github.com/jlblancoc/nanoflann/blob/master/tests/gtest-1.8.0/README.md Generates native build scripts for Nanoflann using CMake. This command creates a build directory and configures the build environment. ```bash mkdir mybuild cd mybuild cmake ${GTEST_DIR} ``` -------------------------------- ### Index Persistence (Save/Load) Source: https://context7.com/jlblancoc/nanoflann/llms.txt How to serialize the KD-tree structure to a file and reload it to avoid re-indexing. ```APIDOC ## Save and Load Index ### Description Persists the tree structure to disk. Note that the raw data points must be re-associated with the index upon loading. ### Methods - **saveIndex(std::ostream&)**: Writes the tree structure to an output stream. - **loadIndex(std::istream&)**: Reads the tree structure from an input stream. ### Usage ```cpp // Saving index.saveIndex(file_stream); // Loading index.loadIndex(file_stream); ``` ``` -------------------------------- ### KDTreeEigenMatrixAdaptor Integration Source: https://context7.com/jlblancoc/nanoflann/llms.txt Demonstrates how to use the KDTreeEigenMatrixAdaptor to perform nearest neighbor searches directly on Eigen matrices without duplicating data. ```APIDOC ## KDTreeEigenMatrixAdaptor ### Description Integrates nanoflann with Eigen matrices. It allows the KD-tree to reference matrix data directly, avoiding memory copies. ### Method N/A (C++ Template Class) ### Parameters - **matrix_t** (Type) - The Eigen matrix type (row-major or column-major). - **D** (size_t) - Dimensionality of the points. - **max_leaf_size** (size_t) - Maximum number of points in a leaf node. ### Request Example ```cpp using my_kd_tree_t = nanoflann::KDTreeEigenMatrixAdaptor; my_kd_tree_t mat_index(D, std::cref(mat), 10); ``` ``` -------------------------------- ### Compile-Time Definitions Source: https://context7.com/jlblancoc/nanoflann/llms.txt Preprocessor macros to customize library behavior at compile time. ```APIDOC ## Compile-Time Definitions ### Description Macros that must be defined before including nanoflann.hpp to modify library behavior. ### Parameters - **NANOFLANN_FIRST_MATCH** (macro) - Optional - Return point with lowest index when distances are equal. - **NANOFLANN_NO_THREADS** (macro) - Optional - Disable multithreading. - **NANOFLANN_NODE_ALIGNMENT** (macro) - Optional - Custom memory alignment (e.g., 32 for AVX). ``` -------------------------------- ### KDTreeSingleIndexAdaptor Parameters Source: https://github.com/jlblancoc/nanoflann/blob/master/README.md Configuration options for the KDTreeSingleIndexAdaptor, influencing tree construction and query performance. ```APIDOC ## KD-Tree Parameters ### `KDTreeSingleIndexAdaptorParams::leaf_max_size` * **Description**: This parameter defines the maximum number of points that can be stored in a leaf node of the KD-tree. During tree construction, nodes are recursively divided until the number of points within them is less than or equal to this threshold. For queries, a linear search is performed within the selected leaf nodes. A larger `leaf_max_size` leads to faster tree construction but slower queries, while a smaller value results in slower construction but potentially faster queries, up to a point. * **Recommendation**: Benchmarking is recommended for optimal selection based on application and hardware. A rule of thumb suggests a value between 10 and 50 for applications where query cost is dominant. The default value is 10. ### `KDTreeSingleIndexAdaptorParams::checks` * **Description**: This parameter is maintained for backward compatibility with the original FLANN interface and is effectively ignored by Nanoflann. It can be disregarded. ### `KDTreeSingleIndexAdaptorParams::n_thread_build` * **Description**: Specifies the maximum number of threads to be used concurrently during the construction of the KD-tree. The default value is 1. If set to 0, Nanoflann automatically determines the optimal number of threads. Benchmarking is advised, as using the maximum number of threads is not always the most efficient approach. ``` -------------------------------- ### Configure gtest Static Library Build with CMake Source: https://github.com/jlblancoc/nanoflann/blob/master/tests/gtest-1.8.0/CMakeLists.txt This CMake script sets up the build for the gtest framework as a static library. It includes directives for including directories, adding source files, and applying compiler flags specific to certain environments like MSVC and GNU C++ on Unix-like systems. The target is organized within a '3rd party' folder in the build system. ```cmake # ---------------------------------------------------------------------------- # Auxiliary static library: gtest (Google test framework) # ---------------------------------------------------------------------------- project(mygtest) # Fix a "bug" in VS11 (MSVC 2012): if(MSVC) add_definitions(-D_VARIADIC_MAX=10) endif(MSVC) include_directories("include") include_directories(".") add_library(mygtest STATIC src/gtest-all.cc) if(CMAKE_COMPILER_IS_GNUCXX AND UNIX) add_compile_options("-fPIC") endif() set_target_properties(mygtest PROPERTIES FOLDER "3rd party") ``` -------------------------------- ### Nanoflann Compile-Time Definitions Source: https://github.com/jlblancoc/nanoflann/blob/master/README.md These definitions allow customization of Nanoflann's behavior at compile time, affecting aspects like nearest neighbor selection and multithreading. ```APIDOC ## Compile-Time Definitions ### `NANOFLANN_FIRST_MATCH` * **Description**: If defined, and two points have the same distance to the query point, the point with the lower index will be returned first. If not defined, there is no particular order for points with equal distances. * **Usage**: Define this macro before including Nanoflann headers to enable this behavior. ### `NANOFLANN_NO_THREADS` * **Description**: If defined, Nanoflann's multithreading capabilities are disabled. This allows the library to be used without linking against pthreads. Attempting to use multiple threads when this is defined will result in an exception. * **Usage**: Define this macro before including Nanoflann headers to disable multithreading. ``` -------------------------------- ### Extract nanoflann version from header Source: https://github.com/jlblancoc/nanoflann/blob/master/CMakeLists.txt This snippet reads the nanoflann.hpp file, uses regular expressions to extract the version hex code, and parses it into major, minor, and patch components for project configuration. ```cmake file(READ "${CMAKE_CURRENT_SOURCE_DIR}/include/nanoflann.hpp" STR_HPP) string(REGEX MATCHALL "NANOFLANN_VERSION.*0x[0-9,A-F]+" CMAKE_VERSION_LINE "${STR_HPP}") string(REGEX MATCHALL "0x[0-9,A-F]+" NANOFLANN_VERSION_HEX "${CMAKE_VERSION_LINE}") string(REGEX REPLACE "0x(.).*" "\\1" NANOFLANN_VERSION_MAJOR "${NANOFLANN_VERSION_HEX}" ) string(REGEX REPLACE "0x.(.).*" "\\1" NANOFLANN_VERSION_MINOR "${NANOFLANN_VERSION_HEX}" ) string(REGEX REPLACE "0x..(.).*" "\\1" NANOFLANN_VERSION_PATCH "${NANOFLANN_VERSION_HEX}" ) ``` -------------------------------- ### KDTreeSingleIndexDynamicAdaptor - Dynamic Indexing Source: https://context7.com/jlblancoc/nanoflann/llms.txt Provides support for datasets that change over time, allowing for point addition and removal without full index rebuilds. ```APIDOC ## KDTreeSingleIndexDynamicAdaptor ### Description Allows dynamic management of points in a KD-tree structure. ### Method Class Methods ### Endpoint index.addPoints(start, end) / index.removePoint(index) ### Parameters #### Path Parameters - **start** (size_t) - Required - Start index of points to add. - **end** (size_t) - Required - End index of points to add. - **index** (size_t) - Required - Index of the point to remove. ### Request Example index.addPoints(0, 100); index.removePoint(5000); ### Response #### Success Response (200) - **void** - Operations update the internal index structure. ``` -------------------------------- ### KDTreeSingleIndexAdaptorParams Source: https://context7.com/jlblancoc/nanoflann/llms.txt Configuration options for KD-tree construction including leaf size and threading settings. ```APIDOC ## KDTreeSingleIndexAdaptorParams ### Description Configures the construction of the KD-tree index, allowing control over leaf node size, build flags, and multi-threading behavior. ### Method Constructor ### Parameters #### Request Body - **leaf_max_size** (int) - Required - Tradeoff between build time and query time. Recommended: 10-50. - **flags** (enum) - Required - Flags such as None or SkipInitialBuildIndex. - **n_thread_build** (int) - Required - Number of threads for building. 0 for auto-detect. ### Request Example { "leaf_max_size": 10, "flags": "nanoflann::KDTreeSingleIndexAdaptorFlags::None", "n_thread_build": 1 } ``` -------------------------------- ### Regenerate Google Test Source Files Source: https://github.com/jlblancoc/nanoflann/blob/master/tests/gtest-1.8.0/README.md Instructions for regenerating Google Test's source files from their .pump definitions using the pump.py script. This is necessary when modifications are made to the .pump files. ```python Run pump.py to regenerate source files: python scripts/pump.py ``` -------------------------------- ### Distance Metrics Configuration Source: https://context7.com/jlblancoc/nanoflann/llms.txt Overview of supported distance metrics in nanoflann, including Euclidean, Manhattan, and rotation group metrics. ```APIDOC ## Distance Metrics ### Description Defines the metric used for distance calculations within the KD-tree index. ### Supported Metrics - **L2_Adaptor**: Squared Euclidean distance (optimized for high dimensions). - **L2_Simple_Adaptor**: Squared Euclidean distance (optimized for 2D/3D). - **L1_Adaptor**: Manhattan distance. - **SO2_Adaptor**: Angular difference for 2D rotations. - **SO3_Adaptor**: Quaternion inner product for 3D rotations. ### Example ```cpp using tree_L2 = nanoflann::KDTreeSingleIndexAdaptor< nanoflann::L2_Adaptor>, PointCloud, 3>; ``` -------------------------------- ### Define Custom Uninstall Target Source: https://github.com/jlblancoc/nanoflann/blob/master/CMakeLists.txt Creates a custom CMake target to handle library uninstallation by executing a generated script. It checks for existing targets to avoid conflicts in master projects. ```cmake configure_file( "${nanoflann_SOURCE_DIR}/scripts/cmake_uninstall.cmake.in" "${nanoflann_BINARY_DIR}/cmake_uninstall.cmake" @ONLY IMMEDIATE) add_custom_target(uninstall "${CMAKE_COMMAND}" -P "${nanoflann_BINARY_DIR}/cmake_uninstall.cmake") ``` -------------------------------- ### findNeighbors - Low-Level Search Source: https://context7.com/jlblancoc/nanoflann/llms.txt Direct access to search algorithms using result set objects for fine-grained control over search behavior. ```APIDOC ## findNeighbors ### Description Performs a search using a specific result set object (KNN or Radius) for advanced control. ### Method Method Call ### Endpoint index.findNeighbors(resultSet, query_pt) ### Parameters #### Path Parameters - **resultSet** (object) - Required - A KNNResultSet or RadiusResultSet instance. - **query_pt** (pointer) - Required - Pointer to the query point coordinates. ### Request Example nanoflann::KNNResultSet resultSet(1); resultSet.init(&ret_index, &out_dist_sqr); index.findNeighbors(resultSet, &query_pt[0]); ### Response #### Success Response (200) - **resultSet** (object) - Populated result set containing indices and distances. ``` -------------------------------- ### KDTreeVectorOfVectorsAdaptor Source: https://context7.com/jlblancoc/nanoflann/llms.txt Adaptor interface for using std::vector> with nanoflann. ```APIDOC ## KDTreeVectorOfVectorsAdaptor ### Description Allows the KD-tree to interface directly with nested vector structures without copying data. ### Method Template Class ### Parameters #### Path Parameters - **VectorOfVectorsType** (type) - Required - The container type (e.g., std::vector>). - **num_t** (type) - Optional - Numeric type, defaults to double. - **DIM** (int) - Optional - Dimensionality of points, defaults to -1. ### Request Example { "dim": 3, "data": "std::vector>", "leaf_max_size": 10 } ``` -------------------------------- ### Implement Vector of Vectors Adaptor Source: https://context7.com/jlblancoc/nanoflann/llms.txt Provides a template structure to adapt std::vector> for use with nanoflann. This allows the library to perform spatial queries directly on nested vector data structures without copying. ```cpp #include #include #include template struct KDTreeVectorOfVectorsAdaptor { using self_t = KDTreeVectorOfVectorsAdaptor; using metric_t = typename Distance::template traits::distance_t; using index_t = nanoflann::KDTreeSingleIndexAdaptor; index_t* index = nullptr; const VectorOfVectorsType& m_data; KDTreeVectorOfVectorsAdaptor(const size_t dim, const VectorOfVectorsType& mat, const int leaf_max_size = 10) : m_data(mat) { index = new index_t(static_cast(dim), *this, {leaf_max_size}); } ~KDTreeVectorOfVectorsAdaptor() { delete index; } size_t kdtree_get_point_count() const { return m_data.size(); } num_t kdtree_get_pt(const size_t idx, const size_t dim) const { return m_data[idx][dim]; } template bool kdtree_get_bbox(BBOX&) const { return false; } }; ``` -------------------------------- ### Avoid Macro Name Clashes in Google Test Source: https://github.com/jlblancoc/nanoflann/blob/master/tests/gtest-1.8.0/README.md Demonstrates how to prevent Google Test's macros from clashing with macros from other libraries by using compiler flags to rename Google Test's macros. This is particularly useful for macros like FAIL, SUCCEED, and TEST. ```bash To avoid clashes with macro FOO: -DGTEST_DONT_DEFINE_FOO=1 Example for TEST macro: -DGTEST_DONT_DEFINE_TEST=1 Usage after renaming TEST macro: GTEST_TEST(SomeTest, DoesThis) { ... } ``` -------------------------------- ### radiusSearch - Radius-Based Search Source: https://context7.com/jlblancoc/nanoflann/llms.txt Finds all points within a specified radius from a query point. Note that for L2 metrics, the radius provided must be squared. ```APIDOC ## radiusSearch ### Description Finds all points within a specified radius from the query point. For L2 metrics, the search radius and returned distances are squared. ### Method Method Call ### Endpoint index.radiusSearch(query_pt, search_radius, matches, params) ### Parameters #### Path Parameters - **query_pt** (pointer) - Required - Pointer to the query point coordinates. - **search_radius** (float) - Required - The squared search radius. - **matches** (vector) - Required - Output container for index/distance pairs. - **params** (SearchParameters) - Optional - Configuration for search behavior (e.g., sorting). ### Request Example const float query_pt[3] = {0.5f, 0.5f, 0.5f}; const float search_radius = 0.1f; std::vector> matches; index.radiusSearch(&query_pt[0], search_radius, matches); ### Response #### Success Response (200) - **nMatches** (size_t) - Number of points found within the radius. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.