summaryrefslogtreecommitdiffstats
path: root/Triangle.cpp
blob: 758758990fd92f1a4d14325037124529e3391c60 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include "Triangle.h"
#include "Line.h"
#include <math.h>
#include <stdio.h>


Triangle::Direction Triangle::getDirection() const {
  float c = (va.getX()-vb.getX())*(vc.getY()-vb.getY()) - (vc.getX()-vb.getX())*(va.getY()-vb.getY());
  
  return (c < 0) ? CW : (c > 0) ? CCW : UNKNOWN;
}

float Triangle::area() const {
  float a = vb.distanceSq(vc);
  float b = vc.distanceSq(va);
  float c = va.distanceSq(vb);
  
  return sqrt((a+b+c)*a+b+c - 2*(a*a+b*b+c*c))/4;
}

float Triangle::perimeter() const {
  return va.distance(vb) + vb.distance(vc) + vc.distance(va);
}

bool Triangle::contains(const Vertex &v) const {
  float a = (v.getX()-vb.getX())*(vc.getY()-vb.getY()) - (vc.getX()-vb.getX())*(v.getY()-vb.getY());
  float b = (v.getX()-vc.getX())*(va.getY()-vc.getY()) - (va.getX()-vc.getX())*(v.getY()-vc.getY());
  float c = (v.getX()-va.getX())*(vb.getY()-va.getY()) - (vb.getX()-va.getX())*(v.getY()-va.getY());
  
  switch(getDirection()) {
    case CW:
      return ((a < 1E-6) && (b < 1E-6) && (c < 1E-6));
    case CCW:
      return ((a > -1E-6) && (b > -1E-6) && (c > -1E-6));
    default:
      return false;
  }
}

bool Triangle::onEdge(const Vertex &v) const {
  return (Line(va, vb).contains(v) || Line(vb, vc).contains(v) || Line(vc, va).contains(v));
}

int Triangle::intersectionCount(const Line &l) const {
  int ret = 0;
  Vertex v1, v2, v3;
  
  printf("Testing line: (%f %f) (%f %f)\n", l.getVertex1().getX(), l.getVertex1().getY(), l.getVertex2().getX(), l.getVertex2().getY());
  if(Line(va, vb).intersects(l, &v1) == INTERSECTION_SEGMENT_SEGMENT) {
    printf("Intersection: (%f %f)\n", v1.getX(), v1.getY());
    ret++;
  }
  
  if(Line(vb, vc).intersects(l, &v2) == INTERSECTION_SEGMENT_SEGMENT) {
    printf("Intersection: (%f %f)\n", v2.getX(), v2.getY());
    if(v2.distanceSq(v1) >= 1E-6)
      ret++;
  }
  
  if(Line(vc, va).intersects(l, &v3) == INTERSECTION_SEGMENT_SEGMENT) {
    printf("Intersection: (%f %f)\n", v3.getX(), v3.getY());
    if(v3.distanceSq(v1) >= 1E-6 && v3.distanceSq(v2) >= 1E-6)
      ret++;
  }
  
  printf("Found %i intersections.\n", ret);
  
  
  return ret;
}