Class: BorderPatrol::Polygon
- Inherits:
-
Object
- Object
- BorderPatrol::Polygon
- Extended by:
- Forwardable
- Defined in:
- lib/border_patrol/polygon.rb
Instance Method Summary collapse
- #==(other) ⇒ Object
- #bounding_box ⇒ Object
- #contains_point?(point) ⇒ Boolean
-
#hash ⇒ Object
Quick and dirty hash function.
-
#initialize(*args) ⇒ Polygon
constructor
A new instance of Polygon.
- #inside_bounding_box?(point) ⇒ Boolean
Constructor Details
#initialize(*args) ⇒ Polygon
Returns a new instance of Polygon.
5 6 7 8 9 10 |
# File 'lib/border_patrol/polygon.rb', line 5 def initialize(*args) args.flatten! args.uniq! raise InsufficientPointsToActuallyFormAPolygonError unless args.size > 2 @points = Array.new(args) end |
Instance Method Details
#==(other) ⇒ Object
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/border_patrol/polygon.rb', line 14 def ==(other) # Do we have the right number of points? return false unless other.size == size # Are the points in the right order? first, second = first(2) index = other.index(first) return false unless index direction = (other[index-1] == second) ? -1 : 1 # Check if the two polygons have the same edges and the same points # i.e. [point1, point2, point3] is the same as [point2, point3, point1] is the same as [point3, point2, point1] each do |i| return false unless i == other[index] index = index + direction index = 0 if index == size end true end |
#bounding_box ⇒ Object
66 67 68 69 70 71 72 73 74 75 |
# File 'lib/border_patrol/polygon.rb', line 66 def bounding_box max_x, min_x, max_y, min_y = -Float::MAX, Float::MAX, -Float::MAX, Float::MAX each do |point| max_y = point.y if point.y > max_y min_y = point.y if point.y < min_y max_x = point.x if point.x > max_x min_x = point.x if point.x < min_x end [Point.new(min_x, max_y), Point.new(max_x, min_y)] end |
#contains_point?(point) ⇒ Boolean
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/border_patrol/polygon.rb', line 38 def contains_point?(point) return false unless inside_bounding_box?(point) c = false i = -1 j = self.size - 1 while (i += 1) < self.size if ((self[i].y <= point.y && point.y < self[j].y) || (self[j].y <= point.y && point.y < self[i].y)) if (point.x < (self[j].x - self[i].x) * (point.y - self[i].y) / (self[j].y - self[i].y) + self[i].x) c = !c end end j = i end return c end |
#hash ⇒ Object
Quick and dirty hash function
34 35 36 |
# File 'lib/border_patrol/polygon.rb', line 34 def hash @points.inject(0) { |sum, point| sum += point.x + point.y } end |
#inside_bounding_box?(point) ⇒ Boolean
56 57 58 59 60 61 62 63 64 |
# File 'lib/border_patrol/polygon.rb', line 56 def inside_bounding_box?(point) bb_point_1, bb_point_2 = bounding_box max_x = [bb_point_1.x, bb_point_2.x].max max_y = [bb_point_1.y, bb_point_2.y].max min_x = [bb_point_1.x, bb_point_2.x].min min_y = [bb_point_1.y, bb_point_2.y].min !(point.x < min_x || point.x > max_x || point.y < min_y || point.y > max_y) end |