Skip to content

Instantly share code, notes, and snippets.

@KakCAT
Created February 24, 2022 10:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KakCAT/59d59fbc738831b844896b691fd0259e to your computer and use it in GitHub Desktop.
Save KakCAT/59d59fbc738831b844896b691fd0259e to your computer and use it in GitHub Desktop.
BoundingFrustum test
static void testFunction ()
{
Vector3 camPos,camDir;
// test camera looking into X direction
camPos=new Vector3 (0,0,0);
camDir=new Vector3 (1,0,0);
doFrustumTest (camPos,camDir);
// test camera looking into Z direction
camPos=new Vector3 (0,0,0);
camDir=new Vector3 (0,0,1);
doFrustumTest (camPos,camDir);
// test camera looking into Z direction, slightly looking into the sky
camPos=new Vector3 (0,0,0);
camDir=Vector3.Normalize (new Vector3 (0,0.1f,1));
doFrustumTest (camPos,camDir); // FAILS !! Says box behind camera intersects
}
static void doFrustumTest (Vector3 cameraPos,Vector3 cameraDir)
{
// I use up, but the crossproducts inside CreateLookAt should correct it to the real up (as long as cameraDir is not too steep)
var view = Matrix.CreateLookAt (cameraPos,cameraDir, Vector3.Up);
var projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, 1, 1, 100);
var frustum = new BoundingFrustum(view * projection);
// use a very tall box
Vector3 boxSize=new Vector3 (4,1000,4);
// create a box IN FRONT OF the camera, inside the viewing frustum. It should intersect it because the box is very tall
Vector3 boxPos1=cameraPos + cameraDir*10;
var bbox1 = new BoundingBox (boxPos1-boxSize/2,boxPos1+boxSize/2);
Debug.Assert (frustum.Contains (bbox1) == ContainmentType.Intersects);
// create a box BEHIND the camera. It should be disjoint, because it's behind.
Vector3 boxPos2=cameraPos - cameraDir*10;
var bbox2 = new BoundingBox (boxPos2-boxSize/2,boxPos2+boxSize/2);
Debug.Assert (frustum.Contains (bbox2) == ContainmentType.Disjoint);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment