光线与AABB包围盒的相交检测算法SlabMethod

最近在看recast&detour源码的时候有遇到许多数学上的算法问题,特此记录,以便以后查看。


原理

下图是2D的情况,

看 Inside-y-slab(光线在 y=ymin  和  y=ymax 的那段) 和

Inside-x-slab(光线在 x=xmin  和  x=xmax 的那段)有没有重叠。

如果有重叠部分,那么光线与包围盒相交。


如何判断有没有重叠部分?

假设已知射线的起点为Orig,射线的方向为 Dir ,那么射线方程表示成:

P = Orig + t*Dir;

通过与直线方程  x=xmin    x=xmax   y=ymin   y=ymax 联立可以求得 参数t值

假设与 x = k 相交交点参数为 t1 t2, t1 < t2

与y = b 相交交点参数为 t3 t4,t3 < t4

那么判断是否重叠,就转换成两个区间范围是否有重复

令tmin = max(t1,t3), tmax = min(t2, t4) ,那么当 tmin  > tmax  的时候就是不重叠。

当光线是射线的时候,

    tmin 初始为 0,tmin = max(t1,t3,0) 

当光线是线段的时候,

    tmin 初始为0,  tmin = max(t1, t3, 0) 

    tmax 初始为1, tmax = min(t2, t4, 1)


源码

2D情况下

// 线段 与 AABB矩形 是否相交
static bool checkOverlapSegment(const float p[2], const float q[2],
								const float bmin[2], const float bmax[2])
{
	static const float EPSILON = 1e-6f;

	float tmin = 0;
	float tmax = 1;
	float d[2];
	d[0] = q[0] - p[0];
	d[1] = q[1] - p[1];
	
	for (int i = 0; i < 2; i++)
	{
		if (fabsf(d[i]) < EPSILON)
		{
			// Ray is parallel to slab. No hit if origin not within slab
			if (p[i] < bmin[i] || p[i] > bmax[i])
				return false;
		}
		else
		{
			// Compute intersection t value of ray with near and far plane of slab
			float ood = 1.0f / d[i];
			float t1 = (bmin[i] - p[i]) * ood;
			float t2 = (bmax[i] - p[i]) * ood;
			if (t1 > t2) { float tmp = t1; t1 = t2; t2 = tmp; }
			if (t1 > tmin) tmin = t1;
			if (t2 < tmax) tmax = t2;
			if (tmin > tmax) return false;
		}
	}
	return true;
}

3D的情况,跟2D类似。

看光线和6个面的相交的情况,即求点和面相交的交点的t值有无重叠。

// sp 线起点 
// sq 线终点
// amin amax  表示 AABB包围盒
static bool isectSegAABB(const float* sp, const float* sq,
						 const float* amin, const float* amax,
						 float& tmin, float& tmax)
{
	static const float EPS = 1e-6f;
	
	// 光线方向
	float d[3];
	d[0] = sq[0] - sp[0];
	d[1] = sq[1] - sp[1];
	d[2] = sq[2] - sp[2];
	// 因为是线段 所以参数t取值在0和1之间
	tmin = 0.0;
	tmax = 1.0f;
	
	for (int i = 0; i < 3; i++)
	{
		// 如果光线某一个轴分量为 0,且在包围盒这个轴分量之外,那么直接判定不相交 
		if (fabsf(d[i]) < EPS)
		{
			if (sp[i] < amin[i] || sp[i] > amax[i])
				return false;
		}
		else
		{
			const float ood = 1.0f / d[i];
			// 计算参数t 并令 t1为较小值 t2为较大值
			float t1 = (amin[i] - sp[i]) * ood;
			float t2 = (amax[i] - sp[i]) * ood;
			if (t1 > t2) { float tmp = t1; t1 = t2; t2 = tmp; }
			
			if (t1 > tmin) tmin = t1;
			if (t2 < tmax) tmax = t2;

			// 判定不相交
			if (tmin > tmax) return false;
		}
	}
	
	return true;
}

tip

平面的方程可以表示为:

X*n = d 

其中 X 为平面上的点的集合, n 为平面的单位法向量,d为原点到平面的有向距离(正负取决于 单位法向量 的方向,和平面上的点表示的向量,的夹角大小)


参考

http://blog.sina.com.cn/s/blog_a30e0bed0102v0r7.html

猜你喜欢

转载自blog.csdn.net/u012138730/article/details/80111586