2xsaiko
2xsaiko

Reputation: 1071

Draw 2d box outline around 3d object

I want to draw a 2d box (smallest possible containing the object) around a 3d object with OpenGL.

Image: https://i.sstatic.net/LINWX.jpg

What I have is:

Camera X/Y/Z/yaw/pitch, Object X/Y/Z/width/height/depth

I can draw on a 2d surface and a 3d surface.

How would I go about this?

Upvotes: 0

Views: 527

Answers (1)

Martin Hennig
Martin Hennig

Reputation: 551

I went here and found a function for getting screen coordinates out of your 3D points:

function point2D get2dPoint(Point3D point3D, Matrix viewMatrix,
             Matrix projectionMatrix, int width, int height) {

  Matrix4 viewProjectionMatrix = projectionMatrix * viewMatrix;
  //transform world to clipping coordinates
  point3D = viewProjectionMatrix.multiply(point3D);
  int winX = (int) Math.round((( point3D.getX() + 1 ) / 2.0) *
                               width );
  //we calculate -point3D.getY() because the screen Y axis is
  //oriented top->down 
  int winY = (int) Math.round((( 1 - point3D.getY() ) / 2.0) *
                               height );
  return new Point2D(winX, winY);
}

If your not sure how to get the matrices:

glGetDoublev (GL_MODELVIEW_MATRIX, mvmatrix);
glGetDoublev (GL_PROJECTION_MATRIX,pjmatrix);

After getting your 2D coordinates you go like this: (pseudo code)

int minX, maxX, minY, maxY;
for each 2dpoint p:
   if (p.x<minX) minX=p.x;
   if (p.x>maxX) maxX=p.x;
   if (p.y<minY) minY=p.y;
   if (p.y>maxY) maxY=p.y;

Then you draw a box with

P1=(minX,minY)
P2=(maxX,minY)
P3=(maxX,maxY)
P4=(minX,maxY)

Upvotes: 1

Related Questions