You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

52 lines
2.1 KiB

  1. #include <Eigen/StdVector>
  2. #include <unsupported/Eigen/BVH>
  3. #include <iostream>
  4. using namespace Eigen;
  5. typedef AlignedBox<double, 2> Box2d;
  6. namespace Eigen {
  7. namespace internal {
  8. Box2d bounding_box(const Vector2d &v) { return Box2d(v, v); } //compute the bounding box of a single point
  9. }
  10. }
  11. struct PointPointMinimizer //how to compute squared distances between points and rectangles
  12. {
  13. PointPointMinimizer() : calls(0) {}
  14. typedef double Scalar;
  15. double minimumOnVolumeVolume(const Box2d &r1, const Box2d &r2) { ++calls; return r1.squaredExteriorDistance(r2); }
  16. double minimumOnVolumeObject(const Box2d &r, const Vector2d &v) { ++calls; return r.squaredExteriorDistance(v); }
  17. double minimumOnObjectVolume(const Vector2d &v, const Box2d &r) { ++calls; return r.squaredExteriorDistance(v); }
  18. double minimumOnObjectObject(const Vector2d &v1, const Vector2d &v2) { ++calls; return (v1 - v2).squaredNorm(); }
  19. int calls;
  20. };
  21. int main()
  22. {
  23. typedef std::vector<Vector2d, aligned_allocator<Vector2d> > StdVectorOfVector2d;
  24. StdVectorOfVector2d redPoints, bluePoints;
  25. for(int i = 0; i < 100; ++i) { //initialize random set of red points and blue points
  26. redPoints.push_back(Vector2d::Random());
  27. bluePoints.push_back(Vector2d::Random());
  28. }
  29. PointPointMinimizer minimizer;
  30. double minDistSq = std::numeric_limits<double>::max();
  31. //brute force to find closest red-blue pair
  32. for(int i = 0; i < (int)redPoints.size(); ++i)
  33. for(int j = 0; j < (int)bluePoints.size(); ++j)
  34. minDistSq = std::min(minDistSq, minimizer.minimumOnObjectObject(redPoints[i], bluePoints[j]));
  35. std::cout << "Brute force distance = " << sqrt(minDistSq) << ", calls = " << minimizer.calls << std::endl;
  36. //using BVH to find closest red-blue pair
  37. minimizer.calls = 0;
  38. KdBVH<double, 2, Vector2d> redTree(redPoints.begin(), redPoints.end()), blueTree(bluePoints.begin(), bluePoints.end()); //construct the trees
  39. minDistSq = BVMinimize(redTree, blueTree, minimizer); //actual BVH minimization call
  40. std::cout << "BVH distance = " << sqrt(minDistSq) << ", calls = " << minimizer.calls << std::endl;
  41. return 0;
  42. }