Overview
Nearest-neighbour trees, a GPU-ready BVH, a cell list, hulls, Delaunay/Voronoi and point-cloud operations. Depends only on riptide_math (robust predicates, the 3 \times 3 eigen solver).
Data layout. Points are interleaved Float64Lists (x0 y0 z0 x1 y1 z1 …, dim values per point), never copied: trees keep an index permutation. That maps one-to-one onto a C-contiguous (n, dim) NDArray from part A when it lands.
What's in it
| File | Contents | Cost |
|---|---|---|
kd_tree.ray | KdTree: any dimension, nanoflann-style sliding-midpoint splits, leaf buckets, k-nearest (knn, knnBatch, allocation-free knnInto), radius, countWithin | build O(n \log n); query O(\log n + k) expected in low dimension |
ball_tree.ray | BallTree: median splits, centroid + radius nodes; kNN and radius | same; better for clustered data |
neighbors.ray | KnnResult, RadiusResult, KnnHeap, bruteForceKnn, bruteForceRadius (references) | O(n \cdot m \cdot d) |
aabb_bvh.ray | AabbBvh: binned SAH on 3 axes, flattened 32-byte nodes with miss links (layout below), stackless queryAabb and raycast, overlapPairs (broadphase), refit, sahCost, depth | build O(n \log n); refit O(n) |
cell_list.ray | CellList: uniform grid by counting sort (SoA cellStart/sorted/cellOf), 27-cell neighbour visits, pairsWithin — for SPH and particle-in-cell | O(n + cells) |
hull.ray | convexHull2d (monotone chain, robust), polygonArea, ConvexHull3d.quickHull (volume, area, vertices) | O(n \log n) |
delaunay.ray | Delaunay2d (Delaunator sweep-hull, robust predicates; half-edges, hull, neighbours, circumcentres), Voronoi2d (cells clipped to a box) | O(n \log n); O(n) cells |
delaunay3.ray | Delaunay3d (Bowyer–Watson, Morton insertion order, exact in-sphere/orientation), orient3, inSphere | O(n \log n) expected |
point_cloud.ray | PointCloud: centroid, bounds, voxel downsample, normals (PCA of k neighbours), statistical outlier removal, rigidTransform (Horn quaternion), point-to-point icp, transform; symmetricEigen (small Jacobi) | |
morton.ray | Morton: 3-D 63-bit and 2-D 62-bit encode/decode, 30-bit morton3d30 for GPUs | O(1) |
riptide_math keeps its simple O(n^{2}) convexHull3 (used by its EPA) and delaunay2 (Bowyer–Watson) as small references; this package has the fast versions. The triangle Bvh in riptide_math stays the ray-tracing BVH for meshes; AabbBvh is the general one (boxes, points, broadphase, GPU upload).
BVH node layout (GPU)
32 bytes per node, 8 little-endian 32-bit words, nodes in depth-first pre-order (node i at byte 32 \cdot i):
| word | type | meaning |
|---|---|---|
| 0–2 | f32 | min.x, min.y, min.z (rounded towards -\infty) |
| 3 | i32 | miss: next node after this subtree in pre-order (nodeCount = done) |
| 4–6 | f32 | max.x, max.y, max.z (rounded towards +\infty) |
| 7 | i32 | prim: -1 interior; leaf (first << 4) \| (count − 1), count 1–16 entries of primOrder from first |
Interior node i: left child i + 1, right child miss of node i + 1. Upload nodes (bytes) and primOrder (u32) as two storage buffers; the stackless loop is in the AabbBvh doc comment. In GLSL std430: struct Node { vec3 lo; int miss; vec3 hi; int prim; }; (a vec3 followed by a 4-byte scalar packs into 16 bytes).
Functions and constants
Functions
double f32Down(double v)v rounded to the nearest float32 not above it.
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final x = 0.1;
print('f32Down(0.1) = ${f32Down(x)} ≤ 0.1: ${f32Down(x) <= x}');
print('f32Up(0.1) = ${f32Up(x)} ≥ 0.1: ${f32Up(x) >= x}');
}f32Down(0.1) = 0.09999999403953552 ≤ 0.1: true f32Up(0.1) = 0.10000000149011612 ≥ 0.1: true
double f32Up(double v)v rounded to the nearest float32 not below it.
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// Conservative float32 bounds keep boxes in a float32 BVH from shrinking.
for (final v in [1.0, 1 / 3, -2.7]) {
print('$v in [${f32Down(v)}, ${f32Up(v)}]');
}
}1.0 in [1.0, 1.0] 0.3333333333333333 in [0.3333333134651184, 0.3333333432674408] -2.7 in [-2.700000047683716, -2.6999998092651367]
(double, double) circumcenter(double ax, double ay, double bx, double by, double cx, double cy)Circumcentre of triangle (a, b, c).
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final (x, y) = circumcenter(0, 0, 4, 0, 0, 3);
final r = math.sqrt(x * x + y * y);
print('circumcenter ($x, $y), radius $r');
}circumcenter (2.0, 1.5), radius 2.5
int orient3(Float64List p, int a, int b, int c, int d)Sign of \det(a - d, b - d, c - d).
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final p = Float64List.fromList([0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, -1, 1, 1, 0]);
print('d above the plane abc: ${orient3(p, 0, 1, 2, 3)}');
print('d below: ${orient3(p, 0, 1, 2, 4)}');
print('d on it (exactly): ${orient3(p, 0, 1, 2, 5)}');
}d above the plane abc: -1 d below: 1 d on it (exactly): 0
int inSphere(Float64List p, int a, int b, int c, int d, int e)0 when e is strictly inside the sphere through positively oriented a, b, c, d; 0 on it; < 0 outside.
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// Unit-sphere points a..d and two test points.
final p = Float64List.fromList([1, 0, 0, -1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0.5, 0, 0, 2]);
print('(0, 0, 0.5): ${inSphere(p, 0, 1, 2, 3, 4)}');
print('(0, 0, 2): ${inSphere(p, 0, 1, 2, 3, 5)}');
}(0, 0, 0.5): 1 (0, 0, 2): -1
Int32List convexHull2d(Float64List xy)Convex hull of 2-D points (interleaved x y) by Andrew's monotone chain (1979), O(n \log n), with Shewchuk's robust orientation test from riptide_math, so near-collinear input never produces a reflex vertex. Returns the indices of the hull vertices counter-clockwise, starting at the lowest-x (then lowest-y) point; collinear points on edges and duplicates are left out. Fewer than 3 distinct non-collinear points give the distinct extremes.
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final rng = math.Random(7);
const n = 30;
final xy = Float64List.fromList([for (var i = 0; i < 2 * n; i++) (rng.nextDouble() * 100).roundToDouble()]);
final h = convexHull2d(xy);
print('${h.length} hull corners: $h');
}9 hull corners: [23, 15, 4, 17, 20, 28, 14, 5, 3]
double polygonArea(Float64List xy, List<int> poly)Area enclosed by a polygon given as indices into interleaved xy (positive when counter-clockwise).
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final xy = Float64List.fromList([0, 0, 4, 0, 4, 3, 1, 3, 1, 1, 0, 1]);
final poly = [0, 1, 2, 3, 4, 5];
print('area ${polygonArea(xy, poly)}');
print('clockwise gives ${polygonArea(xy, poly.reversed.toList())}');
}area 10.0 clockwise gives -10.0
KnnResult bruteForceKnn(Float64List points, Float64List queries, int dim, int k)Exact k nearest neighbours by brute force, O(n \cdot m \cdot d): the reference the trees are tested against. points and queries are interleaved (x0 y0 z0 x1 y1 z1 …, dim values per point).
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final rng = math.Random(7);
const n = 30;
final xy = Float64List.fromList([for (var i = 0; i < 2 * n; i++) (rng.nextDouble() * 100).roundToDouble()]);
final r = bruteForceKnn(xy, Float64List.fromList([50, 50]), 2, 4);
print('4 nearest to (50, 50): ${r.indices}, quadrances ${r.dist2}');
}4 nearest to (50, 50): [1, 9, 24, 10], quadrances [5.0, 100.0, 144.0, 389.0]
RadiusResult bruteForceRadius(Float64List points, List<double> query, int dim, double radius)Points within radius of query by brute force (the reference for the trees' radius search), nearest first.
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final rng = math.Random(7);
const n = 30;
final xy = Float64List.fromList([for (var i = 0; i < 2 * n; i++) (rng.nextDouble() * 100).roundToDouble()]);
final r = bruteForceRadius(xy, [50, 50], 2, 25);
print('${r.length} points within 25: ${r.indices}');
}7 points within 25: [1, 9, 24, 10, 18, 12, 13]
RadiusResult sortedRadius(List<(double, int)> hits)import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final r = sortedRadius([(9.0, 2), (1.0, 7), (4.0, 3)]);
print('indices ${r.indices}, quadrances ${r.dist2}');
}indices [7, 3, 2], quadrances [1.0, 4.0, 9.0]
(Float64List, Float64List) symmetricEigen(Float64List a, int n, {int maxSweeps = 50})Eigen-decomposition of a small symmetric n \times n matrix a (row-major) by cyclic Jacobi rotations. Returns the eigenvalues (unsorted) and the eigenvectors as the columns of a row-major n \times n matrix. For the 4 \times 4 of Horn's method and other tiny problems; part A's dense eigensolvers are the general tool.
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final a = Float64List.fromList([2, 1, 0, 1, 2, 1, 0, 1, 2]);
final (w, v) = symmetricEigen(a, 3);
print('eigenvalues ${w.map((x) => x.toStringAsFixed(6)).toList()}');
print('(2 − √2, 2, 2 + √2) = ${[2 - math.sqrt2, 2.0, 2 + math.sqrt2].map((x) => x.toStringAsFixed(6)).toList()}');
}eigenvalues [0.585786, 3.414214, 2.000000] (2 − √2, 2, 2 + √2) = [0.585786, 2.000000, 3.414214]
Classes
AabbBvh
final class AabbBvh
A bounding volume hierarchy over axis-aligned boxes (or points) in 3-D, built top-down with the binned surface area heuristic (Wald 2007) on all three axes, and stored flattened for the GPU: one 32-byte node per entry in depth-first (pre-)order with a miss link, so a compute shader walks it without a stack.
Node layout (32 bytes, 8 little-endian 32-bit words; node i starts at byte 32 \cdot i)
| word | type | meaning | |
|---|---|---|---|
| 0–2 | f32 | min.x, min.y, min.z (rounded towards -\infty from the double-precision build) | |
| 3 | i32 | miss: the node to visit when this one is missed or finished — the next node after this subtree in pre-order; nodeCount means done | |
| 4–6 | f32 | max.x, max.y, max.z (rounded towards +\infty) | |
| 7 | i32 | prim: -1 for an interior node; for a leaf `(first << 4) | (count − 1): count (1–16) primitives at primOrder[first …]` |
An interior node's left child is always i + 1 and its right child is miss of node i + 1. Stackless traversal, the same in Raya (queryAabb, raycast) and GLSL:
int i = 0;
while (i < nodeCount) {
Node n = nodes[i];
if (!overlaps(n)) { i = n.miss; continue; }
if (n.prim < 0) { i = i + 1; continue; } // interior: descend into the left child
int first = n.prim >> 4, count = (n.prim & 15) + 1;
for (int k = 0; k < count; k++) visit(primOrder[first + k]);
i = n.miss;
}
refit updates the boxes after primitives move without rebuilding (children always follow parents in the array, so one reverse pass suffices); quality degrades as the scene drifts, so rebuild when sahCost has grown a lot.
Constructors
factory AabbBvh.build(Float64List mins, Float64List maxs, {int maxLeaf = 4, int bins = 16})Builds over count boxes given as interleaved mins and maxs (3 doubles per box). maxLeaf is 1–16.
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// 12 boxes in a row (min corners and max corners, xyz).
const n = 12;
final mins = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5, (i % 3) * 0.5, 0]]);
final maxs = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5 + 1.8, (i % 3) * 0.5 + 1, 1]]);
final bvh = AabbBvh.build(mins, maxs, maxLeaf: 2);
print('${bvh.nodeCount} nodes for ${bvh.primCount} boxes, depth ${bvh.depth}, SAH cost ${bvh.sahCost.toStringAsFixed(3)}');
}23 nodes for 12 boxes, depth 4, SAH cost 4.859
factory AabbBvh.points(Float64List xyz, {int maxLeaf = 4})Builds over points (zero-size boxes), interleaved xyz.
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final rng = math.Random(3);
const n = 200;
final xyz = Float64List.fromList([for (var i = 0; i < 3 * n; i++) rng.nextDouble() * 10]);
final bvh = AabbBvh.points(xyz, maxLeaf: 8);
print('${bvh.primCount} points in ${bvh.nodeCount} nodes');
var hits = 0;
bvh.queryAabb([0, 0, 0], [5, 5, 5], (p) => hits++);
print('$hits points in the corner box [0, 5]³');
}200 points in 399 nodes 23 points in the corner box [0, 5]³
Properties
final Uint8List nodesThe flattened nodes (32 bytes each), ready to copy into a GPU storage buffer.
final Uint32List primOrderLeaf primitive ranges index this permutation of the input boxes.
final int nodeCountfinal int primCountfinal Int32List i32double get sahCostThe SAH cost of the tree (traversal 1, intersection 1), relative to the root's area: lower is better.
Methods
int miss(int node)import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// 12 boxes in a row (min corners and max corners, xyz).
const n = 12;
final mins = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5, (i % 3) * 0.5, 0]]);
final maxs = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5 + 1.8, (i % 3) * 0.5 + 1, 1]]);
final bvh = AabbBvh.build(mins, maxs, maxLeaf: 2);
// Walk the flattened tree: a node is followed by its left child; miss() jumps past its subtree.
for (var node = 0; node < math.min(bvh.nodeCount, 7); node++) {
if (bvh.isLeaf(node)) {
print('node $node: leaf, prim code ${bvh.prim(node)} -> boxes ${[for (var s = 0; s < bvh.leafCount(node); s++) bvh.primOrder[bvh.leafFirst(node) + s]]}, miss -> ${bvh.miss(node)}');
} else {
print('node $node: inner, right child ${bvh.right(node)}, miss -> ${bvh.miss(node)}');
}
}
}node 0: inner, right child 12, miss -> 23 node 1: inner, right child 7, miss -> 12 node 2: inner, right child 4, miss -> 7 node 3: leaf, prim code 0 -> boxes [0], miss -> 4 node 4: inner, right child 6, miss -> 7 node 5: leaf, prim code 16 -> boxes [1], miss -> 6 node 6: leaf, prim code 32 -> boxes [2], miss -> 7
int prim(int node)import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// 12 boxes in a row (min corners and max corners, xyz).
const n = 12;
final mins = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5, (i % 3) * 0.5, 0]]);
final maxs = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5 + 1.8, (i % 3) * 0.5 + 1, 1]]);
final bvh = AabbBvh.build(mins, maxs, maxLeaf: 2);
// Walk the flattened tree: a node is followed by its left child; miss() jumps past its subtree.
for (var node = 0; node < math.min(bvh.nodeCount, 7); node++) {
if (bvh.isLeaf(node)) {
print('node $node: leaf, prim code ${bvh.prim(node)} -> boxes ${[for (var s = 0; s < bvh.leafCount(node); s++) bvh.primOrder[bvh.leafFirst(node) + s]]}, miss -> ${bvh.miss(node)}');
} else {
print('node $node: inner, right child ${bvh.right(node)}, miss -> ${bvh.miss(node)}');
}
}
}node 0: inner, right child 12, miss -> 23 node 1: inner, right child 7, miss -> 12 node 2: inner, right child 4, miss -> 7 node 3: leaf, prim code 0 -> boxes [0], miss -> 4 node 4: inner, right child 6, miss -> 7 node 5: leaf, prim code 16 -> boxes [1], miss -> 6 node 6: leaf, prim code 32 -> boxes [2], miss -> 7
bool isLeaf(int node)import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// 12 boxes in a row (min corners and max corners, xyz).
const n = 12;
final mins = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5, (i % 3) * 0.5, 0]]);
final maxs = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5 + 1.8, (i % 3) * 0.5 + 1, 1]]);
final bvh = AabbBvh.build(mins, maxs, maxLeaf: 2);
// Walk the flattened tree: a node is followed by its left child; miss() jumps past its subtree.
for (var node = 0; node < math.min(bvh.nodeCount, 7); node++) {
if (bvh.isLeaf(node)) {
print('node $node: leaf, prim code ${bvh.prim(node)} -> boxes ${[for (var s = 0; s < bvh.leafCount(node); s++) bvh.primOrder[bvh.leafFirst(node) + s]]}, miss -> ${bvh.miss(node)}');
} else {
print('node $node: inner, right child ${bvh.right(node)}, miss -> ${bvh.miss(node)}');
}
}
}node 0: inner, right child 12, miss -> 23 node 1: inner, right child 7, miss -> 12 node 2: inner, right child 4, miss -> 7 node 3: leaf, prim code 0 -> boxes [0], miss -> 4 node 4: inner, right child 6, miss -> 7 node 5: leaf, prim code 16 -> boxes [1], miss -> 6 node 6: leaf, prim code 32 -> boxes [2], miss -> 7
int leafFirst(int node)import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// 12 boxes in a row (min corners and max corners, xyz).
const n = 12;
final mins = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5, (i % 3) * 0.5, 0]]);
final maxs = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5 + 1.8, (i % 3) * 0.5 + 1, 1]]);
final bvh = AabbBvh.build(mins, maxs, maxLeaf: 2);
// Walk the flattened tree: a node is followed by its left child; miss() jumps past its subtree.
for (var node = 0; node < math.min(bvh.nodeCount, 7); node++) {
if (bvh.isLeaf(node)) {
print('node $node: leaf, prim code ${bvh.prim(node)} -> boxes ${[for (var s = 0; s < bvh.leafCount(node); s++) bvh.primOrder[bvh.leafFirst(node) + s]]}, miss -> ${bvh.miss(node)}');
} else {
print('node $node: inner, right child ${bvh.right(node)}, miss -> ${bvh.miss(node)}');
}
}
}node 0: inner, right child 12, miss -> 23 node 1: inner, right child 7, miss -> 12 node 2: inner, right child 4, miss -> 7 node 3: leaf, prim code 0 -> boxes [0], miss -> 4 node 4: inner, right child 6, miss -> 7 node 5: leaf, prim code 16 -> boxes [1], miss -> 6 node 6: leaf, prim code 32 -> boxes [2], miss -> 7
int leafCount(int node)import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// 12 boxes in a row (min corners and max corners, xyz).
const n = 12;
final mins = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5, (i % 3) * 0.5, 0]]);
final maxs = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5 + 1.8, (i % 3) * 0.5 + 1, 1]]);
final bvh = AabbBvh.build(mins, maxs, maxLeaf: 2);
// Walk the flattened tree: a node is followed by its left child; miss() jumps past its subtree.
for (var node = 0; node < math.min(bvh.nodeCount, 7); node++) {
if (bvh.isLeaf(node)) {
print('node $node: leaf, prim code ${bvh.prim(node)} -> boxes ${[for (var s = 0; s < bvh.leafCount(node); s++) bvh.primOrder[bvh.leafFirst(node) + s]]}, miss -> ${bvh.miss(node)}');
} else {
print('node $node: inner, right child ${bvh.right(node)}, miss -> ${bvh.miss(node)}');
}
}
}node 0: inner, right child 12, miss -> 23 node 1: inner, right child 7, miss -> 12 node 2: inner, right child 4, miss -> 7 node 3: leaf, prim code 0 -> boxes [0], miss -> 4 node 4: inner, right child 6, miss -> 7 node 5: leaf, prim code 16 -> boxes [1], miss -> 6 node 6: leaf, prim code 32 -> boxes [2], miss -> 7
int right(int node)import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// 12 boxes in a row (min corners and max corners, xyz).
const n = 12;
final mins = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5, (i % 3) * 0.5, 0]]);
final maxs = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5 + 1.8, (i % 3) * 0.5 + 1, 1]]);
final bvh = AabbBvh.build(mins, maxs, maxLeaf: 2);
// Walk the flattened tree: a node is followed by its left child; miss() jumps past its subtree.
for (var node = 0; node < math.min(bvh.nodeCount, 7); node++) {
if (bvh.isLeaf(node)) {
print('node $node: leaf, prim code ${bvh.prim(node)} -> boxes ${[for (var s = 0; s < bvh.leafCount(node); s++) bvh.primOrder[bvh.leafFirst(node) + s]]}, miss -> ${bvh.miss(node)}');
} else {
print('node $node: inner, right child ${bvh.right(node)}, miss -> ${bvh.miss(node)}');
}
}
}node 0: inner, right child 12, miss -> 23 node 1: inner, right child 7, miss -> 12 node 2: inner, right child 4, miss -> 7 node 3: leaf, prim code 0 -> boxes [0], miss -> 4 node 4: inner, right child 6, miss -> 7 node 5: leaf, prim code 16 -> boxes [1], miss -> 6 node 6: leaf, prim code 32 -> boxes [2], miss -> 7
void queryAabb(List<double> lo, List<double> hi, void Function(int prim) visit)Calls visit with every primitive whose node box overlaps lo..hi (3 values each). Candidates only: the caller tests the primitive itself. Stackless, exactly as a shader would walk it.
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// 12 boxes in a row (min corners and max corners, xyz).
const n = 12;
final mins = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5, (i % 3) * 0.5, 0]]);
final maxs = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5 + 1.8, (i % 3) * 0.5 + 1, 1]]);
final bvh = AabbBvh.build(mins, maxs, maxLeaf: 2);
final found = <int>[];
bvh.queryAabb([4, 0, 0], [9, 0.8, 1], found.add);
print('boxes overlapping the query: ${found..sort()}');
}boxes overlapping the query: [3, 4, 6]
({int prim, double t})? raycast(double ox, double oy, double oz, double dx, double dy, double dz, double? Function(int prim) hit, {double tMax = double.infinity})Closest hit along the ray o + t \cdot d for t in [0, tMax]: hit tests one primitive and returns its hit distance (or null). Returns the nearest (prim, t) or null. Stackless; boxes beyond the current best are skipped.
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// 12 boxes in a row (min corners and max corners, xyz).
const n = 12;
final mins = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5, (i % 3) * 0.5, 0]]);
final maxs = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5 + 1.8, (i % 3) * 0.5 + 1, 1]]);
final bvh = AabbBvh.build(mins, maxs, maxLeaf: 2);
// A ray along +x at y = 1.2; hit() returns the entry distance into a primitive box.
double? hit(int i) => mins[3 * i + 1] <= 1.2 && 1.2 <= maxs[3 * i + 1] ? math.max(0, mins[3 * i] - (-1)) : null;
final h = bvh.raycast(-1, 1.2, 0.5, 1, 0, 0, hit);
print('first hit: box ${h?.prim} at t = ${h?.t}');
}first hit: box 1 at t = 2.5
List<(int, int)> overlapPairs(Float64List mins, Float64List maxs)Every pair (i, j), i < j, of input boxes in mins/maxs that overlap: the broadphase. O(n \log n + k).
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// 12 boxes in a row (min corners and max corners, xyz).
const n = 12;
final mins = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5, (i % 3) * 0.5, 0]]);
final maxs = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5 + 1.8, (i % 3) * 0.5 + 1, 1]]);
final bvh = AabbBvh.build(mins, maxs, maxLeaf: 2);
final pairs = bvh.overlapPairs(mins, maxs);
print('${pairs.length} overlapping pairs: ${pairs.take(6).toList()}');
}11 overlapping pairs: [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]
void refit(Float64List mins, Float64List maxs)Recomputes every node box from moved primitives (same topology), O(n).
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// 12 boxes in a row (min corners and max corners, xyz).
const n = 12;
final mins = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5, (i % 3) * 0.5, 0]]);
final maxs = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5 + 1.8, (i % 3) * 0.5 + 1, 1]]);
final bvh = AabbBvh.build(mins, maxs, maxLeaf: 2);
for (var i = 0; i < 3 * n; i++) {
mins[i] += 10;
maxs[i] += 10;
}
bvh.refit(mins, maxs); // same topology, new bounds
final found = <int>[];
bvh.queryAabb([10, 10, 10], [11, 11, 11], found.add);
print('after moving everything by 10: $found');
}after moving everything by 10: [0]
BallTree
final class BallTree
A ball tree (Omohundro 1989; the layout of scikit-learn's BallTree, BSD-3-Clause): every node is a hypersphere (centroid, radius) around its points, split at the median of the dimension of largest spread. Pruning uses \max(0, |q - c| - r), which stays useful in higher dimensions and for clustered data where k-d cells get long and thin. Points are interleaved (dim per point) and not copied.
Constructors
factory BallTree(Float64List points, int dim, {int leafSize = 16})import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final rng = math.Random(7);
const n = 30;
final xy = Float64List.fromList([for (var i = 0; i < 2 * n; i++) (rng.nextDouble() * 100).roundToDouble()]);
final t = BallTree(xy, 2, leafSize: 4);
print('${t.length} points, ${t.nodeCount} nodes');
}30 points, 15 nodes
Properties
final Float64List pointsfinal int dimfinal Int32List orderfinal Int32List childPer node: left child (right is +1) or -1 for a leaf; leaf ranges [start, end) of order.
final Int32List startPer node: left child (right is +1) or -1 for a leaf; leaf ranges [start, end) of order.
final Int32List endPer node: left child (right is +1) or -1 for a leaf; leaf ranges [start, end) of order.
int get lengthint get nodeCountMethods
KnnResult knn(List<double> query, int k)import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final rng = math.Random(7);
const n = 30;
final xy = Float64List.fromList([for (var i = 0; i < 2 * n; i++) (rng.nextDouble() * 100).roundToDouble()]);
final r = BallTree(xy, 2).knn([20, 80], 5);
print('5 nearest to (20, 80): ${r.indices}');
}5 nearest to (20, 80): [7, 0, 16, 3, 5]
KnnResult knnBatch(Float64List queries, int k)import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final rng = math.Random(7);
const n = 30;
final xy = Float64List.fromList([for (var i = 0; i < 2 * n; i++) (rng.nextDouble() * 100).roundToDouble()]);
final r = BallTree(xy, 2).knnBatch(Float64List.fromList([0, 0, 100, 100]), 2);
print('${r.queries} queries; nearest to (0, 0): ${r.indices.sublist(0, 2)}, to (100, 100): ${r.indices.sublist(2, 4)}');
}2 queries; nearest to (0, 0): [15, 29], to (100, 100): [28, 20]
void knnInto(List<double> query, KnnHeap heap)import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final rng = math.Random(7);
const n = 30;
final xy = Float64List.fromList([for (var i = 0; i < 2 * n; i++) (rng.nextDouble() * 100).roundToDouble()]);
final t = BallTree(xy, 2), heap = KnnHeap(3);
t.knnInto([50, 50], heap);
print('heap holds ${heap.count}, worst quadrance ${heap.worst}');
}heap holds 3, worst quadrance 144.0
RadiusResult radius(List<double> query, double radius)import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final rng = math.Random(7);
const n = 30;
final xy = Float64List.fromList([for (var i = 0; i < 2 * n; i++) (rng.nextDouble() * 100).roundToDouble()]);
final r = BallTree(xy, 2).radius([50, 50], 20);
print('${r.length} points within 20');
}4 points within 20
CellList
final class CellList
A uniform-grid cell list over 3-D points, built by counting sort (two passes, no per-cell lists): the neighbour structure for SPH, particle-in-cell deposition and short-range forces, where the search radius equals the cell size and points move every step (rebuild is O(n + cells), cheaper than any tree).
Layout (all SoA typed data, so a compute shader can read the same arrays):
Constructors
factory CellList.build(Float64List xyz, double cellSize, {List<double>? boxMin, List<double>? boxMax})Bins interleaved xyz points into cells of cellSize covering their bounds (or the given box).
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final rng = math.Random(3);
const n = 200;
final xyz = Float64List.fromList([for (var i = 0; i < 3 * n; i++) rng.nextDouble() * 10]);
final c = CellList.build(xyz, 2.5);
print('${c.cellCount} cells (${c.nx} × ${c.ny} × ${c.nz})');
}64 cells (4 × 4 × 4)
Properties
final double originXfinal double originYfinal double originZfinal double cellSizefinal int nxfinal int nyfinal int nzfinal Int32List cellStartfinal Int32List sortedfinal Int32List cellOfint get cellCountMethods
void forEachNear(double x, double y, double z, void Function(int point) visit)Calls visit with every point in the 27 cells around (x, y, z): candidates within cellSize of it (and some farther ones; the caller checks the distance).
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final rng = math.Random(3);
const n = 200;
final xyz = Float64List.fromList([for (var i = 0; i < 3 * n; i++) rng.nextDouble() * 10]);
final c = CellList.build(xyz, 2);
var count = 0;
c.forEachNear(5, 5, 5, (i) => count++);
print('$count candidates in the 27 cells around (5, 5, 5)');
}47 candidates in the 27 cells around (5, 5, 5)
List<(int, int)> pairsWithin(Float64List xyz, double radius)Every pair (i, j), i < j, of points closer than radius ≤ cellSize in interleaved xyz.
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final rng = math.Random(4);
const n = 60;
final xyz = Float64List.fromList([for (var i = 0; i < n; i++) ...[rng.nextDouble() * 10, rng.nextDouble() * 10, 0]]);
final pairs = CellList.build(xyz, 1.5).pairsWithin(xyz, 1.5);
print('${pairs.length} pairs closer than 1.5');
}93 pairs closer than 1.5
Delaunay2d
final class Delaunay2d
2-D Delaunay triangulation by the sweep-hull method of Delaunator: sort points by distance from the circumcentre of a seed triangle, add them one by one outside a convex hull kept as a linked list with an angular hash, fan to the visible hull edges and restore the Delaunay condition by edge flips. O(n \log n) in practice. Unlike Delaunator, both predicates are the robust ones from riptide_math (orientation and in-circle), so cocircular input (grids) never flips forever and never makes a reflex hull.
Output in Delaunator's half-edge form: triangle t has vertices triangles[3t.. 3t+2] (counter-clockwise, y up); half-edge e goes from triangles[e] to triangles[next(e)], and halfedges[e] is the opposite half-edge in the neighbouring triangle, or -1 on the hull.
Constructors
factory Delaunay2d(Float64List points)Triangulates interleaved x y points. Exact duplicates are skipped (they appear in no triangle). All points collinear: no triangles, and hull lists them in order along the line.
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final rng = math.Random(7);
const n = 30;
final xy = Float64List.fromList([for (var i = 0; i < 2 * n; i++) (rng.nextDouble() * 100).roundToDouble()]);
final d = Delaunay2d(xy);
print('${d.triangleCount} triangles, hull ${d.hull.length}: 2n − 2 − h = ${2 * n - 2 - d.hull.length}');
}49 triangles, hull 9: 2n − 2 − h = 49
Static
static int nextHalfedge(int e)import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// Half-edges come in threes per triangle: 0 → 1 → 2 → 0.
print([for (var e = 0; e < 6; e++) Delaunay2d.nextHalfedge(e)]);
}[1, 2, 0, 4, 5, 3]
static int prevHalfedge(int e)import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
print([for (var e = 0; e < 6; e++) Delaunay2d.prevHalfedge(e)]);
}[2, 0, 1, 5, 3, 4]
Properties
final Float64List pointsfinal Int32List trianglesfinal Int32List halfedgesint get triangleCountMethods
List<List<int>> neighbors()Delaunay neighbours of every point (sorted), from the half-edges.
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final rng = math.Random(7);
const n = 30;
final xy = Float64List.fromList([for (var i = 0; i < 2 * n; i++) (rng.nextDouble() * 100).roundToDouble()]);
final d = Delaunay2d(xy);
final nb = d.neighbors();
print('point 0 has neighbours ${nb[0]}');
print('average degree ${(nb.fold<int>(0, (s, l) => s + l.length) / n).toStringAsFixed(2)}');
}point 0 has neighbours [3, 7, 16, 23] average degree 5.20
Float64List circumcenters()The circumcentre of every triangle (interleaved), the vertices of the Voronoi diagram.
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final rng = math.Random(7);
const n = 30;
final xy = Float64List.fromList([for (var i = 0; i < 2 * n; i++) (rng.nextDouble() * 100).roundToDouble()]);
final d = Delaunay2d(xy);
final c = d.circumcenters();
print('${c.length ~/ 2} circumcentres; first (${c[0].toStringAsFixed(2)}, ${c[1].toStringAsFixed(2)})');
final t0 = d.triangles[0];
final r = math.sqrt(math.pow(c[0] - xy[2 * t0], 2) + math.pow(c[1] - xy[2 * t0 + 1], 2));
}49 circumcentres; first (55.33, 50.11)
Voronoi2d voronoi(double x0, double y0, double x1, double y1)The Voronoi diagram, every cell clipped to the box [x_{0}, x_{1}] \times [y_{0}, y_{1}].
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final rng = math.Random(7);
const n = 30;
final xy = Float64List.fromList([for (var i = 0; i < 2 * n; i++) (rng.nextDouble() * 100).roundToDouble()]);
final v = Delaunay2d(xy).voronoi(0, 0, 100, 100);
var total = 0.0;
for (var i = 0; i < n; i++) {
total += v.cellArea(i);
}
print('cell areas sum to ${total.toStringAsFixed(6)} (the box is 10000)');
}cell areas sum to 10000.000000 (the box is 10000)
Voronoi2d
final class Voronoi2d
A Voronoi diagram as the dual of a Delaunay2d: cell i is the box cut by the bisector half-planes of point i and each of its Delaunay neighbours (exactly the cell, since Voronoi neighbours are Delaunay neighbours), so hull sites get closed cells too. O(degree) per cell, O(n) in all.
Properties
final Delaunay2d delaunayfinal double x0final double y0final double x1final double y1Methods
Float64List cell(int i)The vertices of cell i, counter-clockwise, interleaved; empty for a skipped duplicate point outside the box.
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final xy = Float64List.fromList([25, 25, 75, 25, 50, 75]);
final v = Delaunay2d(xy).voronoi(0, 0, 100, 100);
final c = v.cell(2);
print('cell of the top point: ${[for (var k = 0; k < c.length ~/ 2; k++) '(${c[2 * k].toStringAsFixed(1)}, ${c[2 * k + 1].toStringAsFixed(1)})']}');
}cell of the top point: [(100.0, 68.8), (100.0, 100.0), (0.0, 100.0), (0.0, 68.8), (50.0, 43.8)]
double cellArea(int i)Area of cell i.
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final xy = Float64List.fromList([25, 25, 75, 25, 50, 75]);
final v = Delaunay2d(xy).voronoi(0, 0, 100, 100);
print([for (var i = 0; i < 3; i++) v.cellArea(i).toStringAsFixed(2)]);
}[2812.50, 2812.50, 4375.00]
Delaunay3d
final class Delaunay3d
3-D Delaunay tetrahedralisation by Bowyer–Watson insertion (Bowyer 1981, Watson 1981): points are inserted in Morton order inside a large enclosing tetrahedron; each one is located by a visibility walk, the tetrahedra whose circumsphere strictly contains it are removed, and the cavity is re-filled with a fan from the point. Both predicates (orientation, in-sphere) use a floating-point filter with Shewchuk's error bounds and an exact BigInt fallback, so cospherical input (grids) is handled without inconsistency. O(n \log n) expected for uniform input.
Tetrahedra are positively oriented: \det(a - d, b - d, c - d) > 0. Exact duplicates are skipped. With fewer than 4 non-coplanar points there are no tetrahedra.
Constructors
factory Delaunay3d(Float64List xyz)import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final rng = math.Random(3);
const n = 40;
final xyz = Float64List.fromList([for (var i = 0; i < 3 * n; i++) rng.nextDouble() * 10]);
final d = Delaunay3d(xyz);
final hull = ConvexHull3d.quickHull(xyz);
print('${d.tetrahedronCount} tetrahedra, volume ${d.volume.toStringAsFixed(6)}');
print('hull volume ${hull.volume.toStringAsFixed(6)} (the same)');
}164 tetrahedra, volume 484.109405 hull volume 484.109405 (the same)
Properties
final Int32List neighbors4 per tetrahedron: the neighbour across the face opposite vertex k, or -1 on the hull.
int get tetrahedronCountConvexHull3d
final class ConvexHull3d
A 3-D convex hull: triangles (3 vertex indices each, counter-clockwise seen from outside) over the input points.
Constructors
factory ConvexHull3d.quickHull(Float64List xyz)QuickHull (Barber, Dobkin and Huhdanpaa 1996; the algorithm qhull implements, written here from the paper): start from an extreme tetrahedron, give each outside point to a face it sees, then repeatedly take a face's farthest point, find the faces visible from it by walking neighbours, and replace them with a fan from the horizon. Points within the tolerance \varepsilon = 3 \cdot 2^{-52}·(max|x| + max|y| + max|z|) of a face count as inside, so coplanar points never become vertices (qhull's default for vertices). O(n \log n) expected.
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// A cube's 8 corners plus an inside point.
final xyz = Float64List.fromList([0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0.5, 0.5, 0.5]);
final h = ConvexHull3d.quickHull(xyz);
print('${h.faceCount} triangles, vertices ${h.vertices}');
print('volume ${h.volume}, area ${h.area}');
}12 triangles, vertices [0, 1, 2, 3, 4, 5, 6, 7] volume 1.0, area 6.0
Properties
final Int32List trianglesFlat triangle list, 3 indices per face, wound counter-clockwise from outside. Empty when the input is degenerate (fewer than 4 points, or all coplanar within tolerance).
int get faceCountdouble get volumedouble get areaKdTree
final class KdTree
A k-d tree over points in any dimension (Float64), after nanoflann (Blanco and Rai, BSD-2-Clause): sliding-midpoint splits on the dimension of largest spread, leaf buckets of up to leafSize points, nodes as flat typed arrays, each split keeping both the largest coordinate on the low side and the smallest on the high side (nanoflann's divlow/divhigh) so the far child is pruned with the true gap, and searches that update the query-to-cell distance incrementally (Arya and Mount) instead of recomputing it.
Points are interleaved (x0 y0 … x1 y1 …, dim values per point) and are not copied: the tree keeps a permutation order into them. Build is O(n \log n); a k-nearest query is O(\log n + k) expected in low dimensions.
Constructors
factory KdTree(Float64List points, int dim, {int leafSize = 10})import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final rng = math.Random(7);
const n = 30;
final xy = Float64List.fromList([for (var i = 0; i < 2 * n; i++) (rng.nextDouble() * 100).roundToDouble()]);
final t = KdTree(xy, 2, leafSize: 4);
print('${t.length} points, ${t.nodeCount} nodes; root box ${t.rootMin} … ${t.rootMax}');
}30 points, 17 nodes; root box [8.0, 1.0] … [97.0, 100.0]
Properties
final int dimfinal Int32List orderLeaf buckets are contiguous ranges of this permutation of point indices.
final Int32List childPer node: left child index (the right child is child + 1), or -1 for a leaf.
final Int32List splitDimfinal Float64List splitLowPer interior node: the largest coordinate on the low side and the smallest on the high side.
final Float64List splitHighPer interior node: the largest coordinate on the low side and the smallest on the high side.
int get lengthint get nodeCountMethods
KnnResult knn(List<double> query, int k)The k nearest points to query (length dim).
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final rng = math.Random(7);
const n = 30;
final xy = Float64List.fromList([for (var i = 0; i < 2 * n; i++) (rng.nextDouble() * 100).roundToDouble()]);
final r = KdTree(xy, 2).knn([70, 30], 3);
for (var j = 0; j < 3; j++) {
print('neighbour ${j + 1}: point ${r.indices[j]}, quadrance ${r.dist2[j]}');
}
}neighbour 1: point 13, quadrance 40.0 neighbour 2: point 18, quadrance 85.0 neighbour 3: point 25, quadrance 164.0
KnnResult knnBatch(Float64List queries, int k)k nearest neighbours of every query in queries (interleaved), k per query.
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final rng = math.Random(7);
const n = 30;
final xy = Float64List.fromList([for (var i = 0; i < 2 * n; i++) (rng.nextDouble() * 100).roundToDouble()]);
final q = Float64List.fromList([10, 10, 90, 90, 50, 50]);
final r = KdTree(xy, 2).knnBatch(q, 1);
print('nearest point to each query: ${r.indices}');
}nearest point to each query: [15, 28, 1]
void knnInto(List<double> query, KnnHeap heap)Fills heap (call KnnHeap.reset first) with the nearest points to query; allocates nothing.
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final rng = math.Random(7);
const n = 30;
final xy = Float64List.fromList([for (var i = 0; i < 2 * n; i++) (rng.nextDouble() * 100).roundToDouble()]);
final t = KdTree(xy, 2), heap = KnnHeap(4);
for (final q in [[0.0, 0.0], [100.0, 0.0]]) {
heap.reset();
t.knnInto(q, heap);
print('$q: worst of 4 nearest at quadrance ${heap.worst}');
}
}[0.0, 0.0]: worst of 4 nearest at quadrance 2689.0 [100.0, 0.0]: worst of 4 nearest at quadrance 1844.0
RadiusResult radius(List<double> query, double radius, {bool sorted = true})Every point within radius of query, nearest first when sorted.
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final rng = math.Random(7);
const n = 30;
final xy = Float64List.fromList([for (var i = 0; i < 2 * n; i++) (rng.nextDouble() * 100).roundToDouble()]);
final r = KdTree(xy, 2).radius([50, 50], 22);
print('${r.length} within 22, nearest first: ${r.indices}');
}6 within 22, nearest first: [1, 9, 24, 10, 18, 12]
int countWithin(List<double> query, double radius)The number of points within radius of query (no result list).
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final rng = math.Random(7);
const n = 30;
final xy = Float64List.fromList([for (var i = 0; i < 2 * n; i++) (rng.nextDouble() * 100).roundToDouble()]);
final t = KdTree(xy, 2);
final counts = [for (var r = 0; r <= 60; r += 5) [r, t.countWithin([50, 50], r.toDouble())]];
print('within 30: ${t.countWithin([50, 50], 30)}');
}within 30: 8
Morton
abstract final class Morton
Morton (Z-order) codes: interleave the bits of integer cell coordinates so points close in space get close codes. Used to sort points for cache-friendly traversal, LBVH builds and GPU-friendly spatial hashing. 64-bit codes need native Raya ints (not the web's 53-bit numbers); morton3d30 fits a GPU uint.
Static
static int encode3(int x, int y, int z)3-D code from 21-bit coordinates (0 \cdots 2^{21} - 1 each), 63 bits.
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
print('encode3(1, 2, 3) = ${Morton.encode3(1, 2, 3)}');
print('binary ${Morton.encode3(1, 2, 3).toRadixString(2)}');
}encode3(1, 2, 3) = 53 binary 110101
static (int, int, int) decode3(int code)import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
print(Morton.decode3(Morton.encode3(5, 9, 2)));
}(5, 9, 2)
static int encode2(int x, int y)2-D code from 31-bit coordinates, 62 bits.
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// The Z-order curve through an 8 × 8 grid.
final order = List<List<int>>.filled(64, const [0, 0]);
for (var x = 0; x < 8; x++) {
for (var y = 0; y < 8; y++) {
order[Morton.encode2(x, y)] = [x, y];
}
}
print('encode2(3, 5) = ${Morton.encode2(3, 5)}');
}encode2(3, 5) = 39
static (int, int) decode2(int code)import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
print([for (var c = 0; c < 8; c++) Morton.decode2(c)]);
}[(0, 0), (1, 0), (0, 1), (1, 1), (2, 0), (3, 0), (2, 1), (3, 1)]
static int morton3d30(double x, double y, double z)30-bit 3-D code (10 bits per axis) of a point already normalised to [0, 1]^{3}: the LBVH / GPU form.
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
print(Morton.morton3d30(0, 0, 0));
print(Morton.morton3d30(0.5, 0.5, 0.5));
print(Morton.morton3d30(1, 1, 1));
}0 939524096 1073741823
KnnResult
final class KnnResult
The k nearest neighbours of one or more queries: indices and squared Euclidean distances dist2, k per query, nearest first. When the data set has fewer than k points the missing slots are -1 and +\infty.
Constructors
KnnResult(this.k, this.indices, this.dist2)import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final r = KnnResult(2, Int32List.fromList([4, 1, 0, 3]), Float64List.fromList([1, 2, 0.5, 9]));
print('${r.queries} queries of k = ${r.k}');
}2 queries of k = 2
Properties
final int kfinal Int32List indicesfinal Float64List dist2RadiusResult
final class RadiusResult
Points within a radius of one query: indices and squared distances dist2, nearest first when sorted.
Constructors
RadiusResult(this.indices, this.dist2)import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final r = RadiusResult(Int32List.fromList([3, 7]), Float64List.fromList([0.25, 4]));
print('${r.length} hits: ${r.indices}');
}2 hits: [3, 7]
Properties
final Int32List indicesfinal Float64List dist2int get lengthKnnHeap
final class KnnHeap
A fixed-capacity list of the best k candidates, kept sorted by insertion (k is small in practice; nanoflann's KNNResultSet does the same). Reused across queries so a batch search allocates nothing per query.
Constructors
KnnHeap(this.k)import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final h = KnnHeap(3);
for (final (i, d) in [(0, 9.0), (1, 4.0), (2, 1.0), (3, 16.0), (4, 2.0)]) {
h.add(i, d);
}
print('kept ${h.count}, worst ${h.worst}');
}kept 3, worst 4.0
Properties
final int kfinal Int32List idxfinal Float64List d2int countdouble get worstThe current pruning bound: the k-th best distance, or \infty while fewer than k are held.
Methods
void reset()import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final h = KnnHeap(2)..add(0, 1)..add(1, 2);
h.reset();
print('after reset: count ${h.count}, worst ${h.worst}');
}after reset: count 0, worst Infinity
void add(int index, double dist2)import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final h = KnnHeap(2);
h.add(5, 3);
h.add(6, 1);
h.add(7, 2); // replaces the worst (3)
print('worst now ${h.worst}');
}worst now 2.0
PointCloud
abstract final class PointCloud
Point-cloud operations on interleaved xyz Float64List clouds (the layouts Open3D and PCL describe; the algorithms are the textbook ones, written here).
Static
static Float64List centroid(Float64List xyz)import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final rng = math.Random(3);
const n = 200;
final xyz = Float64List.fromList([for (var i = 0; i < 3 * n; i++) rng.nextDouble() * 10]);
print('centroid ${PointCloud.centroid(xyz).map((v) => v.toStringAsFixed(3)).toList()}');
}centroid [5.039, 4.537, 5.094]
static (Float64List, Float64List) bounds(Float64List xyz)(min xyz, max xyz).
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final rng = math.Random(3);
const n = 200;
final xyz = Float64List.fromList([for (var i = 0; i < 3 * n; i++) rng.nextDouble() * 10]);
final (lo, hi) = PointCloud.bounds(xyz);
print('min ${lo.map((v) => v.toStringAsFixed(2)).toList()}, max ${hi.map((v) => v.toStringAsFixed(2)).toList()}');
}min [0.07, 0.02, 0.00], max [9.97, 9.88, 9.95]
static Float64List voxelDownsample(Float64List xyz, double voxel)Voxel-grid downsampling: one point per occupied voxel of size voxel, the mean of the points in it. Output order follows the first point of each voxel.
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final rng = math.Random(3);
const n = 200;
final xyz = Float64List.fromList([for (var i = 0; i < 3 * n; i++) rng.nextDouble() * 10]);
final d = PointCloud.voxelDownsample(xyz, 4);
print('${n} points -> ${d.length ~/ 3} voxel centroids');
}200 points -> 27 voxel centroids
static Float64List estimateNormals(Float64List xyz, {int k = 10, List<double>? viewpoint, KdTree? tree})Unit normals by PCA of each point's k nearest neighbours: the eigenvector of the smallest eigenvalue of the neighbourhood covariance. Normals point towards viewpoint when given (otherwise their sign is arbitrary).
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
// Points on the plane z = 0.5x: every normal is ±(−0.5, 0, 1)/|…|.
final rng = math.Random(2);
final xyz = Float64List.fromList([for (var i = 0; i < 100; i++) ...(() { final x = rng.nextDouble(), y = rng.nextDouble(); return [x, y, 0.5 * x]; })()]);
final nrm = PointCloud.estimateNormals(xyz, viewpoint: [0, 0, 10]);
print('normal at point 0: ${nrm.sublist(0, 3).map((v) => v.toStringAsFixed(4)).toList()}');
}normal at point 0: [-0.4472, -0.0000, 0.8944]
static Int32List removeStatisticalOutliers(Float64List xyz, {int k = 8, double stdRatio = 2})Statistical outlier removal (PCL's StatisticalOutlierRemoval): the mean distance d_{i} from each point to its k nearest others; points with d_{i} > \mu + stdRatio·\sigma are outliers. Returns the inlier indices.
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final rng = math.Random(5);
final pts = <double>[for (var i = 0; i < 60; i++) ...[rng.nextDouble(), rng.nextDouble(), 0]];
pts.addAll([5, 5, 0, -4, 3, 0]);
final xyz = Float64List.fromList(pts);
final keep = PointCloud.removeStatisticalOutliers(xyz);
print('kept ${keep.length} of ${xyz.length ~/ 3}');
}kept 60 of 62
static ({Float64List rotation, Float64List translation}) rigidTransform(Float64List a, Float64List b, {Float64List? weights})Least-squares rigid transform taking points a onto corresponding points b (same count, interleaved): b \approx R \cdot a + t. Horn's closed-form quaternion method (1987): the rotation is the eigenvector of the largest eigenvalue of a symmetric 4 \times 4 matrix built from the cross-covariance, so it is always a proper rotation (no SVD reflection fix-up). weights optional. Returns R row-major (9) and t (3).
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final a = Float64List.fromList([0, 0, 0, 1, 0, 0, 0, 2, 0, 1, 1, 1]);
// b = R a + t with R a quarter turn about z, t = (3, 1, 0).
final b = Float64List.fromList([3, 1, 0, 3, 2, 0, 1, 1, 0, 2, 2, 1]);
final f = PointCloud.rigidTransform(a, b);
print('R = ${f.rotation.map((v) => v.toStringAsFixed(6)).toList()}');
print('t = ${f.translation.map((v) => v.toStringAsFixed(6)).toList()}');
}R = [0.000000, -1.000000, -0.000000, 1.000000, 0.000000, -0.000000, 0.000000, -0.000000, 1.000000] t = [3.000000, 1.000000, -0.000000]
static ({Float64List rotation, Float64List translation, double rmse, int iterations}) icp(Float64List source, Float64List target, {int maxIterations = 50, double tolerance = 1e-10, double maxDistance = double.infinity})Point-to-point ICP (Besl and McKay 1992): repeatedly match every source point to its nearest target point (k-d tree) and solve the rigid transform (rigidTransform) until the RMS error stops improving by more than tolerance. Returns the accumulated transform taking source onto target, the final RMS distance and the iteration count. Pairs farther than maxDistance are ignored.
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final rng = math.Random(9);
final target = Float64List.fromList([for (var i = 0; i < 80; i++) ...(() { final u = rng.nextDouble() * 2 * math.pi; return [math.cos(u) * 2, math.sin(u), 0.0]; })()]);
final source = Float64List.fromList(target);
final c = math.cos(0.3), s = math.sin(0.3);
PointCloud.transform(Float64List.fromList([c, -s, 0, s, c, 0, 0, 0, 1]), Float64List.fromList([0.4, -0.2, 0]), source);
final r = PointCloud.icp(source, target);
print('ICP: rmse ${r.rmse.toStringAsExponential(2)} after ${r.iterations} iterations');
final aligned = Float64List.fromList(source);
PointCloud.transform(r.rotation, r.translation, aligned);
}ICP: rmse 4.91e-16 after 13 iterations
static void transform(Float64List r, Float64List t, Float64List xyz)Applies x \to R \cdot x + t in place to interleaved xyz.
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
void main() {
final a = Float64List.fromList([0, 0, 0, 1, 0, 0, 0, 2, 0, 1, 1, 1]);
// b = R a + t with R a quarter turn about z, t = (3, 1, 0).
final b = Float64List.fromList([3, 1, 0, 3, 2, 0, 1, 1, 0, 2, 2, 1]);
final f = PointCloud.rigidTransform(a, b);
final moved = Float64List.fromList(a);
PointCloud.transform(f.rotation, f.translation, moved);
print('moved ≈ b: ${[for (var i = 0; i < 12; i++) (moved[i] - b[i]).abs() < 1e-9].every((v) => v)}');
}moved ≈ b: true