internal void UpdateMassProps(HkRigidBody rb)
 {
     var mp = new HkMassProperties();
     mp.InertiaTensor = rb.InertiaTensor;
     mp.Mass = rb.Mass;
     mp.CenterOfMass = rb.CenterOfMassLocal;
     MassElement = new HkMassElement();
     MassElement.Properties = mp;
     MassElement.Tranform = Transform;
     //MassElement.Tranform.Translation = Vector3.Transform(rb.CenterOfMassLocal, Transform);
 }
        public void SyncRigidBodiesTransforms(MatrixD worldTransform)
        {
            bool changed = m_lastSyncedWorldMatrix != worldTransform;

            foreach (var rigidBodyIndex in m_rigidBodiesToBonesIndices.Keys)
            {
                Debug.Assert(Ragdoll.RigidBodies.IsValidIndex(rigidBodyIndex), "Sync - Ragdoll rigid body index is invalid. Is the ragdoll model correctly built?");
                HkRigidBody rigidBody = Ragdoll.RigidBodies[rigidBodyIndex];

                Matrix transform = Ragdoll.GetRigidBodyLocalTransform(rigidBodyIndex);
                changed = m_ragdollRigidBodiesAbsoluteTransforms[rigidBodyIndex] != transform || changed;
                m_ragdollRigidBodiesAbsoluteTransforms[rigidBodyIndex] = transform;
            }
            if (changed && MyFakes.ENABLE_RAGDOLL_CLIENT_SYNC)
            {
                m_character.SyncObject.SendRagdollTransforms(worldTransform, m_ragdollRigidBodiesAbsoluteTransforms);
                m_lastSyncedWorldMatrix = worldTransform;
            }
        }
Exemple #3
0
        internal static HkRigidBody GetRigidBody(Object entity)
        {
            try
            {
                Object physicsObject = GetEntityPhysicsObject(entity);
                if (physicsObject == null)
                {
                    return(null);
                }
                HkRigidBody rigidBody = (HkRigidBody)InvokeEntityMethod(physicsObject, PhysicsManagerGetRigidBodyMethod);

                return(rigidBody);
            }
            catch (Exception ex)
            {
                LogManager.ErrorLog.WriteLine(ex);
                return(null);
            }
        }
Exemple #4
0
        protected void InternalUpdateOrientation()
        {
            try
            {
                HkRigidBody havokBody = PhysicsBody;
                if (havokBody == null)
                {
                    return;
                }

                Matrix     orientationMatrix = m_positionOrientation.GetMatrix().GetOrientation();
                Quaternion orientation       = Quaternion.CreateFromRotationMatrix(orientationMatrix);
                havokBody.Rotation = orientation;
            }
            catch (Exception ex)
            {
                LogManager.ErrorLog.WriteLine(ex);
            }
        }
        public static MyPhysicsBody GetPhysicsBody(this HkContactPointEvent eventInfo, int index)
        {
            var body = eventInfo.Base.GetRigidBody(index).GetBody();

            if (body.IsWelded)
            {
                uint shapeKey = 0;
                int  i        = 0;
                for (; i < 4; i++)
                {
                    if (eventInfo.GetShapeKey(0, i) == uint.MaxValue)
                    {
                        break;
                    }
                }
                shapeKey = eventInfo.GetShapeKey(0, i - 1);
                body     = HkRigidBody.FromShape(eventInfo.Base.BodyA.GetShape().GetContainer().GetShape(shapeKey)).GetBody();
            }
            return(body);
        }
Exemple #6
0
        public static void RemoveDestructions(HkRigidBody body)
        {
            var list = m_destructionQueue.ToList();

            for (int i = 0; i < list.Count; i++)
            {
                if (!list[i].Details.IsValid() || list[i].Details.GetBreakingBody() == body)
                {
                    list[i].Details.RemoveReference();
                    list.RemoveAt(i);
                    i--;
                }
            }

            m_destructionQueue.Clear();
            foreach (var details in list)
            {
                m_destructionQueue.Enqueue(details);
            }
        }
 private void RemoveConstraints(HkRigidBody hkRigidBody)
 {
     foreach (var constraint in m_constraints)
     {
         if (constraint.IsDisposed || (constraint.RigidBodyA == hkRigidBody || constraint.RigidBodyB == hkRigidBody))
             m_constraintsRemoveBatch.Add(constraint);
     }
     foreach (var constraint in m_constraintsRemoveBatch)
     {
         m_constraints.Remove(constraint);
         if (!constraint.IsDisposed && constraint.InWorld)
         {
             //System.Diagnostics.Debug.Assert(world.RigidBodies.Contains(constraint.RigidBodyA), "Object was removed prior to constraint");
             //System.Diagnostics.Debug.Assert(world.RigidBodies.Contains(constraint.RigidBodyB), "Object was removed prior to constraint");
             constraint.OnRemovedFromWorld();
             HavokWorld.RemoveConstraint(constraint);
         }
     }
     m_constraintsRemoveBatch.Clear();
 }
Exemple #8
0
        private bool IsAcceptableContact(HkRigidBody rb)
        {
            object userObject = rb.UserObject;

            if (userObject == null)
            {
                return(false);
            }
            if (userObject == base.CubeGrid.Physics)
            {
                return(false);
            }
            if (userObject is MyVoxelPhysicsBody)
            {
                return(true);
            }
            MyGridPhysics physics = userObject as MyGridPhysics;

            return((physics != null) && physics.IsStatic);
        }
        void phantom_Enter(HkPhantomCallbackShape sender, HkRigidBody body)
        {
            ProfilerShort.Begin("GravityEnter");
            var entity = MyPhysicsExtensions.GetEntity(body, 0);// jn: TODO we should collect bodies not entities

            // HACK: disabled gravity for ships (there may be more changes so I won't add Entity.RespectsGravity now)
            lock (m_locker)
            {
                if (entity != null && !(entity is MyCubeGrid))
                {
                    MyTrace.Send(TraceWindow.EntityId, string.Format("Entity entered gravity field, entity: {0}", entity));
                    m_containedEntities.Add(entity);

                    if (entity.Physics.HasRigidBody)
                    {
                        ((MyPhysicsBody)entity.Physics).RigidBody.Activate();
                    }
                }
            }
            ProfilerShort.End();
        }
        protected void InternalUpdateLinearVelocity( )
        {
            try
            {
                HkRigidBody havokBody = PhysicsBody;
                if (havokBody == null)
                {
                    return;
                }

                if (ExtenderOptions.IsDebugging)
                {
                    ApplicationLog.BaseLog.Debug("{0} - Changing linear velocity of '{1}' from '{2}' to '{3}'", GetType( ).Name, Name, havokBody.LinearVelocity, m_linearVelocity);
                }

                havokBody.LinearVelocity = m_linearVelocity;
            }
            catch (Exception ex)
            {
                ApplicationLog.BaseLog.Error(ex);
            }
        }
Exemple #11
0
        protected void InternalUpdateAngularVelocity( )
        {
            try
            {
                HkRigidBody havokBody = PhysicsBody;
                if (havokBody == null)
                {
                    return;
                }

                if (SandboxGameAssemblyWrapper.IsDebugging)
                {
                    ApplicationLog.BaseLog.Debug("{0} - Changing angular velocity of '{1}' from '{2}' to '{3}'", GetType( ).Name, Name, havokBody.AngularVelocity.ToString( ), m_angularVelocity.ToString( ));
                }

                havokBody.AngularVelocity = m_angularVelocity;
            }
            catch (Exception ex)
            {
                ApplicationLog.BaseLog.Error(ex);
            }
        }
Exemple #12
0
        private void phantom_Enter(HkPhantomCallbackShape shape, HkRigidBody body)
        {
            if (!Sync.IsServer)
            {
                return;
            }
            var entity = body.GetEntity();

            if (entity is MyFloatingObject)
            {
                m_entitiesToTake.Add(entity as MyFloatingObject);
                NeedsUpdate |= MyEntityUpdateEnum.BEFORE_NEXT_FRAME;
            }

            //if (!Sync.IsServer)
            //    return;
            //var entity = body.GetEntity();
            //if (entity is MyFloatingObject)
            //{
            //    m_inventory.TakeFloatingObject(entity as MyFloatingObject);
            //}
        }
        public static IMyEntity GetEntity(this HkEntity hkEntity, uint shapeKey)
        {
            var body = hkEntity.GetBody();

            if (body != null)
            {
                if (shapeKey == 0)
                {
                    return(body.Entity);
                }
                if (shapeKey > body.WeldInfo.Children.Count)
                {
                    return(body.Entity);
                }
                var shape = body.RigidBody.GetShape().GetContainer().GetShape(shapeKey);
                if (shape.IsValid)
                {
                    body = HkRigidBody.FromShape(shape).GetBody();
                }
            }
            return(body != null ? body.Entity : null);
        }
Exemple #14
0
        protected void InternalUpdateAngularVelocity()
        {
            try
            {
                HkRigidBody havokBody = PhysicsBody;
                if (havokBody == null)
                {
                    return;
                }

                if (SandboxGameAssemblyWrapper.IsDebugging)
                {
                    LogManager.APILog.WriteLine(this.GetType().Name + " - Changing angular velocity of '" + Name + "' from '" + havokBody.AngularVelocity.ToString() + "' to '" + m_angularVelocity.ToString() + "'");
                }

                havokBody.AngularVelocity = m_angularVelocity;
            }
            catch (Exception ex)
            {
                LogManager.ErrorLog.WriteLine(ex);
            }
        }
Exemple #15
0
        private void phantom_Enter(HkPhantomCallbackShape shape, HkRigidBody body)
        {
            VRage.ProfilerShort.Begin("MergeEnter");
            var entities = MyPhysicsExtensions.GetAllEntities(body);

            foreach (var entity in entities)
            {
                var other = entity as MyCubeGrid;
                if (other == null || other.GridSizeEnum != CubeGrid.GridSizeEnum || other == this.CubeGrid)
                {
                    continue;
                }
                if (other.Physics.RigidBody != body)
                {
                    continue;
                }
                var added = m_gridList.Add(other);
                //Debug.Assert(added, "entity already in list");
            }
            entities.Clear();
            VRage.ProfilerShort.End();
        }
Exemple #16
0
        private static bool IsCharacter(HkRigidBody rb, MyPhysicsBody character)
        {
            if (character == null)
            {
                return(false);
            }

            var c = character.Entity as MyCharacter;

            if (c == null)
            {
                return(false);
            }
            if (c.Physics == null)
            {
                return(false);                      // Physics may have been already released / Entity removed from the world?
            }
            if (c.Physics.CharacterProxy != null)
            {
                return(c.Physics.CharacterProxy.GetHitRigidBody() == rb);
            }
            return(c.Physics.RigidBody == rb);      // Otherwise we do proper check
        }
Exemple #17
0
        /// <summary>
        /// Compute the transforms that should be used for rigid bodies based on current bones tranforms in the havokWorld
        /// </summary>
        /// <param name="worldMatrix"></param>
        private void CalculateRagdollTransformsFromBones()
        {
            Debug.Assert(Ragdoll != null, "Ragdoll mapper ragdoll in not inicialized, calculate ragdoll transforms!");
            if (Ragdoll == null)
            {
                return;
            }
            if (!m_inicialized || !IsActive)
            {
                return;
            }

            foreach (var rigidBodyIndex in m_rigidBodiesToBonesIndices.Keys)
            {
                HkRigidBody rigidBody   = Ragdoll.RigidBodies[rigidBodyIndex];
                var         boneIndices = m_rigidBodiesToBonesIndices[rigidBodyIndex];

                Matrix finalTransform = m_bones[boneIndices.First()].AbsoluteTransform;

                m_ragdollRigidBodiesAbsoluteTransforms[rigidBodyIndex] = finalTransform;

                Debug.Assert(m_ragdollRigidBodiesAbsoluteTransforms[rigidBodyIndex].IsValid(), "Ragdoll body transform is invalid");
            }
        }
Exemple #18
0
        public void SetLimitedVelocities()
        {
            List <HkRigidBody> rigidBodies = this.Ragdoll.RigidBodies;

            if (rigidBodies[0] != null)
            {
                float       num;
                float       num2;
                HkRigidBody rigidBody = this.m_character.Physics.RigidBody;
                if (rigidBody != null)
                {
                    num  = rigidBody.MaxLinearVelocity + 5f;
                    num2 = rigidBody.MaxAngularVelocity + 1f;
                }
                else
                {
                    num  = Math.Max((float)10f, (float)(rigidBodies[0].LinearVelocity.Length() + 5f));
                    num2 = Math.Max((float)12.56637f, (float)(rigidBodies[0].AngularVelocity.Length() + 1f));
                }
                foreach (int num3 in this.m_dynamicBodies)
                {
                    if (this.IsPartiallySimulated)
                    {
                        rigidBodies[num3].MaxLinearVelocity  = num;
                        rigidBodies[num3].MaxAngularVelocity = num2;
                        rigidBodies[num3].LinearDamping      = 0.2f;
                        rigidBodies[num3].AngularDamping     = 0.2f;
                        continue;
                    }
                    rigidBodies[num3].MaxLinearVelocity  = this.Ragdoll.MaxLinearVelocity;
                    rigidBodies[num3].MaxAngularVelocity = this.Ragdoll.MaxAngularVelocity;
                    rigidBodies[num3].LinearDamping      = 0.5f;
                    rigidBodies[num3].AngularDamping     = 0.5f;
                }
            }
        }
Exemple #19
0
        protected void InternalUpdatePosition()
        {
            try
            {
                HkRigidBody havokBody = PhysicsBody;
                if (havokBody == null)
                {
                    return;
                }

                Vector3 newPosition = m_positionOrientation.Position;

                if (SandboxGameAssemblyWrapper.IsDebugging)
                {
                    LogManager.APILog.WriteLine(this.GetType().Name + " - Changing position of '" + Name + "' from '" + havokBody.Position.ToString() + "' to '" + newPosition.ToString() + "'");
                }

                havokBody.Position = newPosition;
            }
            catch (Exception ex)
            {
                LogManager.ErrorLog.WriteLine(ex);
            }
        }
 private void phantom_Enter(HkPhantomCallbackShape shape, HkRigidBody body)
 {
     ProfilerShort.Begin("MergeEnter");
     var entities = MyPhysicsExtensions.GetAllEntities(body);
     foreach (var entity in entities)
     {
         var other = entity as MyCubeGrid;
         if (other == null || other.GridSizeEnum != CubeGrid.GridSizeEnum || other == this.CubeGrid)
             continue;
         if(other.Physics.RigidBody != body)
             continue;
         var added = m_gridList.Add(other);
         //Debug.Assert(added, "entity already in list");
     }
     entities.Clear();
     ProfilerShort.End();
 }
Exemple #21
0
        public void StopManipulation()
        {
            if (m_state != MyState.NONE && Owner != null)
            {
                var characterMovementState = Owner.GetCurrentMovementState();
                switch (characterMovementState)
                {
                case MyCharacterMovementEnum.Walking:
                case MyCharacterMovementEnum.BackWalking:
                case MyCharacterMovementEnum.WalkingLeftFront:
                case MyCharacterMovementEnum.WalkingRightFront:
                case MyCharacterMovementEnum.WalkingLeftBack:
                case MyCharacterMovementEnum.WalkingRightBack:
                case MyCharacterMovementEnum.WalkStrafingLeft:
                case MyCharacterMovementEnum.WalkStrafingRight:
                case MyCharacterMovementEnum.Running:
                case MyCharacterMovementEnum.Backrunning:
                case MyCharacterMovementEnum.RunStrafingLeft:
                case MyCharacterMovementEnum.RunStrafingRight:
                case MyCharacterMovementEnum.RunningRightFront:
                case MyCharacterMovementEnum.RunningRightBack:
                case MyCharacterMovementEnum.RunningLeftFront:
                case MyCharacterMovementEnum.RunningLeftBack:
                    Owner.PlayCharacterAnimation("WalkBack", true, MyPlayAnimationMode.Immediate | MyPlayAnimationMode.Play, 0.2f, 1f);
                    break;

                case MyCharacterMovementEnum.Standing:
                case MyCharacterMovementEnum.RotatingLeft:
                case MyCharacterMovementEnum.RotatingRight:
                case MyCharacterMovementEnum.Flying:
                    Owner.PlayCharacterAnimation("Idle", true, MyPlayAnimationMode.Immediate | MyPlayAnimationMode.Play, 0.2f, 1f);
                    break;
                }
            }


            if (m_constraint != null)
            {
                if (Owner != null && Owner.VirtualPhysics != null)
                {
                    Owner.VirtualPhysics.RemoveConstraint(m_constraint);
                }

                m_constraint.Dispose();
                m_constraint = null;
            }

            if (m_fixedConstraintData != null)
            {
                if (!m_fixedConstraintData.IsDisposed)
                {
                    m_fixedConstraintData.Dispose();
                }

                m_fixedConstraintData = null;
            }

            m_headLocalPivotMatrix  = Matrix.Zero;
            m_otherLocalPivotMatrix = Matrix.Zero;
            if (m_otherEntity != null)
            {
                SetTransparent(m_otherEntity);
                SetTransparent(m_otherEntity);

                if (m_state == MyState.HOLD)
                {
                    SetMotionOnClient(m_otherEntity, HkMotionType.Keyframed);
                }

                m_manipulatedEntitites.Remove(m_otherEntity);

                m_otherEntity.SyncFlag = true;

                if (m_otherEntity.Physics != null && m_otherRigidBody != null && !m_otherRigidBody.IsDisposed)
                {
                    SetManipulated(m_otherEntity, false);
                    //m_otherRigidBody.AngularDamping = m_otherAngularDamping;
                    //m_otherRigidBody.LinearDamping = m_otherLinearDamping;
                    m_otherRigidBody.Restitution        = m_otherRestitution;
                    m_otherRigidBody.MaxLinearVelocity  = m_otherMaxLinearVelocity;
                    m_otherRigidBody.MaxAngularVelocity = m_otherMaxAngularVelocity;
                    if (m_massChange != null)
                    {
                        m_massChange.Remove();
                    }
                    m_massChange = null;
                    // Clamp output velocity
                    m_otherRigidBody.LinearVelocity  = Vector3.Clamp(m_otherRigidBody.LinearVelocity, -2 * Vector3.One, 2 * Vector3.One);
                    m_otherRigidBody.AngularVelocity = Vector3.Clamp(m_otherRigidBody.AngularVelocity, -Vector3.One * (float)Math.PI, Vector3.One * (float)Math.PI);
                    if (!m_otherRigidBody.IsActive)
                    {
                        m_otherRigidBody.Activate();
                    }
                    m_otherRigidBody.EnableDeactivation = false;
                    m_otherRigidBody.EnableDeactivation = true; //resets deactivation counter
                    m_otherRigidBody = null;
                }

                m_otherEntity.OnClosing -= OtherEntity_OnClosing;
                m_otherEntity            = null;
            }

            m_constraintInitialized = false;

            if (Owner != null)
            {
                Owner.ManipulatedEntity = null;
            }
            m_state = MyState.NONE;
        }
        private DamageImpactEnum GetDamageFromSqueeze(HkRigidBody collidingBody, MyEntity collidingEntity, ref HkContactPointEvent value)
        {
            if (collidingBody.IsFixed || collidingBody.Mass < MyPerGameSettings.CharacterSqueezeMinMass) return DamageImpactEnum.NoDamage;

            if (value.ContactProperties.IsNew) return DamageImpactEnum.NoDamage;

            // the object has to be moving towards the character even slowly and that also the character is not moving away from it
            Vector3 direction = Physics.CharacterProxy.GetHitRigidBody().Position - collidingBody.Position;
            Vector3 gravity = MyGravityProviderSystem.CalculateTotalGravityInPoint(PositionComp.WorldAABB.Center) + Physics.HavokWorld.Gravity;
            direction.Normalize();
            gravity.Normalize();

            float resultToPlayer = Vector3.Dot(direction, gravity);

            if (resultToPlayer < 0.5f) return DamageImpactEnum.NoDamage;

            if (m_squeezeDamageTimer > 0)
            {
                m_squeezeDamageTimer -= VRage.Game.MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS;
                return DamageImpactEnum.NoDamage;
            }
            m_squeezeDamageTimer = MyPerGameSettings.CharacterSqueezeDamageDelay;

            if (MyDebugDrawSettings.ENABLE_DEBUG_DRAW && MyDebugDrawSettings.DEBUG_DRAW_SHOW_DAMAGE)
            {
                MatrixD worldMatrix = collidingEntity.Physics.GetWorldMatrix();
                int index = 2;
                MyPhysicsDebugDraw.DrawCollisionShape(collidingBody.GetShape(), worldMatrix, 1, ref index);
                VRageRender.MyRenderProxy.DebugDrawText3D(worldMatrix.Translation, "SQUEEZE, MASS:" + collidingBody.Mass, Color.Yellow, 2, false);
            }

            if (collidingBody.Mass > MyPerGameSettings.CharacterSqueezeDeadlyDamageMass) return DamageImpactEnum.DeadlyDamage;

            if (collidingBody.Mass > MyPerGameSettings.CharacterSqueezeCriticalDamageMass) return DamageImpactEnum.CriticalDamage;

            if (collidingBody.Mass > MyPerGameSettings.CharacterSqueezeMediumDamageMass) return DamageImpactEnum.MediumDamage;

            return DamageImpactEnum.SmallDamage;
        }
        private void ApplyImplusesWorld(Vector3? force, Vector3D? position, Vector3? torque, HkRigidBody rigidBody)
        {
            if (rigidBody == null)
                return;

            var offset = MyPhysics.Clusters.GetObjectOffset(ClusterObjectID);

            if (force.HasValue && position.HasValue)
                rigidBody.ApplyPointImpulse(force.Value, (Vector3)(position.Value - offset));

            if (torque.HasValue)
                rigidBody.ApplyAngularImpulse(torque.Value * MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS * MyFakes.SIMULATION_SPEED);
        }
            private void DrawBodyInfo()
            {
                Vector2  pos       = new Vector2(400, 10);
                MyEntity hitEntity = null;

                HkRigidBody body = null;

                if (SelectedEntity != null && SelectedEntity.Physics != null)
                {
                    body = ((MyEntity)SelectedEntity).Physics.RigidBody;
                }

                if (MySector.MainCamera != null && body == null)
                {
                    List <MyPhysics.HitInfo> lst = new List <MyPhysics.HitInfo>();
                    MyPhysics.CastRay(MySector.MainCamera.Position, MySector.MainCamera.Position + MySector.MainCamera.ForwardVector * 100, lst);
                    foreach (var hit in lst)
                    {
                        body = hit.HkHitInfo.Body;
                        if (body == null || body.Layer == MyPhysics.CollisionLayers.NoCollisionLayer)
                        {
                            continue;
                        }
                        hitEntity = hit.HkHitInfo.GetHitEntity() as MyEntity;

                        var sb = new System.Text.StringBuilder("ShapeKeys: ");
                        for (int i = 0; i < HkWorld.HitInfo.ShapeKeyCount; i++)
                        {
                            var key = hit.HkHitInfo.GetShapeKey(i);
                            if (key == uint.MaxValue)
                            {
                                break;
                            }
                            sb.Append(string.Format("{0} ", key));
                        }
                        VRageRender.MyRenderProxy.DebugDrawText2D(pos, sb.ToString(), Color.White, 0.7f);
                        pos.Y += 20;
                        if (hitEntity != null)
                        {
                            VRageRender.MyRenderProxy.DebugDrawText2D(pos, string.Format("Weld: {0}", hitEntity.GetPhysicsBody().WeldInfo.Children.Count), Color.White, 0.7f);
                        }
                        pos.Y += 20;
                        break;
                    }
                }
                //if (MySector.MainCamera != null)
                //{
                //    LineD line = new LineD(MySector.MainCamera.Position, MySector.MainCamera.Position + MySector.MainCamera.ForwardVector * 100);
                //    var intersect = MyEntities.GetIntersectionWithLine(ref line, MySession.ControlledEntity.Entity, null);
                //    if (intersect.HasValue)
                //    {
                //        VRageRender.MyRenderProxy.DebugDrawText2D(pos, intersect.Value.Entity.ToString() + " "
                //              , Color.White, 0.8f);
                //    }
                //}

                if (body != null && m_drawBodyInfo)
                {
                    //body.Activate();
                    //VRageRender.MyRenderProxy.DebugDrawText2D(pos, body.GetEntity(0).ToString() + " "
                    //       + MyDestructionHelper.MassFromHavok(body.Mass), Color.White, 0.8f);
                    pos.Y += 20;
                    VRageRender.MyRenderProxy.DebugDrawText2D(pos, "Layer: " + body.Layer, body.Layer == 0 ? Color.Red : Color.White, 0.7f);
                    pos.Y += 20;
                    VRageRender.MyRenderProxy.DebugDrawText2D(pos, string.Format("Friction: {0}  Restitution: {1}", body.Friction, body.Restitution), Color.White, 0.7f);
                    pos.Y += 20;
                    VRageRender.MyRenderProxy.DebugDrawText2D(pos, "Lin: " + body.LinearVelocity.Length(), Color.White, 0.7f);
                    pos.Y += 20;
                    VRageRender.MyRenderProxy.DebugDrawText2D(pos, "Ang: " + body.AngularVelocity.Length(), Color.White, 0.7f);
                    pos.Y += 20;
                    VRageRender.MyRenderProxy.DebugDrawText2D(pos, "Act: " + (body.IsActive ? "true" : "false"), Color.White, 0.7f);
                    pos.Y += 20;
                    VRageRender.MyRenderProxy.DebugDrawText2D(pos, "Stat: " + (body.IsFixedOrKeyframed ? "true" : "false"), Color.White, 0.7f);
                    pos.Y += 20;
                    VRageRender.MyRenderProxy.DebugDrawText2D(pos, "Solver: " + (body.Motion.GetDeactivationClass()), Color.White, 0.7f);
                    pos.Y += 20;
                    VRageRender.MyRenderProxy.DebugDrawText2D(pos, "Mass: " + body.Mass, Color.White, 0.7f);
                    pos.Y += 20;
                    //VRageRender.MyRenderProxy.DebugDrawText2D(pos, "SysID: " + body.GetBody().HavokCollisionSystemID, Color.White, 0.7f);
                    pos.Y += 20;
                    //VRageRender.MyRenderProxy.DebugDrawText2D(pos, "CharLin: " + MySession.ControlledEntity.Entity.Physics.LinearVelocity.Length(), Color.White, 0.7f);
                }

                if (SelectedEntity != null && m_drawUpdateInfo)
                {
                    VRageRender.MyRenderProxy.DebugDrawText2D(pos, "Updates: " + m_counter, Color.White, 0.7f);
                    pos.Y += 20;
                    VRageRender.MyRenderProxy.DebugDrawText2D(pos, "PositionUpd: " + dbgPosCounter, Color.White, 0.7f);
                    pos.Y += 20;
                    VRageRender.MyRenderProxy.DebugDrawText2D(pos, "Frames per update: " + m_counter / (float)dbgPosCounter, Color.White, 0.7f);
                    pos.Y += 20;
                }
            }
Exemple #25
0
        public void StopManipulation()
        {
            if (m_state != MyState.NONE && Owner != null)
            {
                var characterMovementState = Owner.GetCurrentMovementState();
                switch (characterMovementState)
                {
                case MyCharacterMovementEnum.Walking:
                case MyCharacterMovementEnum.BackWalking:
                case MyCharacterMovementEnum.WalkingLeftFront:
                case MyCharacterMovementEnum.WalkingRightFront:
                case MyCharacterMovementEnum.WalkingLeftBack:
                case MyCharacterMovementEnum.WalkingRightBack:
                case MyCharacterMovementEnum.WalkStrafingLeft:
                case MyCharacterMovementEnum.WalkStrafingRight:
                case MyCharacterMovementEnum.Running:
                case MyCharacterMovementEnum.Backrunning:
                case MyCharacterMovementEnum.RunStrafingLeft:
                case MyCharacterMovementEnum.RunStrafingRight:
                case MyCharacterMovementEnum.RunningRightFront:
                case MyCharacterMovementEnum.RunningRightBack:
                case MyCharacterMovementEnum.RunningLeftFront:
                case MyCharacterMovementEnum.RunningLeftBack:
                    Owner.PlayCharacterAnimation("WalkBack", MyBlendOption.Immediate, MyFrameOption.Loop, 0.2f, 1f);
                    break;

                case MyCharacterMovementEnum.Standing:
                case MyCharacterMovementEnum.RotatingLeft:
                case MyCharacterMovementEnum.RotatingRight:
                case MyCharacterMovementEnum.Flying:
                    Owner.PlayCharacterAnimation("Idle", MyBlendOption.Immediate, MyFrameOption.Loop, 0.2f, 1f);
                    break;
                }
            }


            if (m_constraint != null)
            {
                if (OwnerVirtualPhysics != null)
                {
                    OwnerVirtualPhysics.RemoveConstraint(m_constraint);
                }

                m_constraint.Dispose();
                m_constraint = null;
            }

            if (m_fixedConstraintData != null)
            {
                if (!m_fixedConstraintData.IsDisposed)
                {
                    m_fixedConstraintData.Dispose();
                }

                m_fixedConstraintData = null;
            }

            m_headLocalPivotMatrix  = Matrix.Zero;
            m_otherLocalPivotMatrix = Matrix.Zero;
            if (m_otherEntity != null)
            {
                SetTransparent(m_otherEntity);

                if (m_state == MyState.HOLD)
                {
                    SetMotionOnClient(m_otherEntity, HkMotionType.Dynamic);

                    // Do not send when disconnecting
                    if (IsOwnerLocalPlayer() && !MyEntities.CloseAllowed && !(m_otherEntity is MyCharacter))
                    {
                        Sync.Players.RemoveControlledEntity(m_otherEntity);
                    }
                }

                m_manipulatedEntitites.Remove(m_otherEntity);
                var handler = ManipulationStopped;
                if (handler != null)
                {
                    handler(m_otherEntity);
                }

                m_otherEntity.SyncFlag = true;

                if (m_otherEntity.Physics != null && m_otherRigidBody != null && !m_otherRigidBody.IsDisposed)
                {
                    SetManipulated(m_otherEntity, false);
                    //m_otherRigidBody.AngularDamping = m_otherAngularDamping;
                    //m_otherRigidBody.LinearDamping = m_otherLinearDamping;
                    if (m_otherEntity is MyCharacter)
                    {
                        m_otherEntity.Physics.SetRagdollDefaults();
                    }
                    else
                    {
                        m_otherRigidBody.Restitution        = m_otherRestitution;
                        m_otherRigidBody.MaxLinearVelocity  = m_otherMaxLinearVelocity;
                        m_otherRigidBody.MaxAngularVelocity = m_otherMaxAngularVelocity;
                        if (m_massChange != null)
                        {
                            m_massChange.Remove();
                        }
                        m_massChange = null;
                        // Clamp output velocity
                        m_otherRigidBody.LinearVelocity  = Vector3.Clamp(m_otherRigidBody.LinearVelocity, -2 * Vector3.One, 2 * Vector3.One);
                        m_otherRigidBody.AngularVelocity = Vector3.Clamp(m_otherRigidBody.AngularVelocity, -Vector3.One * (float)Math.PI, Vector3.One * (float)Math.PI);
                        if (!m_otherRigidBody.IsActive)
                        {
                            m_otherRigidBody.Activate();
                        }
                        m_otherRigidBody.EnableDeactivation = false;
                        m_otherRigidBody.EnableDeactivation = true; //resets deactivation counter
                    }
                    m_otherRigidBody = null;
                }

                m_otherEntity.OnClosing -= OtherEntity_OnClosing;
                m_otherEntity            = null;
            }

            m_constraintInitialized = false;

            RemoveOwnerVirtualPhysics();

            if (Owner != null)
            {
                Owner.ManipulatedEntity = null;
            }
            m_state = MyState.NONE;
        }
Exemple #26
0
 public override void OnMotion(HkRigidBody rbo, float step)
 {
     // Do nothing
 }
 void phantom_Leave(HkPhantomCallbackShape sender, HkRigidBody body)
 {
 }
 void phantom_Enter(HkPhantomCallbackShape sender, HkRigidBody body)
 {
 }
Exemple #29
0
        public override bool HandleInput()
        {
            m_counter++;
            if (base.HandleInput())
            {
                return(true);
            }

            bool handled = false;

            if (MyInput.Static.IsAnyCtrlKeyPressed() && MyInput.Static.IsNewLeftMouseReleased())
            {
                Hammer();
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad1))
            {
                ApplyMassMultiplier = !ApplyMassMultiplier;
                handled             = true;
            }
            var mul = 1;

            if (MyInput.Static.IsKeyPress(MyKeys.N))
            {
                mul = 10;
            }
            if (MyInput.Static.IsKeyPress(MyKeys.B))
            {
                mul = 100;
            }
            if (MyInput.Static.IsNewKeyPressed(MyKeys.OemQuotes))
            {
                if (MassMultiplier > 1)
                {
                    MassMultiplier += mul;
                }
                else
                {
                    MassMultiplier *= mul;
                }
                handled = true;
            }
            if (MyInput.Static.IsNewKeyPressed(MyKeys.OemSemicolon))
            {
                if (MassMultiplier > 1)
                {
                    MassMultiplier -= mul;
                }
                else
                {
                    MassMultiplier /= mul;
                }
                handled = true;
            }

            if (MyInput.Static.IsAnyCtrlKeyPressed() && MyInput.Static.IsNewLeftMousePressed() && SpawnFlora != null)
            {
                MyDefinitionId id = new MyDefinitionId(typeof(MyObjectBuilder_ConsumableItem), "Mushrooms");
                SpawnFlora(MySector.MainCamera.Position + MySector.MainCamera.ForwardVector, new BoundingBox(Vector3.Zero, Vector3.One), id, 1);
                SpawnFlora(MySector.MainCamera.Position + MySector.MainCamera.ForwardVector, new BoundingBox(Vector3.Zero, Vector3.One), id, 1);
                SpawnFlora(MySector.MainCamera.Position + MySector.MainCamera.ForwardVector, new BoundingBox(Vector3.Zero, Vector3.One), id, 1);
                SpawnFlora(MySector.MainCamera.Position + MySector.MainCamera.ForwardVector, new BoundingBox(Vector3.Zero, Vector3.One), id, 1);
                SpawnFlora(MySector.MainCamera.Position + MySector.MainCamera.ForwardVector, new BoundingBox(Vector3.Zero, Vector3.One), id, 1);
                SpawnFlora(MySector.MainCamera.Position + MySector.MainCamera.ForwardVector, new BoundingBox(Vector3.Zero, Vector3.One), id, 1);
                SpawnFlora(MySector.MainCamera.Position + MySector.MainCamera.ForwardVector, new BoundingBox(Vector3.Zero, Vector3.One), id, 1);
                SpawnFlora(MySector.MainCamera.Position + MySector.MainCamera.ForwardVector, new BoundingBox(Vector3.Zero, Vector3.One), id, 1);
            }

            Vector2  pos       = new Vector2(400, 10);
            MyEntity hitEntity = null;

            if (MyInput.Static.IsAnyShiftKeyPressed() && MyInput.Static.IsNewLeftMousePressed() && SelectedEntity != null)
            {
                SelectedEntity = null;
            }

            HkRigidBody body = null;

            if (SelectedEntity != null && SelectedEntity.Physics != null)
            {
                body = ((MyEntity)SelectedEntity).Physics.RigidBody;
            }

            if (MySector.MainCamera != null && body == null)
            {
                List <MyPhysics.HitInfo> lst = new List <MyPhysics.HitInfo>();
                MyPhysics.CastRay(MySector.MainCamera.Position, MySector.MainCamera.Position + MySector.MainCamera.ForwardVector * 100, lst);
                foreach (var hit in lst)
                {
                    body = hit.HkHitInfo.Body;
                    if (body == null || body.Layer == MyPhysics.NoCollisionLayer)
                    {
                        continue;
                    }
                    hitEntity = hit.HkHitInfo.GetHitEntity() as MyEntity;
                    if (MyInput.Static.IsAnyShiftKeyPressed() && MyInput.Static.IsNewLeftMousePressed())
                    {
                        SelectedEntity = hit.HkHitInfo.GetHitEntity();
                    }
                    var sb = new System.Text.StringBuilder("ShapeKeys: ");
                    for (int i = 0; i < HkWorld.HitInfo.ShapeKeyCount; i++)
                    {
                        var key = hit.HkHitInfo.GetShapeKey(i);
                        if (key == uint.MaxValue)
                        {
                            break;
                        }
                        sb.Append(string.Format("{0} ", key));
                    }
                    VRageRender.MyRenderProxy.DebugDrawText2D(pos, sb.ToString(), Color.White, 0.7f);
                    pos.Y += 20;
                    if (hitEntity != null)
                    {
                        VRageRender.MyRenderProxy.DebugDrawText2D(pos, string.Format("Weld: {0}", hitEntity.Physics.WeldInfo.Children.Count), Color.White, 0.7f);
                    }
                    pos.Y += 20;
                    break;
                }
            }
            //if (MySector.MainCamera != null)
            //{
            //    LineD line = new LineD(MySector.MainCamera.Position, MySector.MainCamera.Position + MySector.MainCamera.ForwardVector * 100);
            //    var intersect = MyEntities.GetIntersectionWithLine(ref line, MySession.ControlledEntity.Entity, null);
            //    if (intersect.HasValue)
            //    {
            //        VRageRender.MyRenderProxy.DebugDrawText2D(pos, intersect.Value.Entity.ToString() + " "
            //              , Color.White, 0.8f);
            //    }
            //}

            if (body != null && m_drawBodyInfo)
            {
                //VRageRender.MyRenderProxy.DebugDrawText2D(pos, body.GetEntity(0).ToString() + " "
                //       + MyDestructionHelper.MassFromHavok(body.Mass), Color.White, 0.8f);
                pos.Y += 20;
                VRageRender.MyRenderProxy.DebugDrawText2D(pos, "Layer: " + body.Layer, body.Layer == 0 ? Color.Red : Color.White, 0.7f);
                pos.Y += 20;
                VRageRender.MyRenderProxy.DebugDrawText2D(pos, string.Format("Friction: {0}  Restitution: {1}", body.Friction, body.Restitution), Color.White, 0.7f);
                pos.Y += 20;
                VRageRender.MyRenderProxy.DebugDrawText2D(pos, "Lin: " + body.LinearVelocity.Length(), Color.White, 0.7f);
                pos.Y += 20;
                VRageRender.MyRenderProxy.DebugDrawText2D(pos, "Ang: " + body.AngularVelocity.Length(), Color.White, 0.7f);
                pos.Y += 20;
                VRageRender.MyRenderProxy.DebugDrawText2D(pos, "Act: " + (body.IsActive ? "true" : "false"), Color.White, 0.7f);
                pos.Y += 20;
                VRageRender.MyRenderProxy.DebugDrawText2D(pos, "Stat: " + (body.IsFixedOrKeyframed ? "true" : "false"), Color.White, 0.7f);
                pos.Y += 20;
                VRageRender.MyRenderProxy.DebugDrawText2D(pos, "Solver: " + (body.Motion.GetDeactivationClass()), Color.White, 0.7f);
                pos.Y += 20;
                VRageRender.MyRenderProxy.DebugDrawText2D(pos, "Mass: " + body.Mass, Color.White, 0.7f);
                pos.Y += 20;
                //VRageRender.MyRenderProxy.DebugDrawText2D(pos, "CharLin: " + MySession.ControlledEntity.Entity.Physics.LinearVelocity.Length(), Color.White, 0.7f);
            }

            if (SelectedEntity != null && m_drawUpdateInfo)
            {
                VRageRender.MyRenderProxy.DebugDrawText2D(pos, "Updates: " + m_counter, Color.White, 0.7f);
                pos.Y += 20;
                VRageRender.MyRenderProxy.DebugDrawText2D(pos, "PositionUpd: " + dbgPosCounter, Color.White, 0.7f);
                pos.Y += 20;
                VRageRender.MyRenderProxy.DebugDrawText2D(pos, "Frames per update: " + m_counter / (float)dbgPosCounter, Color.White, 0.7f);
                pos.Y += 20;
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad9))
            {
                MyScriptManager.Static.LoadData();
            }

            if (MyAudio.Static != null)
            {
                foreach (var em in MyAudio.Static.Get3DSounds())
                {
                    VRageRender.MyRenderProxy.DebugDrawSphere(em.SourcePosition, 0.1f, Color.Red, 1, false);
                }
            }

            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.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;
        }
 void phantom_Leave(HkPhantomCallbackShape sender, HkRigidBody body)
 {
 }
 void phantom_Enter(HkPhantomCallbackShape sender, HkRigidBody body)
 {
 }
Exemple #33
0
        public void Weld(MyPhysicsBody other, bool recreateShape = true)
        {
            if (other.WeldInfo.Parent == this) //already welded to this
            {
                return;
            }

            if (other.IsWelded && !IsWelded)
            {
                other.Weld(this);
                return;
            }

            if (IsWelded)
            {
                WeldInfo.Parent.Weld(other);
                return;
            }
            if (other.WeldInfo.Children.Count > 0)
            {
                Debug.Fail("Welding other welded gorup");
                other.UnweldAll(false); //they should end in same group and get welded
            }
            ProfilerShort.Begin("Weld");
            HkShape thisShape;
            bool    firstWelded = WeldInfo.Children.Count == 0;

            if (firstWelded)
            {
                //RemoveConstraints(RigidBody);
                WeldedRigidBody = RigidBody;
                thisShape       = RigidBody.GetShape();
                if (HavokWorld != null)
                {
                    HavokWorld.RemoveRigidBody(WeldedRigidBody);
                }
                RigidBody = HkRigidBody.Clone(WeldedRigidBody);
                if (HavokWorld != null)
                {
                    HavokWorld.AddRigidBody(RigidBody);
                }
                HkShape.SetUserData(thisShape, RigidBody);
                Entity.OnPhysicsChanged += WeldedEntity_OnPhysicsChanged;
                WeldInfo.UpdateMassProps(RigidBody);
                //Entity.OnClose += Entity_OnClose;
            }
            else
            {
                thisShape = GetShape();
            }

            other.Deactivate();

            var transform = other.Entity.WorldMatrix * Entity.WorldMatrixInvScaled;

            other.WeldInfo.Transform = transform;
            other.WeldInfo.UpdateMassProps(other.RigidBody);
            Debug.Assert(other.WeldedRigidBody == null);
            other.WeldedRigidBody = other.RigidBody;
            other.RigidBody       = RigidBody;
            other.WeldInfo.Parent = this;
            other.ClusterObjectID = ClusterObjectID;
            WeldInfo.Children.Add(other);

            //if(recreateShape)
            //    RecreateWeldedShape(thisShape);

            ProfilerShort.BeginNextBlock("OnPhysicsChanged");
            //(other.Entity as MyEntity).RaisePhysicsChanged();
            //other.Entity.OnPhysicsChanged += WeldedEntity_OnPhysicsChanged;
            //Debug.Assert(other.m_constraints.Count == 0, "Constraints left in welded body");
            ProfilerShort.BeginNextBlock("RemoveConstraints");
            ProfilerShort.End();
            OnWelded(other);
            other.OnWelded(this);
        }
        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);
        }
        private void phantom_EnterConnector(HkPhantomCallbackShape shape, HkRigidBody body)
        {
            var other = body.GetEntity() as MyCubeGrid;
            if (other == null || other == this.CubeGrid)
                return;

            m_detectedGrids.Add(other);
        }
        private static bool IsCharacter(HkRigidBody rb, MyPhysicsBody character)
        {
            if (character == null)
                return false;

            var c = character.Entity as MyCharacter;
            if (c == null) return false;
            if (c.Physics == null) return false;    // Physics may have been already released / Entity removed from the world?
            if (c.Physics.CharacterProxy != null)
                return c.Physics.CharacterProxy.GetHitRigidBody() == rb;
            return (c.Physics.RigidBody == rb);     // Otherwise we do proper check
        }
Exemple #37
0
        public void StartManipulation(MyState state, MyEntity otherEntity, Vector3D hitPosition, ref MatrixD ownerWorldHeadMatrix, bool fromServer = false)
        {
            Debug.Assert(m_constraintInitialized == false);

            // Commenting this out to allow picking up dead bodies and characters
            if (otherEntity is MyCharacter)
            {
                return;
            }

            if (Owner == null)
            {
                Debug.Assert(!fromServer, "Desync!");
                return;
            }

            if (otherEntity.Physics == null)
            {
                return;
            }

            m_otherRigidBody   = otherEntity.Physics.RigidBody;
            m_otherPhysicsBody = otherEntity.Physics;

            if (otherEntity is MyCharacter)
            {
                if (!(otherEntity as MyCharacter).IsDead || !((otherEntity as MyCharacter).Components.Has <MyCharacterRagdollComponent>() && (otherEntity as MyCharacter).Components.Get <MyCharacterRagdollComponent>().IsRagdollActivated))
                {
                    Debug.Assert(!fromServer, "Desync!");
                    return;
                }

                m_otherRigidBody = (otherEntity as MyCharacter).Physics.Ragdoll.GetRootRigidBody();
            }
            // else (!otherEntity.Physics.RigidBody.InWorld) // Do we need to check if the body is in the world when this was returned byt RayCast ? Commenting this out for now..

            var characterMovementState = Owner.GetCurrentMovementState();

            if (!CanManipulate(characterMovementState))
            {
                Debug.Assert(!fromServer, "Desync!");
                return;
            }

            if (!CanManipulateEntity(otherEntity))
            {
                Debug.Assert(!fromServer, "Desync!");
                return;
            }

            m_otherRigidBody.Activate();

            Vector3D hitUp = Vector3D.Up;
            Vector3D hitRight;
            double   dot = Vector3D.Dot(ownerWorldHeadMatrix.Forward, hitUp);

            if (dot == 1 || dot == -1)
            {
                hitRight = ownerWorldHeadMatrix.Right;
            }
            else
            {
                hitRight = Vector3D.Cross(ownerWorldHeadMatrix.Forward, hitUp);
                hitRight.Normalize();
            }

            Vector3D hitForward = Vector3D.Cross(hitUp, hitRight);

            hitForward.Normalize();

            // Matrix of constraint for other body in world
            MatrixD otherWorldMatrix = MatrixD.Identity;

            otherWorldMatrix.Forward     = hitForward;
            otherWorldMatrix.Right       = hitRight;
            otherWorldMatrix.Up          = hitUp;
            otherWorldMatrix.Translation = hitPosition;

            const float headPivotOffset = 1.5f;

            MatrixD headPivotWorldMatrix = ownerWorldHeadMatrix;

            headPivotWorldMatrix.Translation = ownerWorldHeadMatrix.Translation + headPivotOffset * ownerWorldHeadMatrix.Forward;
            //float distanceToHead = (float)(headPivotWorldMatrix.Translation - otherWorldMatrix.Translation).Length();
            //distanceToHead = MathHelper.Clamp(distanceToHead, 0.6f, 2.5f);

            // Matrix of constraint for other body in local
            m_otherLocalPivotMatrix = (Matrix)(otherWorldMatrix * otherEntity.PositionComp.WorldMatrixNormalizedInv);
            m_otherWorldPivotOrigin = otherWorldMatrix.Translation;

            MatrixD ownerWorldMatrixInverse = MatrixD.Normalize(MatrixD.Invert(ownerWorldHeadMatrix));

            m_headLocalPivotMatrix             = Matrix.Identity;
            m_headLocalPivotMatrix.Translation = Vector3D.Transform(headPivotWorldMatrix.Translation, ownerWorldMatrixInverse);

            HkConstraintData data;

            if (state == MyState.HOLD)
            {
                if (!fromServer)
                {
                    float mass = 0;
                    if (otherEntity is MyCubeGrid)
                    {
                        var group = MyCubeGridGroups.Static.Physical.GetGroup((otherEntity as MyCubeGrid));
                        foreach (var node in group.Nodes)
                        {
                            if (node.NodeData.IsStatic) //fixed constraint on part connected to static grid isnt good idea
                            {
                                return;
                            }
                            mass += node.NodeData.Physics.Mass;
                        }
                        mass = GetRealMass(mass);
                    }
                    else if (otherEntity is MyCharacter)
                    {
                        mass = (otherEntity as MyCharacter).Definition.Mass;
                    }
                    else
                    {
                        mass = GetRealMass(m_otherRigidBody.Mass);
                    }

                    // Player can hold large projectile (~222kg)
                    if ((mass > 210) || ((otherEntity is MyCharacter) && (otherEntity.Physics.Mass > 210)))
                    {
                        return;
                    }
                }

                if (!CreateOwnerVirtualPhysics())
                {
                    return;
                }

                if (IsOwnerLocalPlayer())
                {
                    var controllingPlayer = Sync.Players.GetControllingPlayer(otherEntity);
                    if (controllingPlayer != null)
                    {
                        RemoveOwnerVirtualPhysics();
                        return;
                    }

                    if (!(otherEntity is MyCharacter)) // this would cause to start controlling the dead body..
                    {
                        Sync.Players.TrySetControlledEntity(Owner.ControllerInfo.Controller.Player.Id, otherEntity);
                    }
                }

                SetMotionOnClient(otherEntity, HkMotionType.Dynamic);

                data = CreateFixedConstraintData(ref m_otherLocalPivotMatrix, headPivotOffset);
                if (otherEntity is MyCharacter)
                {
                    if (MyFakes.MANIPULATION_TOOL_VELOCITY_LIMIT)
                    {
                        HkMalleableConstraintData mcData = data as HkMalleableConstraintData;
                        mcData.Strength = 0.005f;
                    }
                    else
                    {
                        HkFixedConstraintData fcData = data as HkFixedConstraintData;
                        fcData.MaximumAngularImpulse = 0.0005f;
                        fcData.MaximumLinearImpulse  = 0.0005f;
                        fcData.BreachImpulse         = 0.0004f;
                    }
                }
            }
            else
            {
                if (!CreateOwnerVirtualPhysics())
                {
                    return;
                }

                data = CreateBallAndSocketConstraintData(ref m_otherLocalPivotMatrix, ref m_headLocalPivotMatrix);
                if (otherEntity is MyCharacter)
                {
                    HkMalleableConstraintData mcData = data as HkMalleableConstraintData;
                    mcData.Strength = 0.005f;
                }
            }

            m_otherEntity            = otherEntity;
            m_otherEntity.OnClosing += OtherEntity_OnClosing;

            //m_otherAngularDamping = m_otherRigidBody.AngularDamping;
            //m_otherLinearDamping = m_otherRigidBody.LinearDamping;
            m_otherRestitution        = m_otherRigidBody.Restitution;
            m_otherMaxLinearVelocity  = m_otherRigidBody.MaxLinearVelocity;
            m_otherMaxAngularVelocity = m_otherRigidBody.MaxAngularVelocity;

            SetManipulated(m_otherEntity, true);
            if (state == MyState.HOLD)
            {
                if (m_otherEntity is MyCharacter)
                {
                    foreach (var body in m_otherEntity.Physics.Ragdoll.RigidBodies)
                    {
                        //body.AngularDamping = TARGET_ANGULAR_DAMPING;
                        //body.LinearDamping = TARGET_LINEAR_DAMPING;
                        //body.Mass = 5;
                        body.Restitution        = TARGET_RESTITUTION;
                        body.MaxLinearVelocity  = m_limitingLinearVelocity;
                        body.MaxAngularVelocity = (float)Math.PI * 0.1f;
                    }
                }
                else
                {
                    m_massChange = HkMassChangerUtil.Create(m_otherRigidBody, int.MaxValue, 1, 0.001f);
                    //m_otherRigidBody.AngularDamping = TARGET_ANGULAR_DAMPING;
                    //m_otherRigidBody.LinearDamping = TARGET_LINEAR_DAMPING;
                    m_otherRigidBody.Restitution        = TARGET_RESTITUTION;
                    m_otherRigidBody.MaxLinearVelocity  = m_limitingLinearVelocity;
                    m_otherRigidBody.MaxAngularVelocity = (float)Math.PI;
                }

                const float holdingTransparency = 0.4f;
                SetTransparent(otherEntity, holdingTransparency);
            }

            m_constraint = new HkConstraint(m_otherRigidBody, OwnerVirtualPhysics.RigidBody, data);

            OwnerVirtualPhysics.AddConstraint(m_constraint);

            m_constraintCreationTime = MySandboxGame.Static.UpdateTime;

            m_state = state;

            m_previousCharacterMovementState = Owner.GetCurrentMovementState();

            if (m_state == MyState.HOLD)
            {
                Owner.PlayCharacterAnimation("PickLumber", MyBlendOption.Immediate, MyFrameOption.PlayOnce, 0.2f, 1f);
            }
            else
            {
                Owner.PlayCharacterAnimation("PullLumber", MyBlendOption.Immediate, MyFrameOption.PlayOnce, 0.2f, 1f);
            }

            m_manipulatedEntitites.Add(m_otherEntity);

            Owner.ManipulatedEntity = m_otherEntity;

            var handler = ManipulationStarted;

            if (handler != null)
            {
                handler(m_otherEntity);
            }
        }
        private DamageImpactEnum GetDamageFromFall(HkRigidBody collidingBody, MyEntity collidingEntity, ref HkContactPointEvent value)
        {
            //if (m_currentMovementState != MyCharacterMovementEnum.Falling || m_currentMovementState != MyCharacterMovementEnum.Jump) return DamageImpactEnum.NoDamage;
            //if (!collidingBody.IsFixed && collidingBody.Mass < Physics.Mass * 50) return DamageImpactEnum.NoDamage;

            float dotProd = Vector3.Dot(value.ContactPoint.Normal, Vector3.Normalize(Physics.HavokWorld.Gravity));

            bool falledOnEntity = dotProd <= 0.0f;

            if (!falledOnEntity) return DamageImpactEnum.NoDamage;

            if (Math.Abs(value.SeparatingVelocity * dotProd) < MyPerGameSettings.CharacterDamageMinVelocity) return DamageImpactEnum.NoDamage;

            if (Math.Abs(value.SeparatingVelocity * dotProd) > MyPerGameSettings.CharacterDamageDeadlyDamageVelocity) return DamageImpactEnum.DeadlyDamage;

            if (Math.Abs(value.SeparatingVelocity * dotProd) > MyPerGameSettings.CharacterDamageMediumDamageVelocity) return DamageImpactEnum.MediumDamage;

            return DamageImpactEnum.SmallDamage;
        }
        private HkShape CreateBreakableBody(HkShape shape, HkMassProperties? massProperties)
        {
            ProfilerShort.Begin("CreateGridBody");

            HkdBreakableShape breakable;
            HkMassProperties massProps = massProperties.HasValue ? massProperties.Value : new HkMassProperties();

            if (!Shape.BreakableShape.IsValid())
                Shape.CreateBreakableShape();

            breakable = Shape.BreakableShape;

            if (!breakable.IsValid())
            {
                breakable = new HkdBreakableShape(shape);
                if (massProperties.HasValue)
                {
                    var mp = massProperties.Value;
                    breakable.SetMassProperties(ref mp);
                }
                else
                    breakable.SetMassRecursively(50);
            }
            else
                breakable.BuildMassProperties(ref massProps);

            shape = breakable.GetShape(); //doesnt add reference
            HkRigidBodyCinfo rbInfo = new HkRigidBodyCinfo();
            rbInfo.AngularDamping = m_angularDamping;
            rbInfo.LinearDamping = m_linearDamping;
            rbInfo.SolverDeactivation = m_grid.IsStatic ? InitialSolverDeactivation : HkSolverDeactivation.Low;
            rbInfo.ContactPointCallbackDelay = ContactPointDelay;
            rbInfo.Shape = shape;
            rbInfo.SetMassProperties(massProps);
            //rbInfo.Position = Entity.PositionComp.GetPosition(); //obsolete with large worlds?
            GetInfoFromFlags(rbInfo, Flags);
            if (m_grid.IsStatic)
            {
                rbInfo.MotionType = HkMotionType.Dynamic;
                rbInfo.QualityType = HkCollidableQualityType.Moving;
            }
            HkRigidBody rb = new HkRigidBody(rbInfo);
            if (m_grid.IsStatic)
            {
                rb.UpdateMotionType(HkMotionType.Fixed);
            }
            rb.EnableDeactivation = true;
            BreakableBody = new HkdBreakableBody(breakable, rb, null, Matrix.Identity);
            //DestructionBody.ConnectToWorld(HavokWorld, 0.05f);

            BreakableBody.AfterReplaceBody += FracturedBody_AfterReplaceBody;

            //RigidBody.SetWorldMatrix(Entity.PositionComp.WorldMatrix);
            //breakable.Dispose();

            ProfilerShort.End();
            return shape;
        }
Exemple #40
0
 private void phantom_Enter(HkPhantomCallbackShape shape, HkRigidBody body)
 {
     if (!Sync.IsServer)
         return;
     var entities = body.GetAllEntities();
     foreach (var entity in entities)
     {
         if (entity is MyFloatingObject)
         {
             m_entitiesToTake.Add(entity as MyFloatingObject);
             NeedsUpdate |= MyEntityUpdateEnum.BEFORE_NEXT_FRAME;
         }
     }
     entities.Clear();
     //if (!Sync.IsServer)
     //    return;
     //var entity = body.GetEntity();
     //if (entity is MyFloatingObject)
     //{
     //    m_inventory.TakeFloatingObject(entity as MyFloatingObject);
     //}
 }
        private void ApplyForceWorld(Vector3? force, Vector3D? position, HkRigidBody rigidBody)
        {
            if (rigidBody == null || force == null || MyUtils.IsZero(force.Value))
                return;

            var offset = MyPhysics.Clusters.GetObjectOffset(ClusterObjectID);

            if (position.HasValue)
            {
                Vector3 point = position.Value - offset;
                rigidBody.ApplyForce(MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS, force.Value, point);
            }
            else
                rigidBody.ApplyForce(MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS, force.Value);
        }
        protected virtual void CreateBody(ref HkShape shape, HkMassProperties? massProperties)
        {
            ProfilerShort.Begin("CreateBody");
            HkRigidBodyCinfo rbInfo = new HkRigidBodyCinfo();

            rbInfo.AngularDamping = m_angularDamping;
            rbInfo.LinearDamping = m_linearDamping;
            rbInfo.Shape = shape;
            rbInfo.SolverDeactivation = InitialSolverDeactivation;
            rbInfo.ContactPointCallbackDelay = ContactPointDelay;

            if (massProperties.HasValue)
            {
                rbInfo.SetMassProperties(massProperties.Value);
            }

            GetInfoFromFlags(rbInfo, Flags);

            RigidBody = new HkRigidBody(rbInfo);

            ProfilerShort.End();
        }
        private static void AddForceTorqueBody(Vector3? force, Vector3? torque, HkRigidBody rigidBody, ref Matrix transform)
        {
            Matrix tempM = transform;
            tempM.Translation = Vector3.Zero;

            if (force != null && !MyUtils.IsZero(force.Value))
            {
                Vector3 tmpForce = Vector3.Transform(force.Value, tempM);
                rigidBody.ApplyLinearImpulse(tmpForce * MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS * MyFakes.SIMULATION_SPEED);
            }

            if (torque != null && !MyUtils.IsZero(torque.Value))
            {
                Vector3 tmpTorque = Vector3.Transform(torque.Value, tempM);
                rigidBody.ApplyAngularImpulse(tmpTorque * MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS * MyFakes.SIMULATION_SPEED);
            }
        }
 public HkRigidBody SwitchRigidBody(HkRigidBody newBody)
 {
     HkRigidBody old = RigidBody;
     RigidBody = newBody;
     return old;
 }
        private DamageImpactEnum GetDamageFromHit(HkRigidBody collidingBody, MyEntity collidingEntity, ref HkContactPointEvent value)
        {
            if (collidingBody.LinearVelocity.Length() < MyPerGameSettings.CharacterDamageHitObjectMinVelocity) return DamageImpactEnum.NoDamage;

            if (collidingEntity == ManipulatedEntity) return DamageImpactEnum.NoDamage;

            if (collidingBody.HasProperty(HkCharacterRigidBody.MANIPULATED_OBJECT)) return DamageImpactEnum.NoDamage;

            var mass = (MyPerGameSettings.Destruction ? MyDestructionHelper.MassFromHavok(collidingBody.Mass) : collidingBody.Mass);
            if (mass < MyPerGameSettings.CharacterDamageHitObjectMinMass) return DamageImpactEnum.NoDamage;

            // Get the objects energies to calculate the damage - must be higher above treshold
            float objectEnergy = Math.Abs(value.SeparatingVelocity) * mass;

            if (objectEnergy > MyPerGameSettings.CharacterDamageHitObjectDeadlyEnergy) return DamageImpactEnum.DeadlyDamage;
            if (objectEnergy > MyPerGameSettings.CharacterDamageHitObjectCriticalEnergy) return DamageImpactEnum.CriticalDamage;
            if (objectEnergy > MyPerGameSettings.CharacterDamageHitObjectMediumEnergy) return DamageImpactEnum.MediumDamage;
            if (objectEnergy > MyPerGameSettings.CharacterDamageHitObjectSmallEnergy) return DamageImpactEnum.SmallDamage;

            return DamageImpactEnum.NoDamage;
        }
        private void DoDetection(bool useHead, bool doModelIntersection)
        {
            if (Character == MySession.Static.ControlledEntity)
            {
                MyHud.SelectedObjectHighlight.RemoveHighlight();
            }

            var      head = Character.GetHeadMatrix(false);
            Vector3D from = head.Translation;
            Vector3D dir  = head.Forward;

            if (!useHead)
            {
                var headPos = head.Translation - (Vector3D)head.Forward * 0.3; // Move to center of head, we don't want eyes (in front of head)

                if (Character == MySession.Static.LocalCharacter)
                {
                    from = MySector.MainCamera.WorldMatrix.Translation;
                    dir  = MySector.MainCamera.WorldMatrix.Forward;

                    from = MyUtils.LinePlaneIntersection(headPos, (Vector3)dir, from, (Vector3)dir);
                }
                else
                {
                    from = headPos;
                    dir  = head.Forward;
                }
            }

            Vector3D to = from + dir * 2.5;//MyConstants.DEFAULT_INTERACTIVE_DISTANCE;

            StartPosition = from;

            MatrixD   matrix    = MatrixD.CreateTranslation(from);
            HkShape   shape     = new HkSphereShape(ShapeRadius);
            IMyEntity hitEntity = null;

            ShapeKey    = uint.MaxValue;
            HitPosition = Vector3D.Zero;
            HitNormal   = Vector3.Zero;
            HitMaterial = MyStringHash.NullOrEmpty;
            HitTag      = null;
            m_hits.Clear();

            Vector3 interactivePosition = Vector3D.Zero;

            try
            {
                EnableDetectorsInArea(from);

                MyPhysics.CastShapeReturnContactBodyDatas(to, shape, ref matrix, 0, 0f, m_hits);

                m_rayOrigin    = from;
                m_rayDirection = dir;
                m_hits.Sort(CompareHits);

                if (m_hits.Count > 0)
                {
                    bool isValidBlock    = false;
                    bool isPhysicalBlock = false;

                    for (int index = 0; index < m_hits.Count; index++)
                    {
                        HkRigidBody body   = m_hits[index].HkHitInfo.Body;
                        IMyEntity   entity = m_hits[index].HkHitInfo.GetHitEntity();

                        // Ignore self-interaction
                        if (entity == Character)
                        {
                            continue;
                        }

                        if (entity is VRage.Game.Entity.MyEntitySubpart)
                        {
                            entity = entity.Parent;
                        }

                        isValidBlock    = body != null && entity != null && entity != Character && !body.HasProperty(HkCharacterRigidBody.MANIPULATED_OBJECT);
                        isPhysicalBlock = entity != null && entity.Physics != null;

                        if (hitEntity == null && isValidBlock)
                        {
                            hitEntity = entity;
                            ShapeKey  = m_hits[index].HkHitInfo.GetShapeKey(0);
                        }

                        // If hit-entity is a grid, raycast it to see which block we hit first
                        if (entity is MyCubeGrid)
                        {
                            MyCubeGrid    grid     = entity as MyCubeGrid;
                            List <MyCube> cubeList = grid.RayCastBlocksAllOrdered(from, to);
                            if (cubeList != null && cubeList.Count > 0)
                            {
                                var slimblock = cubeList[0].CubeBlock;
                                if (slimblock.FatBlock != null)
                                {
                                    entity          = slimblock.FatBlock;
                                    isPhysicalBlock = true;
                                    hitEntity       = entity;
                                    ShapeKey        = 0;
                                }
                            }
                        }

                        // Set hit material etc. only for object's that have physical representation in the world, this exclude detectors
                        if (HitMaterial.Equals(MyStringHash.NullOrEmpty) && isValidBlock && isPhysicalBlock)
                        {
                            HitBody     = body;
                            HitNormal   = m_hits[index].HkHitInfo.Normal;
                            HitPosition = m_hits[index].GetFixedPosition();
                            HitMaterial = body.GetBody().GetMaterialAt(HitPosition);

                            interactivePosition = HitPosition;
                            break;
                        }
                        else if (body != null)
                        {
                            interactivePosition = m_hits[index].GetFixedPosition();
                            break;
                        }

                        index++;
                    }
                }
            }
            finally
            {
                shape.RemoveReference();
            }

            bool hasInteractive = false;

            var interactive = hitEntity as IMyUseObject;

            DetectedEntity = hitEntity;

            if (hitEntity != null)
            {
                MyUseObjectsComponentBase useObject = null;
                hitEntity.Components.TryGet <MyUseObjectsComponentBase>(out useObject);
                if (useObject != null)
                {
                    interactive = useObject.GetInteractiveObject(ShapeKey);
                }

                // Do accurate collision checking on model
                if (doModelIntersection)
                {
                    LineD line      = new LineD(from, to);
                    var   character = hitEntity as MyCharacter;
                    if (character == null)
                    {
                        MyIntersectionResultLineTriangleEx?result;
                        bool success = hitEntity.GetIntersectionWithLine(ref line, out result, IntersectionFlags.ALL_TRIANGLES);
                        if (success)
                        {
                            HitPosition = result.Value.IntersectionPointInWorldSpace;
                            HitNormal   = result.Value.NormalInWorldSpace;
                        }
                    }
                    else
                    {
                        bool success = character.GetIntersectionWithLine(ref line, ref CharHitInfo);
                        if (success)
                        {
                            HitPosition = CharHitInfo.Triangle.IntersectionPointInWorldSpace;
                            HitNormal   = CharHitInfo.Triangle.NormalInWorldSpace;
                            HitTag      = CharHitInfo;
                        }
                    }
                }
            }

            if (UseObject != null && interactive != null && UseObject != interactive)
            {
                UseObject.OnSelectionLost();
            }

            if (interactive != null && interactive.SupportedActions != UseActionEnum.None && (Vector3D.Distance(from, interactivePosition)) < interactive.InteractiveDistance && Character == MySession.Static.ControlledEntity)
            {
                HandleInteractiveObject(interactive);

                UseObject      = interactive;
                hasInteractive = true;
            }

            if (!hasInteractive)
            {
                if (UseObject != null)
                {
                    UseObject.OnSelectionLost();
                }

                UseObject = null;
            }

            DisableDetectors();
        }
Exemple #47
0
 private void phantom_Leave(HkPhantomCallbackShape shape, HkRigidBody body)
 {
     if (!Sync.IsServer)
         return;
     var entities = body.GetAllEntities();
     foreach(var entity in entities)
         m_entitiesToTake.Remove(entity as MyFloatingObject);
     entities.Clear();
 }
        private void phantom_EnterEjector(HkPhantomCallbackShape shape, HkRigidBody body)
        {
            ProfilerShort.Begin("ShipConnectorEnterEjector");
            bool updateEmissivity = false;
            var entities = body.GetAllEntities();
            foreach (var entity in entities)
            {
                Debug.Assert(entity is MyFloatingObject);
                if (entity is MyFloatingObject)
                {
                    updateEmissivity |= (m_detectedFloaters.Count == 1);
                    m_detectedFloaters.Add(entity);
                }
            }
            entities.Clear();

            if (updateEmissivity)
                UpdateEmissivity();
            ProfilerShort.End();
        }
        public virtual void CreateFromCollisionObject(HkShape shape, Vector3 center, MatrixD worldTransform, HkMassProperties? massProperties = null, int collisionFilter = MyPhysics.DefaultCollisionLayer)
        {
            MyPhysics.AssertThread();

            VRageRender.MyRenderProxy.GetRenderProfiler().StartProfilingBlock("MyPhysicsBody::CreateFromCollisionObject()");
            Debug.Assert(RigidBody == null, "Must be removed from scene and null");

            CloseRigidBody();

            Center = center;
            CanUpdateAccelerations = true;

            //m_motionState = new MyMotionState(worldTransform);

            CreateBody(ref shape, massProperties);

            RigidBody.UserObject = this;
            //RigidBody.SetWorldMatrix(worldTransform);
            RigidBody.Layer = collisionFilter;

            if ((int)(Flags & RigidBodyFlag.RBF_DISABLE_COLLISION_RESPONSE) > 0)
            {
                RigidBody.Layer = MyPhysics.NoCollisionLayer;
            }
            
            if ((int)(Flags & RigidBodyFlag.RBF_DOUBLED_KINEMATIC) > 0)
            {
                HkRigidBodyCinfo rbInfo2 = new HkRigidBodyCinfo();
                rbInfo2.AngularDamping = m_angularDamping;
                rbInfo2.LinearDamping = m_linearDamping;
                rbInfo2.Shape = shape;

                rbInfo2.MotionType = HkMotionType.Keyframed;
                rbInfo2.QualityType = HkCollidableQualityType.Keyframed;

                RigidBody2 = new HkRigidBody(rbInfo2);
                RigidBody2.UserObject = this;
                RigidBody2.SetWorldMatrix(worldTransform);
            }

            //m_motionState.Body = this;

            VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();
        }
        private void phantom_EnterConnector(HkPhantomCallbackShape shape, HkRigidBody body)
        {
            ProfilerShort.Begin("ShipConnectorEnterConnector");
            var entities = body.GetAllEntities();
            using (entities.GetClearToken())
            {
                foreach (var entity in entities)
                {
                    var other = entity as MyCubeGrid;
                    if (other == null || other == this.CubeGrid)
                        continue;

                    m_detectedGrids.Add(other);
                }
            }
            ProfilerShort.End();
        }
        /// <summary>
        /// Called when [motion].
        /// </summary>
        /// <param name="rbo">The rbo.</param>
        /// <param name="step">The step.</param>
        public virtual void OnMotion(HkRigidBody rbo, float step)
        {
            if (Entity == null)
                return;

            if (this.Flags == RigidBodyFlag.RBF_DISABLE_COLLISION_RESPONSE)
            {
                return;
            }

            if (IsPhantom)
            {
                return;
            }

            ProfilerShort.Begin(RigidBody2 != null ? "Double kinematic" : "Normal");

            ProfilerShort.Begin("Update acceleration");
            if (CanUpdateAccelerations)
                UpdateAccelerations();
            ProfilerShort.End();

            if (RigidBody2 != null && rbo == RigidBody)
            {
                // To prevent disconnect movement between dynamic and kinematic
                // Setting motion to prevent body activation (we don't want to activate kinematic body)
                ProfilerShort.Begin("Set doubled body");
                RigidBody2.Motion.SetWorldMatrix(rbo.GetRigidBodyMatrix());
                ProfilerShort.End();
            }

            if (LinearVelocity.LengthSquared() > 0.000005f || AngularVelocity.LengthSquared() > 0.000005f)
            {
                ProfilerShort.Begin("GetWorldMatrix");
                var matrix = GetWorldMatrix();
                ProfilerShort.End();

                ProfilerShort.Begin("SetWorldMatrix");
                this.Entity.PositionComp.SetWorldMatrix(matrix, this);
                ProfilerShort.End();
            }

            ProfilerShort.Begin("UpdateCluster");
            UpdateCluster();
            ProfilerShort.End();

            ProfilerShort.End();
        }
 private void phantom_LeaveEjector(HkPhantomCallbackShape shape, HkRigidBody body)
 {
     var updateEmissivity = (m_detectedFloaters.Count == 2);
     m_detectedFloaters.Remove(body.GetEntity());
     if (updateEmissivity)
         UpdateEmissivity();
 }
 private void phantom_Leave(HkPhantomCallbackShape shape, HkRigidBody body)
 {
     ProfilerShort.Begin("MergeLeave");
     var entities = MyPhysicsExtensions.GetAllEntities(body);
     foreach (var entity in entities)
     {
         m_gridList.Remove(entity as MyCubeGrid);
     }
     entities.Clear();
     ProfilerShort.End();
 }
        private void phantom_EnterEjector(HkPhantomCallbackShape shape, HkRigidBody body)
        {
            var entity = body.GetEntity();

            Debug.Assert(entity is MyFloatingObject);
            if (entity is MyFloatingObject)
            {
                var updateEmissivity = (m_detectedFloaters.Count == 1);
                m_detectedFloaters.Add(entity);
                if (updateEmissivity)
                    UpdateEmissivity();
            }
        }
        private void Attach(HkRigidBody body, Vector3 gearSpacePivot, Matrix otherBodySpacePivot)
        {
            if (CubeGrid.Physics.Enabled)
            {
                var entity = body.GetEntity();
                Debug.Assert(m_attachedTo == null, "Already attached");
                Debug.Assert(entity != null, "Landing gear is attached to body which has no entity");
                Debug.Assert(m_constraint == null);

                if (m_attachedTo != null || entity == null || m_constraint != null)
                    return;

                body.Activate();
                CubeGrid.Physics.RigidBody.Activate();

                m_attachedTo = entity;

                if (entity != null)
                {
                    entity.OnPhysicsChanged += m_physicsChangedHandler;
                }

                this.OnPhysicsChanged += m_physicsChangedHandler;

                Matrix gearLocalSpacePivot = Matrix.Identity;
                gearLocalSpacePivot.Translation = gearSpacePivot;
                
                var fixedData = new HkFixedConstraintData();
                if (MyFakes.OVERRIDE_LANDING_GEAR_INERTIA)
                {
                    fixedData.SetInertiaStabilizationFactor(MyFakes.LANDING_GEAR_INTERTIA);
                }
                else
                {
                    fixedData.SetInertiaStabilizationFactor(1);
                }

                fixedData.SetSolvingMethod(HkSolvingMethod.MethodStabilized);
                fixedData.SetInBodySpace(ref gearLocalSpacePivot, ref otherBodySpacePivot);

                HkConstraintData data = fixedData;

                if (MyFakes.LANDING_GEAR_BREAKABLE && BreakForce < MaxSolverImpulse)
                {
                    var breakData = new HkBreakableConstraintData(fixedData);
                    fixedData.Dispose();

                    breakData.Threshold = BreakForce;
                    breakData.ReapplyVelocityOnBreak = true;
                    breakData.RemoveFromWorldOnBrake = true;

                    data = breakData;
                }

                if (!m_needsToRetryLock)
                    StartSound(m_lockSound);

                m_constraint = new HkConstraint(CubeGrid.Physics.RigidBody, body, data);
                CubeGrid.Physics.AddConstraint(m_constraint);
                m_constraint.Enabled = true;

                LockMode = LandingGearMode.Locked;
                if (CanAutoLock)
                    ResetAutolock();

                OnConstraintAdded(GridLinkTypeEnum.Physical, entity);
                OnConstraintAdded(GridLinkTypeEnum.NoContactDamage, entity);

                var handle = StateChanged;
                if (handle != null) handle(true);
            }
        }
Exemple #56
0
 private static bool IsDynamicGrid(HkRigidBody rb, MyGridPhysics grid)
 {
     return(grid != null && grid.RigidBody == rb && !grid.IsStatic);
 }
 private static bool IsDynamicGrid(HkRigidBody rb, MyGridPhysics grid)
 {
     return (grid != null && grid.RigidBody == rb && !grid.IsStatic);
 }
 private void phantom_LeaveEjector(HkPhantomCallbackShape shape, HkRigidBody body)
 {
     ProfilerShort.Begin("ShipConnectorLeaveEjector");
     var updateEmissivity = (m_detectedFloaters.Count == 2);
     var entities = body.GetAllEntities();
     foreach (var entity in entities)
         m_detectedFloaters.Remove(entity);
     entities.Clear();
     if (updateEmissivity)
         UpdateEmissivity();
     ProfilerShort.End();
 }
        public static void TriggerDestruction(HkWorld world, HkRigidBody body, Vector3 havokPosition, float radius = 0.0005f)
        {
            Havok.HkdFractureImpactDetails details = Havok.HkdFractureImpactDetails.Create();
            details.SetBreakingBody(body);
            details.SetContactPoint(havokPosition);
            details.SetDestructionRadius(radius);
            details.SetBreakingImpulse(Sandbox.MyDestructionConstants.STRENGTH * 10);
            //details.SetParticlePosition(havokPosition);
            //details.SetParticleMass(1000000);
            details.Flag = details.Flag | Havok.HkdFractureImpactDetails.Flags.FLAG_DONT_RECURSE;

            Sandbox.Engine.Physics.MyPhysics.FractureImpactDetails destruction = new Sandbox.Engine.Physics.MyPhysics.FractureImpactDetails();
            destruction.Details = details;
            destruction.World = world;
            Sandbox.Engine.Physics.MyPhysics.EnqueueDestruction(destruction);
        }
 private void phantom_LeaveConnector(HkPhantomCallbackShape shape, HkRigidBody body)
 {
     ProfilerShort.Begin("ShipConnectorLeaveConnector");
     var entities = body.GetAllEntities();
     foreach (var entity in entities)
     {
          m_detectedGrids.Remove(entity as MyCubeGrid);
     }
     entities.Clear();
     ProfilerShort.End();
 }