-
Notifications
You must be signed in to change notification settings - Fork 0
/
Triangle.cs
66 lines (46 loc) · 2.82 KB
/
Triangle.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace randomImage
{
class Triangle : Shape
{
public Vector secondPoint, thirdPoint;
//public double alpha, beta, gamma;
public Triangle(Vector position, Vector secondPoint, Vector thirdPoint, Material material) : base(position, material){
this.secondPoint = secondPoint;
this.thirdPoint = thirdPoint;
}
public override double DoesIntersect(Vector origin, Vector direction)
{
Matrix A = new Matrix(new Vector(position.x - secondPoint.x, position.y - secondPoint.y, position.z - secondPoint.z), new Vector(position.x - thirdPoint.x, position.y - thirdPoint.y, position.z - thirdPoint.z), new Vector(direction.x, direction.y, direction.z));
Matrix A0 = new Matrix(new Vector(position.x - origin.x, position.y - origin.y, position.z - origin.z), new Vector(position.x - thirdPoint.x, position.y - thirdPoint.y, position.z - thirdPoint.z), new Vector(direction.x, direction.y, direction.z));
Matrix A1 = new Matrix(new Vector(position.x - secondPoint.x, position.y - secondPoint.y, position.z - secondPoint.z), new Vector(position.x - origin.x, position.y - origin.y, position.z - origin.z), new Vector(direction.x, direction.y, direction.z));
double beta = (A0.Determinant()) / (A.Determinant());
double gamma = (A1.Determinant()) / (A.Determinant());
if ((beta + gamma) > 1)
return -1;
double alpha = 1 - (beta + gamma);
if ((0 < alpha && alpha < 1) && (0 < beta && beta < 1) && (0 < gamma && gamma < 1) && (beta + gamma) < 1 && (alpha + beta) < 1 && (alpha + gamma) < 1)
{
Matrix A2 = new Matrix(new Vector(position.x - secondPoint.x, position.y - secondPoint.y, position.z - secondPoint.z), new Vector(position.x - thirdPoint.x, position.y - thirdPoint.y, position.z - thirdPoint.z), new Vector(position.x - origin.x, position.y - origin.y, position.z - origin.z));
double t = (A2.Determinant()) / (A.Determinant());
return t;
}
return -1;
}
// to find the normal of a triangle
public override Vector NormalAtPoint(Vector point)
{
// finding out the first position vector
Vector onePointToAnother = (secondPoint - position);
// another position vector of the triangle
Vector anotherPointToAnother = (thirdPoint - position);
// and then finding out the normal by cross product of those two position vectors
Vector normal = (onePointToAnother % anotherPointToAnother).Normalize(); // and so normalizing the normal
return normal;
}
}
}