diff --git a/lib/Slic3r/ExPolygon.pm b/lib/Slic3r/ExPolygon.pm index 18789a747..0ef2d977a 100644 --- a/lib/Slic3r/ExPolygon.pm +++ b/lib/Slic3r/ExPolygon.pm @@ -5,7 +5,7 @@ use warnings; # an ExPolygon is a polygon with holes use Math::Geometry::Voronoi; -use Slic3r::Geometry qw(point_in_polygon X Y A B); +use Slic3r::Geometry qw(X Y A B point_in_polygon); use Slic3r::Geometry::Clipper qw(union_ex JT_MITER); # the constructor accepts an array of polygons diff --git a/lib/Slic3r/Geometry.pm b/lib/Slic3r/Geometry.pm index f28db1507..599cde44a 100644 --- a/lib/Slic3r/Geometry.pm +++ b/lib/Slic3r/Geometry.pm @@ -19,7 +19,7 @@ our @EXPORT_OK = qw( polygon_remove_acute_vertices polygon_remove_parallel_continuous_edges shortest_path collinear scale unscale merge_collinear_lines rad2deg_dir bounding_box_center line_intersects_any douglas_peucker - polyline_remove_short_segments normal triangle_normal + polyline_remove_short_segments normal triangle_normal polygon_is_convex ); use XXX; @@ -295,6 +295,15 @@ sub polygon_has_vertex { return 0; } +sub polygon_is_convex { + my ($points) = @_; + for (my $i = 0; $i <= $#$points; $i++) { + my $angle = angle3points($points->[$i-1], $points->[$i-2], $points->[$i]); + return 0 if $angle < PI; + } + return 1; +} + sub polyline_length { my ($polyline) = @_; my $length = 0; diff --git a/t/geometry.t b/t/geometry.t index bc81cb610..0ff61e375 100644 --- a/t/geometry.t +++ b/t/geometry.t @@ -2,7 +2,7 @@ use Test::More; use strict; use warnings; -plan tests => 17; +plan tests => 20; BEGIN { use FindBin; @@ -12,7 +12,7 @@ BEGIN { use Slic3r; use Slic3r::Geometry qw(PI polyline_remove_parallel_continuous_edges polyline_remove_acute_vertices polygon_remove_acute_vertices - polygon_remove_parallel_continuous_edges); + polygon_remove_parallel_continuous_edges polygon_is_convex); #========================================================== @@ -143,4 +143,15 @@ is Slic3r::Geometry::can_connect_points(@$points, $polygons), 0, 'can_connect_po is scalar(@$polygon), 6, 'polyline_remove_acute_vertices'; } +#========================================================== + +{ + my $cw_square = [ [0,0], [0,10], [10,10], [10,0] ]; + is polygon_is_convex($cw_square), 0, 'cw square is not convex'; + is polygon_is_convex([ reverse @$cw_square ]), 1, 'ccw square is convex'; + + my $convex1 = [ [0,0], [10,0], [10,10], [0,10], [0,6], [4,6], [4,4], [0,4] ]; + is polygon_is_convex($convex1), 0, 'concave polygon'; +} + #========================================================== \ No newline at end of file