Search code examples
c++mathdirectxdirectx-11directxmath

How to check if object is in viewport Directx 11


I'm trying to check if an object is currently on the screen in directx. I have the view matrix and the projection matrix and the x y z of both the object and the camera.

This seems like a common issue people have but Ive tried looking all over google and cant find anyone talking about this in directx only about javascript stuff.

Im not really sure where to start takling this issue. Im guessing it uses some kind of complex math involving the view matrix and the location of the cube (the object is being translated to world space on the gpu and no scaling or rotation). (im also using c++) Can anyone help?? thanks


Solution

  • For a perspective projection, this is a 'frustum' vs. 'box' bounding-volume intersection test.

    For a orthographic projection, this is a 'box' vs. 'box' bounding-volume intersection test.

    The DirectXMath library (it's also in the Windows SDK) includes functions to perform these tests in the DirectXCollision.h header. Create a BoundingFrustum object instance using your projection matrix from your camera:

    BoundingFrustum fr(proj);
    // use fr(proj, true) if using right-handed instead of left-handed view setup
    

    Create a BoundingBox or BoundingOrientedBox for your object's location:

    BoundingBox box(position, extents);
    

    Then use fr.Contains(box) to see if it returns DISJOINT.

    References for these kinds of computations include:

    • Akenine-Möller, Haines, and Hoffman, "Real-Time Rendering", AK Peters/CRC Press (2018)

    • Ericson, "Real-Time Collision Detection", Morgan Kaufmann (2005)

    • Glassner, "An Introduction to Ray Tracing", Morgan Kaufmann (1989)

    • Schneider and Eberly, "Geometric Tools for Computer Graphics", Morgan Kaufmann (2003)