Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions localization/autoware_ndt_scan_matcher_common/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
cmake_minimum_required(VERSION 3.14)
project(autoware_ndt_scan_matcher_common)

find_package(autoware_cmake REQUIRED)
autoware_package()

# This package has headers only. They include Eigen and PCL, so the packages that depend on this
# package find both. Export all of PCL: a package that first finds only some components of PCL can
# miss the targets of the other components when it finds PCL again (for example, through pcl_ros).
find_package(eigen3_cmake_module REQUIRED)
find_package(Eigen3 REQUIRED)
find_package(PCL REQUIRED COMPONENTS common)
ament_export_dependencies(eigen3_cmake_module Eigen3 PCL)

# A backend package links this target. It gives the include directory, Eigen and PCL.
add_library(${PROJECT_NAME} INTERFACE)
target_include_directories(${PROJECT_NAME} INTERFACE
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include/${PROJECT_NAME}>)
target_link_libraries(${PROJECT_NAME} INTERFACE Eigen3::Eigen pcl_common)
install(TARGETS ${PROJECT_NAME} EXPORT export_${PROJECT_NAME})
ament_export_targets(export_${PROJECT_NAME})

if(BUILD_TESTING)
find_package(ament_cmake_gtest REQUIRED)
find_package(class_loader REQUIRED)

# The same fake backend as several plugin libraries: once with the Eigen configuration of the
# test, and once for each definition that can change the layout of the Eigen types or the heap
# allocator of Eigen, as a backend that was built with other compiler options.
set(fake_backend_definitions_same "")
set(fake_backend_definitions_align_0 EIGEN_MAX_STATIC_ALIGN_BYTES=0)
set(fake_backend_definitions_align_16 EIGEN_MAX_STATIC_ALIGN_BYTES=16)
set(fake_backend_definitions_align_32 EIGEN_MAX_STATIC_ALIGN_BYTES=32)
set(fake_backend_definitions_align_64 EIGEN_MAX_STATIC_ALIGN_BYTES=64)
set(fake_backend_definitions_allocator_eigen EIGEN_MALLOC_ALREADY_ALIGNED=0)
set(fake_backend_definitions_allocator_std EIGEN_MALLOC_ALREADY_ALIGNED=1)

ament_add_gtest(test_ndt_backend_abi
test/test_ndt_backend_abi.cpp
)
target_link_libraries(test_ndt_backend_abi
${PROJECT_NAME} class_loader::class_loader ${CMAKE_DL_LIBS})

foreach(variant
same align_0 align_16 align_32 align_64 allocator_eigen allocator_std)
add_library(fake_ndt_backend_${variant} MODULE test/fake_ndt_backend.cpp)
target_link_libraries(fake_ndt_backend_${variant} ${PROJECT_NAME} class_loader::class_loader)
target_compile_definitions(fake_ndt_backend_${variant} PRIVATE
${fake_backend_definitions_${variant}})
# $<1:...> keeps a multi-config generator from adding a directory for each configuration.
set_target_properties(fake_ndt_backend_${variant} PROPERTIES
LIBRARY_OUTPUT_DIRECTORY $<1:${CMAKE_CURRENT_BINARY_DIR}/fake_ndt_backends>)
add_dependencies(test_ndt_backend_abi fake_ndt_backend_${variant})
endforeach()
target_compile_definitions(test_ndt_backend_abi PRIVATE
FAKE_BACKEND_DIRECTORY="${CMAKE_CURRENT_BINARY_DIR}/fake_ndt_backends")
endif()

autoware_ament_auto_package(
USE_SCOPED_HEADER_INSTALL_DIR
)
76 changes: 76 additions & 0 deletions localization/autoware_ndt_scan_matcher_common/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# autoware_ndt_scan_matcher_common

## Purpose

This package holds the interface between [autoware_ndt_scan_matcher](../autoware_ndt_scan_matcher/README.md) and its NDT backends. An NDT backend is an implementation of NDT scan matching that the node loads with [pluginlib](https://github.com/ros/pluginlib). This package has headers only.

A backend package depends on this package, not on the node and its ROS dependencies.

![The interface package holds NdtBackend, NdtParams, NdtResult and an ABI guard. The node calls the interface, and backend packages implement it.](media/ndt-backend-interface.svg)

## Contents

- `autoware::ndt_scan_matcher::NdtBackend` in `autoware/ndt_scan_matcher_common/ndt_backend.hpp`: the interface of a backend. Its comments state the rules for a backend: instances, threads, the order of calls, exceptions, copies and the lifetime of the library.
- `autoware::ndt_scan_matcher::NdtParams` and `autoware::ndt_scan_matcher::NdtResult` in `autoware/ndt_scan_matcher_common/ndt_types.hpp`: the parameters and the result of an alignment. The comments of `NdtResult` state how the node uses each field and how a backend must compute the scores.

## How the node uses a backend

The node has two instances of the backend: the active instance, and the instance that the map update thread builds. It calls them in three places:

1. At startup, pluginlib makes the backend with the name in `ndt.backend`, and the node calls `initialize()`.
2. The map update thread changes the map of the second instance with `add_target()`, `remove_target()` and `commit_target()`. Then the node swaps the two instances under a short lock.
3. The scan callback calls `align()` on the active instance for each scan. The node compares the scores of the `NdtResult` with its thresholds and accepts or rejects the pose.

![At startup, pluginlib makes the backend and the node calls initialize(). The map update thread fills an instance and the node swaps the instances. The scan callback calls align() on the active instance.](media/ndt-backend-calls.svg)

The comments in `ndt_backend.hpp` state the exact rules for each of these calls.

## Add a backend

![Add a backend in four steps: depend, implement, build and register. Then the node loads the backend when ndt.backend has its name.](media/ndt-backend-add.svg)

A backend package does these steps:

1. Depend on `autoware_ndt_scan_matcher_common` and `pluginlib` in `package.xml`.
2. Implement `autoware::ndt_scan_matcher::NdtBackend`, and export the class with `PLUGINLIB_EXPORT_CLASS`.
3. Build the class into a library with `add_library()`, link the targets of `autoware_ndt_scan_matcher_common` and `pluginlib` with `target_link_libraries()`, and install the library. Do not use `ament_auto_add_library()`: ament_auto exports the library and links it into the packages that depend on the backend package. pluginlib loads the library at runtime, so no other library may link it. The target of `autoware_ndt_scan_matcher_common` gives only the `common` component of PCL. A backend that uses another component of PCL, for example `kdtree`, finds and links that component itself.
4. Register the class with `pluginlib_export_plugin_description_file(autoware_ndt_scan_matcher_common <file>.xml)`.

`CMakeLists.txt`:

```cmake
cmake_minimum_required(VERSION 3.14)
project(my_package)

find_package(ament_cmake REQUIRED)
find_package(autoware_ndt_scan_matcher_common REQUIRED)
find_package(pluginlib REQUIRED)

add_library(my_ndt_backend SHARED src/my_ndt_backend.cpp)
target_link_libraries(my_ndt_backend
${autoware_ndt_scan_matcher_common_TARGETS} ${pluginlib_TARGETS})
install(TARGETS my_ndt_backend LIBRARY DESTINATION lib)
pluginlib_export_plugin_description_file(autoware_ndt_scan_matcher_common plugins.xml)

ament_package()
```

`plugins.xml`:

```xml
<library path="my_ndt_backend">
<class name="my" type="my_package::MyNdtBackend" base_class_type="autoware::ndt_scan_matcher::NdtBackend">
<description>My NDT backend.</description>
</class>
</library>
```

`path` is the name of the library. `type` is the class that `PLUGINLIB_EXPORT_CLASS` exports. `name` is the value of `ndt.backend` that selects the backend. Use a short, lowercase name that tells the implementation, for example `ndt_omp` or `ndt_cuda`. A name must be unique among all installed backends, so do not use only the name of a technology that other implementations can also use, for example `cuda`.

## Compile options

`NdtResult` holds fixed-size `Eigen` types, which pass between the node and the backend library. Their memory layout depends on the static alignment of `Eigen`, which depends on the SIMD options of the compiler: AVX changes it, and SSE does not. The node also frees vectors that the backend allocated with the allocator of `Eigen`. Some options change this allocator, for example AVX or the address sanitizer of GCC.

The types and the interface are in an inline namespace whose name holds the version of the interface, the `Eigen` alignment (`EIGEN_MAX_STATIC_ALIGN_BYTES`) and the `Eigen` allocator. A backend that was built against another version of the interface, or with an alignment or an allocator that differs from the node, has other C++ symbols. Then the node loads its library but finds no factory for the backend, and it stops with an error message that names this cause. Rebuild the backend against the same version of Autoware Core, and do not enable AVX or a sanitizer in only one of the two. The name does not hold the version of `Eigen` or of PCL, so the node and the backend must also use the same `Eigen` and the same PCL. `NdtBackend` passes `pcl::PointCloud` between them.

When a declaration in `ndt_types.hpp` or `ndt_backend.hpp` changes, change the version `v1` in the name of the inline namespace.
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
// Copyright 2026 Autoware Foundation
//
// 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 AUTOWARE__NDT_SCAN_MATCHER_COMMON__NDT_BACKEND_HPP_
#define AUTOWARE__NDT_SCAN_MATCHER_COMMON__NDT_BACKEND_HPP_

#include "autoware/ndt_scan_matcher_common/ndt_types.hpp"

#include <Eigen/Core>

#include <pcl/point_cloud.h>
#include <pcl/point_types.h>

#include <memory>
#include <string>
#include <vector>

namespace autoware::ndt_scan_matcher
{
inline namespace AUTOWARE_NDT_BACKEND_ABI
{
/// An implementation of NDT scan matching for autoware_ndt_scan_matcher. The node loads it with
/// pluginlib, by the name in its parameter `ndt.backend`. The README of this package explains how
/// a package adds a backend.
///
/// Instances: the node calls initialize() only on the instance that pluginlib makes. clone() and
/// clone_empty() make instances that are ready without initialize(), so they must share or take
/// again what initialize() took. The node destroys the instance from pluginlib at the first full
/// map rebuild.
///
/// Threads: one thread at a time uses one instance, but different threads use it over its life.
/// So a backend must not need a resource that works only in one thread. Two instances (the active
/// one and the one that the map update module builds) run at the same time in two threads, so they
/// must not share mutable state.
///
/// Order of calls: after add_target() or remove_target(), the node calls commit_target() before it
/// calls any function of the instance other than these two. The node calls align() and the
/// calculate functions only while has_target() is true. The source of align() always has points.
/// The cloud of a calculate function can be empty.
///
/// Exceptions: an exception from initialize() stops the node at startup. The node does not catch
/// exceptions from the other functions either, so such an exception stops the node.
///
/// Library lifetime: the node never unloads a backend library. So clone() and clone_empty() can
/// make instances in the library without pluginlib.
class NdtBackend
{
public:
using PointSource = pcl::PointXYZ;
using PointTarget = pcl::PointXYZ;
using SharedPtr = std::shared_ptr<NdtBackend>;

virtual ~NdtBackend() = default;

/// Called once, after pluginlib makes the instance. A backend that needs a resource (for
/// example, a GPU) gets it here, and throws std::runtime_error if it cannot run on this computer.
virtual void initialize(const NdtParams & params) = 0;

/// The name of the backend, for logs.
virtual std::string name() const = 0;

/// The parameters that the backend uses. The node compares NdtResult::iteration_num with
/// get_params().max_iterations.
virtual NdtParams get_params() const = 0;

/// add_target() and remove_target() change the map, and commit_target() finishes the change.
/// These three functions do all the map work, on an instance that no other thread uses at the
/// same time. align() must not do map work that these functions deferred.
///
/// The backend can keep the cloud. The node takes the ids from the map loader and does not
/// examine them. Normally, each map_id is unique among the added clouds and remove_target() gets
/// only ids that were added. remove_target() must ignore an id that was not added.
virtual void add_target(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we could rename this to add_map instead of add_target to make it more obvious, but that can come after all the migration to pluginlib is done.

const pcl::PointCloud<PointTarget>::ConstPtr & cloud, const std::string & map_id) = 0;
virtual void remove_target(const std::string & map_id) = 0;
virtual void commit_target() = 0;
/// The ids of the map clouds that were added and not removed.
virtual std::vector<std::string> get_current_map_ids() const = 0;
/// True if get_current_map_ids() is not empty. The map can still have no voxel, for example if
/// no cell has enough points. Then align() must return a result and must not fail.
virtual bool has_target() const = 0;

/// An independent instance with the same parameters, map, regularization pose and state. Later
/// changes to one instance do not change the other. The node calls it on the active instance
/// while it holds the lock of that instance, so a long copy delays the alignments. It also calls
/// it on the instance that the map update thread builds, which no other thread uses at that time.
/// The instances can share immutable data, for example a map that is already on the GPU.
virtual SharedPtr clone() const = 0;
/// A new instance of the same backend, with the same parameters, without a map and without a
/// regularization pose.
virtual SharedPtr clone_empty() const = 0;

/// Sets the regularization pose (base_link to map) for the next alignments, until
/// unset_regularization_pose(). The regularization pulls the aligned pose toward the x and y of
/// this pose, along the heading of the vehicle, with the weight
/// NdtParams::regularization_scale_factor. The node sets it only if its parameter
/// `ndt.regularization.enable` is true.
virtual void set_regularization_pose(const Eigen::Matrix4f & pose) = 0;
virtual void unset_regularization_pose() = 0;

/// Aligns source (in the base_link frame) to the map, from guess (base_link to map). The backend
/// does not keep source after it returns. NdtResult describes what the node needs from each
/// field.
virtual NdtResult align(
const Eigen::Matrix4f & guess, const pcl::PointCloud<PointSource>::ConstPtr & source) = 0;

/// The scores of NdtResult for a cloud that is already in the map frame, without the
/// regularization. For an empty cloud, the two scores are 0 and the cloud of the third function
/// is empty.
virtual double calculate_transformation_probability(
const pcl::PointCloud<PointSource> & cloud_in_map) const = 0;
virtual double calculate_nearest_voxel_transformation_likelihood(
const pcl::PointCloud<PointSource> & cloud_in_map) const = 0;
/// The points of the cloud that have at least one voxel near them, each with its largest NDT
/// score as the intensity, in any order.
virtual pcl::PointCloud<pcl::PointXYZI> calculate_nearest_voxel_score_each_point(
const pcl::PointCloud<PointSource> & cloud_in_map) const = 0;

protected:
NdtBackend() = default;
// Only a derived class copies the base, for clone(). This prevents slicing.
NdtBackend(const NdtBackend &) = default;
NdtBackend & operator=(const NdtBackend &) = delete;
};
} // namespace AUTOWARE_NDT_BACKEND_ABI
} // namespace autoware::ndt_scan_matcher

#endif // AUTOWARE__NDT_SCAN_MATCHER_COMMON__NDT_BACKEND_HPP_
Loading
Loading