kd3

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.

Try the demosSee benchmarks
Embedded first

No exceptions, no RTTI, bounded query stack, and no allocation during queries.

Parallel construction

OpenMP task-based building for large point sets.

Low-dimensional

Designed for 2D to 4D keys, with support for higher dimensions.

Header-only

Drop include/kd3/ into your project. No required runtime.

C interface

A stb-style C wrapper for FFI and non-C++ callers.

GLSL generator

Generate shader query functions for the 2D to 4D tree layouts.

Performance

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.

operationRyzen 9 5950Xmedian speedupRyzen 9 9950X3D2median speedupXeon 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.

Comparison with nanoflann

kd3 targets static low-dimensional point clouds. nanoflann covers a broader feature set. The full matrix is on the comparison page.

kd3 is stronger for

  • Static 2D-4D clouds, near-data queries, and AABB pruning.
  • Built-in filtered, ray, and cylinder queries.
  • Caller-owned k-NN buffers and a trivially copyable view.
  • C API, GLSL generator, and header-only C++23.

nanoflann is stronger for

  • Radius, approximate, and custom-metric search.
  • Dynamic, incremental, and runtime-dimensional indexes.
  • Non-owning adaptors and built-in index serialization.
  • C++11, no OpenMP requirement, and a permissive licence.

Query the tree in the browser

The first demo runs editable kd3 queries against a rebuilt tree. The second queries a 3D point cloud.

Edit the C++ call, see the result

Every query function is an editable kd3 call. Change the parameters, rebuild the tree, and watch the canvas and returned values update.

Loading demo...

points n/aleaves n/a

Move a query through a trefoil cloud

Loading demo...

Raytrace the kd3 tree on the GPU

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.

Interact with the canvas to render. 480 by 300, 30 fps cap.fps --
Click or scroll to start. Drag to orbit, wheel to zoom.
Drag: orbit · Wheel: zoom · Right-drag or Shift-drag: pan
Keys: arrows orbit · +/- zoom · R reset

Balanced tree, flat storage, explicit queries

kd3 builds a balanced binary tree over fixed-size leaf buckets. The payload is application-defined.

Split on the widest axis

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.

pointsmedian splitleaf bucketsbucket 0 | left halfbucket 1 | right half

Each split removes half the remaining points from consideration. The leaves are the only place where full point coordinates are stored.

Four flat arrays

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.

vals 3.5 KB
dims 224 B
buckets 109 KB
boxes 41 KB
arraycontentsize
split_valssplit coordinate per internal nodeB-1 scalars
split_dimspacked axis idsbit-packed words
bucketscoords[D][leaf_size] + ids[leaf_size]B x bucket
node_boxesoptional tight AABB per subtree2B-1 boxes
one LeafBucket | 8 slots
slot 0id 12
slot 1id 4
slot 2id 27
slot 3id 8
slot 4id 19
slot 5id 2
INFINF_IDX
INFINF_IDX

Slots hold coordinates and a payload ID. Empty slots use INF coordinates and the INF_IDX payload sentinel.

Build from runtime data, then query

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.

From your own container

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);

Scalar, dimension, distance, payload

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>>;

Same index, different answers

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];
    });

STB-style wrapper for FFI

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);

Query functions for the GPU

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}
>();

Rebuild, do not mutate the view

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.

Other spatial indexes from the same family

Separate libraries because their public interfaces cannot fully overlap, but the design principles and storage model are shared.

bvh3BVH

Bounding volume hierarchy for ray and primitive queries.

oc3octree

Octree index for spatial subdivision and volume queries.

Licence

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.