Skip to content

Instantly share code, notes, and snippets.

@cathode
Created April 24, 2013 23:02
Show Gist options
  • Save cathode/5456294 to your computer and use it in GitHub Desktop.
Save cathode/5456294 to your computer and use it in GitHub Desktop.
/// <summary>
/// Gets the position on the current polygon at which the specified edge intersects it.
/// </summary>
/// <param name="line"></param>
/// <returns></returns>
public Vector3 GetIntersection(Edge3 line)
{
// Set up vector variables;
Vector3 a, b, c, p, q;
a = this.A.ToVector3();
b = this.B.ToVector3();
c = this.C.ToVector3();
p = line.P.ToVector3();
q = line.Q.ToVector3();
// Vector from A to C
var ex = this.C.X - this.A.X;
var ey = this.C.Y - this.A.Y;
var ez = this.C.Z - this.A.Z;
// Vector from A to B
var fx = this.B.X - this.A.X;
var fy = this.B.Y - this.A.Y;
var fz = this.B.Z - this.A.Z;
// Cross product of e and f
var nx = (fy * ez) - (fz * ey);
var ny = (fz * ex) - (fx * ez);
var nz = (fx * ey) - (fy * ex);
// Normalize
var m = Math.Sqrt((nx * nx) + (ny * ny) + (nz * nz));
nx /= m;
ny /= m;
nz /= m;
// Ray direction vector
var dx = line.Q.X - line.P.X;
var dy = line.Q.Y - line.P.Y;
var dz = line.Q.Z - line.P.Z;
m = Math.Sqrt((dx * dx) + (dy * dy) + (dz * dz));
dx /= m;
dy /= m;
dz /= m;
// Dot product of ray and normal, tells us if ray is pointing towards the triangle.
m = (dx * nx) + (dy * ny) + (dz * nz);
// Value of m determines the relationship of the vectors:
// m < 0: Vectors are opposed
// m == 0: Vectors are perpendicular
// m > 0: Vectors point the same way
if (m < 0)
{
var gx = this.A.X - line.P.X;
var gy = this.A.Y - line.P.Y;
var gz = this.A.Z - line.P.Z;
var t = (gx * nx) + (gy * ny) + (gz * nz);
if (t < 0)
{
var k = t / m;
var sx = p.X + (dx * k);
var sy = p.Y + (dy * k);
var sz = p.Z + (dz * k);
return new Vector3(sx, sy, sz);
}
}
throw new NotImplementedException();
//return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment