public class NGlbVec3d
{// 三维点
public double x, y, z;
public NGlbVec3d()
{
}
public NGlbVec3d(double vx, double vy, double vz)
{
x = vx; y = vy; z = vz;
}
public static double operator *(NGlbVec3d a, NGlbVec3d b)
{
return (a.x * b.x + a.y * b.y + a.z * b.z);
}
public static NGlbVec3d operator -(NGlbVec3d a, NGlbVec3d b)
{
NGlbVec3d t = new NGlbVec3d();
t.x = a.x - b.x;
t.y = a.y - b.y;
t.z = a.z - b.z;
return t;
}
public static NGlbVec3d operator ^(NGlbVec3d a, NGlbVec3d b)
{
NGlbVec3d t = new NGlbVec3d();
t.x = a.y*b.z - a.z*b.y;
t.y = a.z*b.x - a.x*b.z;
t.z = a.x*b.y - a.y*b.x;
return t;
}
public void set(double vx, double vy, double vz)
{
x = vx; y = vy; z = vz;
}
public void normalize()
{
double t = Math.Sqrt(Math.Pow(x, 2) + Math.Pow(y, 2) + Math.Pow(z, 2));
if (t == 0.0) return;
x = x / t; y = y / t; z = z / t;
}
}
public class NGlbPlane
{// 平面
public double A,B,C,D;
public NGlbPlane()
{
}
public NGlbPlane(double a, double b, double c, double d)
{
A = a; B = b; C = c; D = d;
}
public NGlbPlane(NGlbVec3d v1, NGlbVec3d v2, NGlbVec3d v3)
{// 根据三个点计算平面方程 A,B,C,D
NGlbVec3d v = (v3 - v1) ^ (v2 - v1);
v.normalize();
A = v.x;
B = v.y;
C = v.z;
D = -(A * v1.x + B * v1.y + C * v1.z);
}
}
// 计算线ln[2] 与平面plane[4]的交点 interPt
private bool IsLineInterPlane(NGlbVec3d[] ln, NGlbPlane plane, NGlbVec3d interPt)
{
// 直线方程P(t) = Q + tV
NGlbVec3d Q = ln[0];
NGlbVec3d V = ln[1] - ln[0];
V.normalize();
// 平面方程 N * P(x,y,z) + D = 0
NGlbVec3d N = new NGlbVec3d(plane.A,plane.B,plane.C);
//N.normalize();
double D = plane.D;
double s = N * V;
if (s == 0.0) // 直线与平面平行
return false;
double q = - D - N * Q;
double t = q / s;
// 将t带入直线方程P(t) = Q + tV,就可得到直线与平面的交点
interPt.x = Q.x + t * V.x;
interPt.y = Q.y + t * V.y;
interPt.z = Q.z + t * V.z;
return true;
}