# 1. 原理推导

## 1.1. 直线公式

$\frac{x-x_0}{m} = \frac{y-y_0}{n} = \frac{z-z_0}{p}$

$\begin{cases} x = x_0 + m * t\\ y = y_0 + n * t\\ z = z_0 + p * t\\ \end{cases}$

$P=O+tD$

$\begin{cases} x = O_x + D_x * t\\ y = O_y + D_y * t\\ z = O_z + D_z * t\\ \end{cases} \tag {1}$

## 1.2. 求交

$(X-C_x)^2 + (Y-C_y)^2 + (Z-C_z)^2 = R^2 \tag{2}$

$(O_x + D_x * t-C_x)^2 + ( O_y + D_y * t-C_y)^2 + (O_z + D_z * t-C_z)^2 = R^2$

# 2. 具体实现

#include <iostream>
#include <string>
#include <vector>

using namespace std;

const double EPSILON = 0.0000000001;

// 3D vector
struct Vector3d
{
public:
Vector3d()
{
}

~Vector3d()
{
}

Vector3d(double dx, double dy, double dz)
{
x = dx;
y = dy;
z = dz;
}

// 矢量赋值
void set(double dx, double dy, double dz)
{
x = dx;
y = dy;
z = dz;
}

// 矢量相加
Vector3d operator + (const Vector3d& v) const
{
return Vector3d(x + v.x, y + v.y, z + v.z);
}

// 矢量相减
Vector3d operator - (const Vector3d& v) const
{
return Vector3d(x - v.x, y - v.y, z - v.z);
}

//矢量数乘
Vector3d Scalar(double c) const
{
return Vector3d(c*x, c*y, c*z);
}

// 矢量点积
double Dot(const Vector3d& v) const
{
return x * v.x + y * v.y + z * v.z;
}

// 矢量叉积
Vector3d Cross(const Vector3d& v) const
{
return Vector3d(y * v.z - z * v.y, z * v.x - x * v.z, x * v.y - y * v.x);
}

bool operator == (const Vector3d& v) const
{
if (abs(x - v.x) < EPSILON && abs(y - v.y) < EPSILON && abs(z - v.z) < EPSILON)
{
return true;
}
return false;
}

double x, y, z;
};

//求解一元二次方程组ax*x + b*x + c = 0
void SolvingQuadratics(double a, double b, double c, vector<double>& t)
{
double delta = b * b - 4 * a * c;
if (delta < 0)
{
return;
}

if (abs(delta) < EPSILON)
{
t.push_back(-b / (2 * a));
}
else
{
t.push_back((-b + sqrt(delta)) / (2 * a));
t.push_back((-b - sqrt(delta)) / (2 * a));
}
}

void LineIntersectSphere(Vector3d& O, Vector3d& E, Vector3d& Center, double R, vector<Vector3d>& points)
{
Vector3d D = E - O;			//线段方向向量

double a = (D.x * D.x) + (D.y * D.y) + (D.z * D.z);
double b = (2 * D.x * (O.x - Center.x) + 2 * D.y * (O.y - Center.y) + 2 * D.z* (O.z - Center.z));
double c = ((O.x - Center.x)*(O.x - Center.x) + (O.y - Center.y) * (O.y - Center.y) + (O.z - Center.z) * (O.z - Center.z)) - R * R;

vector<double> t;

for (auto it : t)
{
if (it >= 0 && it <= 1)
{
points.push_back(O + D.Scalar(it));
}
}
}

int main()
{
Vector3d O(20, 30, 40);
Vector3d E(20, 20, 20);
Vector3d Center(20, 20, 20);
double R = 15;

vector<Vector3d> points;
LineIntersectSphere(O, E, Center, R, points);

cout<<"该直线(线段)与球面有"<< points.size() <<"个交点"<<endl;
for (auto it : points)
{
printf("%lf\t%lf\t%lf\n", it.x, it.y, it.z);
}
}


# 3. 参考

posted @ 2020-07-05 18:52  charlee44  阅读(466)  评论(0编辑  收藏