From 55bd550cda129813004d0977adab924cda22f7cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Czapli=C5=84ski?= Date: Mon, 20 Apr 2015 23:52:06 +0200 Subject: [PATCH] fix a bug in Contour.Contains --- geom.go | 11 +++++++++-- geom_test.go | 21 +++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/geom.go b/geom.go index d1a2814..a8c08a0 100644 --- a/geom.go +++ b/geom.go @@ -127,8 +127,15 @@ func (c Contour) Contains(p Point) bool { } next := c[ii] - if (p.Y >= next.Y || p.Y <= curr.Y) && - (p.Y >= curr.Y || p.Y <= next.Y) { + // Is the point out of the edge's bounding box? + // bottom vertex is inclusive (belongs to edge), top vertex is + // exclusive (not part of edge) -- i.e. p lies "slightly above + // the ray" + bottom, top := curr, next + if bottom.Y > top.Y { + bottom, top = top, bottom + } + if p.Y < bottom.Y || p.Y >= top.Y { continue } // Edge is from curr to next. diff --git a/geom_test.go b/geom_test.go index 53a5743..d0d2fff 100644 --- a/geom_test.go +++ b/geom_test.go @@ -140,6 +140,27 @@ func TestContourContains(t *T) { } } +func TestContourContains2(t *T) { + c1 := Contour{{55, 35}, {25, 35}, {25, 119}, {55, 119}} + c2 := Contour{{145, 35}, {145, 77}, {105, 77}, {105, 119}, {55, 119}, {55, 35}} + cases := []struct { + Contour + Point + Result bool + }{ + {c1, Point{54.95, 77}, true}, + {c1, Point{55.05, 77}, false}, + {c2, Point{54.95, 77}, false}, + {c2, Point{55.05, 77}, true}, + } + for _, c := range cases { + result := c.Contour.Contains(c.Point) + if result != c.Result { + t.Errorf("case %v expected %v, got %v", c, c.Result, result) + } + } +} + func ExamplePolygon_Construct() { subject := Polygon{{{1, 1}, {1, 2}, {2, 2}, {2, 1}}} // small square clipping := Polygon{{{0, 0}, {0, 3}, {3, 0}}} // overlapping triangle