3

I'm supposed to write code that calculates the bounding box of a triangle. The bounding box coordinates should be written to

triangle->bx, triangle->by, triangle->bw, triangle->bh

where

bx, by is the upper left corner of the box
bw, bh is the width and height of the box

Do I treat my points as coordinates or should I choose a more geometry-based solution?

I tried finding the minimum and maximum values for every coordinate, but it didn't work. Any help would be much appreciated!

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);
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
user6995957
  • 31
  • 1
  • 3

2 Answers2

4

To find the bounds of the box containing a triangle, you simply need to find the smallest and largest x and y coordinates from the three coordinates making up the triangle. You can do the comparisons using ternary expressions, which makes the code a bit less ugly. In the code below, I port the x and y triangle coordinates into separate variables so the ternary expression can be more easily read.

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;
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

i might be late on the question but if you have vectorization you can do :

vec3 v1;
vec3 v2;
vec3 v3;

aabb->min = min(v1,min(v2,v3));
aabb->max = max(v1,max(v2,v3));
Cewein
  • 396
  • 2
  • 14