jbuckmccready / CavalierContours

2D polyline library for offsetting, combining, etc.
MIT License
427 stars 79 forks source link

Glitches on intersection calculation #28

Closed deinvict closed 3 years ago

deinvict commented 3 years ago

I stumbled on some glitches while calculating polyline intersections if a polyline intersects the other one in vertex. Take the following example :

#include "cavc/polyline.hpp"
#include "cavc/polylineintersects.hpp"

#include <iostream>
#include <cmath>

using namespace cavc;

int main(int argc, char *argv[]) {
  (void)argc;
  (void)argv;

  Polyline<double> arc;
  arc.addVertex(0., 1., -std::tan(cavc::utils::pi<double>() / 8));

  // y = 1e-15 works but y = -1e-15 not
  arc.addVertex(1., -1e-15, -std::tan(cavc::utils::pi<double>() / 8));

  arc.addVertex(-1., -1., 0.);
  arc.isClosed() = false;

  Polyline<double> line;
  line.addVertex(-2., 0, 0.);
  line.addVertex(2., 0., 0.);
  line.isClosed() = false;

  cavc::StaticSpatialIndex<double> spatial_index_poly1 = cavc::createApproxSpatialIndex(arc);
  cavc::PlineIntersectsResult<double> intersections;
  findIntersects(arc, line, spatial_index_poly1, intersections);

  std::cout << intersections.intersects.size() << "\n";

  for (auto p : intersections.intersects)
    std::cout << p.pos.x() << " " << p.pos.y() << "\n";

  return 0;
}

On my system, I observe the following behavior using the master branch of cavc: If the y value of the second vertex of the arc is slightly positive, everything works fine and the correct intersection point is printed. But if y is slightly negative, no intersection is found.

Is this the intended behavior and if so, is there some kind of workaround to overcome this problem?

jbuckmccready commented 3 years ago

Thanks for the report and minimal working example, made it very easy to debug. I fixed the issue and committed to master branch, commit: https://github.com/jbuckmccready/CavalierContours/commit/b955785cc3db9689704d6135cbb60177fab835bb