No exceptions, no RTTI, bounded query stack, and no allocation during queries.
Embeddable & offloadable. High-performance static kd-trees.
kd3 indexes points for nearest-neighbour queries, k-NN, rays, and predicate-filtered searches. Construction runs in parallel, queries use bounded stack space and caller-provided buffers, and the payload is application-defined.
No exceptions, no RTTI, bounded query stack, and no allocation during queries.
OpenMP task-based building for large point sets.
Designed for 2D to 4D keys, with support for higher dimensions.
Drop include/kd3/ into your project. No required runtime.
A stb-style C wrapper for FFI and non-C++ callers.
Generate shader query functions for the 2D to 4D tree layouts.
kd3 is generally faster than nanoflann across the tested point clouds and query patterns, particularly with subtree bounds and near-surface queries. Construction is parallel.
| operation | Ryzen 9 5950Xmedian speedup | Ryzen 9 9950X3D2median speedup | Xeon Gold 6252median speedup |
|---|---|---|---|
1-NN, bbox-volume, aabb | 3.23x | 3.12x | 2.40x |
1-NN, on-cloud, aabb | 3.09x | 2.50x | 2.46x |
10-NN, bbox-volume, aabb | 2.65x | 1.70x | 1.70x |
10-NN, on-cloud, aabb | 2.59x | 1.57x | 1.71x |
Each value is the median across all 11 datasets for the same operation and configuration. These rows use the aabb configuration with subtree bounds. Results without subtree bounds are mixed and are listed on the benchmark page.
kd3 targets static low-dimensional point clouds. nanoflann covers a broader feature set. The full matrix is on the comparison page.
The first demo runs editable kd3 queries against a rebuilt tree. The second queries a 3D point cloud.
Every query function is an editable kd3 call. Change the parameters, rebuild the tree, and watch the canvas and returned values update.
Loading demo...
Loading demo...
The tree is built in WebAssembly, its flat buffers are uploaded to the GPU, and a fragment shader generated by kd3::generate_glsl traces one ray per pixel. kd3 does not provide a shader backend for web use; this demo manually adapts the generated GLSL to WebGL2 texture storage for visualization only. It is not a supported web rendering path.
kd3 builds a balanced binary tree over fixed-size leaf buckets. The payload is application-defined.
The builder computes tight bounds for each subtree, splits along the widest axis at the median, and recurses until each leaf holds at mostleaf_size points. Leaves are packed into fixed-size buckets; empty slots are padded with INF andINF_IDX.
Each split removes half the remaining points from consideration. The leaves are the only place where full point coordinates are stored.
For N = 7000, leaf_size = 8, andD = 3, the tree has B = 875 leaf buckets. The owning KdTree holds four contiguous arrays; the non-owning KdTreeView is just spans into them plus the root bounds.
| array | content | size |
|---|---|---|
split_vals | split coordinate per internal node | B-1 scalars |
split_dims | packed axis ids | bit-packed words |
buckets | coords[D][leaf_size] + ids[leaf_size] | B x bucket |
node_boxes | optional tight AABB per subtree | 2B-1 boxes |
LeafBucket | 8 slotsSlots hold coordinates and a payload ID. Empty slots use INF coordinates and the INF_IDX payload sentinel.
The tree is constructed from a mutable span of points. It sorts the input, owns the resulting arrays, and returns anstd::expected. Rebuild after data changes; the query view itself stays trivially copyable.
Build takes a mutable span of FatPoint. It partitions the data in place and allocates the final tree storage up front.
using Tree = kd3::KdTree<kd3::limits<float, 3>>;
std::vector<Tree::FatPoint> points;
for (const auto& sample : samples) {
points.push_back({sample.position, sample.id});
}
auto tree = Tree::build(points);
if (!tree) return false;
auto hit = tree->query_1nn(target);limits controls all four. Higher-dimensional keys work for position plus normal. Integer scalars and wider distance accumulators are supported.
using Point2 = kd3::KdTree<kd3::limits<float, 2>>;
using Fixed5 = kd3::KdTree<
kd3::limits<std::int16_t, 5, std::int64_t, std::uint32_t>
>;
using Oriented = kd3::KdTree<kd3::limits<float, 6>>;Queries return std::expected. k-NN writes into a caller buffer. Filtered queries take a predicate and never update the bound for rejected points.
auto nearest = tree->query_1nn(target);
std::array<Tree::KnnResult, 8> buffer;
auto nearest8 = tree->query_knn(target, buffer);
auto valid = tree->query_1nn_if(
target,
[&](std::uint32_t id, const auto&) {
return enabled[id];
});Define KD3_CXX_IMPL once, include the C header elsewhere. It exposes create, destroy, 1-NN, k-NN, distance, and ray queries. Filtered queries remain C++ only for now.
#define KD3_CXX_IMPL
#include <kd3/kd3-c.h>
kd3_tree_t* tree = kd3_tree_create(points, n, &err);
kd3_knn_result_t hit;
kd3_tree_query_1nn(tree, target, &hit);
kd3_tree_destroy(tree);Generates 1-NN, k-NN, and ray query functions for 2D to 4D trees. The generated code uses the same split and bucket layout as the CPU tree.
auto glsl = kd3::generate_glsl<
kd3::limits<float>,
Tree::cfg,
{.binding_vals = 1, .binding_dims = 2,
.binding_bks = 3, .binding_boxes = 4}
>();The core tree is immutable. Rebuild after data changes, or use the example mutable wrapper. Keeping construction separate is what makes the view trivially copyable.
// After points change:
auto rebuilt = Tree::build(points);
if (rebuilt) tree = std::move(*rebuilt);
// Or see examples/mutable/mut.hpp.Separate libraries because their public interfaces cannot fully overlap, but the design principles and storage model are shared.
kd3 is free software licensed under the GNU Affero General Public License, version 3 only (AGPL-3.0-only). A commercial licence is available on request.
The full licence text is in the repository's LICENCE.txt file. Read the AGPL-3.0 text.