#pragma once #include "vde/spatial/spatial_index.h" #include namespace vde::spatial { using core::AABB3D; using core::Point3D; using core::Vector3D; using core::Ray3Dd; using core::Triangle3D; template class KDTree : public SpatialIndex { public: void build(const std::vector& items) override; void insert(const T& item) override; bool remove(const T& item) override; std::vector query_range(const AABB3D& range) const override; std::vector query_knn(const Point3D& point, size_t k) const override; std::vector query_ray(const Ray3Dd& ray) const override; void clear() override; size_t size() const override { return items_.size(); } private: struct Node { AABB3D bounds; int item_idx = -1; // -1 for internal node; index into items_ for leaf int split_axis = 0; int left = -1; int right = -1; }; std::vector items_; std::vector nodes_; int root_ = -1; /// Return a representative 3D position for the item (used for spatial ordering) static Point3D get_position(const T& item); /// Return an axis-aligned bounding box for the item static AABB3D get_aabb(const T& item); /// Test whether the item intersects a ray static bool ray_hits_item(const T& item, const Ray3Dd& ray); int build_recursive(int start, int end); void query_range_recursive(int node_idx, const AABB3D& range, std::vector& result) const; void query_ray_recursive(int node_idx, const Ray3Dd& ray, std::vector& result) const; }; } // namespace vde::spatial