Class: BorderPatrol::Polygon
- Inherits:
-
Array
- Object
- Array
- BorderPatrol::Polygon
- 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.
3 4 5 6 7 8 |
# File 'lib/border_patrol/polygon.rb', line 3 def initialize(* args) args.flatten! args.uniq! raise InsufficientPointsToActuallyFormAPolygonError unless args.size > 2 super(args) end |
Instance Method Details
#==(other) ⇒ Object
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
# File 'lib/border_patrol/polygon.rb', line 10 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 = self.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
62 63 64 65 66 67 68 69 70 71 |
# File 'lib/border_patrol/polygon.rb', line 62 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
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/border_patrol/polygon.rb', line 34 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
30 31 32 |
# File 'lib/border_patrol/polygon.rb', line 30 def hash inject(0) { |sum, point| sum += point.x + point.y } end |
#inside_bounding_box?(point) ⇒ Boolean
52 53 54 55 56 57 58 59 60 |
# File 'lib/border_patrol/polygon.rb', line 52 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 |