我应该编写计算三角形边界框的代码。边界框坐标应该写入
triangle->bx, triangle->by, triangle->bw, triangle->bh
,
bx, by is the upper left corner of the box
bw, bh is the width and height of the box
我应该把我的点当作坐标还是应该选择一个更基于几何的解决方案?
我试着找到每个坐标的最小值和最大值,但它不起作用。任何帮助将非常感激!
if (triangle->sx1 <= triangle->sx2 <= triangle->sx3)
{
triangle->bx = triangle->sx1;
}
else if (triangle->sx2 <= triangle->sx1 <= triangle->sx3)
{
triangle->bx = triangle->sx2;
}
else (triangle->bx = triangle->sx3);
if (triangle->sy1 <= triangle->sy2 <= triangle->sy3)
{
triangle->by = triangle->sy1;
}
else if (triangle->sy2 <= triangle->sy1 <= triangle->sy3)
{
triangle->by = triangle->sy2;
}
else (triangle->by = triangle->sy3);
if (triangle->sx1 >= triangle->sx2 >= triangle->sx3)
{
triangle->bw = triangle->sx1;
}
else if (triangle->sx2 >= triangle->sx1 >= triangle->sx3)
{
triangle->bw = triangle->sx2;
}
else (triangle->bw = triangle->sx3);
if (triangle->sy1 >= triangle->sy2 >= triangle->sy3)
{
triangle->bh = triangle->sy1;
}
else if (triangle->sy2 >= triangle->sy1 >= triangle->sy3)
{
triangle->bh = triangle->sy2;
}
else (triangle->bh = triangle->sy3);
要找到包含三角形的框的边界,只需要从组成三角形的三个坐标中找到最小和最大的x和y坐标。您可以使用三元表达式进行比较,这使得代码不那么难看。在下面的代码中,我将x和y三角形坐标移植到单独的变量中,以便更容易地读取三元表达式。
int sx1 = triangle->sx1;
int sx2 = triangle->sx2;
int sx3 = triangle->sx3;
int sy1 = triangle->sy1;
int sy2 = triangle->sy2;
int sy3 = triangle->sy3;
int xmax = sx1 > sx2 ? (sx1 > sx3 ? sx1 : sx3) : (sx2 > sx3 ? sx2 : sx3);
int ymax = sy1 > sy2 ? (sy1 > sy3 ? sy1 : sy3) : (sy2 > sy3 ? sy2 : sy3);
int xmin = sx1 < sx2 ? (sx1 < sx3 ? sx1 : sx3) : (sx2 < sx3 ? sx2 : sx3);
int ymin = sy1 < sy2 ? (sy1 < sy3 ? sy1 : sy3) : (sy2 < sy3 ? sy2 : sy3);
triangle->bx = xmin;
triangle->by = ymax;
triangle->bw = xmax - xmin;
triangle->bh = ymax - ymin;
这个问题可能有点晚了但是如果你有矢量化的话你可以这样做:
vec3 v1;
vec3 v2;
vec3 v3;
aabb->min = min(v1,min(v2,v3));
aabb->max = max(v1,max(v2,v3));