tomasslavicek

BoundingBox v XNA 4.0

Nov 29th, 2012
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.43 KB | None | 0 0
  1.         /// <summary>
  2.         /// Precalculate model's bounding box (by its vertices + bone transforms)
  3.         /// - inspired by http://dzindzinovic.blogspot.com/2010/05/xna-get-model-vertices-for-boundingbox.html
  4.         /// - BoundingBox can be also loaded by custom Content Pipeline processor (ModelBoundingBoxProcessor)
  5.         /// </summary>
  6.         public static BoundingBox GetBoundingBox(Model model, Matrix[] boneTransforms)
  7.         {
  8.             Vector3 min = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
  9.             Vector3 max = new Vector3(float.MinValue, float.MinValue, float.MinValue);
  10.             model.CopyAbsoluteBoneTransformsTo(boneTransforms);
  11.             List<Vector3> vertices = new List<Vector3>();
  12.  
  13.             foreach (ModelMesh mesh in model.Meshes)
  14.             {
  15.                 // Get the transform of the current mesh
  16.                 Matrix transform = boneTransforms[mesh.ParentBone.Index];
  17.  
  18.                 foreach (ModelMeshPart part in mesh.MeshParts)
  19.                 {
  20.                     // Get the current mesh info
  21.                     int stride = part.VertexBuffer.VertexDeclaration.VertexStride;
  22.                     int numVertices = part.NumVertices;
  23.                     byte[] verticesData = new byte[stride * numVertices];
  24.  
  25.                     part.VertexBuffer.GetData<byte>(verticesData);
  26.  
  27.                     for (int i = 0; i < verticesData.Length; i += stride)
  28.                     {
  29.                         float x = BitConverter.ToSingle(verticesData, i);
  30.                         float y = BitConverter.ToSingle(verticesData, i + sizeof(float));
  31.                         float z = BitConverter.ToSingle(verticesData, i + 2 * sizeof(float));
  32.  
  33.                         // Apply transform to the current point
  34.                         Vector3 vector = new Vector3(x, y, z);
  35.                         vector = Vector3.Transform(vector, transform);
  36.                         vertices.Add(vector);
  37.  
  38.                         if (vector.X < min.X) min.X = vector.X;
  39.                         if (vector.Y < min.Y) min.Y = vector.Y;
  40.                         if (vector.Z < min.Z) min.Z = vector.Z;
  41.                         if (vector.X > max.X) max.X = vector.X;
  42.                         if (vector.Y > max.Y) max.Y = vector.Y;
  43.                         if (vector.Z > max.Z) max.Z = vector.Z;
  44.                     }
  45.                 }
  46.             }
  47.             return new BoundingBox(min, max);
  48.         }
Advertisement
Add Comment
Please, Sign In to add comment