public static MyFracturedPiece CreateFracturePiece(MyFracturedBlock fracturedBlock, bool sync)
        {
            System.Diagnostics.Debug.Assert(Sync.IsServer, "Only on server");
            var m = fracturedBlock.CubeGrid.PositionComp.WorldMatrix;

            m.Translation = fracturedBlock.CubeGrid.GridIntegerToWorld(fracturedBlock.Position);
            var fp = CreateFracturePiece(ref fracturedBlock.Shape, ref m, false);

            fp.OriginalBlocks = fracturedBlock.OriginalBlocks;

            MyPhysicalModelDefinition def;

            if (MyDefinitionManager.Static.TryGetDefinition <MyPhysicalModelDefinition>(fp.OriginalBlocks[0], out def))
            {
                fp.Physics.MaterialType = def.PhysicalMaterial.Id.SubtypeId;
            }

            // Check valid shapes from block definitions.
            if (MyFakes.ENABLE_FRACTURE_PIECE_SHAPE_CHECK)
            {
                fp.DebugCheckValidShapes();
            }

            ProfilerShort.Begin("MyEntities.Add");
            if (MyExternalReplicable.FindByObject(fp) == null)
            {
                MyEntities.RaiseEntityCreated(fp);
            }
            MyEntities.Add(fp);
            ProfilerShort.End();

            return(fp);
        }
Exemple #2
0
        static bool TryFindCryoChamberCharacter(MyPlayer player)
        {
            if (player == null)
            {
                return(false);
            }

            var entities = MyEntities.GetEntities();

            foreach (var entity in entities)
            {
                var cubeGrid = entity as MyCubeGrid;
                if (cubeGrid != null)
                {
                    var blocks = cubeGrid.GetFatBlocks <Sandbox.Game.Entities.Blocks.MyCryoChamber>();
                    foreach (var cryoChamber in blocks)
                    {
                        if (cryoChamber.TryToControlPilot(player))
                        {
                            MyMultiplayer.ReplicateImmediatelly(MyExternalReplicable.FindByObject(cryoChamber.CubeGrid), new EndpointId(player.Id.SteamId));
                            MyMultiplayer.ReplicateImmediatelly(MyExternalReplicable.FindByObject(cryoChamber.Pilot), new EndpointId(player.Id.SteamId));
                            return(true);
                        }
                    }
                }
            }

            return(false);
        }
Exemple #3
0
        private void WritePhysics(BitStream stream, MyEntity controlledEntity)
        {
            IMyReplicable player = MyExternalReplicable.FindByObject(controlledEntity);

            if (player == null)
            {
                stream.WriteBool(false);
                return;
            }

            var stateGroup = player.FindStateGroup <MyEntityPhysicsStateGroup>();

            if (stateGroup == null)
            {
                stream.WriteBool(false);
                return;
            }
            bool isResponsible = stateGroup.ResponsibleForUpdate(new EndpointId(Sync.MyId));

            stream.WriteBool(isResponsible);
            if (isResponsible)
            {
                stateGroup.Serialize(stream, null, 0, 65535);
            }
        }
Exemple #4
0
 public void SubscribeInventory(MyInventoryBase inventory)
 {
     try
     {
         if (inventory is MyInventoryAggregate agg)
         {
             foreach (MyInventory i in agg.ChildList.Reader)
             {
                 if (i == null)
                 {
                     continue;
                 }
                 inventories.Add(i);
                 if (MyExternalReplicable.FindByObject(i) is InventoryReplicable replicable)
                 {
                     replicable.Refresh();
                 }
             }
         }
         else if (inventory is MyInventory i)
         {
             inventories.Add(i);
             if (MyExternalReplicable.FindByObject(i) is InventoryReplicable replicable)
             {
                 replicable.Refresh();
             }
         }
     }
     catch (Exception e)
     {
         Plugin.Error("Subscription error", e);
     }
 }
Exemple #5
0
        public static MyFracturedPiece CreateFracturePiece(HkdBreakableShape shape, ref MatrixD worldMatrix, bool isStatic, MyDefinitionId?definition, bool sync)
        {
            MyFracturedPiece piece = CreateFracturePiece(ref shape, ref worldMatrix, isStatic);

            if (definition == null)
            {
                piece.Save = false;
            }
            else
            {
                MyPhysicalModelDefinition definition2;
                piece.OriginalBlocks.Clear();
                piece.OriginalBlocks.Add(definition.Value);
                if (MyDefinitionManager.Static.TryGetDefinition <MyPhysicalModelDefinition>(definition.Value, out definition2))
                {
                    piece.Physics.MaterialType = definition2.PhysicalMaterial.Id.SubtypeId;
                }
            }
            if (piece.Save && MyFakes.ENABLE_FRACTURE_PIECE_SHAPE_CHECK)
            {
                piece.DebugCheckValidShapes();
            }
            if (MyExternalReplicable.FindByObject(piece) == null)
            {
                Sandbox.Game.Entities.MyEntities.RaiseEntityCreated(piece);
            }
            Sandbox.Game.Entities.MyEntities.Add(piece, true);
            return(piece);
        }
Exemple #6
0
        public static MyFracturedPiece CreateFracturePiece(HkdBreakableBody b, ref MatrixD worldMatrix, List <MyDefinitionId> originalBlocks, MyCubeBlock block = null, bool sync = true)
        {
            if (IsBodyWithoutGeneratedFracturedPieces(b, block))
            {
                return(null);
            }
            MyFracturedPiece pieceFromPool = MyFracturedPiecesManager.Static.GetPieceFromPool(0L, false);

            pieceFromPool.InitFromBreakableBody(b, worldMatrix, block);
            pieceFromPool.NeedsUpdate |= MyEntityUpdateEnum.BEFORE_NEXT_FRAME;
            if ((originalBlocks != null) && (originalBlocks.Count != 0))
            {
                MyPhysicalModelDefinition definition;
                pieceFromPool.OriginalBlocks.Clear();
                pieceFromPool.OriginalBlocks.AddRange(originalBlocks);
                if (MyDefinitionManager.Static.TryGetDefinition <MyPhysicalModelDefinition>(originalBlocks[0], out definition))
                {
                    pieceFromPool.Physics.MaterialType = definition.PhysicalMaterial.Id.SubtypeId;
                }
            }
            if (MyFakes.ENABLE_FRACTURE_PIECE_SHAPE_CHECK)
            {
                pieceFromPool.DebugCheckValidShapes();
            }
            if (MyExternalReplicable.FindByObject(pieceFromPool) == null)
            {
                Sandbox.Game.Entities.MyEntities.RaiseEntityCreated(pieceFromPool);
            }
            Sandbox.Game.Entities.MyEntities.Add(pieceFromPool, true);
            return(pieceFromPool);
        }
Exemple #7
0
        public static MyFracturedPiece CreateFracturePiece(MyFractureComponentCubeBlock fractureBlockComponent, bool sync)
        {
            MyPhysicalModelDefinition definition;

            if (!fractureBlockComponent.Block.BlockDefinition.CreateFracturedPieces)
            {
                return(null);
            }
            if (!fractureBlockComponent.Shape.IsValid())
            {
                MyLog.Default.WriteLine("Invalid shape in fracture component, Id: " + fractureBlockComponent.Block.BlockDefinition.Id.ToString() + ", closed: " + fractureBlockComponent.Block.FatBlock.Closed.ToString());
                return(null);
            }
            MatrixD          worldMatrix = fractureBlockComponent.Block.FatBlock.WorldMatrix;
            MyFracturedPiece piece       = CreateFracturePiece(ref fractureBlockComponent.Shape, ref worldMatrix, false);

            piece.OriginalBlocks.Add(fractureBlockComponent.Block.BlockDefinition.Id);
            if (MyFakes.ENABLE_FRACTURE_PIECE_SHAPE_CHECK)
            {
                piece.DebugCheckValidShapes();
            }
            if (MyDefinitionManager.Static.TryGetDefinition <MyPhysicalModelDefinition>(piece.OriginalBlocks[0], out definition))
            {
                piece.Physics.MaterialType = definition.PhysicalMaterial.Id.SubtypeId;
            }
            if (MyExternalReplicable.FindByObject(piece) == null)
            {
                Sandbox.Game.Entities.MyEntities.RaiseEntityCreated(piece);
            }
            Sandbox.Game.Entities.MyEntities.Add(piece, true);
            return(piece);
        }
        void CreateReplicableForObject(object obj)
        {
            Debug.Assert(obj != null);
            if (obj == null)
            {
                return;
            }

            // TODO: Hack to fix replicating aggregate
            if (obj is MyInventoryAggregate)
            {
                return;
            }

            MyEntity entity = obj as MyEntity;

            if (entity != null && entity.IsPreview)
            {
                return;
            }

            var type = m_factory.FindTypeFor(obj);

            if (type != null && ReplicationLayer.IsTypeReplicated(type))
            {
                Debug.Assert(MyExternalReplicable.FindByObject(obj) == null, "Object is already replicated!");

                var replicable = (MyExternalReplicable)Activator.CreateInstance(type);
                replicable.Hook(obj);
                ReplicationLayer.Replicate(replicable);
                replicable.OnServerReplicate();
            }
        }
        private void CreateTopPart(out MyAttachableTopBlockBase topBlock, long builtBy, MyCubeBlockDefinitionGroup topGroup, bool smallToLarge)
        {
            Debug.Assert(Sync.IsServer, "Server only method.");
            if (topGroup == null)
            {
                topBlock = null;
                return;
            }

            var gridSize = CubeGrid.GridSizeEnum;

            if (smallToLarge && gridSize == MyCubeSize.Large)   //If we have pressed the Attach Small Rotor Head button on large grid take the small grid definition from pair
            {
                gridSize = MyCubeSize.Small;
            }
            var matrix = GetTopGridMatrix();

            var definition = topGroup[gridSize];

            Debug.Assert(definition != null);

            var block = MyCubeGrid.CreateBlockObjectBuilder(definition, Vector3I.Zero, MyBlockOrientation.Identity, MyEntityIdentifier.AllocateId(), OwnerId, fullyBuilt: MySession.Static.CreativeMode);

            matrix.Translation = Vector3D.Transform(-definition.Center * CubeGrid.GridSize, matrix);

            var gridBuilder = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_CubeGrid>();

            gridBuilder.GridSizeEnum           = gridSize;
            gridBuilder.IsStatic               = false;
            gridBuilder.PositionAndOrientation = new MyPositionAndOrientation(matrix);
            gridBuilder.CubeBlocks.Add(block);

            var grid = MyEntityFactory.CreateEntity <MyCubeGrid>(gridBuilder);

            grid.Init(gridBuilder);

            topBlock = (MyAttachableTopBlockBase)grid.GetCubeBlock(Vector3I.Zero).FatBlock;

            if (!CanPlaceTop(topBlock, builtBy))
            {
                topBlock = null;
                grid.Close();
                return;
            }
            grid.PositionComp.SetPosition(grid.WorldMatrix.Translation - (Vector3D.Transform(topBlock.DummyPosLoc, grid.WorldMatrix) - grid.WorldMatrix.Translation));

            MyEntities.Add(grid);
            if (MyFakes.ENABLE_SENT_GROUP_AT_ONCE)
            {
                MyMultiplayer.ReplicateImmediatelly(MyExternalReplicable.FindByObject(grid), MyExternalReplicable.FindByObject(CubeGrid));
            }

            MatrixD masterToSlave = topBlock.CubeGrid.WorldMatrix * MatrixD.Invert(WorldMatrix);

            m_connectionState.Value = new State()
            {
                TopBlockId = topBlock.EntityId, MasterToSlave = masterToSlave
            };
        }
        protected void CreateRotorGrid(out MyCubeGrid rotorGrid, out MyAttachableTopBlockBase rotorBlock, long builtBy, MyCubeBlockDefinitionGroup rotorGroup)
        {
            Debug.Assert(Sync.IsServer, "Rotor grid can be created only on server");
            if (rotorGroup == null)
            {
                rotorGrid  = null;
                rotorBlock = null;
                return;
            }

            var gridSize = CubeGrid.GridSizeEnum;

            float size       = MyDefinitionManager.Static.GetCubeSize(gridSize);
            var   matrix     = MatrixD.CreateWorld(Vector3D.Transform(DummyPosition, CubeGrid.WorldMatrix), WorldMatrix.Forward, WorldMatrix.Up);
            var   definition = rotorGroup[gridSize];

            Debug.Assert(definition != null);

            var block = MyCubeGrid.CreateBlockObjectBuilder(definition, Vector3I.Zero, MyBlockOrientation.Identity, MyEntityIdentifier.AllocateId(), OwnerId, fullyBuilt: MySession.Static.CreativeMode);

            var gridBuilder = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_CubeGrid>();

            gridBuilder.GridSizeEnum           = gridSize;
            gridBuilder.IsStatic               = false;
            gridBuilder.PositionAndOrientation = new MyPositionAndOrientation(matrix);
            gridBuilder.CubeBlocks.Add(block);

            var grid = MyEntityFactory.CreateEntity <MyCubeGrid>(gridBuilder);

            grid.Init(gridBuilder);

            rotorGrid = grid;
            MyMotorRotor rotor = (MyMotorRotor)rotorGrid.GetCubeBlock(Vector3I.Zero).FatBlock;

            rotorBlock = rotor;
            rotorGrid.PositionComp.SetPosition(rotorGrid.WorldMatrix.Translation - (Vector3D.Transform(rotor.DummyPosLoc, rotorGrid.WorldMatrix) - rotorGrid.WorldMatrix.Translation));

            if (!CanPlaceRotor(rotorBlock, builtBy))
            {
                rotorGrid  = null;
                rotorBlock = null;
                grid.Close();
                return;
            }

            MyEntities.Add(grid);

            if (MyFakes.ENABLE_SENT_GROUP_AT_ONCE)
            {
                MyMultiplayer.ReplicateImmediatelly(MyExternalReplicable.FindByObject(grid), MyExternalReplicable.FindByObject(CubeGrid));
            }

            MatrixD masterToSlave = rotorBlock.CubeGrid.WorldMatrix * MatrixD.Invert(WorldMatrix);

            m_connectionState.Value = new State()
            {
                TopBlockId = rotorBlock.EntityId, MasterToSlave = masterToSlave
            };
        }
Exemple #11
0
        private void CreateTopGrid(out MyCubeGrid topGrid, out MyAttachableTopBlockBase topBlock, long builtBy, MyCubeBlockDefinitionGroup topGroup)
        {
            if (topGroup == null)
            {
                topGrid  = null;
                topBlock = null;
                return;
            }

            var gridSize = CubeGrid.GridSizeEnum;

            float size   = MyDefinitionManager.Static.GetCubeSize(gridSize);
            var   matrix = GetTopGridMatrix();

            var definition = topGroup[gridSize];

            Debug.Assert(definition != null);

            var block = MyCubeGrid.CreateBlockObjectBuilder(definition, Vector3I.Zero, MyBlockOrientation.Identity, MyEntityIdentifier.AllocateId(), OwnerId, fullyBuilt: MySession.Static.CreativeMode);

            var gridBuilder = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_CubeGrid>();

            gridBuilder.GridSizeEnum           = gridSize;
            gridBuilder.IsStatic               = false;
            gridBuilder.PositionAndOrientation = new MyPositionAndOrientation(matrix);
            gridBuilder.CubeBlocks.Add(block);

            var grid = MyEntityFactory.CreateEntity <MyCubeGrid>(gridBuilder);

            grid.Init(gridBuilder);

            topGrid  = grid;
            topBlock = (MyAttachableTopBlockBase)topGrid.GetCubeBlock(Vector3I.Zero).FatBlock;

            if (!CanPlaceTop(topBlock, builtBy))
            {
                topGrid  = null;
                topBlock = null;
                grid.Close();
                return;
            }
            //topGrid.SetPosition(topGrid.WorldMatrix.Translation - (topBlock.WorldMatrix.Translation/*Vector3.Transform(topBlock.DummyPosLoc, topGrid.WorldMatrix) - topGrid.WorldMatrix.Translation*/));

            MyEntities.Add(grid);
            if (MyFakes.ENABLE_SENT_GROUP_AT_ONCE)
            {
                MyMultiplayer.ReplicateImmediatelly(MyExternalReplicable.FindByObject(grid), MyExternalReplicable.FindByObject(CubeGrid));
            }

            MatrixD masterToSlave = topBlock.CubeGrid.WorldMatrix * MatrixD.Invert(WorldMatrix);

            m_connectionState.Value = new State()
            {
                TopBlockId = topBlock.EntityId, MasterToSlave = masterToSlave
            };
        }
Exemple #12
0
        private void ReadPhysics(BitStream stream, MyNetworkClient sender, MyEntity controlledEntity)
        {
            var  stateGroup = MyExternalReplicable.FindByObject(controlledEntity).FindStateGroup <MyEntityPhysicsStateGroup>();
            bool hasPhysics = stream.ReadBool();

            if (hasPhysics && stateGroup.ResponsibleForUpdate(new EndpointId(sender.SteamUserId)))
            {
                stateGroup.Serialize(stream, null, 0, 65535);
            }
        }
        private void WritePhysics(BitStream stream, MyEntity controlledEntity)
        {
            IMyReplicable controlledReplicable = MyExternalReplicable.FindByObject(controlledEntity);

            stream.WriteBool(controlledReplicable != null);

            if (controlledReplicable == null)
            {
                return;
            }

            IMyStateGroup stateGroup = null;

            bool             useCharacterOnServer = controlledEntity is MyCharacter && MyFakes.ENABLE_CHARACTER_CONTROL_ON_SERVER;
            bool             useGridOnServer      = controlledEntity is MyCubeGrid && MyFakes.ENABLE_SHIP_CONTROL_ON_SERVER;
            MyShipController controller           = MySession.Static.ControlledEntity as MyShipController;
            bool             hasWheels            = controller != null && controller.HasWheels;
            long?            supportId            = null;

            if (useCharacterOnServer || (useGridOnServer && hasWheels == false))
            {
                MyEntityPositionVerificationStateGroup group = controlledReplicable.FindStateGroup <MyEntityPositionVerificationStateGroup>();
                stateGroup = group;
                supportId  = group.GetSupportID();
            }
            else
            {
                stateGroup = controlledReplicable.FindStateGroup <MyEntityPhysicsStateGroup>();
            }


            stream.WriteBool(useCharacterOnServer || (useGridOnServer && hasWheels == false));
            stream.WriteBool(stateGroup != null);

            if (stateGroup == null)
            {
                return;
            }

            stream.WriteBool(supportId.HasValue);
            if (supportId.HasValue)
            {
                stream.WriteInt64(supportId.Value);
            }

            bool isResponsible = MyEntityPhysicsStateGroup.ResponsibleForUpdate(controlledEntity, new EndpointId(Sync.MyId));

            stream.WriteBool(isResponsible);
            if (isResponsible)
            {
                stateGroup.Serialize(stream, EndpointId, ClientTimeStamp, 0, 1024 * 1024);
            }
        }
        private void SpawnInRespawn(MyPlayer player, MyRespawnComponent respawn, MyBotDefinition botDefinition)
        {
            if (MySession.Static.Settings.EnableOxygen)
            {
                player.Identity.ChangeToOxygenSafeSuit();
            }

            if (respawn.Entity == null)
            {
                Debug.Assert(false, "Respawn does not have entity!");
                SpawnInSuit(player, null, botDefinition);
                return;
            }
            var parent = respawn.Entity.GetTopMostParent();

            if (parent.Physics == null)
            {
                Debug.Assert(false, "Respawn entity parent does not have physics!");
                SpawnInSuit(player, (MyEntity)parent, botDefinition);
                return;
            }

            MatrixD pos;

            var medRoom = respawn.Entity as MyMedicalRoom;

            if (medRoom != null)
            {
                pos = medRoom.GetSpawnPosition();
            }
            else
            {
                pos = respawn.GetSpawnPosition(respawn.Entity.WorldMatrix);
            }

            Vector3 velocity = parent.Physics.GetVelocityAtPoint(pos.Translation);

            MyMultiplayer.ReplicateImmediatelly(MyExternalReplicable.FindByObject(parent), new EndpointId(player.Id.SteamId));

            player.SpawnAt(pos, velocity, (MyEntity)parent, botDefinition, true);

            if (medRoom != null)
            {
                medRoom.TryTakeSpawneeOwnership(player);
                medRoom.TrySetFaction(player);

                if (medRoom.ForceSuitChangeOnRespawn)
                {
                    player.Character.ChangeModelAndColor(medRoom.RespawnSuitName, player.Character.ColorMask);
                }
            }
        }
Exemple #15
0
        public override IMyReplicable GetDependency()
        {
            Debug.Assert(Inventory.Owner != Inventory, "Inventory owner is inventory!");
            Debug.Assert(!((MyEntity)Inventory.Owner).Closed, "Sending inventory of closed entity");
            if (Inventory.Owner is MyCharacter)
            {
                return(MyExternalReplicable.FindByObject(Inventory.Owner));
            }

            if (Inventory.Owner is MyCubeBlock)
            {
                return(MyExternalReplicable.FindByObject((Inventory.Owner as MyCubeBlock).CubeGrid));
            }

            return(null);
        }
        public static MyFracturedPiece CreateFracturePiece(HkdBreakableBody b, ref MatrixD worldMatrix, List <MyDefinitionId> originalBlocks, MyCubeBlock block = null, bool sync = true)
        {
            System.Diagnostics.Debug.Assert(Sync.IsServer, "Only on server");

            if (IsBodyWithoutGeneratedFracturedPieces(b, block))
            {
                return(null);
            }

            ProfilerShort.Begin("CreateFracturePiece");
            var fracturedPiece = MyFracturedPiecesManager.Static.GetPieceFromPool(0);

            fracturedPiece.InitFromBreakableBody(b, worldMatrix, block);
            fracturedPiece.NeedsUpdate |= MyEntityUpdateEnum.BEFORE_NEXT_FRAME;
            //fracturedPiece.Physics.RigidBody.ContactPointCallbackDelay = 0;
            //fracturedPiece.Physics.RigidBody.ContactPointCallbackEnabled = true;
            ProfilerShort.End();

            if (originalBlocks != null && originalBlocks.Count != 0)
            {
                fracturedPiece.OriginalBlocks.Clear();
                fracturedPiece.OriginalBlocks.AddRange(originalBlocks);

                MyPhysicalModelDefinition def;
                if (MyDefinitionManager.Static.TryGetDefinition <MyPhysicalModelDefinition>(originalBlocks[0], out def))
                {
                    fracturedPiece.Physics.MaterialType = def.PhysicalMaterial.Id.SubtypeId;
                }
            }

            // Check valid shapes from block definitions.
            if (MyFakes.ENABLE_FRACTURE_PIECE_SHAPE_CHECK)
            {
                fracturedPiece.DebugCheckValidShapes();
            }

            ProfilerShort.Begin("MyEntities.Add");
            if (MyExternalReplicable.FindByObject(fracturedPiece) == null)
            {
                MyEntities.RaiseEntityCreated(fracturedPiece);
            }
            MyEntities.Add(fracturedPiece);
            ProfilerShort.End();

            return(fracturedPiece);
        }
Exemple #17
0
 private void CreateReplicableForObject(object obj)
 {
     if ((obj != null) && !(obj is MyInventoryAggregate))
     {
         MyEntity entity = obj as MyEntity;
         if ((entity == null) || !entity.IsPreview)
         {
             Type type = this.m_factory.FindTypeFor(obj);
             if ((type != null) && this.ReplicationLayer.IsTypeReplicated(type))
             {
                 MyExternalReplicable replicable = (MyExternalReplicable)Activator.CreateInstance(type);
                 replicable.Hook(obj);
                 this.ReplicationLayer.Replicate(replicable);
                 replicable.OnServerReplicate();
             }
         }
     }
 }
        public static MyFracturedPiece CreateFracturePiece(MyFractureComponentCubeBlock fractureBlockComponent, bool sync)
        {
            if (!fractureBlockComponent.Block.BlockDefinition.CreateFracturedPieces)
            {
                return(null);
            }

            if (!fractureBlockComponent.Shape.IsValid())
            {
                Debug.Fail("Invalid shape in fracture component");
                MyLog.Default.WriteLine("Invalid shape in fracture component, Id: " + fractureBlockComponent.Block.BlockDefinition.Id.ToString() + ", closed: " + fractureBlockComponent.Block.FatBlock.Closed);
                return(null);
            }

            System.Diagnostics.Debug.Assert(Sync.IsServer, "Only on server");
            var m  = fractureBlockComponent.Block.FatBlock.WorldMatrix;
            var fp = CreateFracturePiece(ref fractureBlockComponent.Shape, ref m, false);

            fp.OriginalBlocks.Add(fractureBlockComponent.Block.BlockDefinition.Id);

            // Check valid shapes from block definitions.
            if (MyFakes.ENABLE_FRACTURE_PIECE_SHAPE_CHECK)
            {
                fp.DebugCheckValidShapes();
            }

            MyPhysicalModelDefinition def;

            if (MyDefinitionManager.Static.TryGetDefinition <MyPhysicalModelDefinition>(fp.OriginalBlocks[0], out def))
            {
                fp.Physics.MaterialType = def.PhysicalMaterial.Id.SubtypeId;
            }

            ProfilerShort.Begin("MyEntities.Add");
            if (MyExternalReplicable.FindByObject(fp) == null)
            {
                MyEntities.RaiseEntityCreated(fp);
            }
            MyEntities.Add(fp);
            ProfilerShort.End();

            return(fp);
        }
Exemple #19
0
        private static bool CharacterReplicableGetDependencies(MyEntityReplicableBaseEvent <MyCharacter> __instance,
                                                               ref HashSet <IMyReplicable> __result)
        {
            __result = _characterDependenciesGetter(__instance);
            __result.Clear();
            if (!Sync.IsServer)
            {
                return(false);
            }

            var playerId = __instance.Instance.GetPlayerIdentityId();
            var allRelayedBroadcasters = _broadcasterCache.Value;

            allRelayedBroadcasters.Clear();

            {
                var receivers = _receiverCache.Value;
                receivers.Clear();
                MyAntennaSystem.Static.GetEntityReceivers(__instance.Instance, ref receivers, playerId);

                foreach (var k in receivers)
                {
                    MyAntennaSystem.Static.GetAllRelayedBroadcasters(k, playerId, false, allRelayedBroadcasters);
                }
            }

            var mine = _characterBroadcasterGetter(__instance.Instance);

            foreach (MyDataBroadcaster others in allRelayedBroadcasters)
            {
                if (mine != others && !others.Closed)
                {
                    var rep = MyExternalReplicable.FindByObject(others);
                    if (rep != null && _typeFarBroadcasterReplicable.IsInstanceOfType(rep))
                    {
                        __result.Add(rep);
                    }
                }
            }

            allRelayedBroadcasters.Clear();
            return(false);
        }
        private void ReadPhysics(BitStream stream, MyNetworkClient sender, MyEntity controlledEntity, uint serverTimeStamp)
        {
            bool hasPhysics = stream.ReadBool();

            m_currentServerTimeStamp = serverTimeStamp;

            if (hasPhysics && MyEntityPhysicsStateGroup.ResponsibleForUpdate(controlledEntity, new EndpointId(sender.SteamUserId)))
            {
                IMyStateGroup stateGroup = null;
                SupportId = null;
                bool enableControlOnServer = stream.ReadBool();
                bool stateGroupFound       = stream.ReadBool();
                if (stateGroupFound == false)
                {
                    return;
                }


                if (stream.ReadBool())
                {
                    SupportId = stream.ReadInt64();
                }

                if (enableControlOnServer)
                {
                    stateGroup = MyExternalReplicable.FindByObject(controlledEntity).FindStateGroup <MyEntityPositionVerificationStateGroup>();
                }
                else
                {
                    stateGroup = MyExternalReplicable.FindByObject(controlledEntity).FindStateGroup <MyEntityPhysicsStateGroup>();
                }

                if (stream.ReadBool())
                {
                    stateGroup.Serialize(stream, new EndpointId(sender.SteamUserId), ClientTimeStamp, 0, 65535);
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="shape">Piece takes ownership of shape so clone it first</param>
        /// <param name="worldMatrix"></param>
        /// <param name="definition"> without definition the piece wont save</param>
        /// <returns></returns>
        public static MyFracturedPiece CreateFracturePiece(HkdBreakableShape shape, ref MatrixD worldMatrix, bool isStatic, MyDefinitionId?definition, bool sync)
        {
            System.Diagnostics.Debug.Assert(Sync.IsServer, "Only on server");
            var fracturedPiece = CreateFracturePiece(ref shape, ref worldMatrix, isStatic);

            if (definition.HasValue)
            {
                fracturedPiece.OriginalBlocks.Clear();
                fracturedPiece.OriginalBlocks.Add(definition.Value);

                MyPhysicalModelDefinition def;
                if (MyDefinitionManager.Static.TryGetDefinition <MyPhysicalModelDefinition>(definition.Value, out def))
                {
                    fracturedPiece.Physics.MaterialType = def.PhysicalMaterial.Id.SubtypeId;
                }
            }
            else
            {
                fracturedPiece.Save = false;
            }

            // Check valid shapes from block definitions.
            if (fracturedPiece.Save && MyFakes.ENABLE_FRACTURE_PIECE_SHAPE_CHECK)
            {
                fracturedPiece.DebugCheckValidShapes();
            }

            ProfilerShort.Begin("MyEntities.Add");
            if (MyExternalReplicable.FindByObject(fracturedPiece) == null)
            {
                MyEntities.RaiseEntityCreated(fracturedPiece);
            }
            MyEntities.Add(fracturedPiece);
            ProfilerShort.End();

            return(fracturedPiece);
        }
Exemple #22
0
        public static MyFracturedPiece CreateFracturePiece(MyFracturedBlock fracturedBlock, bool sync)
        {
            MyPhysicalModelDefinition definition;
            MatrixD worldMatrix = fracturedBlock.CubeGrid.PositionComp.WorldMatrix;

            worldMatrix.Translation = fracturedBlock.CubeGrid.GridIntegerToWorld(fracturedBlock.Position);
            MyFracturedPiece piece = CreateFracturePiece(ref fracturedBlock.Shape, ref worldMatrix, false);

            piece.OriginalBlocks = fracturedBlock.OriginalBlocks;
            if (MyDefinitionManager.Static.TryGetDefinition <MyPhysicalModelDefinition>(piece.OriginalBlocks[0], out definition))
            {
                piece.Physics.MaterialType = definition.PhysicalMaterial.Id.SubtypeId;
            }
            if (MyFakes.ENABLE_FRACTURE_PIECE_SHAPE_CHECK)
            {
                piece.DebugCheckValidShapes();
            }
            if (MyExternalReplicable.FindByObject(piece) == null)
            {
                Sandbox.Game.Entities.MyEntities.RaiseEntityCreated(piece);
            }
            Sandbox.Game.Entities.MyEntities.Add(piece, true);
            return(piece);
        }
        public override bool HandleCommand(ulong userId, string[] words)
        {
            lock (Docking.Instance)
            {
                foreach (DockingItem dockingItem in Docking.Instance.DockingItems)
                {
                    string dockedShipFileName = Essentials.PluginPath + String.Format("\\Docking\\docked_{0}_{1}_{2}.sbc", dockingItem.PlayerId, dockingItem.TargetEntityId, dockingItem.DockedEntityId);

                    DockingItem dockedShip = dockingItem;
                    IMyEntity   entity     = MyAPIGateway.Entities.GetEntity(x => x.EntityId == dockedShip.TargetEntityId && x is IMyCubeGrid);
                    if (entity == null)
                    {
                        //Communication.SendPrivateInformation(userId, string.Format("Unable to undock ship due to error."));
                        Log.Info(string.Format("Unable to find parent '{0}' for '{1}' - '{2}'", dockingItem.TargetEntityId, dockingItem.DockedEntityId, dockingItem.DockedName));
                        //continue;
                    }

                    if (!File.Exists(dockedShipFileName))
                    {
                        Log.Info(string.Format("Unable to find ship file: {0}", dockedShipFileName));
                        continue;
                    }

//					FileInfo fileInfo = new FileInfo(dockedShipFileName);
                    MyObjectBuilder_CubeGrid cubeGrid;
                    MyObjectBuilderSerializer.DeserializeXML(dockedShipFileName, out cubeGrid);

                    if (entity != null)
                    {
                        // Rotate our ship relative to our saved rotation and the new carrier rotation
                        cubeGrid.PositionAndOrientation = new MyPositionAndOrientation(Matrix.CreateFromQuaternion(Quaternion.CreateFromRotationMatrix(entity.Physics.GetWorldMatrix().GetOrientation()) * dockingItem.SaveQuat).GetOrientation());
                        // Move our ship relative to the new carrier position and orientation
                        Quaternion newQuat    = Quaternion.CreateFromRotationMatrix(entity.Physics.GetWorldMatrix().GetOrientation());
                        Vector3D   rotatedPos = Vector3D.Transform(dockingItem.SavePos, newQuat);
                        //cubeGrid.Position = rotatedPos + parent.GetPosition();
                        cubeGrid.PositionAndOrientation = new MyPositionAndOrientation(MathUtility.RandomPositionFromPoint(entity.GetPosition(), 250f), cubeGrid.PositionAndOrientation.Value.Forward, cubeGrid.PositionAndOrientation.Value.Up);
                    }
                    else
                    {
                        cubeGrid.PositionAndOrientation = new MyPositionAndOrientation(MathUtility.RandomPositionFromPoint(cubeGrid.PositionAndOrientation.Value.Position, 500f), cubeGrid.PositionAndOrientation.Value.Forward, cubeGrid.PositionAndOrientation.Value.Up);
                    }

                    // Add object to world
                    cubeGrid.EntityId        = BaseEntity.GenerateEntityId();
                    cubeGrid.LinearVelocity  = Vector3.Zero;
                    cubeGrid.AngularVelocity = Vector3.Zero;

                    bool undock = false;
                    Wrapper.GameAction(() =>
                    {
                        try
                        {
                            IMyEntity newEntity = MyAPIGateway.Entities.CreateFromObjectBuilderAndAdd(cubeGrid);
                            MyMultiplayer.ReplicateImmediatelly(MyExternalReplicable.FindByObject(newEntity));
                            undock = true;
                        }
                        catch (Exception ex)
                        {
                            Log.Info(string.Format("Error undocking ship: {0}", ex.ToString()));
                            Communication.SendPrivateInformation(userId, string.Format("Unable to undock ship due to error."));
                        }
                    });

                    if (!undock)
                    {
                        return(true);
                    }

                    File.Delete(dockedShipFileName);
                    Communication.SendPrivateInformation(userId, string.Format("The ship '{0}' has been undocked from docking zone", dockingItem.DockedName));
                }

                Docking.Instance.DockingItems.Clear();
                Docking.Instance.Save();
            }

            return(true);
        }
 void DestroyReplicable(MyExternalReplicable obj)
 {
     ReplicationLayer.Destroy(obj);
 }
Exemple #25
0
        public static bool Move(string userName, Vector3D position)
        {
            //CharacterEntity charEntity = SectorObjectManager.Instance.GetTypedInternalData<CharacterEntity>().FirstOrDefault(x => x.DisplayName.ToLower() == userName.ToLower() && x.Health > 0);
            MyObjectBuilder_Character charEntity = FindCharacter(userName);

            if (charEntity == null)
            {
                Essentials.Log.Info(string.Format("Unable to find CharacterEntity of '{0}'", userName));
                return(false);
            }

            CubeGridEntity gridEntity = new CubeGridEntity(new FileInfo(Essentials.PluginPath + "MovePlayer.sbc"));

            gridEntity.EntityId = BaseEntity.GenerateEntityId();
            foreach (MyObjectBuilder_CubeBlock block in gridEntity.BaseCubeBlocks)
            {
                // set ownership
                MyObjectBuilder_Cockpit cockpit = block as MyObjectBuilder_Cockpit;
                if (cockpit != null)
                {
                    cockpit.Pilot = charEntity;
                }
            }

            gridEntity.PositionAndOrientation = new MyPositionAndOrientation(position, Vector3.Forward, Vector3.Up);

            Wrapper.GameAction(() =>
            {
                MyObjectBuilder_EntityBase baseEntity = gridEntity.Export();
                MyAPIGateway.Entities.RemapObjectBuilder(baseEntity);
                IMyEntity entity = MyAPIGateway.Entities.CreateFromObjectBuilderAndAdd(baseEntity);
                Type someManager = SandboxGameAssemblyWrapper.Instance.GetAssemblyType(SectorObjectManager.EntityBaseNetManagerNamespace, SectorObjectManager.EntityBaseNetManagerClass);
                Wrapper.InvokeStaticMethod(someManager, SectorObjectManager.EntityBaseNetManagerSendEntity, new object[] { entity.GetObjectBuilder() });
                gridEntity = new CubeGridEntity((MyObjectBuilder_CubeGrid)entity.GetObjectBuilder(), entity);

                MyMultiplayer.ReplicateImmediatelly(MyExternalReplicable.FindByObject(entity));
            });


            DateTime _loadTime = DateTime.Now;

            while (gridEntity.IsLoading)
            {
                if (DateTime.Now - _loadTime > TimeSpan.FromSeconds(20))
                {
                    break;
                }
            }

            if (gridEntity.IsLoading)
            {
                Essentials.Log.Info("Failed to load cockpit entity: {0}", gridEntity.EntityId);
                return(false);
            }

            foreach (CubeBlockEntity block in gridEntity.CubeBlocks)
            {
                if (block is CockpitEntity)
                {
                    block.IntegrityPercent = 0.1f;
                }
            }

            gridEntity.Dispose();
            MyMultiplayer.ReplicateImmediatelly(MyExternalReplicable.FindByObject(gridEntity));
            return(true);
        }
Exemple #26
0
        public void SpawnAtShip(MyPlayer player, string respawnShipId, MyBotDefinition botDefinition)
        {
            Debug.Assert(Sync.IsServer, "Spawning can only be called on the server!");
            if (!Sync.IsServer)
            {
                return;
            }

            ResetRespawnCooldown(player.Id);
            if (Sync.MultiplayerActive)
            {
                SyncCooldownToPlayer(player.Id.SteamId, player.Id.SteamId == Sync.MyId);
            }

            MyCharacter       character    = null;
            MyCockpit         cockpit      = null;
            List <MyCubeGrid> respawnGrids = new List <MyCubeGrid>();

            var respawnShipDef           = MyDefinitionManager.Static.GetRespawnShipDefinition(respawnShipId);
            MyPrefabDefinition prefabDef = respawnShipDef.Prefab;

            // Deploy ship
            Vector3D position = Vector3D.Zero;
            float    planetSpawnHeightRatio = 0.3f;
            float    spawnRangeMin          = 500f;
            float    spawnRangeMax          = 650f;

            if (prefabDef.CubeGrids != null && prefabDef.CubeGrids.Length > 0)
            {
                MyObjectBuilder_CubeGrid firstGrid = prefabDef.CubeGrids[0];
                if (firstGrid.UsePositionForSpawn)
                {
                    position = new Vector3D(
                        firstGrid.PositionAndOrientation.Value.Position.x,
                        firstGrid.PositionAndOrientation.Value.Position.y,
                        firstGrid.PositionAndOrientation.Value.Position.z);
                }

                planetSpawnHeightRatio = MyMath.Clamp(firstGrid.PlanetSpawnHeightRatio, 0.05f, 0.95f); // Clamped to prevent crazy data
                spawnRangeMin          = firstGrid.SpawnRangeMin;
                spawnRangeMax          = firstGrid.SpawnRangeMax;
            }
            Vector3D forward = Vector3.Forward;
            Vector3D up      = Vector3D.Up;

            GetSpawnPosition(prefabDef.BoundingSphere.Radius, ref position, out forward, out up, planetSpawnHeightRatio, spawnRangeMin, spawnRangeMax);

            MyPrefabManager.Static.SpawnPrefab(
                respawnGrids,
                prefabDef.Id.SubtypeName,
                position,
                forward,
                up,
                spawningOptions: VRage.Game.ModAPI.SpawningOptions.RotateFirstCockpitTowardsDirection,
                updateSync: true);

            // Find cockpits
            List <MyCockpit> shipCockpits = new List <MyCockpit>();

            foreach (MyCubeGrid grid in respawnGrids)
            {
                foreach (MyCockpit gridCockpit in grid.GetFatBlocks <MyCockpit>())
                {
                    // Ignore non-functional cockpits
                    if (!gridCockpit.IsFunctional)
                    {
                        continue;
                    }
                    shipCockpits.Add(gridCockpit);
                }
            }

            // First sort cockpits by order: Ship controlling cockpits set to main, then ship controlling cockpits not set to main, lastly whatever remains, e.g. CryoChambers and Passenger Seats
            if (shipCockpits.Count > 1)
            {
                shipCockpits.Sort(delegate(MyCockpit cockpitA, MyCockpit cockpitB)
                {
                    int controlCompare = cockpitB.EnableShipControl.CompareTo(cockpitA.EnableShipControl);
                    if (controlCompare != 0)
                    {
                        return(controlCompare);
                    }

                    int mainCompare = cockpitB.IsMainCockpit.CompareTo(cockpitA.IsMainCockpit);
                    if (mainCompare != 0)
                    {
                        return(mainCompare);
                    }

                    return(0);
                });
            }

            // Finally, select the most important cockpit
            if (shipCockpits.Count > 0)
            {
                cockpit = shipCockpits[0];
            }

            System.Diagnostics.Debug.Assert(cockpit != null, "character is spawning in ship without cockpit !");

            // Create character
            MatrixD matrix = MatrixD.Identity;

            if (cockpit != null)
            {
                matrix             = cockpit.WorldMatrix;
                matrix.Translation = cockpit.WorldMatrix.Translation - Vector3.Up - Vector3.Forward;
            }
            else if (respawnGrids.Count > 0)
            {
                matrix.Translation = respawnGrids[0].PositionComp.WorldAABB.Center + respawnGrids[0].PositionComp.WorldAABB.HalfExtents;
            }

            character = MyCharacter.CreateCharacter(matrix, Vector3.Zero, player.Identity.DisplayName, player.Identity.Model, null, botDefinition, cockpit: cockpit, playerSteamId: player.Id.SteamId);

            CloseRespawnShip(player);
            foreach (var respawnGrid in respawnGrids)
            {
                respawnGrid.ChangeGridOwnership(player.Identity.IdentityId, MyOwnershipShareModeEnum.None);
                respawnGrid.IsRespawnGrid = true;
                player.RespawnShip.Add(respawnGrid.EntityId);
            }

            if (cockpit != null)
            {
                cockpit.AttachPilot(character, false);
                MyMultiplayer.ReplicateImmediatelly(MyExternalReplicable.FindByObject(cockpit.CubeGrid), new EndpointId(player.Id.SteamId));
            }

            if (cockpit == null)
            {
                Sync.Players.SetPlayerCharacter(player, character, null);
            }
            else
            {
                character.SetPlayer(player);
                Sync.Players.SetPlayerToCockpit(player, cockpit);
            }
            Sync.Players.RevivePlayer(player);
        }
Exemple #27
0
        protected void InternalAddEntity( )
        {
            try
            {
                if (AddEntityQueue.Count == 0)
                {
                    return;
                }

                BaseEntity entityToAdd = AddEntityQueue.Dequeue( );

                if (ExtenderOptions.IsDebugging)
                {
                    ApplicationLog.BaseLog.Debug(String.Format("{0} '{1}': Adding to scene...", entityToAdd.GetType().Name, entityToAdd.DisplayName));
                }

                //Create the backing object
                Type entityType   = entityToAdd.GetType( );
                Type internalType = (Type)BaseEntity.InvokeStaticMethod(entityType, "get_InternalType");
                if (internalType == null)
                {
                    throw new Exception("Could not get internal type of entity");
                }
                entityToAdd.BackingObject = Activator.CreateInstance(internalType);

                //Add the backing object to the main game object manager
                //I don't think this is actually used anywhere?
                MyEntity backingObject = (MyEntity)entityToAdd.BackingObject;

                MyEntity newEntity = MyEntities.CreateFromObjectBuilderAndAdd(entityToAdd.ObjectBuilder);


                if (entityToAdd is FloatingObject)
                {
                    try
                    {
                        //Broadcast the new entity to the clients
                        MyObjectBuilder_EntityBase baseEntity = backingObject.GetObjectBuilder( );
                        //TODO - Do stuff

                        entityToAdd.ObjectBuilder = baseEntity;
                    }
                    catch (Exception ex)
                    {
                        ApplicationLog.BaseLog.Error("Failed to broadcast new floating object");
                        ApplicationLog.BaseLog.Error(ex);
                    }
                }
                else
                {
                    try
                    {
                        //Broadcast the new entity to the clients
                        ApplicationLog.BaseLog.Info("Broadcasted entity to clients.");
                        MyMultiplayer.ReplicateImmediatelly(MyExternalReplicable.FindByObject(newEntity));
                        //the misspelling in this function name is driving me  i n s a n e
                    }
                    catch (Exception ex)
                    {
                        ApplicationLog.BaseLog.Error("Failed to broadcast new entity");
                        ApplicationLog.BaseLog.Error(ex);
                    }
                }

                if (ExtenderOptions.IsDebugging)
                {
                    Type type = entityToAdd.GetType( );
                    ApplicationLog.BaseLog.Debug(String.Format("{0} '{1}': Finished adding to scene", entityToAdd.GetType().Name, entityToAdd.DisplayName));
                }
            }
            catch (Exception ex)
            {
                ApplicationLog.BaseLog.Error(ex);
            }
        }
        public override bool Handle(ulong remoteUserId, CallSite site, BitStream stream, object obj)
        {
            //TODO
            return(false);

            MyPropertySyncStateGroup sync = (MyPropertySyncStateGroup)obj;

            var properties = (ListReader <SyncBase>)sync.GetType().GetField("m_properties", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(sync);

            byte            index = 0;
            BitReaderWriter bits  = new BitReaderWriter();

            Serialize(site.MethodInfo, stream, ref index, ref bits);

            MyTerminalBlock entity = null;

            MyExternalReplicable <MySyncedBlock> rep = sync.Owner as MyExternalReplicable <MySyncedBlock>;

            if (rep == null)
            {
                //there are lots of reasons this wouldn't be MySyncedBlock, so just ignore it and move on
                return(false);
            }

            entity = rep.Instance as MyTerminalBlock;

            MyCubeGrid grid = entity?.CubeGrid;

            if (grid == null)
            {
                Essentials.Log.Info("Null grid in SyncPropertyHandler");
                return(false);
            }


            Essentials.Log.Warn($"{entity.CustomName} | {index} | {properties[index].ValueType}");

            if (entity is MyLandingGear)
            {
                //clients sometimes send updates for landing gear for no discernable reason?
                //just ignore it, it's mostly harmless
                return(false);
            }

            //bool found = false;
            //foreach ( ProtectedItem item in PluginSettings.Instance.ProtectedItems )
            //{
            //    if ( !item.Enabled )
            //        continue;

            //    if ( item.EntityId != grid.EntityId )
            //        continue;

            //    if ( !item.ProtectionSettingsDict.Dictionary.ContainsKey( ProtectedItem.ProtectionModeEnum.BlockSettings ) )
            //        continue;

            //    ProtectedItem.ProtectionSettings settings = item.ProtectionSettingsDict[ProtectedItem.ProtectionModeEnum.BlockSettings];

            //    if ( Protection.Instance.CheckPlayerExempt( settings, grid, remoteUserId ) )
            //        continue;

            //    if ( item.LogOnly )
            //    {
            //        Essentials.Log.Info( $"Recieved block settings change request from user {PlayerMap.Instance.GetFastPlayerNameFromSteamId( remoteUserId )}:{remoteUserId} for block {entity.CustomName} on grid {grid.DisplayNameText ?? "ID"}:{item.EntityId}" );
            //        continue;
            //    }

            //    if ( !string.IsNullOrEmpty( settings.PrivateWarningMessage ) )
            //        Communication.Notification( remoteUserId, MyFontEnum.Red, 5000, settings.PrivateWarningMessage );

            //    if ( !string.IsNullOrEmpty( settings.PublicWarningMessage ) )
            //        Communication.SendPublicInformation( settings.PublicWarningMessage.Replace( "%player%", PlayerMap.Instance.GetFastPlayerNameFromSteamId( remoteUserId ) ) );

            //    if ( settings.BroadcastGPS )
            //    {
            //        MyPlayer player = MySession.Static.Players.GetPlayerById( new MyPlayer.PlayerId( remoteUserId, 0 ) );
            //        Vector3D pos = player.GetPosition( );
            //        MyAPIGateway.Utilities.SendMessage( $"GPS:{player.DisplayName}:{pos.X}:{pos.Y}:{pos.Z}:" );
            //    }

            //    Essentials.Log.Info($"Intercepted block settings change request from user {PlayerMap.Instance.GetFastPlayerNameFromSteamId(remoteUserId)}:{remoteUserId} for block {entity.CustomName} on grid {grid.DisplayNameText ?? "ID"}:{item.EntityId}" );

            //    switch ( settings.PunishmentType )
            //    {
            //        case ProtectedItem.PunishmentEnum.Kick:
            //            _kickTimer.Elapsed += ( sender, e ) =>
            //                                  {
            //                                      Essentials.Log.Info( $"Kicked user {PlayerMap.Instance.GetFastPlayerNameFromSteamId( remoteUserId )}:{remoteUserId} for changing block settings on protected grid {grid.DisplayNameText ?? "ID"}:{item.EntityId}" );
            //                                      MyMultiplayer.Static.KickClient( remoteUserId );
            //                                  };
            //            _kickTimer.AutoReset = false;
            //            _kickTimer.Start( );
            //            break;
            //        case ProtectedItem.PunishmentEnum.Ban:
            //            _kickTimer.Elapsed += ( sender, e ) =>
            //                                  {
            //                                      Essentials.Log.Info( $"Banned user {PlayerMap.Instance.GetFastPlayerNameFromSteamId( remoteUserId )}:{remoteUserId} for changing block settings on protected grid {grid.DisplayNameText ?? "ID"}:{item.EntityId}" );
            //                                      MyMultiplayer.Static.BanClient( remoteUserId, true );
            //                                  };
            //            _kickTimer.AutoReset = false;
            //            _kickTimer.Start( );
            //            break;
            //        case ProtectedItem.PunishmentEnum.Speed:
            //            Task.Run( ( ) =>
            //                      {
            //                          lock ( ProcessSpeed.SpeedPlayers )
            //                          {
            //                              long playerId = PlayerMap.Instance.GetFastPlayerIdFromSteamId( remoteUserId );
            //                              ProcessSpeed.SpeedPlayers[playerId] = new Tuple<float, DateTime>( (float)settings.SpeedLimit, DateTime.Now + TimeSpan.FromMinutes( settings.SpeedTime ) );
            //                          }
            //                      } );
            //            Essentials.Log.Info( $"Limited user {PlayerMap.Instance.GetFastPlayerNameFromSteamId( remoteUserId )} to {settings.SpeedLimit}m/s for {settings.SpeedTime} minutes" );
            //            break;
            //    }

            //    found = true;
            //}

            //return found;
        }
Exemple #29
0
        public override ValidationResult HasRights(EndpointId endpointId, ValidationType validationFlags)
        {
            MyExternalReplicable myExternalReplicable = FindByObject(Instance.Owner);

            return(myExternalReplicable?.HasRights(endpointId, validationFlags) ?? base.HasRights(endpointId, validationFlags));
        }
Exemple #30
0
        private void PutPlayerInRespawnGrid(MyPlayer player, List <MyCubeGrid> respawnGrids, MyBotDefinition botDefinition)
        {
            MyCharacter character = null;
            MyCockpit   cockpit   = null;

            // Find cockpits
            List <MyCockpit> shipCockpits = new List <MyCockpit>();

            foreach (MyCubeGrid grid in respawnGrids)
            {
                foreach (MyCockpit gridCockpit in grid.GetFatBlocks <MyCockpit>())
                {
                    // Ignore non-functional cockpits
                    if (!gridCockpit.IsFunctional)
                    {
                        continue;
                    }
                    shipCockpits.Add(gridCockpit);
                }
            }

            // First sort cockpits by order: Ship controlling cockpits set to main, then ship controlling cockpits not set to main, lastly whatever remains, e.g. CryoChambers and Passenger Seats
            if (shipCockpits.Count > 1)
            {
                shipCockpits.Sort(delegate(MyCockpit cockpitA, MyCockpit cockpitB)
                {
                    int controlCompare = cockpitB.EnableShipControl.CompareTo(cockpitA.EnableShipControl);
                    if (controlCompare != 0)
                    {
                        return(controlCompare);
                    }

                    int mainCompare = cockpitB.IsMainCockpit.CompareTo(cockpitA.IsMainCockpit);
                    if (mainCompare != 0)
                    {
                        return(mainCompare);
                    }

                    return(0);
                });
            }

            // Finally, select the most important cockpit
            if (shipCockpits.Count > 0)
            {
                cockpit = shipCockpits[0];
            }

            System.Diagnostics.Debug.Assert(cockpit != null, "character is spawning in ship without cockpit !");

            // Create character
            MatrixD matrix = MatrixD.Identity;

            if (cockpit != null)
            {
                matrix             = cockpit.WorldMatrix;
                matrix.Translation = cockpit.WorldMatrix.Translation - Vector3.Up - Vector3.Forward;
            }
            else if (respawnGrids.Count > 0)
            {
                matrix.Translation = respawnGrids[0].PositionComp.WorldAABB.Center + respawnGrids[0].PositionComp.WorldAABB.HalfExtents;
            }

            character = MyCharacter.CreateCharacter(matrix, Vector3.Zero, player.Identity.DisplayName, player.Identity.Model, null, botDefinition, cockpit: cockpit, playerSteamId: player.Id.SteamId);

            CloseRespawnShip(player);
            foreach (var respawnGrid in respawnGrids)
            {
                respawnGrid.ChangeGridOwnership(player.Identity.IdentityId, MyOwnershipShareModeEnum.None);
                respawnGrid.IsRespawnGrid = true;
                respawnGrid.m_playedTime  = 0;
                player.RespawnShip.Add(respawnGrid.EntityId);
            }
            //SaveRespawnShip(player);

            if (cockpit != null)
            {
                cockpit.AttachPilot(character, false);
                MyMultiplayer.ReplicateImmediatelly(MyExternalReplicable.FindByObject(cockpit.CubeGrid), new EndpointId(player.Id.SteamId));
            }

            if (cockpit == null)
            {
                Sync.Players.SetPlayerCharacter(player, character, null);
            }
            else
            {
                character.SetPlayer(player);
                Sync.Players.SetPlayerToCockpit(player, cockpit);
            }
            Sync.Players.RevivePlayer(player);
        }