From 7413e6d8a870788817fd1aff80e4a472f03fab9d Mon Sep 17 00:00:00 2001 From: flu0r1ne Date: Sun, 28 Nov 2021 19:04:35 -0600 Subject: KDTree Wrapper --- kdtest.cpp | 64 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 kdtest.cpp (limited to 'kdtest.cpp') diff --git a/kdtest.cpp b/kdtest.cpp new file mode 100644 index 0000000..147b16c --- /dev/null +++ b/kdtest.cpp @@ -0,0 +1,64 @@ +/* + Test of the KDTree library + https://github.com/jtsiomb/kdtree +*/ + +#include +#include +#include +#include +#include +#include + +struct xyl_point { + double x; + double y; + uint32_t label; +}; + +int kd_insert_xyl(struct kdtree *tree, struct xyl_point const * pt) { + return kd_insert(tree, (double *) pt, (void *) (&pt->label)); +} + +double l2_norm(struct xyl_point * const x1, struct xyl_point * const x2) { + return sqrt( + (x1->x - x2->x) * (x1->x - x2->x) + + (x1->y - x2->y) * (x1->y - x2->y) + ); +} + +int main() { + struct xyl_point points[5] = { + {0, 0, 0}, + {0, 1, 1}, + {1, 0, 2}, + {1, 1, 3} + }; + + struct kdtree *ptree = kd_create(2); + + for(size_t i = 0; i < sizeof(points); i++) { + assert(0 == kd_insert_xyl(ptree, points + i)); + } + + { + struct xyl_point target = {0.75, 0.80, 0}; + struct xyl_point found; + double dist; + struct kdres * presults = kd_nearest(ptree, (double*) &target); + + while(!kd_res_end(presults)) { + found.label = *(uint32_t*) kd_res_item(presults, (double *) &found); + + dist = l2_norm(&found, &target); + + printf("found [(%.3f, %.3f), %u] a distance of %.3f\n", found.x, found.y, found.label, dist); + + kd_res_next(presults); + } + + kd_res_free( presults ); + } + + kd_free(ptree); +} -- cgit v1.2.3