Exemple #1
0
        private void RequestShapeBlocking(int x, int y, int z, out HkBvCompressedMeshShape shape, out HkReferencePolicy refPolicy)
        {
            ProfilerShort.Begin("MyVoxelPhysicsBody.RequestShapeBlocking");

            const int lod       = 0;
            var       cellCoord = new MyCellCoord(lod, new Vector3I(x, y, z));

            shape = (HkBvCompressedMeshShape)HkShape.Empty;
            // shape must take ownership, otherwise shapes created here will leak, since I can't remove reference
            refPolicy = HkReferencePolicy.TakeOwnership;
            MyPrecalcComponent.QueueJobCancel(m_workTracker, cellCoord.CoordInLod);

            if (m_voxelMap.MarkedForClose)
            {
                ProfilerShort.End();
                return;
            }

            ProfilerShort.Begin("Generating geometry");
            MyIsoMesh geometryData = CreateMesh(m_voxelMap.Storage, cellCoord.CoordInLod);

            ProfilerShort.End();

            if (!MyIsoMesh.IsEmpty(geometryData))
            {
                ProfilerShort.Begin("Shape from geometry");
                shape = CreateShape(geometryData);
                m_needsShapeUpdate = true;
                ProfilerShort.End();
            }

            ProfilerShort.End();
        }
        public override void DoWork()
        {
            ProfilerShort.Begin("MyPrecalcJobPhysicsPrefetch.DoWork");
            try
            {
                if (m_isCancelled)
                {
                    return;
                }

                var geometryData = m_args.TargetPhysics.CreateMesh(m_args.Storage, m_args.GeometryCell);

                if (m_isCancelled)
                {
                    return;
                }

                if (!MyIsoMesh.IsEmpty(geometryData))
                {
                    m_result = m_args.TargetPhysics.CreateShape(geometryData);
                }
            }
            finally
            {
                ProfilerShort.End();
            }
        }
Exemple #3
0
 public override void DoWork()
 {
     try
     {
         if (!this.m_isCancelled)
         {
             using (VrVoxelMesh mesh = this.m_args.TargetPhysics.CreateMesh(this.m_args.GeometryCell))
             {
                 if (!mesh.IsEmpty())
                 {
                     if (!this.m_isCancelled)
                     {
                         this.Result = this.m_args.TargetPhysics.CreateShape(mesh, this.m_args.GeometryCell.Lod);
                     }
                     else
                     {
                         return;
                     }
                 }
             }
             this.ResultComplete = true;
         }
     }
     finally
     {
     }
 }
Exemple #4
0
        private void RequestShapeBlockingInternal(int x, int y, int z, out HkBvCompressedMeshShape shape, out HkReferencePolicy refPolicy, bool lod1physics)
        {
            ProfilerShort.Begin("MyVoxelPhysicsBody.RequestShapeBlocking");

            const int lod       = 0;
            var       cellCoord = new MyCellCoord(lod, new Vector3I(x, y, z));

            shape = (HkBvCompressedMeshShape)HkShape.Empty;
            // shape must take ownership, otherwise shapes created here will leak, since I can't remove reference
            refPolicy = HkReferencePolicy.TakeOwnership;
            MyPrecalcComponent.QueueJobCancel(m_workTracker, cellCoord.CoordInLod);

            if (m_voxelMap.MarkedForClose)
            {
                ProfilerShort.End();
                return;
            }
            //BoundingBoxD aabb;
            //MyVoxelCoordSystems.GeometryCellCoordToWorldAABB(m_voxelMap.PositionLeftBottomCorner, ref cellCoord.CoordInLod, out aabb);
            //MyRenderProxy.DebugDrawAABB(aabb, Color.Red, 1, 1, false);
            ProfilerShort.Begin("Generating geometry");
            MyIsoMesh geometryData = CreateMesh(m_voxelMap.Storage, cellCoord.CoordInLod, lod1physics);

            ProfilerShort.End();

            if (!MyIsoMesh.IsEmpty(geometryData))
            {
                ProfilerShort.Begin("Shape from geometry");
                shape = CreateShape(geometryData);
                m_needsShapeUpdate = true;
                ProfilerShort.End();
            }

            ProfilerShort.End();
        }
Exemple #5
0
        internal HkBvCompressedMeshShape CreateShape(MyIsoMesh mesh)
        {
            // mk:NOTE This method must be thread safe. Called from worker threads.

            if (mesh == null || mesh.TrianglesCount == 0 || mesh.VerticesCount == 0)
            {
                return((HkBvCompressedMeshShape)HkShape.Empty);
            }

            List <int>     indexList  = new List <int>(mesh.TrianglesCount * 3);
            List <Vector3> vertexList = new List <Vector3>(mesh.VerticesCount);

            for (int i = 0; i < mesh.TrianglesCount; i++)
            {
                indexList.Add(mesh.Triangles[i].VertexIndex0);
                indexList.Add(mesh.Triangles[i].VertexIndex2);
                indexList.Add(mesh.Triangles[i].VertexIndex1);
            }

            // mk:TODO Unify denormalizing of positions with what is in MyIsoMesh.
            var positionOffset = mesh.PositionOffset - m_voxelMap.StorageMin * MyVoxelConstants.VOXEL_SIZE_IN_METRES;
            var positions      = mesh.Positions.GetInternalArray();

            for (int i = 0; i < mesh.VerticesCount; i++)
            {
                vertexList.Add(positions[i] * mesh.PositionScale + positionOffset);
            }
            using (var cellGeometry = new HkGeometry(vertexList, indexList))
            {
                var result = new HkBvCompressedMeshShape(cellGeometry, null, null, HkWeldingType.None, MyPerGameSettings.PhysicsConvexRadius);
                Debug.Assert(result.Base.ReferenceCount == 1);
                return(result);
            }
        }
Exemple #6
0
        public bool GetShape(int lod, Vector3D localPos, out HkBvCompressedMeshShape mesh)
        {
            HkUniformGridShape shape = (HkUniformGridShape)this.GetRigidBody(lod).GetShape();

            localPos += this.m_voxelMap.SizeInMetresHalf;
            Vector3I vectori = new Vector3I(localPos / ((double)(8f * (1 << (lod & 0x1f)))));

            return(shape.GetChild(vectori.X, vectori.Y, vectori.Z, out mesh));
        }
Exemple #7
0
 public void UnloadData()
 {
     if (!m_meshShape.Base.IsZero)
     {
         MyPhysics.AssertThread();
         Debug.Assert(m_meshShape.Base.ReferenceCount > 0);
         m_meshShape.Base.RemoveReference();
     }
     m_meshShape = (HkBvCompressedMeshShape)HkShape.Empty;
 }
Exemple #8
0
 internal void OnTaskComplete(Vector3I coord, HkBvCompressedMeshShape childShape)
 {
     Debug.Assert(RigidBody != null, "RigidBody in voxel physics is null! This must not happen.");
     if (RigidBody != null)
     {
         var shape = (HkUniformGridShape)RigidBody.GetShape();
         shape.SetChild(coord.X, coord.Y, coord.Z, childShape, HkReferencePolicy.None);
         m_needsShapeUpdate = true;
     }
 }
Exemple #9
0
 private void RequestShapeBatchBlockingInternal(HkShapeBatch info, bool lod1physics)
 {
     if (!MyPhysics.InsideSimulation && !ReferenceEquals(Thread.CurrentThread, MyUtils.MainThread))
     {
         MyLog.Default.Error("Invalid request shape Thread id: " + Thread.CurrentThread.ManagedThreadId.ToString() + " Stack trace: " + Environment.StackTrace, Array.Empty <object>());
     }
     if (!this.m_voxelMap.MarkedForClose)
     {
         if (!this.m_bodiesInitialized)
         {
             this.CreateRigidBodies();
         }
         this.m_needsShapeUpdate = true;
         int count = info.Count;
         if (((count > 0x4e20) || (Interlocked.Add(ref this.m_voxelQueriesInLastFrames, count) >= 0x2710)) && (Interlocked.Exchange(ref this.m_hasExtendedCache, 1) == 0))
         {
             HkUniformGridShape shape;
             Interlocked.Increment(ref ActiveVoxelPhysicsBodiesWithExtendedCache);
             if (this.GetShape(lod1physics ? 1 : 0, out shape))
             {
                 shape.EnableExtendedCache();
             }
         }
         Parallel.For(0, count, delegate(int i) {
             Vector3I vectori;
             info.GetInfo(i, out vectori);
             int lod = lod1physics ? 1 : 0;
             MyCellCoord geometryCellCoord = new MyCellCoord(lod, vectori);
             if (MyDebugDrawSettings.DEBUG_DRAW_REQUEST_SHAPE_BLOCKING)
             {
                 BoundingBoxD xd;
                 MyVoxelCoordSystems.GeometryCellCoordToWorldAABB(this.m_voxelMap.PositionLeftBottomCorner, ref geometryCellCoord, out xd);
                 MyRenderProxy.DebugDrawAABB(xd, lod1physics ? Color.Yellow : Color.Red, 1f, 1f, false, false, false);
             }
             bool flag = false;
             HkBvCompressedMeshShape empty        = (HkBvCompressedMeshShape)HkShape.Empty;
             MyPrecalcJobPhysicsPrefetch prefetch = this.m_workTracker.Cancel(geometryCellCoord);
             if (((prefetch != null) && prefetch.ResultComplete) && (Interlocked.Exchange(ref prefetch.Taken, 1) == 0))
             {
                 flag  = true;
                 empty = prefetch.Result;
             }
             if (!flag)
             {
                 VrVoxelMesh mesh = this.CreateMesh(geometryCellCoord);
                 empty            = this.CreateShape(mesh, lod);
                 if (mesh != null)
                 {
                     mesh.Dispose();
                 }
             }
             info.SetResult(i, ref empty);
         }, 1, WorkPriority.VeryHigh, new WorkOptions?(Parallel.DefaultOptions.WithDebugInfo(MyProfiler.TaskType.Voxels, "RequestBatch")), true);
     }
 }
Exemple #10
0
 internal void OnTaskComplete(MyCellCoord coord, HkBvCompressedMeshShape childShape)
 {
     if (this.RigidBody != null)
     {
         HkUniformGridShape shape;
         this.GetShape(coord.Lod, out shape);
         shape.SetChild(coord.CoordInLod.X, coord.CoordInLod.Y, coord.CoordInLod.Z, childShape, HkReferencePolicy.None);
         if (!childShape.IsZero)
         {
             this.m_needsShapeUpdate = true;
         }
     }
 }
Exemple #11
0
        internal unsafe HkShape CreateShape(MyIsoMesh mesh, bool simple = false)
        {
            // mk:NOTE This method must be thread safe. Called from worker threads.

            if (mesh == null || mesh.TrianglesCount == 0 || mesh.VerticesCount == 0)
            {
                return(HkShape.Empty);
            }

            if (s_indexList.Capacity < mesh.TrianglesCount * 3)
            {
                s_indexList.Capacity = mesh.TrianglesCount * 3;
            }
            if (s_vertexList.Capacity < mesh.VerticesCount)
            {
                s_vertexList.Capacity = mesh.VerticesCount;
            }

            for (int i = 0; i < mesh.TrianglesCount; i++)
            {
                s_indexList.Add(mesh.Triangles[i].VertexIndex0);
                s_indexList.Add(mesh.Triangles[i].VertexIndex2);
                s_indexList.Add(mesh.Triangles[i].VertexIndex1);
            }

            // mk:TODO Unify denormalizing of positions with what is in MyIsoMesh.
            var positionOffset = mesh.PositionOffset - m_voxelMap.StorageMin * MyVoxelConstants.VOXEL_SIZE_IN_METRES;
            var positions      = mesh.Positions.GetInternalArray();

            for (int i = 0; i < mesh.VerticesCount; i++)
            {
                s_vertexList.Add(positions[i] * mesh.PositionScale + positionOffset);
            }
            {
                HkShape result;
                if (simple)
                {
                    result = new HkSimpleMeshShape(s_vertexList, s_indexList);
                }
                else
                {
                    s_cellGeometry.SetGeometry(s_vertexList, s_indexList);
                    result = new HkBvCompressedMeshShape(s_cellGeometry, null, null, HkWeldingType.None,
                                                         MyPerGameSettings.PhysicsConvexRadius);
                }
                Debug.Assert(result.ReferenceCount == 1);
                s_vertexList.Clear();
                s_indexList.Clear();
                return(result);
            }
        }
Exemple #12
0
 internal void OnTaskComplete(Vector3I coord, HkBvCompressedMeshShape childShape)
 {
     Debug.Assert(RigidBody != null, "RigidBody in voxel physics is null! This must not happen.");
     if (RigidBody != null)
     {
         var shape = (HkUniformGridShape)GetShape();//RigidBody.GetShape();
         Debug.Assert(shape.Base.IsValid);
         shape.SetChild(coord.X, coord.Y, coord.Z, childShape, HkReferencePolicy.None);
         //BoundingBoxD worldAabb;
         //MyVoxelCoordSystems.GeometryCellCoordToWorldAABB(m_voxelMap.PositionLeftBottomCorner, ref coord, out worldAabb);
         //VRageRender.MyRenderProxy.DebugDrawAABB(worldAabb, Color.Green, 1f, 1f, true);
         m_needsShapeUpdate = true;
     }
 }
Exemple #13
0
 internal void OnBatchTaskComplete(Dictionary <Vector3I, HkBvCompressedMeshShape> newShapes, int lod)
 {
     if (this.RigidBody != null)
     {
         HkUniformGridShape shape;
         this.GetShape(lod, out shape);
         bool flag = false;
         foreach (KeyValuePair <Vector3I, HkBvCompressedMeshShape> pair in newShapes)
         {
             Vector3I key = pair.Key;
             HkBvCompressedMeshShape shape2 = pair.Value;
             shape.SetChild(key.X, key.Y, key.Z, shape2, HkReferencePolicy.None);
             flag |= !shape2.IsZero;
         }
         if (flag)
         {
             this.m_needsShapeUpdate = true;
         }
     }
 }
Exemple #14
0
 protected override void OnComplete()
 {
     base.OnComplete();
     if (!this.m_isCancelled && (this.m_args.TargetPhysics.Entity != null))
     {
         this.m_args.TargetPhysics.OnTaskComplete(this.m_args.GeometryCell, this.Result);
     }
     if (!this.m_isCancelled)
     {
         this.m_args.Tracker.Complete(this.m_args.GeometryCell);
     }
     if (!this.Result.Base.IsZero && (this.Taken == 0))
     {
         this.Result.Base.RemoveReference();
     }
     this.Taken          = 0;
     this.m_args         = new Args();
     this.m_isCancelled  = false;
     this.ResultComplete = false;
     this.Result         = (HkBvCompressedMeshShape)HkShape.Empty;
     m_instancePool.Deallocate(this);
 }
        protected override void OnComplete()
        {
            base.OnComplete();

            if (MyPrecalcComponent.Loaded && !m_isCancelled)
            {
                m_args.TargetPhysics.OnTaskComplete(m_args.GeometryCell, m_result);
            }

            if (!m_isCancelled)
            {
                m_args.Tracker.Complete(m_args.GeometryCell);
            }

            if (!m_result.Base.IsZero)
                m_result.Base.RemoveReference();

            m_args = default(Args);
            m_isCancelled = false;
            m_result = (HkBvCompressedMeshShape)HkShape.Empty;
            m_instancePool.Deallocate(this);
        }
        public override void DoWork()
        {
            ProfilerShort.Begin("MyPrecalcJobPhysicsPrefetch.DoWork");
            try
            {
                if (m_isCancelled)
                    return;

                var geometryData = m_args.TargetPhysics.CreateMesh(m_args.Storage, m_args.GeometryCell);

                if (m_isCancelled)
                    return;

                if (!MyIsoMesh.IsEmpty(geometryData))
                {
                    m_result = m_args.TargetPhysics.CreateShape(geometryData);
                }
            }
            finally
            {
                ProfilerShort.End();
            }
        }
Exemple #17
0
            //  This methods needs to be called after every cell cache released!! It releases vertex buffer. It's important,
            //  because when this cell cache will be associated to a new cell, not same material vertex buffer will be used so unused needs to be disposed!!
            public void Reset()
            {
                using (m_syncRoot.AcquireExclusiveUsing())
                {
                    if (!m_meshShape.Base.IsZero)
                    {
                        MyPhysics.AssertThread();
                        Debug.Assert(m_meshShape.Base.ReferenceCount > 0);
                        m_meshShape.Base.RemoveReference();
                    }
                    m_meshShape = (HkBvCompressedMeshShape)HkShape.Empty;

                    VoxelTrianglesCount = 0;
                    VoxelTriangles      = null;
                    m_octree            = null;

                    VoxelVerticesCount = 0;
                    m_voxelVertices    = null;
                    Key = INVALID_KEY;

                    m_octree = null;
                }
            }
Exemple #18
0
            private void CreateMeshShape()
            {
                Profiler.Begin("MyVoxelGeometry.CellData.CreateMeshShape");
                try
                {
                    if (!m_meshShape.Base.IsZero)
                    {
                        return;
                    }

                    List <int>     indexList  = new List <int>(VoxelTrianglesCount * 3);
                    List <Vector3> vertexList = new List <Vector3>(VoxelVerticesCount);

                    for (int i = 0; i < VoxelTrianglesCount; i++)
                    {
                        indexList.Add(VoxelTriangles[i].VertexIndex0);
                        indexList.Add(VoxelTriangles[i].VertexIndex2);
                        indexList.Add(VoxelTriangles[i].VertexIndex1);
                    }
                    Vector3 tmp;
                    for (int i = 0; i < VoxelVerticesCount; i++)
                    {
                        GetUnpackedPosition(ref m_voxelVertices[i], out tmp);
                        vertexList.Add(tmp);
                    }
                    using (var cellGeometry = new HkGeometry(vertexList, indexList))
                    {
                        var newShape = new HkBvCompressedMeshShape(cellGeometry, null, null, HkWeldingType.None);
                        Debug.Assert(newShape.Base.ReferenceCount == 1);
                        m_meshShape = newShape;
                    }
                }
                finally
                {
                    Profiler.End();
                }
            }
        protected override void OnComplete()
        {
            base.OnComplete();

            if (MyPrecalcComponent.Loaded && !m_isCancelled)
            {
                m_args.TargetPhysics.OnTaskComplete(m_args.GeometryCell, m_result);
            }

            if (!m_isCancelled)
            {
                m_args.Tracker.Complete(m_args.GeometryCell);
            }

            if (!m_result.Base.IsZero)
            {
                m_result.Base.RemoveReference();
            }

            m_args        = default(Args);
            m_isCancelled = false;
            m_result      = (HkBvCompressedMeshShape)HkShape.Empty;
            m_instancePool.Deallocate(this);
        }
        private void RequestShapeBlocking(int x, int y, int z, out HkBvCompressedMeshShape shape, out HkReferencePolicy refPolicy)
        {
            ProfilerShort.Begin("MyVoxelPhysicsBody.RequestShapeBlocking");

            const int lod = 0;
            var cellCoord = new MyCellCoord(lod, new Vector3I(x, y, z));
            shape = (HkBvCompressedMeshShape)HkShape.Empty;
            // shape must take ownership, otherwise shapes created here will leak, since I can't remove reference
            refPolicy = HkReferencePolicy.TakeOwnership;
            MyPrecalcComponent.QueueJobCancel(m_workTracker, cellCoord.CoordInLod);

            if (m_voxelMap.MarkedForClose)
            {
                ProfilerShort.End();
                return;
            }

            ProfilerShort.Begin("Generating geometry");
            MyIsoMesh geometryData = CreateMesh(m_voxelMap.Storage, cellCoord.CoordInLod);
            ProfilerShort.End();

            if (!MyIsoMesh.IsEmpty(geometryData))
            {
                ProfilerShort.Begin("Shape from geometry");
                shape = CreateShape(geometryData);
                m_needsShapeUpdate = true;
                ProfilerShort.End();
            }

            ProfilerShort.End();
        }
 internal void OnTaskComplete(Vector3I coord, HkBvCompressedMeshShape childShape)
 {
     Debug.Assert(RigidBody != null, "RigidBody in voxel physics is null! This must not happen.");
     if (RigidBody != null)
     {
         var shape = (HkUniformGridShape)RigidBody.GetShape();
         shape.SetChild(coord.X, coord.Y, coord.Z, childShape, HkReferencePolicy.None);
         m_needsShapeUpdate = true;
     }
 }
 internal void OnTaskComplete(MyCellCoord coord, HkBvCompressedMeshShape childShape)
 {
     Debug.Assert(RigidBody != null, "RigidBody in voxel physics is null! This must not happen.");
     if (RigidBody != null)
     {
         HkUniformGridShape shape = GetShape(coord.Lod);
         Debug.Assert(shape.Base.IsValid);
         shape.SetChild(coord.CoordInLod.X, coord.CoordInLod.Y, coord.CoordInLod.Z, childShape, HkReferencePolicy.None);
         //BoundingBoxD worldAabb;
         //MyVoxelCoordSystems.GeometryCellCoordToWorldAABB(m_voxelMap.PositionLeftBottomCorner, ref coord, out worldAabb);
         //VRageRender.MyRenderProxy.DebugDrawAABB(worldAabb, Color.Green, 1f, 1f, true);
         m_needsShapeUpdate = true;
     }
 }
 private void RequestShapeBlocking(int x, int y, int z, out HkBvCompressedMeshShape shape, out HkReferencePolicy refPolicy)
 {
     RequestShapeBlockingInternal(x, y, z, out shape, out refPolicy, false);
 }
        internal unsafe HkShape CreateShape(MyIsoMesh mesh, bool simple = false)
        {
            // mk:NOTE This method must be thread safe. Called from worker threads.

            if (mesh == null || mesh.TrianglesCount == 0 || mesh.VerticesCount == 0)
                return HkShape.Empty;

            if (s_indexList.Capacity < mesh.TrianglesCount * 3)
                s_indexList.Capacity = mesh.TrianglesCount * 3;
            if (s_vertexList.Capacity < mesh.VerticesCount)
                s_vertexList.Capacity = mesh.VerticesCount;

            for (int i = 0; i < mesh.TrianglesCount; i++)
            {
                s_indexList.Add(mesh.Triangles[i].VertexIndex0);
                s_indexList.Add(mesh.Triangles[i].VertexIndex2);
                s_indexList.Add(mesh.Triangles[i].VertexIndex1);
            }

            // mk:TODO Unify denormalizing of positions with what is in MyIsoMesh.
            var positionOffset = mesh.PositionOffset - m_voxelMap.StorageMin * MyVoxelConstants.VOXEL_SIZE_IN_METRES;
            var positions = mesh.Positions.GetInternalArray();
            for (int i = 0; i < mesh.VerticesCount; i++)
            {
                s_vertexList.Add(positions[i] * mesh.PositionScale + positionOffset);
            }
            {
                HkShape result;
                if (simple)
                {
                    result = new HkSimpleMeshShape(s_vertexList, s_indexList);
                }
                else
                {
                    s_cellGeometry.SetGeometry(s_vertexList, s_indexList);
                    result = new HkBvCompressedMeshShape(s_cellGeometry, null, null, HkWeldingType.None,
                        MyPerGameSettings.PhysicsConvexRadius);

                }
                Debug.Assert(result.ReferenceCount == 1);
                s_vertexList.Clear();
                s_indexList.Clear();
                return result;
            }
        }
            private void CreateMeshShape()
            {
                Profiler.Begin("MyVoxelGeometry.CellData.CreateMeshShape");
                try
                {
                    if (!m_meshShape.Base.IsZero)
                        return;

                    List<int> indexList = new List<int>(VoxelTrianglesCount * 3);
                    List<Vector3> vertexList = new List<Vector3>(VoxelVerticesCount);

                    for (int i = 0; i < VoxelTrianglesCount; i++)
                    {
                        indexList.Add(VoxelTriangles[i].VertexIndex0);
                        indexList.Add(VoxelTriangles[i].VertexIndex2);
                        indexList.Add(VoxelTriangles[i].VertexIndex1);
                    }
                    Vector3 tmp;
                    for (int i = 0; i < VoxelVerticesCount; i++)
                    {
                        GetUnpackedPosition(ref m_voxelVertices[i], out tmp);
                        vertexList.Add(tmp);
                    }
                    using (var cellGeometry = new HkGeometry(vertexList, indexList))
                    {
                        var newShape = new HkBvCompressedMeshShape(cellGeometry, null, null, HkWeldingType.None);
                        Debug.Assert(newShape.Base.ReferenceCount == 1);
                        m_meshShape = newShape;
                    }
                }
                finally
                {
                    Profiler.End();
                }
            }
            //  This methods needs to be called after every cell cache released!! It releases vertex buffer. It's important, 
            //  because when this cell cache will be associated to a new cell, not same material vertex buffer will be used so unused needs to be disposed!!
            public void Reset()
            {
                using (m_syncRoot.AcquireExclusiveUsing())
                {
                    if (!m_meshShape.Base.IsZero)
                    {
                        MyPhysics.AssertThread();
                        Debug.Assert(m_meshShape.Base.ReferenceCount > 0);
                        m_meshShape.Base.RemoveReference();
                    }
                    m_meshShape = (HkBvCompressedMeshShape)HkShape.Empty;

                    VoxelTrianglesCount = 0;
                    VoxelTriangles = null;
                    m_octree = null;

                    VoxelVerticesCount = 0;
                    m_voxelVertices = null;
                    Key = INVALID_KEY;

                    m_octree = null;
                }
            }
        public override bool HandleInput()
        {
            bool handled = false;

            if (m_gridDebugInfo)
            {
                LineD line = new LineD(MySector.MainCamera.Position, MySector.MainCamera.Position + MySector.MainCamera.ForwardVector * 1000);
                MyCubeGrid grid;
                Vector3I cubePos;
                double distance;
                if (MyCubeGrid.GetLineIntersection(ref line, out grid, out cubePos, out distance))
                {
                    var gridMatrix = grid.WorldMatrix;
                    var boxMatrix = Matrix.CreateTranslation(cubePos * grid.GridSize) * gridMatrix;
                    var block = grid.GetCubeBlock(cubePos);

                    MyRenderProxy.DebugDrawText2D(new Vector2(), cubePos.ToString(), Color.White, 0.7f);
                    MyRenderProxy.DebugDrawOBB(Matrix.CreateScale(new Vector3(grid.GridSize) + new Vector3(0.15f)) * boxMatrix, Color.Red.ToVector3(), 0.2f, true, true);

                    //int[, ,] bones = grid.Skeleton.AddCubeBones(cubePos);

                    //Vector3 closestBone = Vector3.Zero;
                    //Vector3I closestPoint = Vector3I.Zero;
                    //float closestPointDist = float.MaxValue;
                    //int closestBoneIndex = 0;

                    //for (int x = -1; x <= 1; x += 1)
                    //{
                    //    for (int y = -1; y <= 1; y += 1)
                    //    {
                    //        for (int z = -1; z <= 1; z += 1)
                    //        {
                    //            int boneIndex = bones[x + 1, y + 1, z + 1];
                    //            Vector3 bone = grid.Skeleton[boneIndex];

                    //            var pos = boxMatrix.Translation + new Vector3(grid.GridSize / 2) * new Vector3(x, y, z);
                    //            //MyRenderProxy.DebugDrawSphere(pos, 0.2f, Color.Blue.ToVector3(), 1.0f, false);
                    //            MyRenderProxy.DebugDrawText3D(pos, String.Format("{0:G2}, {1:G2}, {2:G2}", bone.X, bone.Y, bone.Z), Color.White, 0.5f, false);

                    //            var dist = MyUtils.GetPointLineDistance(ref line, ref pos);
                    //            if (dist < closestPointDist)
                    //            {
                    //                closestPointDist = dist;
                    //                closestPoint = new Vector3I(x, y, z);
                    //                closestBoneIndex = boneIndex;
                    //                closestBone = bone;

                    //            }
                    //        }
                    //    }
                    //}

                    //MyRenderProxy.DebugDrawText3D(boxMatrix.Translation + new Vector3(grid.GridSize / 2) * closestPoint * 1.0f, String.Format("{0:G2}, {1:G2}, {2:G2}", closestBone.X, closestBone.Y, closestBone.Z), Color.Red, 0.5f, false);
                    //var bonePos = grid.Skeleton[bones[closestPoint.X + 1, closestPoint.Y + 1, closestPoint.Z + 1]];
                    //MyRenderProxy.DebugDrawSphere(boxMatrix.Translation + new Vector3(grid.GridSize / 2) * closestPoint * 1.0f + bonePos, 0.5f, Color.Red.ToVector3(), 0.4f, true, true);

                    //if (input.IsNewKeyPressed(Keys.P) && block != null)
                    //{
                    //    if (input.IsAnyShiftKeyPressed())
                    //    {
                    //        grid.ResetBlockSkeleton(block);
                    //    }
                    //    else
                    //    {
                    //        grid.Skeleton[bones[closestPoint.X + 1, closestPoint.Y + 1, closestPoint.Z + 1]] = Vector3.Zero;
                    //        grid.AddDirtyBone(cubePos, closestPoint + Vector3I.One);
                    //        //grid.SetBlockDirty(block);
                    //    }
                    //    handled = true;
                    //}

                    //// Move bones to center by 0.1f
                    //if (input.IsNewKeyPressed(Keys.OemOpenBrackets))
                    //{
                    //    int index = bones[closestPoint.X + 1, closestPoint.Y + 1, closestPoint.Z + 1];
                    //    grid.Skeleton[index] -= Vector3.Sign(grid.Skeleton[index]) * 0.1f;
                    //    grid.AddDirtyBone(cubePos, closestPoint + Vector3I.One);
                    //    //grid.SetBlockDirty(block);
                    //    handled = true;
                    //}

                    //// Reduce max offset by 0.1f
                    //if (input.IsNewKeyPressed(Keys.OemCloseBrackets))
                    //{
                    //    int index = bones[closestPoint.X + 1, closestPoint.Y + 1, closestPoint.Z + 1];
                    //    var old = Vector3.Abs(grid.Skeleton[index]);
                    //    var max = new Vector3(Math.Max(Math.Max(old.X, old.Y), old.Z));
                    //    if (max.X > 0.1f)
                    //    {
                    //        grid.Skeleton[index] = Vector3.Clamp(grid.Skeleton[index], -max + 0.1f, max - 0.1f);
                    //    }
                    //    else
                    //    {
                    //        grid.Skeleton[index] = Vector3.Zero;
                    //    }
                    //    grid.AddDirtyBone(cubePos, closestPoint + Vector3I.One);
                    //    //grid.SetBlockDirty(block);
                    //    handled = true;
                    //}
                }
            }

            if (MyInput.Static.IsAnyAltKeyPressed())
                return handled;

            bool shift = MyInput.Static.IsAnyShiftKeyPressed();
            bool ctrl = MyInput.Static.IsAnyCtrlKeyPressed();

            //if (input.IsNewKeyPressed(Keys.I))
            //{
            //    foreach (var grid in MyEntities.GetEntities().OfType<MyCubeGrid>())
            //    {
            //        foreach (var block in grid.GetBlocks().ToArray())
            //        {
            //            grid.DetectMerge(block.Min, block.Max);
            //        }
            //    }
            //    handled = true;
            //}

            // Disabled since it is common to have normal control bound to O key.
            // If you ever need this again, bind it to something more complicated, like key combination.
            //if (input.IsNewKeyPressed(Keys.O))
            //{
            //    m_gridDebugInfo = !m_gridDebugInfo;
            //    handled = true;
            //}

            //for (int i = 0; i <= 9; i++)
            //{
            //    if (MyInput.Static.IsNewKeyPressed((Keys)(((int)Keys.D0) + i)))
            //    {
            //        string name = "Slot" + i.ToString();
            //        if (ctrl)
            //        {
            //            MySession.Static.Name = name;
            //            MySession.Static.WorldID = MySession.GetNewWorldId();
            //            MySession.Static.Save(name);
            //        }
            //        else if (shift)
            //        {
            //            var path = MyLocalCache.GetSessionSavesPath(name, false, false);
            //            if (System.IO.Directory.Exists(path))
            //            {
            //                MySession.Static.Unload();
            //                MySession.Load(path);
            //            }
            //        }
            //        handled = true;
            //    }
            //}

            //if (MyInput.Static.IsNewKeyPressed(Keys.End))
            //{
            //    MyMeteorShower.MeteorWave(null);
            //}

            // Disabled for god sake!
            //if (MyInput.Static.IsNewKeyPressed(Keys.PageUp) && MyInput.Static.IsAnyCtrlKeyPressed())
            //{
            //    MyReloadTestComponent.Enabled = true;
            //}
            //if (MyInput.Static.IsNewKeyPressed(Keys.PageDown) && MyInput.Static.IsAnyCtrlKeyPressed())
            //{
            //    MyReloadTestComponent.Enabled = false;
            //}

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad6))
            {
                var view = MySession.Static.CameraController.GetViewMatrix();
                var inv = Matrix.Invert(view);

                //MyPhysicalInventoryItem item = new MyPhysicalInventoryItem(100, 
                var oreBuilder = MyObjectBuilderSerializer.CreateNewObject<MyObjectBuilder_Ore>("Stone");
                var item = new MyPhysicalInventoryItem(1, oreBuilder);
                var obj = MyFloatingObjects.Spawn(item, inv.Translation + inv.Forward * 1.0f, inv.Forward, inv.Up);
                obj.Physics.LinearVelocity = inv.Forward * 50;
            }

            if (false && MyInput.Static.IsNewKeyPressed(MyKeys.NumPad9))
            {
                List<HkShape> trShapes = new List<HkShape>();
                List<HkConvexShape> shapes = new List<HkConvexShape>();
                List<Matrix> matrices = new List<Matrix>();

                var grid = new HkGridShape(2.5f, HkReferencePolicy.None);
                const short size = 50;
                for (short x = 0; x < size; x++)
                {
                    for (short y = 0; y < size; y++)
                    {
                        for (short z = 0; z < size; z++)
                        {
                            var box = new HkBoxShape(Vector3.One);
                            grid.AddShapes(new System.Collections.Generic.List<HkShape>() { box }, new Vector3S(x, y, z), new Vector3S(x, y, z));
                            trShapes.Add(new HkConvexTranslateShape(box, new Vector3(x, y, z), HkReferencePolicy.None));
                            shapes.Add(box);
                            matrices.Add(Matrix.CreateTranslation(new Vector3(x, y, z)));
                        }
                    }
                }

                var emptyGeom = new HkGeometry(new List<Vector3>(), new List<int>());

                var list = new HkListShape(trShapes.ToArray(), trShapes.Count, HkReferencePolicy.None);
                var compressedBv = new HkBvCompressedMeshShape(emptyGeom, shapes, matrices, HkWeldingType.None);
                var mopp = new HkMoppBvTreeShape(list, HkReferencePolicy.None);

                HkShapeBuffer buf = new HkShapeBuffer();

                //HkShapeContainerIterator i = compressedBv.GetIterator(buf);
                //int count = 0; // will be 125000
                //while (i.IsValid)
                //{
                //    count++;
                //    i.Next();
                //}                

                buf.Dispose();
                var info = new HkRigidBodyCinfo();
                info.Mass = 10;
                info.CalculateBoxInertiaTensor(Vector3.One, 10);
                info.MotionType = HkMotionType.Dynamic;
                info.QualityType = HkCollidableQualityType.Moving;
                info.Shape = compressedBv;
                var body = new HkRigidBody(info);

                //MyPhysics.HavokWorld.AddRigidBody(body);
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad7))
            {
                foreach (var g in MyEntities.GetEntities().OfType<MyCubeGrid>())
                {
                    foreach (var s in g.CubeBlocks.Select(s => s.FatBlock).Where(s => s != null).OfType<MyMotorStator>())
                    {
                        if (s.Rotor != null)
                        {
                            var q = Quaternion.CreateFromAxisAngle(s.Rotor.WorldMatrix.Up, MathHelper.ToRadians(45));
                            s.Rotor.CubeGrid.WorldMatrix = MatrixD.CreateFromQuaternion(q) * s.Rotor.CubeGrid.WorldMatrix;
                        }
                    }
                }
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad8))
            {
                var view = MySession.Static.CameraController.GetViewMatrix();
                var inv = Matrix.Invert(view);

                var oreBuilder = MyObjectBuilderSerializer.CreateNewObject<MyObjectBuilder_Ore>("Stone");
                var obj = new MyObjectBuilder_FloatingObject() { Item = new MyObjectBuilder_InventoryItem() { Content = oreBuilder, Amount = 1000 } };
                obj.PositionAndOrientation = new MyPositionAndOrientation(inv.Translation + 2.0f * inv.Forward, inv.Forward, inv.Up);
                obj.PersistentFlags = MyPersistentEntityFlags2.InScene;
                var e = MyEntities.CreateFromObjectBuilderAndAdd(obj);
                e.Physics.LinearVelocity = Vector3.Normalize(inv.Forward) * 50.0f;
            }


            if (MyInput.Static.IsNewKeyPressed(MyKeys.Divide))
            {
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.Multiply))
            {
                MyDebugDrawSettings.ENABLE_DEBUG_DRAW = !MyDebugDrawSettings.ENABLE_DEBUG_DRAW;
                MyStructuralIntegrity.Enabled = true;
                MyDebugDrawSettings.DEBUG_DRAW_STRUCTURAL_INTEGRITY = true;

                var grids = MyEntities.GetEntities().OfType<MyCubeGrid>();
                foreach (var g in grids)
                {
                    if (!g.IsStatic)// || g.GetBlocks().Count < 800) //to compute only castle
                        continue;

                    g.CreateStructuralIntegrity();
                }
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad1))
            {
                var e = MyEntities.GetEntities().OfType<MyCubeGrid>().FirstOrDefault();
                if (e != null)
                {
                    e.Physics.RigidBody.MaxLinearVelocity = 1000;
                    if (e.Physics.RigidBody2 != null)
                        e.Physics.RigidBody2.MaxLinearVelocity = 1000;

                    e.Physics.LinearVelocity = new Vector3(1000, 0, 0);
                }
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.Decimal))
            {
                MyPrefabManager.Static.SpawnPrefab("respawnship", MySector.MainCamera.Position, MySector.MainCamera.ForwardVector, MySector.MainCamera.UpVector);
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.Multiply) && MyInput.Static.IsAnyShiftKeyPressed())
            {
                GC.Collect(2);
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad5))
            {
                Thread.Sleep(250);
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad9))
            {
                var obj = MySession.ControlledEntity != null ? MySession.ControlledEntity.Entity : null;
                if (obj != null)
                {
                    const float dist = 5.0f;
                    obj.PositionComp.SetPosition(obj.PositionComp.GetPosition() + obj.WorldMatrix.Forward * dist);
                }
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad4))
            {
                IMyInventoryOwner invObject = MySession.ControlledEntity as IMyInventoryOwner;
                if (invObject != null)
                {
                    MyFixedPoint amount = 20000;

                    var oreBuilder = MyObjectBuilderSerializer.CreateNewObject<MyObjectBuilder_Ore>("Stone");
                    MyInventory inventory = invObject.GetInventory(0);
                    inventory.AddItems(amount, oreBuilder);
                }

                handled = true;
            }

            //if (MyInput.Static.IsNewKeyPressed(Keys.NumPad8))
            //{
            //    var pos = MySector.MainCamera.Position + MySector.MainCamera.ForwardVector * 2;
            //    var grid = (MyObjectBuilder_CubeGrid)MyObjectBuilderSerializer.CreateNewObject(MyObjectBuilderTypeEnum.CubeGrid);
            //    grid.PositionAndOrientation = new MyPositionAndOrientation(pos, Vector3.Forward, Vector3.Up);
            //    grid.CubeBlocks = new List<MyObjectBuilder_CubeBlock>();
            //    grid.GridSizeEnum = MyCubeSize.Large;

            //    var block = new MyObjectBuilder_CubeBlock();
            //    block.BlockOrientation = MyBlockOrientation.Identity;
            //    block.Min = Vector3I.Zero;
            //    //var blockDefinition = Sandbox.Game.Managers.MyDefinitionManager.Static.GetCubeBlockDefinition(new CommonLib.ObjectBuilders.Definitions.MyDefinitionId(typeof(MyObjectBuilder_CubeBlock), "LargeBlockArmorBlock"));
            //    block.SubtypeName = "LargeBlockArmorBlock";
            //    grid.CubeBlocks.Add(block);
            //    grid.LinearVelocity = MySector.MainCamera.ForwardVector * 20;
            //    grid.PersistentFlags = MyPersistentEntityFlags2.Enabled | MyPersistentEntityFlags2.InScene;

            //    var x = MyEntities.CreateFromObjectBuilderAndAdd(grid);
            //}

            //if (MyInput.Static.IsNewKeyPressed(Keys.NumPad9))
            //{
            //    var pos = MySector.MainCamera.Position + MySector.MainCamera.ForwardVector * 2;
            //    var grid =  (MyObjectBuilder_CubeGrid)MyObjectBuilderSerializer.CreateNewObject(MyObjectBuilderTypeEnum.CubeGrid);
            //    grid.PositionAndOrientation = new MyPositionAndOrientation(pos, Vector3.Forward, Vector3.Up);
            //    grid.CubeBlocks = new List<MyObjectBuilder_CubeBlock>();
            //    grid.GridSizeEnum = MyCubeSize.Large;

            //    var block = new MyObjectBuilder_CubeBlock();
            //    block.BlockOrientation = MyBlockOrientation.Identity;
            //    block.Min = Vector3I.Zero;
            //    //var blockDefinition = Sandbox.Game.Managers.MyDefinitionManager.Static.GetCubeBlockDefinition(new CommonLib.ObjectBuilders.Definitions.MyDefinitionId(typeof(MyObjectBuilder_CubeBlock), "LargeBlockArmorBlock"));
            //    block.SubtypeName = "LargeBlockGyro";
            //    grid.CubeBlocks.Add(block);
            //    grid.LinearVelocity = MySector.MainCamera.ForwardVector * 20;
            //    grid.PersistentFlags = MyPersistentEntityFlags2.Enabled | MyPersistentEntityFlags2.InScene;

            //    var x = MyEntities.CreateFromObjectBuilderAndAdd(grid);
            //}

            if (MyInput.Static.IsAnyCtrlKeyPressed() && MyInput.Static.IsNewKeyPressed(MyKeys.Delete))
            {
                int count = MyEntities.GetEntities().OfType<MyFloatingObject>().Count();
                foreach (var obj in MyEntities.GetEntities().OfType<MyFloatingObject>())
                {
                    if (obj == MySession.ControlledEntity)
                    {
                        MySession.SetCameraController(MyCameraControllerEnum.Spectator);
                    }
                    obj.Close();
                }
                handled = true;
            }

            if (MyInput.Static.IsAnyCtrlKeyPressed() && MyInput.Static.IsNewKeyPressed(MyKeys.Decimal))
            {
                foreach (var obj in MyEntities.GetEntities())
                {
                    if (obj != MySession.ControlledEntity && (MySession.ControlledEntity == null || obj != MySession.ControlledEntity.Entity.Parent) && obj != MyCubeBuilder.Static.FindClosestGrid())
                        obj.Close();
                }
                handled = true;
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad9) || MyInput.Static.IsNewKeyPressed(MyKeys.NumPad5))
            {
                //MyCubeGrid.UserCollisions = input.IsNewKeyPressed(Keys.NumPad9);

                var body = MySession.ControlledEntity.Entity.GetTopMostParent().Physics;
                if (body.RigidBody != null)
                {
                    //body.AddForce(Engine.Physics.MyPhysicsForceType.ADD_BODY_FORCE_AND_BODY_TORQUE, new Vector3(0, 0, 10 * body.Mass), null, null);
                    body.RigidBody.ApplyLinearImpulse(body.Entity.WorldMatrix.Forward * body.Mass * 2);
                }
                handled = true;
            }

            //if (input.IsNewKeyPressed(Keys.J) && input.IsAnyCtrlKeyPressed())
            //{
            //    MyGlobalInputComponent.CopyCurrentGridToClipboard();

            //    MyEntity addedEntity = MyGlobalInputComponent.PasteEntityFromClipboard();

            //    if (addedEntity != null)
            //    {
            //        Vector3 pos = addedEntity.GetPosition();
            //        pos.Z += addedEntity.WorldVolume.Radius * 1.5f;
            //        addedEntity.SetPosition(pos);
            //    }
            //    handled = true;
            //}

            if (MyInput.Static.IsAnyCtrlKeyPressed() && MyInput.Static.IsNewKeyPressed(MyKeys.OemComma))
            {
                foreach (var e in MyEntities.GetEntities().OfType<MyFloatingObject>().ToArray())
                    e.Close();
            }
            
            return handled;
        }
        public override bool HandleInput()
        {
            bool handled = false;

            if (m_gridDebugInfo)
            {
                LineD      line = new LineD(MySector.MainCamera.Position, MySector.MainCamera.Position + MySector.MainCamera.ForwardVector * 1000);
                MyCubeGrid grid;
                Vector3I   cubePos;
                double     distance;
                if (MyCubeGrid.GetLineIntersection(ref line, out grid, out cubePos, out distance))
                {
                    var gridMatrix = grid.WorldMatrix;
                    var boxMatrix  = Matrix.CreateTranslation(cubePos * grid.GridSize) * gridMatrix;
                    var block      = grid.GetCubeBlock(cubePos);

                    MyRenderProxy.DebugDrawText2D(new Vector2(), cubePos.ToString(), Color.White, 0.7f);
                    MyRenderProxy.DebugDrawOBB(Matrix.CreateScale(new Vector3(grid.GridSize) + new Vector3(0.15f)) * boxMatrix, Color.Red.ToVector3(), 0.2f, true, true);

                    //int[, ,] bones = grid.Skeleton.AddCubeBones(cubePos);

                    //Vector3 closestBone = Vector3.Zero;
                    //Vector3I closestPoint = Vector3I.Zero;
                    //float closestPointDist = float.MaxValue;
                    //int closestBoneIndex = 0;

                    //for (int x = -1; x <= 1; x += 1)
                    //{
                    //    for (int y = -1; y <= 1; y += 1)
                    //    {
                    //        for (int z = -1; z <= 1; z += 1)
                    //        {
                    //            int boneIndex = bones[x + 1, y + 1, z + 1];
                    //            Vector3 bone = grid.Skeleton[boneIndex];

                    //            var pos = boxMatrix.Translation + new Vector3(grid.GridSize / 2) * new Vector3(x, y, z);
                    //            //MyRenderProxy.DebugDrawSphere(pos, 0.2f, Color.Blue.ToVector3(), 1.0f, false);
                    //            MyRenderProxy.DebugDrawText3D(pos, String.Format("{0:G2}, {1:G2}, {2:G2}", bone.X, bone.Y, bone.Z), Color.White, 0.5f, false);

                    //            var dist = MyUtils.GetPointLineDistance(ref line, ref pos);
                    //            if (dist < closestPointDist)
                    //            {
                    //                closestPointDist = dist;
                    //                closestPoint = new Vector3I(x, y, z);
                    //                closestBoneIndex = boneIndex;
                    //                closestBone = bone;

                    //            }
                    //        }
                    //    }
                    //}

                    //MyRenderProxy.DebugDrawText3D(boxMatrix.Translation + new Vector3(grid.GridSize / 2) * closestPoint * 1.0f, String.Format("{0:G2}, {1:G2}, {2:G2}", closestBone.X, closestBone.Y, closestBone.Z), Color.Red, 0.5f, false);
                    //var bonePos = grid.Skeleton[bones[closestPoint.X + 1, closestPoint.Y + 1, closestPoint.Z + 1]];
                    //MyRenderProxy.DebugDrawSphere(boxMatrix.Translation + new Vector3(grid.GridSize / 2) * closestPoint * 1.0f + bonePos, 0.5f, Color.Red.ToVector3(), 0.4f, true, true);

                    //if (input.IsNewKeyPressed(Keys.P) && block != null)
                    //{
                    //    if (input.IsAnyShiftKeyPressed())
                    //    {
                    //        grid.ResetBlockSkeleton(block);
                    //    }
                    //    else
                    //    {
                    //        grid.Skeleton[bones[closestPoint.X + 1, closestPoint.Y + 1, closestPoint.Z + 1]] = Vector3.Zero;
                    //        grid.AddDirtyBone(cubePos, closestPoint + Vector3I.One);
                    //        //grid.SetBlockDirty(block);
                    //    }
                    //    handled = true;
                    //}

                    //// Move bones to center by 0.1f
                    //if (input.IsNewKeyPressed(Keys.OemOpenBrackets))
                    //{
                    //    int index = bones[closestPoint.X + 1, closestPoint.Y + 1, closestPoint.Z + 1];
                    //    grid.Skeleton[index] -= Vector3.Sign(grid.Skeleton[index]) * 0.1f;
                    //    grid.AddDirtyBone(cubePos, closestPoint + Vector3I.One);
                    //    //grid.SetBlockDirty(block);
                    //    handled = true;
                    //}

                    //// Reduce max offset by 0.1f
                    //if (input.IsNewKeyPressed(Keys.OemCloseBrackets))
                    //{
                    //    int index = bones[closestPoint.X + 1, closestPoint.Y + 1, closestPoint.Z + 1];
                    //    var old = Vector3.Abs(grid.Skeleton[index]);
                    //    var max = new Vector3(Math.Max(Math.Max(old.X, old.Y), old.Z));
                    //    if (max.X > 0.1f)
                    //    {
                    //        grid.Skeleton[index] = Vector3.Clamp(grid.Skeleton[index], -max + 0.1f, max - 0.1f);
                    //    }
                    //    else
                    //    {
                    //        grid.Skeleton[index] = Vector3.Zero;
                    //    }
                    //    grid.AddDirtyBone(cubePos, closestPoint + Vector3I.One);
                    //    //grid.SetBlockDirty(block);
                    //    handled = true;
                    //}
                }
            }

            if (MyInput.Static.IsAnyAltKeyPressed())
            {
                return(handled);
            }

            bool shift = MyInput.Static.IsAnyShiftKeyPressed();
            bool ctrl  = MyInput.Static.IsAnyCtrlKeyPressed();

            //if (input.IsNewKeyPressed(Keys.I))
            //{
            //    foreach (var grid in MyEntities.GetEntities().OfType<MyCubeGrid>())
            //    {
            //        foreach (var block in grid.GetBlocks().ToArray())
            //        {
            //            grid.DetectMerge(block.Min, block.Max);
            //        }
            //    }
            //    handled = true;
            //}

            // Disabled since it is common to have normal control bound to O key.
            // If you ever need this again, bind it to something more complicated, like key combination.
            //if (input.IsNewKeyPressed(Keys.O))
            //{
            //    m_gridDebugInfo = !m_gridDebugInfo;
            //    handled = true;
            //}

            //for (int i = 0; i <= 9; i++)
            //{
            //    if (MyInput.Static.IsNewKeyPressed((Keys)(((int)Keys.D0) + i)))
            //    {
            //        string name = "Slot" + i.ToString();
            //        if (ctrl)
            //        {
            //            MySession.Static.Name = name;
            //            MySession.Static.WorldID = MySession.Static.GetNewWorldId();
            //            MySession.Static.Save(name);
            //        }
            //        else if (shift)
            //        {
            //            var path = MyLocalCache.GetSessionSavesPath(name, false, false);
            //            if (System.IO.Directory.Exists(path))
            //            {
            //                MySession.Static.Unload();
            //                MySession.Static.Load(path);
            //            }
            //        }
            //        handled = true;
            //    }
            //}

            //if (MyInput.Static.IsNewKeyPressed(Keys.End))
            //{
            //    MyMeteorShower.MeteorWave(null);
            //}

            // Disabled for god sake!
            //if (MyInput.Static.IsNewKeyPressed(Keys.PageUp) && MyInput.Static.IsAnyCtrlKeyPressed())
            //{
            //    MyReloadTestComponent.Enabled = true;
            //}
            //if (MyInput.Static.IsNewKeyPressed(Keys.PageDown) && MyInput.Static.IsAnyCtrlKeyPressed())
            //{
            //    MyReloadTestComponent.Enabled = false;
            //}

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad6))
            {
                var view = MySession.Static.CameraController.GetViewMatrix();
                var inv  = Matrix.Invert(view);

                //MyPhysicalInventoryItem item = new MyPhysicalInventoryItem(100,
                var oreBuilder = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Ore>("Stone");
                var item       = new MyPhysicalInventoryItem(1, oreBuilder);
                var obj        = MyFloatingObjects.Spawn(item, inv.Translation + inv.Forward * 1.0f, inv.Forward, inv.Up);
                obj.Physics.LinearVelocity = inv.Forward * 50;
            }

            if (false && MyInput.Static.IsNewKeyPressed(MyKeys.NumPad9))
            {
                List <HkShape>       trShapes = new List <HkShape>();
                List <HkConvexShape> shapes   = new List <HkConvexShape>();
                List <Matrix>        matrices = new List <Matrix>();

                var         grid = new HkGridShape(2.5f, HkReferencePolicy.None);
                const short size = 50;
                for (short x = 0; x < size; x++)
                {
                    for (short y = 0; y < size; y++)
                    {
                        for (short z = 0; z < size; z++)
                        {
                            var box = new HkBoxShape(Vector3.One);
                            grid.AddShapes(new System.Collections.Generic.List <HkShape>()
                            {
                                box
                            }, new Vector3S(x, y, z), new Vector3S(x, y, z));
                            trShapes.Add(new HkConvexTranslateShape(box, new Vector3(x, y, z), HkReferencePolicy.None));
                            shapes.Add(box);
                            matrices.Add(Matrix.CreateTranslation(new Vector3(x, y, z)));
                        }
                    }
                }

                var emptyGeom = new HkGeometry(new List <Vector3>(), new List <int>());

                var list         = new HkListShape(trShapes.ToArray(), trShapes.Count, HkReferencePolicy.None);
                var compressedBv = new HkBvCompressedMeshShape(emptyGeom, shapes, matrices, HkWeldingType.None);
                var mopp         = new HkMoppBvTreeShape(list, HkReferencePolicy.None);

                HkShapeBuffer buf = new HkShapeBuffer();

                //HkShapeContainerIterator i = compressedBv.GetIterator(buf);
                //int count = 0; // will be 125000
                //while (i.IsValid)
                //{
                //    count++;
                //    i.Next();
                //}

                buf.Dispose();
                var info = new HkRigidBodyCinfo();
                info.Mass = 10;
                info.CalculateBoxInertiaTensor(Vector3.One, 10);
                info.MotionType  = HkMotionType.Dynamic;
                info.QualityType = HkCollidableQualityType.Moving;
                info.Shape       = compressedBv;
                var body = new HkRigidBody(info);

                //MyPhysics.HavokWorld.AddRigidBody(body);
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad7))
            {
                foreach (var g in MyEntities.GetEntities().OfType <MyCubeGrid>())
                {
                    foreach (var s in g.CubeBlocks.Select(s => s.FatBlock).Where(s => s != null).OfType <MyMotorStator>())
                    {
                        if (s.Rotor != null)
                        {
                            var q = Quaternion.CreateFromAxisAngle(s.Rotor.WorldMatrix.Up, MathHelper.ToRadians(45));
                            s.Rotor.CubeGrid.WorldMatrix = MatrixD.CreateFromQuaternion(q) * s.Rotor.CubeGrid.WorldMatrix;
                        }
                    }
                }
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad8))
            {
                var view = MySession.Static.CameraController.GetViewMatrix();
                var inv  = Matrix.Invert(view);

                var oreBuilder = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Ore>("Stone");
                var obj        = new MyObjectBuilder_FloatingObject()
                {
                    Item = new MyObjectBuilder_InventoryItem()
                    {
                        PhysicalContent = oreBuilder, Amount = 1000
                    }
                };
                obj.PositionAndOrientation = new MyPositionAndOrientation(inv.Translation + 2.0f * inv.Forward, inv.Forward, inv.Up);
                obj.PersistentFlags        = MyPersistentEntityFlags2.InScene;
                var e = MyEntities.CreateFromObjectBuilderAndAdd(obj);
                e.Physics.LinearVelocity = Vector3.Normalize(inv.Forward) * 50.0f;
            }


            if (MyInput.Static.IsNewKeyPressed(MyKeys.Divide))
            {
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.Multiply))
            {
                MyDebugDrawSettings.ENABLE_DEBUG_DRAW = !MyDebugDrawSettings.ENABLE_DEBUG_DRAW;
                MyDebugDrawSettings.DEBUG_DRAW_STRUCTURAL_INTEGRITY = true;

                var grids = MyEntities.GetEntities().OfType <MyCubeGrid>();
                foreach (var g in grids)
                {
                    if (!g.IsStatic)// || g.GetBlocks().Count < 800) //to compute only castle
                    {
                        continue;
                    }

                    g.CreateStructuralIntegrity();
                }
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad1))
            {
                var e = MyEntities.GetEntities().OfType <MyCubeGrid>().FirstOrDefault();
                if (e != null)
                {
                    e.Physics.RigidBody.MaxLinearVelocity = 1000;
                    if (e.Physics.RigidBody2 != null)
                    {
                        e.Physics.RigidBody2.MaxLinearVelocity = 1000;
                    }

                    e.Physics.LinearVelocity = new Vector3(1000, 0, 0);
                }
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.Decimal))
            {
                MyPrefabManager.Static.SpawnPrefab("respawnship", MySector.MainCamera.Position, MySector.MainCamera.ForwardVector, MySector.MainCamera.UpVector);
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.Multiply) && MyInput.Static.IsAnyShiftKeyPressed())
            {
                GC.Collect(2);
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad5))
            {
                Thread.Sleep(250);
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad9))
            {
                var obj = MySession.Static.ControlledEntity != null ? MySession.Static.ControlledEntity.Entity : null;
                if (obj != null)
                {
                    const float dist = 5.0f;
                    obj.PositionComp.SetPosition(obj.PositionComp.GetPosition() + obj.WorldMatrix.Forward * dist);
                }
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad4))
            {
                MyEntity invObject = MySession.Static.ControlledEntity as MyEntity;
                if (invObject != null && invObject.HasInventory)
                {
                    MyFixedPoint amount = 20000;

                    var         oreBuilder = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Ore>("Stone");
                    MyInventory inventory  = invObject.GetInventory(0) as MyInventory;
                    System.Diagnostics.Debug.Assert(inventory != null, "Null or unexpected type returned!");
                    inventory.AddItems(amount, oreBuilder);
                }

                handled = true;
            }

            //if (MyInput.Static.IsNewKeyPressed(Keys.NumPad8))
            //{
            //    var pos = MySector.MainCamera.Position + MySector.MainCamera.ForwardVector * 2;
            //    var grid = (MyObjectBuilder_CubeGrid)MyObjectBuilderSerializer.CreateNewObject(MyObjectBuilderTypeEnum.CubeGrid);
            //    grid.PositionAndOrientation = new MyPositionAndOrientation(pos, Vector3.Forward, Vector3.Up);
            //    grid.CubeBlocks = new List<MyObjectBuilder_CubeBlock>();
            //    grid.GridSizeEnum = MyCubeSize.Large;

            //    var block = new MyObjectBuilder_CubeBlock();
            //    block.BlockOrientation = MyBlockOrientation.Identity;
            //    block.Min = Vector3I.Zero;
            //    //var blockDefinition = Sandbox.Game.Managers.MyDefinitionManager.Static.GetCubeBlockDefinition(new CommonLib.ObjectBuilders.Definitions.MyDefinitionId(typeof(MyObjectBuilder_CubeBlock), "LargeBlockArmorBlock"));
            //    block.SubtypeName = "LargeBlockArmorBlock";
            //    grid.CubeBlocks.Add(block);
            //    grid.LinearVelocity = MySector.MainCamera.ForwardVector * 20;
            //    grid.PersistentFlags = MyPersistentEntityFlags2.Enabled | MyPersistentEntityFlags2.InScene;

            //    var x = MyEntities.CreateFromObjectBuilderAndAdd(grid);
            //}

            //if (MyInput.Static.IsNewKeyPressed(Keys.NumPad9))
            //{
            //    var pos = MySector.MainCamera.Position + MySector.MainCamera.ForwardVector * 2;
            //    var grid =  (MyObjectBuilder_CubeGrid)MyObjectBuilderSerializer.CreateNewObject(MyObjectBuilderTypeEnum.CubeGrid);
            //    grid.PositionAndOrientation = new MyPositionAndOrientation(pos, Vector3.Forward, Vector3.Up);
            //    grid.CubeBlocks = new List<MyObjectBuilder_CubeBlock>();
            //    grid.GridSizeEnum = MyCubeSize.Large;

            //    var block = new MyObjectBuilder_CubeBlock();
            //    block.BlockOrientation = MyBlockOrientation.Identity;
            //    block.Min = Vector3I.Zero;
            //    //var blockDefinition = Sandbox.Game.Managers.MyDefinitionManager.Static.GetCubeBlockDefinition(new CommonLib.ObjectBuilders.Definitions.MyDefinitionId(typeof(MyObjectBuilder_CubeBlock), "LargeBlockArmorBlock"));
            //    block.SubtypeName = "LargeBlockGyro";
            //    grid.CubeBlocks.Add(block);
            //    grid.LinearVelocity = MySector.MainCamera.ForwardVector * 20;
            //    grid.PersistentFlags = MyPersistentEntityFlags2.Enabled | MyPersistentEntityFlags2.InScene;

            //    var x = MyEntities.CreateFromObjectBuilderAndAdd(grid);
            //}

            if (MyInput.Static.IsAnyCtrlKeyPressed() && MyInput.Static.IsNewKeyPressed(MyKeys.Delete))
            {
                int count = MyEntities.GetEntities().OfType <MyFloatingObject>().Count();
                foreach (var obj in MyEntities.GetEntities().OfType <MyFloatingObject>())
                {
                    if (obj == MySession.Static.ControlledEntity)
                    {
                        MySession.Static.SetCameraController(MyCameraControllerEnum.Spectator);
                    }
                    obj.Close();
                }
                handled = true;
            }

            if (MyInput.Static.IsAnyCtrlKeyPressed() && MyInput.Static.IsNewKeyPressed(MyKeys.Decimal))
            {
                foreach (var obj in MyEntities.GetEntities())
                {
                    if (obj != MySession.Static.ControlledEntity && (MySession.Static.ControlledEntity == null || obj != MySession.Static.ControlledEntity.Entity.Parent) && obj != MyCubeBuilder.Static.FindClosestGrid())
                    {
                        obj.Close();
                    }
                }
                handled = true;
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad9) || MyInput.Static.IsNewKeyPressed(MyKeys.NumPad5))
            {
                //MyCubeGrid.UserCollisions = input.IsNewKeyPressed(Keys.NumPad9);

                var body = MySession.Static.ControlledEntity.Entity.GetTopMostParent().Physics;
                if (body.RigidBody != null)
                {
                    //body.AddForce(Engine.Physics.MyPhysicsForceType.ADD_BODY_FORCE_AND_BODY_TORQUE, new Vector3(0, 0, 10 * body.Mass), null, null);
                    body.RigidBody.ApplyLinearImpulse(body.Entity.WorldMatrix.Forward * body.Mass * 2);
                }
                handled = true;
            }

            //if (input.IsNewKeyPressed(Keys.J) && input.IsAnyCtrlKeyPressed())
            //{
            //    MyGlobalInputComponent.CopyCurrentGridToClipboard();

            //    MyEntity addedEntity = MyGlobalInputComponent.PasteEntityFromClipboard();

            //    if (addedEntity != null)
            //    {
            //        Vector3 pos = addedEntity.GetPosition();
            //        pos.Z += addedEntity.WorldVolume.Radius * 1.5f;
            //        addedEntity.SetPosition(pos);
            //    }
            //    handled = true;
            //}

            if (MyInput.Static.IsAnyCtrlKeyPressed() && MyInput.Static.IsNewKeyPressed(MyKeys.OemComma))
            {
                foreach (var e in MyEntities.GetEntities().OfType <MyFloatingObject>().ToArray())
                {
                    e.Close();
                }
            }

            return(handled);
        }
Exemple #29
0
 private void RequestShapeBlocking(int x, int y, int z, out HkBvCompressedMeshShape shape, out HkReferencePolicy refPolicy)
 {
     RequestShapeBlockingInternal(x, y, z, out shape, out refPolicy, false);
 }
        private void RequestShapeBlockingInternal(int x, int y, int z, out HkBvCompressedMeshShape shape, out HkReferencePolicy refPolicy, bool lod1physics)
        {
            ProfilerShort.Begin("MyVoxelPhysicsBody.RequestShapeBlocking");

            if (!m_bodiesInitialized) CreateRigidBodies();

            int lod = lod1physics ? 1 : 0;
            var cellCoord = new MyCellCoord(lod, new Vector3I(x, y, z));
            shape = (HkBvCompressedMeshShape)HkShape.Empty;
            // shape must take ownership, otherwise shapes created here will leak, since I can't remove reference
            refPolicy = HkReferencePolicy.TakeOwnership;
            MyPrecalcComponent.QueueJobCancel(m_workTracker, cellCoord);

            if (m_voxelMap.MarkedForClose)
            {
                ProfilerShort.End();
                return;
            }
            if (MyDebugDrawSettings.DEBUG_DRAW_REQUEST_SHAPE_BLOCKING)
            {
                BoundingBoxD aabb;
                MyVoxelCoordSystems.GeometryCellCoordToWorldAABB(m_voxelMap.PositionLeftBottomCorner, ref cellCoord, out aabb);
                MyRenderProxy.DebugDrawAABB(aabb, lod1physics ? Color.Yellow : Color.Red, 1, 1, true);
            }
            ProfilerShort.Begin("Generating geometry");
            MyIsoMesh geometryData = CreateMesh(m_voxelMap.Storage, cellCoord);
            ProfilerShort.End();

            if (!MyIsoMesh.IsEmpty(geometryData))
            {
                ProfilerShort.Begin("Shape from geometry");
                shape = CreateShape(geometryData);
                m_needsShapeUpdate = true;
                ProfilerShort.End();
            }

            ProfilerShort.End();
        }
Exemple #31
0
        internal unsafe HkBvCompressedMeshShape CreateShape(VrVoxelMesh mesh, int lod)
        {
            HkBvCompressedMeshShape shape;

            if (((mesh == null) || (mesh.TriangleCount == 0)) || (mesh.VertexCount == 0))
            {
                return((HkBvCompressedMeshShape)HkShape.Empty);
            }
            using (MyUtils.ReuseCollection <int>(ref m_indexListCached))
            {
                using (MyUtils.ReuseCollection <Vector3>(ref m_vertexListCached))
                {
                    using (MyUtils.ReuseCollection <byte>(ref m_materialListCached))
                    {
                        List <int>     indexListCached    = m_indexListCached;
                        List <Vector3> vertexListCached   = m_vertexListCached;
                        List <byte>    materialListCached = m_materialListCached;
                        vertexListCached.EnsureCapacity <Vector3>(mesh.VertexCount);
                        indexListCached.EnsureCapacity <int>(mesh.TriangleCount * 3);
                        materialListCached.EnsureCapacity <byte>(mesh.TriangleCount);
                        int index = 0;
                        while (true)
                        {
                            if (index >= mesh.TriangleCount)
                            {
                                float          scale    = mesh.Scale;
                                VrVoxelVertex *vertices = mesh.Vertices;
                                Vector3        vector   = (Vector3)((mesh.Start * scale) - (this.m_voxelMap.StorageMin * 1f));
                                int            num4     = 0;
                                while (true)
                                {
                                    if (num4 >= mesh.VertexCount)
                                    {
                                        uint userData = 0xfffffffe;
                                        int  num5     = 0;
                                        while (true)
                                        {
                                            if (num5 >= mesh.TriangleCount)
                                            {
                                                int[] pinned numArray;
                                                try
                                                {
                                                    int *numPtr;
                                                    byte[] pinned buffer;
                                                    if (((numArray = indexListCached.GetInternalArray <int>()) == null) || (numArray.Length == 0))
                                                    {
                                                        numPtr = null;
                                                    }
                                                    else
                                                    {
                                                        numPtr = numArray;
                                                    }
                                                    try
                                                    {
                                                        byte *numPtr2;
                                                        Vector3[] pinned vectorArray;
                                                        if (((buffer = materialListCached.GetInternalArray <byte>()) == null) || (buffer.Length == 0))
                                                        {
                                                            numPtr2 = null;
                                                        }
                                                        else
                                                        {
                                                            numPtr2 = buffer;
                                                        }
                                                        try
                                                        {
                                                            Vector3 *vectorPtr;
                                                            if (((vectorArray = vertexListCached.GetInternalArray <Vector3>()) == null) || (vectorArray.Length == 0))
                                                            {
                                                                vectorPtr = null;
                                                            }
                                                            else
                                                            {
                                                                vectorPtr = vectorArray;
                                                            }
                                                            float physicsConvexRadius = MyPerGameSettings.PhysicsConvexRadius;
                                                            if (userData == -2)
                                                            {
                                                                userData = uint.MaxValue;
                                                            }
                                                            HkBvCompressedMeshShape local1 = new HkBvCompressedMeshShape(vectorPtr, vertexListCached.Count, numPtr, indexListCached.Count, numPtr2, materialListCached.Count, HkWeldingType.None, physicsConvexRadius);
                                                            HkShape.SetUserData((HkShape)local1, userData);
                                                            shape = local1;
                                                        }
                                                        finally
                                                        {
                                                            vectorArray = null;
                                                        }
                                                    }
                                                    finally
                                                    {
                                                        buffer = null;
                                                    }
                                                }
                                                finally
                                                {
                                                    numArray = null;
                                                }
                                                break;
                                            }
                                            VrVoxelTriangle triangle = mesh.Triangles[num5];
                                            byte            material = vertices[triangle.V0].Material;
                                            if (userData == -2)
                                            {
                                                userData = material;
                                            }
                                            else if (userData != material)
                                            {
                                                userData = uint.MaxValue;
                                            }
                                            materialListCached.Add(material);
                                            num5++;
                                        }
                                        break;
                                    }
                                    vertexListCached.Add((vertices[num4].Position * scale) + vector);
                                    num4++;
                                }
                                break;
                            }
                            indexListCached.Add(mesh.Triangles[index].V0);
                            indexListCached.Add(mesh.Triangles[index].V2);
                            indexListCached.Add(mesh.Triangles[index].V1);
                            index++;
                        }
                    }
                }
            }
            return(shape);
        }
        internal HkBvCompressedMeshShape CreateShape(MyIsoMesh mesh)
        {
            // mk:NOTE This method must be thread safe. Called from worker threads.

            if (mesh == null || mesh.TrianglesCount == 0 || mesh.VerticesCount == 0)
                return (HkBvCompressedMeshShape)HkShape.Empty;

            List<int> indexList = new List<int>(mesh.TrianglesCount * 3);
            List<Vector3> vertexList = new List<Vector3>(mesh.VerticesCount);

            for (int i = 0; i < mesh.TrianglesCount; i++)
            {
                indexList.Add(mesh.Triangles[i].VertexIndex0);
                indexList.Add(mesh.Triangles[i].VertexIndex2);
                indexList.Add(mesh.Triangles[i].VertexIndex1);
            }

            // mk:TODO Unify denormalizing of positions with what is in MyIsoMesh.
            var positionOffset = mesh.PositionOffset - m_voxelMap.StorageMin * MyVoxelConstants.VOXEL_SIZE_IN_METRES;
            var positions = mesh.Positions.GetInternalArray();
            for (int i = 0; i < mesh.VerticesCount; i++)
            {
                vertexList.Add(positions[i] * mesh.PositionScale + positionOffset);
            }
            using (var cellGeometry = new HkGeometry(vertexList, indexList))
            {
                var result = new HkBvCompressedMeshShape(cellGeometry, null, null, HkWeldingType.None, MyPerGameSettings.PhysicsConvexRadius);
                Debug.Assert(result.Base.ReferenceCount == 1);
                return result;
            }
        }
 public void UnloadData()
 {
     if (!m_meshShape.Base.IsZero)
     {
         MyPhysics.AssertThread();
         Debug.Assert(m_meshShape.Base.ReferenceCount > 0);
         m_meshShape.Base.RemoveReference();
     }
     m_meshShape = (HkBvCompressedMeshShape)HkShape.Empty;
 }