三维空间中关于点线面的计算

1. 三维空间中两点间的距离

    设两点为 P1(x1,y1,z1), P2(x2,y2,z2), 则两点间的距离为:

float distance=CalTwoPointDistance(x1,y1,z1,x2,y2,z2);
float CalTwoPointDistance(float x1,float y1,float z1,float x2,float y2,float z2)
{
	float distance=0.0f;
	distance=sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)+(z1-z2)*(z1-z2));
	return distance;
}

2. 三维空间有向线段与坐标轴的夹角

    设两点为 P1(x1,y1,z1), P2(x2,y2,z2), 则由P1指向P2的有向线段P1P2与X轴的夹角为:

float angle=CalLineToXAngle(x1,y1,z1,x2,y2,z2);
float CMesh::CalLineToXAngle(float x1,float y1,float z1,float x2,float y2,float z2)//1->2
{
	if ((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)+(z2-z1)*(z2-z1)==0)
	{
		return 0.0f;
	}
	float linevector[3]={x2-x1,y2-y1,z2-z1};
	float linex[3]={1.0f,0.0f,0.0f};
	float cosangle=(x2-x1)/sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)+(z2-z1)*(z2-z1));
	if (cosangle<-1||cosangle>1)
	{
		ASSERT(1);
	}
	//
	float langle=acos(cosangle);
	//
	float angle=langle*180.0f/PI;
	if (angle<0||angle>180)
	{
		ASSERT(1);
	}
	return angle;
}

其算法思想就是计算P1P2向量与X轴向量的数量积,然后除以两向量的模长即为两向量的夹角余弦值。

\cos{\theta} = \frac{\mathbf{a \cdot b}}{|\vec{a}| \, |\vec{b}|}

3.三维空间中平面的法向量计算

参考我的博客文章:

http://blog.csdn.net/u011442652/article/details/37727977

4. 三维空间中平面与直线的交点

    其原理参考博客:http://blog.csdn.net/abcjennifer/article/details/6688080

bool CalPlaneLineIntersectPoint(float *planeNVector, float *planePoint, float *lineVector, float *linePoint,
								float &resultx,float &resulty,float &resultz)  
{  
	float vp1, vp2, vp3, n1, n2, n3, v1, v2, v3, m1, m2, m3, t,vpt;  
	vp1 = planeNVector[0];  
	vp2 = planeNVector[1];  
	vp3 = planeNVector[2];  
	n1 = planePoint[0];  
	n2 = planePoint[1];  
	n3 = planePoint[2];  
	v1 = lineVector[0];  
	v2 = lineVector[1];  
	v3 = lineVector[2];  
	m1 = linePoint[0];  
	m2 = linePoint[1];  
	m3 = linePoint[2];  
	vpt = v1 * vp1 + v2 * vp2 + v3 * vp3;  //法向量跟直线向量的数量积
	//首先判断直线是否与平面平行  
	if (vpt == 0)  
	{  
		return false;
	}  
	else  
	{  
		t = ((n1 - m1) * vp1 + (n2 - m2) * vp2 + (n3 - m3) * vp3) / vpt;  
		resultx = m1 + v1 * t;  
		resulty = m2 + v2 * t;  
		resultz = m3 + v3 * t;  
	}  
	//
	return true;  
}  






你可能感兴趣的:(C++)