public bool Update(MyPlayer player, MyEntity entity) //returns if lost
        {
            //MySessionComponentMission.Static.TryCreateFromDefault(Id);

            //if (IsLocal(player.Id))
            //    UpdateLocal(player.Id);

            if (!Sync.IsServer)
                return false;

            MyMissionTriggers mtrig;
            if (!MissionTriggers.TryGetValue(player.Id, out mtrig))
            {
                //Debug.Assert(false,"Bad ID for update in missionTriggers");
                mtrig = TryCreateFromDefault(player.Id, false);
            }
            mtrig.UpdateWin(player, entity);
            if (!mtrig.Won)
                mtrig.UpdateLose(player, entity);
            else
            {
                m_someoneWon = true;
                MyAnalyticsHelper.ReportTutorialEnd();
            }
            return mtrig.Lost;
        }
 public override bool Update(MyEntity me)
 {
     bool isSomethingAlive=false;
     foreach(var item in m_blocks)
     {
         if (item.Value == BlockState.MessageShown)
             continue;
         if (item.Key.SlimBlock.IsDestroyed)
         {
             m_blocksHelper.Add(item.Key);
             continue;
         }
         isSomethingAlive = true;
     }
     if (!isSomethingAlive)
         m_IsTrue = true;
     if (m_blocksHelper.Count()>0)
     {
         foreach(var block in m_blocksHelper)
             m_blocks[block] = BlockState.Destroyed;
         m_blocksHelper.Clear();
         m_needsSingleMessage = true;
     }
     return base.Update(me);
 }
 public override bool Update(MyEntity me)
 {
     if (MySession.Static.IsScenario)
         if (m_limit <= DateTime.UtcNow - MyScenarioSystem.Static.ServerStartGameTime)
             m_IsTrue = true;
     return IsTrue;
 }
 public override ChangeInfo Update(MyEntity owner, long playerID = 0)
 {
     if (MyCubeBuilder.Static==null)
         return ChangeInfo.None;
     var blockDefinition = MyCubeBuilder.Static.IsActivated ? MyCubeBuilder.Static.ToolbarBlockDefinition : null;
     if ((MyCubeBuilder.Static.BlockCreationIsActivated || MyCubeBuilder.Static.MultiBlockCreationIsActivated) && blockDefinition != null && (!MyFakes.ENABLE_BATTLE_SYSTEM || !MySession.Static.Battle))
     {
         var blockDef = (this.Definition as Sandbox.Definitions.MyCubeBlockDefinition);
         if (blockDefinition.BlockPairName == blockDef.BlockPairName)
         {
             WantsToBeSelected = true;
         }
         else if (blockDef.BlockStages != null && blockDef.BlockStages.Contains(blockDefinition.Id))
         {
             WantsToBeSelected = true;
         }
         else
         {
             WantsToBeSelected = false;
         }
     }
     else
     {
         WantsToBeSelected = false;
     }
     return ChangeInfo.None;
 }
示例#5
0
 public void SetAbsoluteTarget(Vector3 absoluteTarget)
 {
     m_mode = AimingMode.TARGET;
     m_aimTarget = null;
     m_relativeTarget = absoluteTarget;
     Update();
 }
 public override bool Update(MyPlayer player, MyEntity me)
 {
     if (me!=null)
         if (Vector3D.DistanceSquared(me.PositionComp.GetPosition(), TargetPos) < m_maxDistance2)
             m_IsTrue = true;
     return IsTrue;
 }
		public override void Unregister(MyEntity entity, Vector3I forwardVector)
		{
			base.Unregister(entity, forwardVector);
			var thrust = entity as MyThrust;
			if (thrust == null)
				return;

			thrust.EnabledChanged -= thrust_EnabledChanged;
			thrust.SlimBlock.ComponentStack.IsFunctionalChanged -= ComponentStack_IsFunctionalChanged;

            // Need to recalculate the slowdown factor. Maybe save different levels of the factors and just revert back to previous one
		    SlowdownFactor = 0f;
		    foreach (var direction in Base6Directions.IntDirections)
		    {
		        foreach (var dataByType in m_dataByFuelType)
		        {
		            foreach (var entityInDirection in dataByType.ThrustsByDirection[direction])
		            {
		                var thrustInDirection = entityInDirection as MyThrust;
		                if (thrustInDirection == null)
		                    continue;

		                SlowdownFactor = Math.Max(thrustInDirection.BlockDefinition.SlowdownFactor, SlowdownFactor);
		            }
		        }
		    }
		}
示例#8
0
        //  Not used apparently
        public static void AddShotgun(MyProjectileAmmoDefinition ammoDefinition, MyEntity ignorePhysObject, Vector3 origin, Vector3 initialVelocity, Vector3 directionNormalized, bool groupStart, float thicknessMultiplier, MyEntity weapon, float frontBillboardSize, MyEntity ownerEntity = null, float projectileCountMultiplier = 1)
        {
            MyProjectile newProjectile = m_projectiles.Allocate();
            if (newProjectile != null)
            {
                //newProjectile.Start(
                //    ammoDefinition,
                //    ignorePhysObject,
                //    origin,
                //    initialVelocity,
                //    directionNormalized,
                //    groupStart,
                //    thicknessMultiplier,
                //    1,
                //    weapon,
                //    projectileCountMultiplier
                //    );

            //    newProjectile.BlendByCameraDirection = true;
            //    newProjectile.FrontBillboardMaterial = "ShotgunParticle";
            //    newProjectile.LengthMultiplier = 2;
            //    newProjectile.FrontBillboardSize = frontBillboardSize;
             //   newProjectile.OwnerEntity = ownerEntity != null ? ownerEntity : ignorePhysObject;
            }
        }
        private void voxelMap_OnClose(MyEntity entity)
        {
            var voxelMap = entity as MyVoxelMap;
            if (voxelMap == null) return;

            m_navigationMeshes.Remove(voxelMap);
        }
示例#10
0
 public void SetTarget(MyEntity entity, Vector3? relativeTarget = null)
 {
     m_followMovement = false;
     m_aimTarget = entity;
     m_relativeTarget = relativeTarget;
     Update();
 }
示例#11
0
 public void SetTarget(MyEntity entity, Vector3? relativeTarget = null)
 {
     m_mode = AimingMode.TARGET;
     m_aimTarget = entity;
     m_relativeTarget = relativeTarget;
     Update();
 }
示例#12
0
 public void SetAbsoluteTarget(Vector3 absoluteTarget)
 {
     m_followMovement = false;
     m_aimTarget = null;
     m_relativeTarget = absoluteTarget;
     Update();
 }
        public MyEntity Spawn(MyFixedPoint amount, MatrixD worldMatrix, MyEntity owner = null)
        {
            if (Content is MyObjectBuilder_BlockItem)
            {
                Debug.Assert(MyFixedPoint.IsIntegral(amount), "Spawning fractional number of grids!");

                var blockItem = Content as MyObjectBuilder_BlockItem;
                var builder = MyObjectBuilderSerializer.CreateNewObject(typeof(MyObjectBuilder_CubeGrid)) as MyObjectBuilder_CubeGrid;
                builder.GridSizeEnum = MyCubeSize.Small;
                builder.IsStatic = false;
                builder.PersistentFlags |= MyPersistentEntityFlags2.InScene | MyPersistentEntityFlags2.Enabled;
                builder.PositionAndOrientation = new MyPositionAndOrientation(worldMatrix);

                var block = MyObjectBuilderSerializer.CreateNewObject(blockItem.BlockDefId) as MyObjectBuilder_CubeBlock;
                builder.CubeBlocks.Add(block);

                MyCubeGrid firstGrid = null;
                for (int i = 0; i < amount; ++i)
                {
                    builder.EntityId = MyEntityIdentifier.AllocateId();
                    block.EntityId = MyEntityIdentifier.AllocateId();
                    MyCubeGrid newGrid = MyEntities.CreateFromObjectBuilder(builder) as MyCubeGrid;
                    firstGrid = firstGrid ?? newGrid;
                    MyEntities.Add(newGrid);
                    Sandbox.Game.Multiplayer.MySyncCreate.SendEntityCreated(builder);
                }
                return firstGrid;
            }
            else
                return MyFloatingObjects.Spawn(new MyPhysicalInventoryItem(amount, Content),worldMatrix, owner != null ? owner.Physics : null);
        }
示例#14
0
        private void MyEntities_OnEntityAdd(MyEntity entity)
        {
            var voxelMap = entity as MyVoxelMap;
            if (voxelMap == null) return;

            m_navigationMeshes.Add(voxelMap, new MyVoxelNavigationMesh(voxelMap, m_coordinator, MyAIComponent.Static.Pathfinding.NextTimestampFunction));
            RegisterVoxelMapEvents(voxelMap);
        }
示例#15
0
 void m_entity_OnClose(MyEntity obj)
 {
     if (m_shotSmoke != null)
     {
         MyParticlesManager.RemoveParticleEffect(m_shotSmoke);
         m_shotSmoke = null;
     }
 }
	    protected override float CalculateForceMultiplier(MyEntity thrustEntity)
	    {


	        float forceMultiplier = 1.0f;

	        return forceMultiplier;
	    }
        public override ChangeInfo Update(MyEntity owner, long playerID = 0)
        {
            bool thisWeaponIsCurrent = false;
            bool shipHasThisWeapon = false;
            var character = MySession.LocalCharacter;
            bool characterHasThisWeapon = character != null && (character.GetInventory().ContainItems(1, Definition.Id) || MyPerGameSettings.EnableWeaponWithoutInventory);
            ChangeInfo changed = ChangeInfo.None;

            if (characterHasThisWeapon)
            {
                var currentWeapon = character.CurrentWeapon;
                if (currentWeapon != null)
                    thisWeaponIsCurrent = MyDefinitionManager.Static.GetPhysicalItemForHandItem(currentWeapon.DefinitionId).Id == Definition.Id;
                if (thisWeaponIsCurrent && currentWeapon is MyAutomaticRifleGun)
                {
                    int amount = character.CurrentWeapon.GetAmmunitionAmount();
                    if (m_lastAmmoCount != amount)
                    {
                        m_lastAmmoCount = amount;
                        IconText.Clear().AppendInt32(amount);
                        changed |= ChangeInfo.IconText;
                    }
                }
            }

            var shipControler = MySession.ControlledEntity as MyShipController;
            if (shipControler != null && shipControler.GridSelectionSystem.WeaponSystem != null)
            {
            //    var shipWeaponType = shipControler.GetWeaponType(Definition.Id.TypeId);
            //    shipHasThisWeapon = shipWeaponType.HasValue && shipControler.GridSelectionSystem.WeaponSystem.HasGunsOfId(shipWeaponType.Value);
                shipHasThisWeapon = shipControler.GridSelectionSystem.WeaponSystem.HasGunsOfId(Definition.Id);
                if (shipHasThisWeapon)
                {
                    IMyGunObject<MyDeviceBase> gunObject = shipControler.GridSelectionSystem.WeaponSystem.GetGun(Definition.Id);
                    if (gunObject.GunBase is MyGunBase)
                    {
                        int ammo = 0;
                        foreach (var gun in shipControler.GridSelectionSystem.WeaponSystem.GetGunsById(Definition.Id))
                        {
                            ammo += gun.GetAmmunitionAmount();
                        }
                        if (ammo != m_lastAmmoCount)
                        {
                            m_lastAmmoCount = ammo;
                            IconText.Clear().AppendInt32(ammo);
                            changed |= ChangeInfo.IconText;
                        }
                    }
                }

                thisWeaponIsCurrent = shipControler.GridSelectionSystem.GetGunId() == Definition.Id;
            }

            changed |= SetEnabled(characterHasThisWeapon || shipHasThisWeapon);
            WantsToBeSelected = thisWeaponIsCurrent;
            m_needsWeaponSwitching = !thisWeaponIsCurrent;
            return changed;
        }
示例#18
0
        /// <summary>
        /// Algorithm to predict the position of the target
        /// </summary>
     
        public static bool GetPredictedTargetPosition(MyGunBase gun, MyEntity shooter, MyEntity target, out Vector3 predictedPosition, out float timeToHit, float shootDelay = 0)
        {
            Debug.Assert(target != null && target.PositionComp != null, "Null target!");
            Debug.Assert(shooter != null && shooter.PositionComp != null, "Null shooter!");

            if (target == null || target.PositionComp == null || shooter == null || shooter.PositionComp == null)
            {
                predictedPosition = Vector3.Zero;
                timeToHit = 0;
                return false;
            }
            
            Vector3 targetPosition = target.PositionComp.WorldAABB.Center;
            Vector3 muzzlePosition = gun.GetMuzzleWorldPosition();
            
            Vector3 toTarget = targetPosition - muzzlePosition;
            Vector3 targetVelocity = Vector3.Zero;
            if (target.Physics != null)
            {
                targetVelocity = target.Physics.LinearVelocity;
            }
            Vector3 shooterVelocity = Vector3.Zero;
            if (shooter.Physics != null)
            {
                shooterVelocity = shooter.Physics.LinearVelocity;
            }
            Vector3 diffVelocity = targetVelocity - shooterVelocity;

            float projectileSpeed = GetProjectileSpeed(gun);

            float a = diffVelocity.LengthSquared() - projectileSpeed * projectileSpeed;
            float b = 2 * Vector3.Dot(diffVelocity, toTarget);
            float c = toTarget.LengthSquared();

            float p = -b / (2 * a);
            float q = (float)Math.Sqrt((b * b) - 4 * a * c) / (2 * a);

            float t1 = p - q;
            float t2 = p + q;
            float t;

            if (t1 > t2 && t2 > 0)
            {
                t = t2;
            }
            else
            {
                t = t1;
            }

            t = t + shootDelay;

            predictedPosition = targetPosition + diffVelocity * t;
            Vector3 bulletPath = predictedPosition - muzzlePosition;
            timeToHit = bulletPath.Length() / projectileSpeed;

            return true;
        }
示例#19
0
        void grid_OnClose(MyEntity entity)
        {
            var grid = entity as MyCubeGrid;
            if (grid == null) return;

            if (!GridCanHaveNavmesh(grid)) return;

            m_coordinator.RemoveGridNavmeshLinks(grid);
            m_navigationMeshes.Remove(grid);
        }
        public void StartManipulation(MyManipulationTool.MyState state, MyEntity otherEntity, Vector3D hitPosition, ref MatrixD ownerWorldHeadMatrix)
        {
            StartManipulationMsg msg = new StartManipulationMsg();
            msg.EntityId = m_entityId;
            msg.ToolState = state;
            msg.OtherEntity = otherEntity.EntityId;
            msg.HitPosition = hitPosition;
            msg.OwnerWorldHeadMatrix = ownerWorldHeadMatrix;

            MySession.Static.SyncLayer.SendMessageToAllAndSelf(ref msg);
        }
 public override ChangeInfo Update(MyEntity owner, long playerID = 0)
 {
     if (ActionId == null)
     {
         var actions = AllActions;
         if (actions.Count > 0)
         {
             ActionId = actions.ItemAt(0).Id;
         }
     }
     return ChangeInfo.None;
 }
        static BoundingBoxD GetEntityAABB(MyEntity entity)
        {
            BoundingBoxD bbox = entity.PositionComp.WorldAABB;

            //Include entity velocity to be able to hit fast moving objects
            if (entity.Physics != null)
            {
                bbox = bbox.Include(entity.WorldMatrix.Translation + entity.Physics.LinearVelocity * MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS * 5);
            }

            return bbox;
        }
        public override void Init(MyEntity entity, MyLargeTurretBase turretBase)
        {
            base.Init(entity, turretBase);

            // backward compatibility with old models/mods
            if (!m_gunBase.HasDummies)
            {
                Matrix muzzle = Matrix.Identity;
                muzzle.Translation += entity.PositionComp.WorldMatrix.Forward * 3;
                m_gunBase.AddMuzzleMatrix(MyAmmoType.Missile, muzzle);
            }
        }
示例#24
0
        private void MyEntities_OnEntityAdd(MyEntity entity)
        {
            var grid = entity as MyCubeGrid;
            if (grid == null) return;

            // CH: TODO: Don't add all grids immediately. E.g. copy-paste preview grids don't need to be added

            if (!GridCanHaveNavmesh(grid)) return;

            m_navigationMeshes.Add(grid, new MyGridNavigationMesh(grid, m_coordinator, 32, MyAIComponent.Static.Pathfinding.NextTimestampFunction));
            RegisterGridEvents(grid);
        }
示例#25
0
        public static void DoDamageSynced(MyEntity destroyable, float damage, MyDamageType type)
        {
            Debug.Assert(Sync.IsServer || destroyable.SyncObject is MySyncEntity || (destroyable.SyncObject as MySyncEntity).ResponsibleForUpdate(Sync.Clients.LocalClient));
            if (!(destroyable is IMyDestroyableObject))
                return;

            var msg = new DoDamageMsg();
            msg.DestroyableEntityId = destroyable.EntityId;
            msg.Damage = damage;
            msg.Type = type;

            (destroyable as IMyDestroyableObject).DoDamage(damage, type, false);
            Sync.Layer.SendMessageToAll<DoDamageMsg>(ref msg);
        }
示例#26
0
        public static void AddShrapnel(MyProjectileAmmoDefinition ammoDefinition, MyEntity ignoreEntity, Vector3 origin, Vector3 initialVelocity, Vector3 directionNormalized, bool groupStart, float thicknessMultiplier, float trailProbability, MyEntity weapon, MyEntity ownerEntity = null, float projectileCountMultiplier = 1)
        {
            MyProjectile newProjectile;
            m_projectiles.AllocateOrCreate(out newProjectile);

            newProjectile.Start(
                ammoDefinition,
                ignoreEntity,
                origin,
                initialVelocity,
                directionNormalized,
                weapon
                );
            newProjectile.OwnerEntity = ownerEntity != null ? ownerEntity : ignoreEntity; 
        }
        public static void Remove(MyEntity entity)
        {
            var voxelMap = entity as MyVoxelBase;
            if (voxelMap != null && voxelMap.VoxelMapPruningProxyId != MyConstants.PRUNING_PROXY_ID_UNITIALIZED)
            {
                m_voxelMapsTree.RemoveProxy(voxelMap.VoxelMapPruningProxyId);
                voxelMap.VoxelMapPruningProxyId = MyConstants.PRUNING_PROXY_ID_UNITIALIZED;
            }

            if (entity.TopMostPruningProxyId != MyConstants.PRUNING_PROXY_ID_UNITIALIZED)
            {
                m_topMostEntitiesTree.RemoveProxy(entity.TopMostPruningProxyId);
                entity.TopMostPruningProxyId = MyConstants.PRUNING_PROXY_ID_UNITIALIZED;
            }
        }
 public bool UpdateWin(MyPlayer.PlayerId Id, MyEntity me)
 {
     if (Won || Lost)
         return true;
     for (int i=0;i<m_winTriggers.Count;i++)
     {
         var trigger=m_winTriggers[i];
         if (trigger.IsTrue || trigger.Update(me))
         { //Won!
             MySyncMissionTriggers.PlayerWon(Id, i);
             return true;
         }
     }
     return false;
 }
        // This function does some modifications to the cube block's object builder before it's built, usually integrity changes, etc...
        public virtual void BeforeCreateBlock(MyCubeBlockDefinition definition, MyEntity builder, MyObjectBuilder_CubeBlock ob)
        {
            if (definition.EntityComponents == null) return;

            if (ob.ComponentContainer == null)
            {
                ob.ComponentContainer = new MyObjectBuilder_ComponentContainer();
            }

            foreach (var componentOb in definition.EntityComponents)
            {
                var data = new MyObjectBuilder_ComponentContainer.ComponentData();
                data.TypeId = componentOb.Key.ToString();
                data.Component = componentOb.Value;
                ob.ComponentContainer.Components.Add(data);
            }
        }
        public override bool HasBuildingMaterials(MyEntity builder)
        {
            if (MySession.Static.CreativeMode || MySession.Static.SimpleSurvival)
                return true;

            if (builder == null) return false;
            var inventory = GetBuilderInventory(builder);
            if (inventory == null) return false;

            bool result = true;
            foreach (var entry in m_materialList.RequiredMaterials)
            {
                result &= inventory.GetItemAmount(entry.Key) >= entry.Value;
                if (!result) break;
            }
            return result;
        }
示例#31
0
        protected bool CanHit(IMyHandToolComponent toolComponent, MyCharacterDetectorComponent detectorComponent, ref bool isBlock, out float hitEfficiency)
        {
            bool canHit = true;

            hitEfficiency = 1.0f;
            MyTuple <ushort, MyStringHash> message;

            // TODO(GoodAI/HonzaS): Take care when merging this line.
            // The null check was not encountered with hand tools different from the reward/punishment tool.
            if (detectorComponent.HitBody != null && detectorComponent.HitBody.UserObject is MyBlockingBody)
            {
                var blocking = detectorComponent.HitBody.UserObject as MyBlockingBody;
                if (blocking.HandTool.IsBlocking && blocking.HandTool.m_owner.StatComp != null &&
                    blocking.HandTool.m_owner.StatComp.CanDoAction(blocking.HandTool.m_shotHitCondition.StatsActionIfHit, out message))
                {
                    blocking.HandTool.m_owner.StatComp.DoAction(blocking.HandTool.m_shotHitCondition.StatsActionIfHit);
                    if (!string.IsNullOrEmpty(blocking.HandTool.m_shotHitCondition.StatsModifierIfHit))
                    {
                        blocking.HandTool.m_owner.StatComp.ApplyModifier(blocking.HandTool.m_shotHitCondition.StatsModifierIfHit);
                    }
                    isBlock = true;

                    if (!string.IsNullOrEmpty(blocking.HandTool.m_shotToolAction.Value.StatsEfficiency))
                    {
                        hitEfficiency = 1.0f - blocking.HandTool.m_owner.StatComp.GetEfficiencyModifier(blocking.HandTool.m_shotToolAction.Value.StatsEfficiency);
                    }
                    canHit = hitEfficiency > 0.0f;
                    MyEntityContainerEventExtensions.RaiseEntityEventOn(blocking.HandTool, MyStringHash.GetOrCompute("Hit"), new MyEntityContainerEventExtensions.HitParams(MyStringHash.GetOrCompute("Block"), this.PhysicalItemDefinition.Id.SubtypeId));
                }
            }
            if (!canHit)
            {
                hitEfficiency = 0.0f;
                return(canHit);
            }

            if (!string.IsNullOrEmpty(m_shotHitCondition.StatsActionIfHit))
            {
                canHit = m_owner.StatComp != null && m_owner.StatComp.CanDoAction(m_shotHitCondition.StatsActionIfHit, out message);
                if (!canHit)
                {
                    hitEfficiency = 0.0f;
                    return(canHit);
                }
            }

            float hitDistance = Vector3.Distance(detectorComponent.HitPosition, PositionComp.GetPosition());

            canHit = hitDistance <= m_toolItemDef.HitDistance;
            if (!canHit)
            {
                hitEfficiency = 0.0f;
                return(canHit);
            }

            // checking of player factions
            MyEntity attacker           = m_owner.Entity;
            long     attackerPlayerId   = m_owner.GetPlayerIdentityId();
            var      localPlayerFaction = MySession.Static.Factions.TryGetPlayerFaction(attackerPlayerId) as MyFaction;

            if (localPlayerFaction != null && !localPlayerFaction.EnableFriendlyFire)
            {
                // friendy fire isn't enabled in attacker faction
                IMyEntity   otherPlayerEntity = detectorComponent.DetectedEntity;
                MyCharacter otherPlayer       = otherPlayerEntity as MyCharacter;
                if (otherPlayer != null)
                {
                    bool sameFaction = localPlayerFaction.IsMember(otherPlayer.GetPlayerIdentityId());
                    canHit        = !sameFaction;
                    hitEfficiency = canHit ? hitEfficiency : 0.0f;
                }
            }
            return(canHit);
        }
示例#32
0
 public static MyInventory GetInventory(this MyEntity thisEntity, int index = 0) =>
 (thisEntity.GetInventoryBase(index) as MyInventory);
示例#33
0
 public static bool TryGetInventory(this MyEntity thisEntity, out MyInventoryBase inventoryBase)
 {
     inventoryBase = null;
     return(thisEntity.Components.TryGet <MyInventoryBase>(out inventoryBase));
 }
示例#34
0
 public static bool WeldingGroupExists(this MyEntity thisEntity) =>
 (MyWeldingGroups.Static.GetGroup(thisEntity) != null);
示例#35
0
 public static void AddNodeToWeldingGroups(this MyEntity thisEntity)
 {
     MyWeldingGroups.Static.AddNode(thisEntity);
 }
示例#36
0
 public static void RemoveFromGamePruningStructure(this MyEntity thisEntity)
 {
     MyGamePruningStructure.Remove(thisEntity);
 }
示例#37
0
 public static void AddToGamePruningStructure(this MyEntity thisEntity)
 {
     MyGamePruningStructure.Add(thisEntity);
 }
示例#38
0
 public static MyObjectBuilder_EntityBase EntityFactoryCreateObjectBuilder(this MyEntity thisEntity) =>
 MyEntityFactory.CreateObjectBuilder(thisEntity);
示例#39
0
 public static MyPhysicsBody GetPhysicsBody(this MyEntity thisEntity) =>
 (thisEntity.Physics as MyPhysicsBody);
        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);
                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;

            RemoveOwnerVirtualPhysics();

            if (Owner != null)
            {
                Owner.ManipulatedEntity = null;
            }
            m_state = MyState.NONE;
        }
        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;

            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
                    {
                        mass = GetRealMass(m_otherRigidBody.Mass);
                    }

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

                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 = 2.0f;
                        fcData.MaximumLinearImpulse  = 2.0f;
                    }
                }
            }
            else
            {
                data = CreateBallAndSocketConstraintData(ref m_otherLocalPivotMatrix, ref m_headLocalPivotMatrix);
                if (otherEntity is MyCharacter)
                {
                    HkMalleableConstraintData mcData = data as HkMalleableConstraintData;
                    mcData.Strength = 0.005f;
                }
            }

            if (!CreateOwnerVirtualPhysics())
            {
                data.Dispose();
                return;
            }

            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)
            {
                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;
                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.Restitution        = TARGET_RESTITUTION;
                        body.MaxLinearVelocity  = m_limitingLinearVelocity;
                        body.MaxAngularVelocity = (float)Math.PI;
                    }
                }

                const float holdingTransparency = 0.4f;
                SetTransparent(otherEntity, holdingTransparency); //TODO jt: why it must be called twice?
                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.None, 0.2f, 1f);
            }
            else
            {
                Owner.PlayCharacterAnimation("PullLumber", MyBlendOption.Immediate, MyFrameOption.None, 0.2f, 1f);
            }

            m_manipulatedEntitites.Add(m_otherEntity);

            Owner.ManipulatedEntity = m_otherEntity;
        }
        public void Shoot(MyShootActionEnum action, VRageMath.Vector3 direction, string gunAction)
        {
            m_enabled = false;

            MyState oldState = m_state;

            switch (action)
            {
            case MyShootActionEnum.PrimaryAction:
            {
                if (Sandbox.Game.Multiplayer.Sync.IsServer)
                {
                    if (SafeConstraint != null)
                    {
                        SyncTool.StopManipulation();
                    }
                    else if (oldState == MyState.NONE)
                    {
                        MatrixD  ownerWorldHeadMatrix = Owner.GetHeadMatrix(false, true, false, true);
                        Vector3D hitPosition;
                        MyEntity hitEntity = GetTargetEntity(ref ownerWorldHeadMatrix, out hitPosition);
                        if (hitEntity != null)
                        {
                            SyncTool.StartManipulation(MyState.HOLD, hitEntity, hitPosition, ref ownerWorldHeadMatrix);
                        }
                    }
                }
            }
            break;

            case MyShootActionEnum.SecondaryAction:
                if (SafeConstraint != null)
                {
                    if (Sandbox.Game.Multiplayer.Sync.IsServer)
                    {
                        if (m_state == MyState.HOLD)
                        {
                            ThrowEntity();
                        }
                        else
                        {
                            SyncTool.StopManipulation();
                        }
                    }
                }
                else if (oldState == MyState.NONE)
                {
                    if (Sandbox.Game.Multiplayer.Sync.IsServer)
                    {
                        MatrixD  ownerWorldHeadMatrix = Owner.GetHeadMatrix(false, true, false, true);
                        Vector3D hitPosition;
                        MyEntity hitEntity = GetTargetEntity(ref ownerWorldHeadMatrix, out hitPosition);
                        if (hitEntity != null)
                        {
                            SyncTool.StartManipulation(MyState.PULL, hitEntity, hitPosition, ref ownerWorldHeadMatrix);
                        }
                    }
                }
                break;
            }
        }
 public void StartManipulationSynced(MyState myState, MyEntity spawned, Vector3D position, ref MatrixD ownerWorldHeadMatrix)
 {
     Debug.Assert(Sync.IsServer);
     SyncTool.StartManipulation(myState, spawned, position, ref ownerWorldHeadMatrix);
 }
示例#44
0
 internal static void CreateStandardRenderComponents(this MyEntity thisEntity)
 {
     thisEntity.Render = new MyRenderComponent();
     thisEntity.AddDebugRenderComponent(new MyDebugRenderComponent(thisEntity));
 }
示例#45
0
 public static MySyncComponentBase CreateDefaultSyncEntity(this MyEntity thisEntity) =>
 new MySyncEntity(thisEntity);
示例#46
0
 public MyGridPhysicsStateGroup(MyEntity entity, IMyReplicable ownerReplicable)
     : base(entity, ownerReplicable)
 {
 }
示例#47
0
 public MyDataReceiver(MyEntity parent)
 {
     Parent = parent;
 }
示例#48
0
 public static void GetWeldingGroupNodes(this MyEntity thisEntity, List <MyEntity> result)
 {
     MyWeldingGroups.Static.GetGroupNodes(thisEntity, result);
 }
示例#49
0
 public static void RemoveNodeFromWeldingGroups(this MyEntity thisEntity)
 {
     MyWeldingGroups.Static.RemoveNode(thisEntity);
 }
示例#50
0
 public static MyObjectBuilder_EntityBase CreateObjectBuilder(MyEntity entity)
 {
     return(m_objectFactory.CreateObjectBuilder <MyObjectBuilder_EntityBase>(entity));
 }
示例#51
0
 void UntrackEntity(MyEntity entity)
 {
     entity.PositionComp.OnPositionChanged -= m_entityPositionChanged;
     entity.OnClose -= m_entityClosed;
 }
示例#52
0
 private static bool IsEntityStatic(MyEntity entity)
 {
     return(entity.Physics == null || entity.Physics.IsStatic);
 }
示例#53
0
        private void SwitchWeapon(ref IMyHandheldGunObject <MyDeviceBase> weapon, ref MyVRWeaponInfo weaponInfo, List <MyVRWeaponInfo> weapons, ControllerRole role, Vector2?touchpadPos)
        {
            int currentIndex = -1;

            if (weapon != null)
            {
                for (int i = 0; i < weapons.Count; ++i)
                {
                    var info = weapons[i];
                    if (info.DefinitionId == weapon.DefinitionId)
                    {
                        currentIndex = i;
                        break;
                    }
                }
            }

            int nextIndex = 0;

            if (touchpadPos != null)
            {
                Vector2 pos = touchpadPos.Value;
                if (touchpadPos != Vector2.Zero)
                {
                    pos.Normalize();
                    float anglePerWeaponSector = 360f / weapons.Count;
                    float dot   = Vector2.Dot(Vector2.UnitX, pos);
                    float angle = (float)Math.Acos(Math.Abs(dot));
                    if (pos.Y >= 0)
                    {
                        if (dot < 0)
                        {
                            angle = 180 - angle;
                        }
                    }
                    else
                    {
                        if (dot < 0)
                        {
                            angle = 180 + angle;
                        }
                        else
                        {
                            angle = 360 - angle;
                        }
                    }

                    nextIndex = (int)Math.Floor(angle / anglePerWeaponSector);
                    Debug.Assert(nextIndex < weapons.Count);
                }
            }

            if (nextIndex == currentIndex)
            {
                return;
            }

            if (weapon != null)
            {
                weapon.OnControlReleased();
                MyEntity weaponEntity = (MyEntity)weapon;
                weaponEntity.Close();
                weapon = null;
            }

            {
                weaponInfo = weapons[nextIndex];
                weapon     = CreateWeapon(weaponInfo.DefinitionId, weaponInfo.Reference);
                weapon.OnControlAcquired(null);
                MyEntity weaponEntity = (MyEntity)weapon;
            }

            var    gunBase       = weapon.GunBase as MyGunBase;
            Matrix holdingMatrix = gunBase != null ? gunBase.m_holdingDummyMatrix : Matrix.Identity;

            MyOpenVR.LMUAdd(holdingMatrix, m_worldMatrixOriginal, role, weaponInfo.Reference);
        }
示例#54
0
 public MyBlockingBody(MyHandToolBase tool, MyEntity owner)
     : base(owner, RigidBodyFlag.RBF_KINEMATIC)
 {
     HandTool = tool;
 }
示例#55
0
 public static bool IsForbiddenEntity(MyEntity entity)
 {
     return(entity is MyCharacter ||
            (entity is MyCubeGrid && (entity as MyCubeGrid).IsStatic == false) ||
            (entity is MyCockpit && (entity as MyCockpit).Pilot != null));
 }
 public static bool IsEntityManipulated(MyEntity entity)
 {
     return(m_manipulatedEntitites.Contains(entity));
 }
示例#57
0
 public void SubmitWork(MyObjectBuilder_EntityBase objectBuilder, bool addToScene, Action <MyEntity> doneHandler, MyEntity entity = null)
 {
     SubmitWork(new Item()
     {
         ObjectBuilder = objectBuilder, AddToScene = addToScene, DoneHandler = doneHandler, Result = entity
     });
 }
示例#58
0
 void CubeGrid_OnPhysicsChanged(MyEntity obj)
 {
     UpdatePhysics();
 }
 private void OtherEntity_OnClosing(MyEntity obj)
 {
     StopManipulation();
 }
示例#60
0
 public static void UpdateGamePruningStructure(this MyEntity thisEntity)
 {
     MyGamePruningStructure.Move(thisEntity);
 }