Beispiel #1
0
        static void OnRemoveItemsRequest(ref RemoveItemsMsg msg, MyNetworkClient sender)
        {
            if (!MyEntities.EntityExists(msg.OwnerEntityId))
            {
                return;
            }

            IMyInventoryOwner owner = MyEntities.GetEntityById(msg.OwnerEntityId) as IMyInventoryOwner;
            MyInventory       inv   = null;

            if (owner != null)
            {
                inv = owner.GetInventory(msg.InventoryIndex);
            }
            else
            {
                // NOTE: this should be the default code after we get rid of the inventory owner and should be searched by it's id
                MyEntity        entity = MyEntities.GetEntityById(msg.OwnerEntityId);
                MyInventoryBase baseInventory;
                if (entity.Components.TryGet <MyInventoryBase>(out baseInventory))
                {
                    inv = baseInventory as MyInventory;
                }
            }
            var item = inv.GetItemByID(msg.itemId);

            if (!item.HasValue)
            {
                return;
            }
            inv.RemoveItems(msg.itemId, msg.Amount, spawn: msg.Spawn);
        }
        /// <summary>
        /// Checks all planets of the star system, and whether they are still existent as objects
        /// in the world. Just to clear up deleted objects from the system at world loading
        /// </summary>
        private void CheckIntegrityOfSystem()
        {
            foreach (var obj in StarSystem.GetAllObjects())
            {
                if (obj is MySystemPlanet)
                {
                    if (!MyEntities.EntityExists((obj as MySystemPlanet).EntityId) && (obj as MySystemPlanet).Generated)
                    {
                        MyPluginLog.Debug("Planet " + obj.Id + " does not exist anymore, deleting it", LogLevel.WARNING);
                        StarSystem.RemoveObject(obj.Id);
                        MyGPSManager.Static.RemovePersistentGps(obj.Id);
                    }
                }
                else if (obj is MySystemAsteroids)
                {
                    var instance = obj as MySystemAsteroids;

                    if (MyAsteroidObjectsManager.Static.AsteroidObjectProviders.ContainsKey(instance.AsteroidTypeName))
                    {
                        var data = MyAsteroidObjectsManager.Static.AsteroidObjectProviders[instance.AsteroidTypeName].GetInstanceData(instance);
                        if (data == null)
                        {
                            MyPluginLog.Debug("Asteroid instance " + obj.Id + " has no data attached, deleting it", LogLevel.WARNING);
                            MyAsteroidObjectsManager.Static.AsteroidObjectProviders[instance.AsteroidTypeName].RemoveInstance(instance);
                            MyGPSManager.Static.RemovePersistentGps(obj.Id);
                        }
                    }
                }
            }
        }
Beispiel #3
0
        private static void InventoryBaseTransferItem_Implementation(MyInventoryTransferEventContent eventParams)
        {
            if (!MyEntities.EntityExists(eventParams.DestinationOwnerId) || !MyEntities.EntityExists(eventParams.SourceOwnerId))
            {
                return;
            }

            MyEntity                sourceOwner = MyEntities.GetEntityById(eventParams.SourceOwnerId);
            MyInventoryBase         source      = sourceOwner.GetInventory(eventParams.SourceInventoryId);
            MyEntity                destOwner   = MyEntities.GetEntityById(eventParams.DestinationOwnerId);
            MyInventoryBase         dst         = destOwner.GetInventory(eventParams.DestinationInventoryId);
            var                     items       = source.GetItems();
            MyPhysicalInventoryItem?foundItem   = null;

            foreach (var item in items)
            {
                if (item.ItemId == eventParams.ItemId)
                {
                    foundItem = item;
                }
            }

            if (foundItem.HasValue)
            {
                dst.TransferItemsFrom(source, foundItem, eventParams.Amount);
            }
        }
Beispiel #4
0
        static void OnRemoveItemsSuccess(ref RemoveItemsMsg msg, MyNetworkClient sender)
        {
            if (!MyEntities.EntityExists(msg.OwnerEntityId))
            {
                return;
            }
            IMyInventoryOwner owner = MyEntities.GetEntityById(msg.OwnerEntityId) as IMyInventoryOwner;
            MyInventory       inv   = null;

            if (owner != null)
            {
                inv = owner.GetInventory(msg.InventoryIndex);
            }
            else
            {
                // NOTE: this should be the default code after we get rid of the inventory owner and should be searched by it's id
                MyEntity        entity = MyEntities.GetEntityById(msg.OwnerEntityId);
                MyInventoryBase baseInventory;
                if (entity.Components.TryGet <MyInventoryBase>(out baseInventory))
                {
                    inv = baseInventory as MyInventory;
                }
            }

            if (inv != null)
            {
                inv.RemoveItemsInternal(msg.itemId, msg.Amount);
            }
            else
            {
                Debug.Fail("Inventory was not found!");
            }
        }
        private static MyEntity OnMessageCompressedInternal(ref CreateCompressedMsg msg)
        {
            MyEntity firstEntity = null;

            int bytesOffset = 0;

            for (int i = 0; i < msg.BuilderLengths.Length; ++i)
            {
                MemoryStream stream = new MemoryStream(msg.ObjectBuilders, bytesOffset, msg.BuilderLengths[i]);

                MyObjectBuilder_EntityBase entity;
                if (Sandbox.Common.ObjectBuilders.Serializer.MyObjectBuilderSerializer.DeserializeGZippedXML(stream, out entity))
                {
                    MySandboxGame.Log.WriteLine("CreateCompressedMsg: " + msg.ObjectBuilders.GetType().Name.ToString() + " EntityID: " + entity.EntityId.ToString("X8"));
                    if (i == 0)
                    {
                        firstEntity = MyEntities.CreateFromObjectBuilderAndAdd(entity);
                    }
                    else
                    {
                        MyEntities.CreateFromObjectBuilderAndAdd(entity);
                    }
                    MySandboxGame.Log.WriteLine("Status: Exists(" + MyEntities.EntityExists(entity.EntityId) + ") InScene(" + ((entity.PersistentFlags & MyPersistentEntityFlags2.InScene) == MyPersistentEntityFlags2.InScene) + ")");
                }

                bytesOffset += msg.BuilderLengths[i];
            }

            return(firstEntity);
        }
        static void OnMessageRelativeCompressed(ref CreateRelativeCompressedMsg msg, MyNetworkClient sender)
        {
            MySandboxGame.Log.WriteLine("CreateRelativeCompressedMsg received");

            int bytesOffset = 0;

            for (int i = 0; i < msg.CreateMessage.BuilderLengths.Length; ++i)
            {
                MemoryStream stream = new MemoryStream(msg.CreateMessage.ObjectBuilders, bytesOffset, msg.CreateMessage.BuilderLengths[i]);

                MyObjectBuilder_EntityBase entity;
                if (Sandbox.Common.ObjectBuilders.Serializer.MyObjectBuilderSerializer.DeserializeGZippedXML(stream, out entity))
                {
                    MySandboxGame.Log.WriteLine("CreateRelativeCompressedMsg: " + msg.CreateMessage.ObjectBuilders.GetType().Name.ToString() + " EntityID: " + entity.EntityId.ToString("X8"));

                    MyEntity baseEntity;
                    if (MyEntities.TryGetEntityById(msg.BaseEntity, out baseEntity))
                    {
                        Matrix worldMatrix = entity.PositionAndOrientation.Value.GetMatrix() * baseEntity.WorldMatrix;
                        entity.PositionAndOrientation = new MyPositionAndOrientation(worldMatrix);

                        var newEntity = MyEntities.CreateFromObjectBuilderAndAdd(entity);

                        Vector3 velocity = Vector3.Transform(msg.RelativeVelocity, baseEntity.WorldMatrix.GetOrientation());
                        newEntity.Physics.LinearVelocity = velocity;

                        MySandboxGame.Log.WriteLine("Status: Exists(" + MyEntities.EntityExists(entity.EntityId) + ") InScene(" + ((entity.PersistentFlags & MyPersistentEntityFlags2.InScene) == MyPersistentEntityFlags2.InScene) + ")");
                    }
                }

                bytesOffset += msg.CreateMessage.BuilderLengths[i];
            }
        }
Beispiel #7
0
 static void OnAddItemsSuccess(ref AddItemsMsg msg, MyNetworkClient sender)
 {
     if (!MyEntities.EntityExists(msg.OwnerEntityId))
     {
         return;
     }
     AddItemsInternal(msg);
 }
Beispiel #8
0
 private static void PlayAttackAnimation(long entityId)
 {
     if (MyEntities.EntityExists(entityId))
     {
         MyCharacter character = MyEntities.GetEntityById(entityId) as MyCharacter;
         if (character != null)
             character.AnimationController.TriggerAction(m_stringIdAttackAction);
     }
 }
 static void OnMessage(ref CreateMsg msg, MyNetworkClient sender)
 {
     MySandboxGame.Log.WriteLine("CreateMsg: " + msg.ObjectBuilder.GetType().Name.ToString() + " EntityID: " + msg.ObjectBuilder.EntityId.ToString("X8"));
     MyEntities.CreateFromObjectBuilderAndAdd(msg.ObjectBuilder);
     MySandboxGame.Log.WriteLine("Status: Exists(" + MyEntities.EntityExists(msg.ObjectBuilder.EntityId) + ") InScene(" + ((msg.ObjectBuilder.PersistentFlags & MyPersistentEntityFlags2.InScene) == MyPersistentEntityFlags2.InScene) + ")");
     if (Sync.IsServer)
     {
         MySession.Static.SyncLayer.SendMessageToAll(ref msg);
     }
 }
Beispiel #10
0
        static void OnAddItemsRequest(ref AddItemsMsg msg, MyNetworkClient sender)
        {
            if (!MyEntities.EntityExists(msg.OwnerEntityId))
            {
                return;
            }
            IMyInventoryOwner owner = MyEntities.GetEntityById(msg.OwnerEntityId) as IMyInventoryOwner;

            owner.GetInventory(msg.InventoryIndex).AddItems(msg.Amount, msg.Item, msg.itemIdx);
        }
        public void SaveCameraCollection(MyObjectBuilder_Checkpoint checkpoint)
        {
            MyDebug.AssertDebug(checkpoint.AllPlayersData != null, "Players data not initialized!");
            if (checkpoint.AllPlayersData == null)
            {
                return;
            }

            foreach (var playerData in checkpoint.AllPlayersData.Dictionary)
            {
                PlayerId pid = new PlayerId(playerData.Key.ClientId, playerData.Key.SerialId);
                playerData.Value.EntityCameraData = new List <CameraControllerSettings>();

                if (!m_entityCameraSettings.ContainsKey(pid))
                {
                    continue;
                }

                m_entitiesToRemove.Clear();
                foreach (var cameraSetting in m_entityCameraSettings[pid])
                {
                    if (MyEntities.EntityExists(cameraSetting.Key))
                    {
                        CameraControllerSettings settings = new CameraControllerSettings()
                        {
                            Distance      = cameraSetting.Value.Distance,
                            IsFirstPerson = cameraSetting.Value.IsFirstPerson,
                            HeadAngle     = cameraSetting.Value.HeadAngle,
                            EntityId      = cameraSetting.Key,
                        };
                        playerData.Value.EntityCameraData.Add(settings);
                    }
                    else
                    {
                        m_entitiesToRemove.Add(cameraSetting.Key);
                    }
                }

                foreach (long entityId in m_entitiesToRemove)
                {
                    m_entityCameraSettings[pid].Remove(entityId);
                }

                if (m_characterCameraSettings != null)
                {
                    playerData.Value.CharacterCameraData = new CameraControllerSettings()
                    {
                        Distance      = m_characterCameraSettings.Distance,
                        IsFirstPerson = m_characterCameraSettings.IsFirstPerson,
                        HeadAngle     = m_characterCameraSettings.HeadAngle,
                    };
                }
            }
        }
Beispiel #12
0
        static void OnRemoveItemsSuccess(ref RemoveItemsMsg msg, MyNetworkClient sender)
        {
            if (!MyEntities.EntityExists(msg.OwnerEntityId))
            {
                return;
            }
            IMyInventoryOwner owner = MyEntities.GetEntityById(msg.OwnerEntityId) as IMyInventoryOwner;
            MyInventory       inv   = owner.GetInventory(msg.InventoryIndex);

            inv.RemoveItemsInternal(msg.itemId, msg.Amount);
        }
        private void OnCutAsteroidConfirm(MyVoxelMap targetVoxelMap)
        {
            Debug.Assert(targetVoxelMap != null);

            //Check if entity wasn't deleted by someone else during waiting
            if (MyEntities.EntityExists(targetVoxelMap.EntityId))
            {
                DeactivateCopyPaste(true);
                DeactivateCopyPasteFloatingObject(true);
                targetVoxelMap.SyncObject.SendCloseRequest();
            }
        }
Beispiel #14
0
        static void OnTransferItemsRequest(ref TransferItemsMsg msg, MyNetworkClient sender)
        {
            if (!MyEntities.EntityExists(msg.OwnerEntityId) || !MyEntities.EntityExists(msg.DestOwnerEntityId))
            {
                return;
            }

            IMyInventoryOwner srcOwner  = MyEntities.GetEntityById(msg.OwnerEntityId) as IMyInventoryOwner;
            IMyInventoryOwner destOwner = MyEntities.GetEntityById(msg.DestOwnerEntityId) as IMyInventoryOwner;
            MyInventory       src       = srcOwner.GetInventory(msg.InventoryIndex);
            MyInventory       dst       = destOwner.GetInventory(msg.DestInventoryIndex);

            TransferItemsInternal(src, dst, msg.itemId, msg.Spawn, msg.DestItemIndex, msg.Amount);
        }
Beispiel #15
0
        static void OnRemoveItemsRequest(ref RemoveItemsMsg msg, MyNetworkClient sender)
        {
            if (!MyEntities.EntityExists(msg.OwnerEntityId))
            {
                return;
            }

            IMyInventoryOwner owner = MyEntities.GetEntityById(msg.OwnerEntityId) as IMyInventoryOwner;
            MyInventory       inv   = owner.GetInventory(msg.InventoryIndex);
            var item = inv.GetItemByID(msg.itemId);

            if (!item.HasValue)
            {
                return;
            }
            inv.RemoveItems(msg.itemId, msg.Amount, spawn: msg.Spawn);
        }
Beispiel #16
0
 private void InventoryConsumeItem_Implementation(MyFixedPoint amount, SerializableDefinitionId itemId, long consumerEntityId)
 {
     if ((consumerEntityId == 0) || MyEntities.EntityExists(consumerEntityId))
     {
         MyFixedPoint point = this.GetItemAmount(itemId, MyItemFlags.None, false);
         if (point < amount)
         {
             amount = point;
         }
         MyEntity entityById = null;
         if (consumerEntityId != 0)
         {
             entityById = MyEntities.GetEntityById(consumerEntityId, false);
             if (entityById == null)
             {
                 return;
             }
         }
         if (entityById.Components != null)
         {
             MyUsableItemDefinition definition = MyDefinitionManager.Static.GetDefinition(itemId) as MyUsableItemDefinition;
             if (definition != null)
             {
                 MyCharacter character = entityById as MyCharacter;
                 if (character != null)
                 {
                     character.SoundComp.StartSecondarySound(definition.UseSound, true);
                 }
                 MyConsumableItemDefinition definition2 = definition as MyConsumableItemDefinition;
                 if (definition2 != null)
                 {
                     MyCharacterStatComponent component = entityById.Components.Get <MyEntityStatComponent>() as MyCharacterStatComponent;
                     if (component != null)
                     {
                         component.Consume(amount, definition2);
                     }
                 }
             }
         }
         if (1 != 0)
         {
             this.RemoveItemsOfType(amount, itemId, MyItemFlags.None, false);
         }
     }
 }
Beispiel #17
0
        private static bool TakeFloatingObjectPrepare(long ownerEntityId, long floatingObjectId, byte inventoryIndex, out MyFloatingObject obj, out MyFixedPoint amount)
        {
            obj    = null;
            amount = 0;

            if (!MyEntities.EntityExists(ownerEntityId) || !MyEntities.EntityExists(floatingObjectId))
            {
                return(false);
            }
            obj = MyEntities.GetEntityById(floatingObjectId) as MyFloatingObject;
            if (obj.MarkedForClose)
            {
                return(false);
            }
            var owner = MyEntities.GetEntityById(ownerEntityId) as IMyInventoryOwner;
            var inv   = owner.GetInventory(inventoryIndex);

            return(ComputeFloatingObjectAmount(obj, ref amount, inv));
        }
Beispiel #18
0
        private void InventoryConsumeItem_Implementation(MyFixedPoint amount, SerializableDefinitionId itemId, long consumerEntityId)
        {
            if ((consumerEntityId != 0 && !MyEntities.EntityExists(consumerEntityId)))
            {
                return;
            }

            var existingAmount = GetItemAmount(itemId);

            if (existingAmount < amount)
            {
                amount = existingAmount;
            }

            MyEntity entity = null;

            if (consumerEntityId != 0)
            {
                entity = MyEntities.GetEntityById(consumerEntityId);
                if (entity == null)
                {
                    return;
                }
            }

            if (entity.Components != null)
            {
                var statComp = entity.Components.Get <MyEntityStatComponent>() as MyCharacterStatComponent;
                if (statComp != null)
                {
                    var definition = MyDefinitionManager.Static.GetDefinition(itemId) as MyConsumableItemDefinition;
                    statComp.Consume(amount, definition);
                    var character = entity as MyCharacter;
                    if (character != null)
                    {
                        character.SoundComp.StartSecondarySound(definition.EatingSound, true);
                    }
                }
            }

            RemoveItemsOfType(amount, itemId);
        }
Beispiel #19
0
        private bool ServerMarkedTargetUpdate(PacketObj data)
        {
            var packet       = data.Packet;
            var targetPacket = (FakeTargetPacket)packet;
            var myGrid       = MyEntities.GetEntityByIdOrDefault(packet.EntityId) as MyCubeGrid;

            if (myGrid == null)
            {
                return(Error(data, Msg($"GridId:{packet.EntityId} - entityExists:{MyEntities.EntityExists(packet.EntityId)}")));
            }


            GridAi ai;
            long   playerId;

            if (GridTargetingAIs.TryGetValue(myGrid, out ai) && SteamToPlayer.TryGetValue(packet.SenderId, out playerId))
            {
                GridAi.FakeTargets fakeTargets;
                uint[]             mIds;
                if (PlayerMIds.TryGetValue(packet.SenderId, out mIds) && mIds[(int)packet.PType] < packet.MId && PlayerDummyTargets.TryGetValue(playerId, out fakeTargets))
                {
                    mIds[(int)packet.PType] = packet.MId;

                    fakeTargets.PaintedTarget.Sync(targetPacket, ai);
                    PacketsToClient.Add(new PacketInfo {
                        Entity = myGrid, Packet = targetPacket
                    });

                    data.Report.PacketValid = true;
                }
                else
                {
                    Log.Line($"ServerFakeTargetUpdate: MidsHasSenderId:{PlayerMIds.ContainsKey(packet.SenderId)} - midsNull:{mIds == null} - senderId:{packet.SenderId}");
                }
            }
            else
            {
                return(Error(data, Msg($"GridAi not found, is marked:{myGrid.MarkedForClose}, has root:{GridToMasterAi.ContainsKey(myGrid)}")));
            }

            return(true);
        }
        //private void ShowStationRotationNotification()
        //{
        //    if (MyPerGameSettings.Game == GameEnum.ME_GAME) //TODO: refactor to remove it.
        //        return;

        //    if (m_stationRotationNotificationOff == null)
        //    {
        //        m_stationRotationNotificationOff = new MyHudNotification(MySpaceTexts.NotificationStationRotationOff, 0, priority: 1);
        //        m_stationRotationNotificationOff.SetTextFormatArguments(MyInput.Static.GetGameControl(MyControlsSpace.FREE_ROTATION));
        //    }

        //    MyHud.Notifications.Remove(m_stationRotationNotification);
        //    MyHud.Notifications.Add(m_stationRotationNotificationOff);
        //}

        //private void HideStationRotationNotification()
        //{
        //    if (m_stationRotationNotification != null)
        //    {
        //        MyHud.Notifications.Remove(m_stationRotationNotification);
        //    }
        //    if (m_stationRotationNotificationOff != null)
        //    {
        //        MyHud.Notifications.Remove(m_stationRotationNotificationOff);
        //    }
        //}

        private void OnCutConfirm(MyCubeGrid targetGrid, bool cutGroup, bool cutOverLgs)
        {
            Debug.Assert(targetGrid != null);

            //Check if entity wasn't deleted by someone else during waiting
            if (MyEntities.EntityExists(targetGrid.EntityId))
            {
                DeactivateCopyPasteVoxel(true);
                DeactivateCopyPasteFloatingObject(true);

                if (cutGroup)
                {
                    m_clipboard.CutGroup(targetGrid, cutOverLgs ? GridLinkTypeEnum.Physical : GridLinkTypeEnum.Logical);
                }
                else
                {
                    m_clipboard.CutGrid(targetGrid);
                }
            }
        }
Beispiel #21
0
        static void OnCreateFloatingObjectsCallback(ref FloatingObjectsCreateMsg msg, MyNetworkClient sender)
        {
            //MySandboxGame.Log.WriteLine("FloatingObjectsCreateMsg: " + msg.FloatingObjects.Count);

            foreach (var floatingObject in msg.FloatingObjects)
            {
                foreach (var instance in floatingObject.Instances)
                {
                    System.Diagnostics.Debug.Assert(instance.Amount > 0);

                    if (instance.Amount <= 0)
                    {
                        continue;
                    }

                    if (MyEntities.EntityExists(instance.Location.EntityId))
                    {
                        continue;
                    }

                    var objectBuilder = new MyObjectBuilder_FloatingObject();
                    objectBuilder.Item                   = new MyObjectBuilder_InventoryItem();
                    objectBuilder.Item.Amount            = instance.Amount;
                    objectBuilder.Item.Content           = MyObjectBuilderSerializer.CreateNewObject(((MyDefinitionId)floatingObject.TypeId).TypeId, ((MyDefinitionId)floatingObject.TypeId).SubtypeName);
                    objectBuilder.EntityId               = instance.Location.EntityId;
                    objectBuilder.PositionAndOrientation = new MyPositionAndOrientation(instance.Location.Position, instance.Location.Forward, instance.Location.Up);
                    objectBuilder.PersistentFlags        = MyPersistentEntityFlags2.InScene | MyPersistentEntityFlags2.Enabled | MyPersistentEntityFlags2.CastShadows;

                    MyFloatingObject floatingObjectAdded = (MyFloatingObject)MyEntities.CreateFromObjectBuilderAndAdd(objectBuilder);
                    if (floatingObjectAdded.Physics != null)
                    {
                        floatingObjectAdded.Physics.LinearVelocity  = instance.Location.LinearVelocity;
                        floatingObjectAdded.Physics.AngularVelocity = instance.Location.AngularVelocity;
                    }
                }
            }
            if (Sync.IsServer)
            {
                Sync.Layer.SendMessageToAllButOne(ref msg, sender.SteamUserId);
            }
        }
Beispiel #22
0
        private static void OnUpdateOxygenLevel(ref UpdateOxygenLevelMsg msg, MyNetworkClient sender)
        {
            if (!MyEntities.EntityExists(msg.OwnerEntityId))
            {
                return;
            }

            IMyInventoryOwner owner = MyEntities.GetEntityById(msg.OwnerEntityId) as IMyInventoryOwner;
            MyInventory       inv   = null;

            if (owner != null)
            {
                inv = owner.GetInventory(msg.InventoryIndex);
            }
            else
            {
                // NOTE: this should be the default code after we get rid of the inventory owner and should be searched by it's id
                MyEntity        entity = MyEntities.GetEntityById(msg.OwnerEntityId);
                MyInventoryBase baseInventory;
                if (entity.Components.TryGet <MyInventoryBase>(out baseInventory))
                {
                    inv = baseInventory as MyInventory;
                }
            }

            var item = inv.GetItemByID(msg.ItemId);

            if (!item.HasValue)
            {
                return;
            }

            var oxygenContainer = item.Value.Content as MyObjectBuilder_OxygenContainerObject;

            if (oxygenContainer != null)
            {
                oxygenContainer.OxygenLevel = msg.OxygenLevel;
                inv.UpdateOxygenAmount();
            }
        }
        static void OnMessageCompressed(ref CreateCompressedMsg msg, MyNetworkClient sender)
        {
            MySandboxGame.Log.WriteLine("CreateCompressedMsg received");

            Debug.Assert(msg.BuilderLengths != null);
            Debug.Assert(msg.ObjectBuilders != null);

            if (msg.BuilderLengths == null)
            {
                return;
            }
            if (msg.ObjectBuilders == null)
            {
                return;
            }

            int bytesOffset = 0;

            for (int i = 0; i < msg.BuilderLengths.Length; ++i)
            {
                MemoryStream stream = new MemoryStream(msg.ObjectBuilders, bytesOffset, msg.BuilderLengths[i]);

                MyObjectBuilder_EntityBase entity;
                if (Sandbox.Common.ObjectBuilders.Serializer.MyObjectBuilderSerializer.DeserializeGZippedXML(stream, out entity))
                {
                    Debug.Assert(entity != null);
                    if (entity != null)
                    {
                        MySandboxGame.Log.WriteLine("CreateCompressedMsg: " + msg.ObjectBuilders.GetType().Name.ToString() + " EntityID: " + entity.EntityId.ToString("X8"));
                        MyEntities.CreateFromObjectBuilderAndAdd(entity);
                        MySandboxGame.Log.WriteLine("Status: Exists(" + MyEntities.EntityExists(entity.EntityId) + ") InScene(" + ((entity.PersistentFlags & MyPersistentEntityFlags2.InScene) == MyPersistentEntityFlags2.InScene) + ")");
                    }
                }

                bytesOffset += msg.BuilderLengths[i];
            }
        }
Beispiel #24
0
        private static void OnUpdateOxygenLevel(ref UpdateOxygenLevelMsg msg, MyNetworkClient sender)
        {
            if (!MyEntities.EntityExists(msg.OwnerEntityId))
            {
                return;
            }

            IMyInventoryOwner owner = MyEntities.GetEntityById(msg.OwnerEntityId) as IMyInventoryOwner;
            MyInventory       inv   = owner.GetInventory(msg.InventoryIndex);
            var item = inv.GetItemByID(msg.ItemId);

            if (!item.HasValue)
            {
                return;
            }

            var oxygenContainer = item.Value.Content as MyObjectBuilder_OxygenContainerObject;

            if (oxygenContainer != null)
            {
                oxygenContainer.OxygenLevel = msg.OxygenLevel;
                inv.UpdateOxygenAmount();
            }
        }
        protected override void CustomClientRead(uint timeStamp, ref MyTimeStampValues serverPositionAndOrientation, VRage.Library.Collections.BitStream stream)
        {
            bool hasSupport = stream.ReadBool();

            if (hasSupport)
            {
                long entityId = stream.ReadInt64();

                Vector3D serverDelta      = stream.ReadVector3D();
                Vector3D serverSupportPos = stream.ReadVector3D();

                if (!MyEntities.EntityExists(entityId))
                {
                    return;
                }

                MyEntity support = MyEntities.GetEntityById(entityId);

                MyTimeStampValues?clientTransform = m_timestamp.GetTransform(timeStamp);

                Vector3D   clientDelta    = Vector3.Zero;
                Vector3D   clientVelocity = Vector3D.Zero;
                Quaternion rotationComp   = Quaternion.Identity;

                if (clientTransform != null)
                {
                    if (m_supportTimeStamp == null)
                    {
                        return;
                    }
                    MyTimeStampValues?supportTransform = m_supportTimeStamp.GetTransform(timeStamp);

                    Vector3D supportPosition = support.PositionComp.WorldMatrix.Translation;

                    if (supportTransform.HasValue)
                    {
                        supportPosition = supportTransform.Value.Transform.Position;

                        if (supportTransform.Value.EntityId != entityId)
                        {
                            supportPosition = serverSupportPos;
                            return;
                        }
                    }

                    clientDelta    = supportPosition - clientTransform.Value.Transform.Position;
                    clientVelocity = clientTransform.Value.LinearVelocity;
                    rotationComp   = Quaternion.Inverse(clientTransform.Value.Transform.Rotation);
                }
                else
                {
                    m_character.PositionComp.SetWorldMatrix(serverPositionAndOrientation.Transform.TransformMatrix, null, true);
                    return;
                }

                MyTimeStampValues delta = new MyTimeStampValues();

                Quaternion.Multiply(ref serverPositionAndOrientation.Transform.Rotation, ref rotationComp, out delta.Transform.Rotation);

                delta.Transform.Position = clientDelta - serverDelta;
                delta.LinearVelocity     = serverPositionAndOrientation.LinearVelocity - clientVelocity;

                double deltaL = delta.Transform.Position.Length();

                //if difference is more than
                if (deltaL < (MyGridPhysics.ShipMaxLinearVelocity() * Sync.RelativeSimulationRatio))
                {
                    delta.Transform.Position = delta.Transform.Position * 0.2;
                    delta.Transform.Rotation = Quaternion.Slerp(delta.Transform.Rotation, Quaternion.Identity, 0.2f);
                }


                Quaternion normalized = delta.Transform.Rotation;
                normalized.Normalize();
                delta.Transform.Rotation = normalized;
                normalized = serverPositionAndOrientation.Transform.Rotation;
                normalized.Normalize();
                serverPositionAndOrientation.Transform.Rotation = normalized;

                Quaternion clientNormalized = clientTransform.Value.Transform.Rotation;
                clientNormalized.Normalize();

                double eps = 0.001;
                if (Math.Abs(Quaternion.Dot(serverPositionAndOrientation.Transform.Rotation, clientNormalized)) < 1 - eps && m_character.IsDead == false)
                {
                    Quaternion currentOrientation = Quaternion.CreateFromForwardUp(m_character.WorldMatrix.Forward, m_character.WorldMatrix.Up);
                    Quaternion.Multiply(ref delta.Transform.Rotation, ref currentOrientation, out currentOrientation);

                    MatrixD matrix        = MatrixD.CreateFromQuaternion(currentOrientation);
                    MatrixD currentMatrix = m_character.PositionComp.WorldMatrix;
                    currentMatrix.Translation = Vector3D.Zero;

                    if (currentMatrix.EqualsFast(ref matrix) == false)
                    {
                        if (m_character.Physics.CharacterProxy != null)
                        {
                            m_character.Physics.CharacterProxy.Forward = matrix.Forward;
                            m_character.Physics.CharacterProxy.Up      = matrix.Up;
                        }
                    }
                }

                if (deltaL > (MyGridPhysics.ShipMaxLinearVelocity() * Sync.RelativeSimulationRatio))
                {
                    m_character.PositionComp.SetPosition(serverPositionAndOrientation.Transform.Position);
                    m_character.Physics.LinearVelocity = serverPositionAndOrientation.LinearVelocity;
                    m_timestamp.OverwriteServerPosition(timeStamp, ref serverPositionAndOrientation);
                    return;
                }
                else if (deltaL > 5.0f * MyTimestampHelper.POSITION_TOLERANCE)
                {
                    m_character.CacheMoveDelta(ref delta.Transform.Position);
                }

                m_character.Physics.LinearVelocity += delta.LinearVelocity;

                m_timestamp.UpdateDeltaPosition(timeStamp, ref delta);
            }
            else
            {
                base.CustomClientRead(timeStamp, ref serverPositionAndOrientation, stream);
            }
        }
Beispiel #26
0
        private void InventoryConsumeItem_Implementation(MyFixedPoint amount, SerializableDefinitionId itemId, long consumerEntityId)
        {
            if ((consumerEntityId != 0 && !MyEntities.EntityExists(consumerEntityId)))
            {
                return;
            }

            var existingAmount = GetItemAmount(itemId);

            if (existingAmount < amount)
            {
                amount = existingAmount;
            }

            MyEntity entity = null;

            if (consumerEntityId != 0)
            {
                entity = MyEntities.GetEntityById(consumerEntityId);
                if (entity == null)
                {
                    return;
                }
            }

            bool removeItem = true;

            if (entity.Components != null)
            {
                var definition = MyDefinitionManager.Static.GetDefinition(itemId) as MyUsableItemDefinition;
                if (definition != null)
                {
                    var character = entity as MyCharacter;
                    if (character != null)
                    {
                        character.SoundComp.StartSecondarySound(definition.UseSound, true);
                    }

                    var consumableDef = definition as MyConsumableItemDefinition;
                    if (consumableDef != null)
                    {
                        var statComp = entity.Components.Get <MyEntityStatComponent>() as MyCharacterStatComponent;
                        if (statComp != null)
                        {
                            statComp.Consume(amount, consumableDef);
                        }
                    }

                    var schematicDef = definition as MySchematicItemDefinition;
                    if (schematicDef != null)
                    {
                        removeItem &= MySessionComponentResearch.Static.UnlockResearch(character, schematicDef.Research);
                    }
                }
            }

            if (removeItem)
            {
                RemoveItemsOfType(amount, itemId);
            }
        }
Beispiel #27
0
 bool IMyEntities.EntityExists(string name)
 {
     return(MyEntities.EntityExists(name));
 }
Beispiel #28
0
 bool IMyEntities.EntityExists(long entityId)
 {
     return(MyEntities.EntityExists(entityId));
 }
Beispiel #29
0
        public static MySmallShipBot InsertFriend(MyActorEnum actorEnum, MyMwcObjectBuilder_SmallShip_TypesEnum?shipType = null)
        {
            MyMwcObjectBuilder_SmallShip_TypesEnum selectedShipType;

            if (shipType.HasValue)
            {
                selectedShipType = shipType.Value;
            }
            else
            {
                switch (actorEnum)
                {
                case MyActorEnum.TARJA:
                    selectedShipType = MyMwcObjectBuilder_SmallShip_TypesEnum.DOON;
                    break;

                case MyActorEnum.VALENTIN:
                    selectedShipType = MyMwcObjectBuilder_SmallShip_TypesEnum.HAMMER;
                    break;

                default:
                    selectedShipType = MyMwcObjectBuilder_SmallShip_TypesEnum.GETTYSBURG;
                    break;
                }
            }

            MySmallShipBot bot;

            string actorSystemName = MyActorConstants.GetActorName(actorEnum);

            if (!MyEntities.EntityExists(actorSystemName))
            {
                MyMwcLog.WriteLine("Insert " + actorSystemName + " - START");

                bot = MyGuiScreenGamePlay.Static.CreateFriend(MyTextsWrapper.Get(MyActorConstants.GetActorProperties(actorEnum).DisplayName).ToString(), 100000, 1, selectedShipType);
                bot.SetName(actorSystemName);
                bot.Save = true;
                bot.LeaderLostEnabled = true;
                bot.IsDestructible    = false;
                bot.SetWorldMatrix(Matrix.CreateWorld(bot.GetPosition(), MySession.PlayerShip.WorldMatrix.Forward, MySession.PlayerShip.WorldMatrix.Up));
                bot.Faction    = MyMwcObjectBuilder_FactionEnum.Rainiers;
                bot.AIPriority = -5;

                MyMwcLog.WriteLine("Insert " + actorSystemName + " - END");
            }
            else
            {
                bot      = MyEntities.GetEntityByName(actorSystemName) as MySmallShipBot;
                bot.Save = true;
                bot.LeaderLostEnabled = true;     // Not persisted for now
                MyMwcLog.WriteLine("Insert " + actorSystemName + " - already loaded");
            }

            //Init smaller box physics because of following player problems
            bot.InitPhysics(1 / MySmallShipConstants.FRIEND_SMALL_SHIP_MODEL_SCALE, bot.ShipTypeProperties.Visual.MaterialType);
            bot.Follow(MySession.PlayerShip);

            if (!MySession.PlayerFriends.Contains(bot))
            {
                MySession.PlayerFriends.Add(bot);
            }

            Debug.Assert(bot.Save, "Bot must have save flag to work in coop");

            return(bot);
        }
Beispiel #30
0
        protected override void CustomClientRead(uint timeStamp, ref MyTransformD serverPositionAndOrientation, VRage.Library.Collections.BitStream stream)
        {
            bool hasSupport = stream.ReadBool();

            if (hasSupport)
            {
                long entityId = stream.ReadInt64();

                Vector3D serverSupportPos = stream.ReadVector3D();

                if (!MyEntities.EntityExists(entityId))
                {
                    return;
                }

                MyEntity support = MyEntities.GetEntityById(entityId);

                MyTimeStampValues?clientTransform = m_timestamp.GetTransform(timeStamp);

                Vector3D   clientPosition        = Vector3D.Zero;
                Vector3D   clientSupportPosition = Vector3D.Zero;
                Quaternion rotationComp          = Quaternion.Identity;

                if (clientTransform != null)
                {
                    if (m_supportTimeStamp == null)
                    {
                        return;
                    }

                    MyTimeStampValues?supportTransform = m_supportTimeStamp.GetTransform(timeStamp);
                    Vector3D          supportPosition  = support.PositionComp.WorldMatrix.Translation;

                    if (supportTransform.HasValue)
                    {
                        supportPosition = supportTransform.Value.Transform.Position;

                        if (supportTransform.Value.EntityId != entityId)
                        {
                            return;
                        }
                    }

                    clientPosition        = clientTransform.Value.Transform.Position;
                    clientSupportPosition = supportPosition;
                    rotationComp          = Quaternion.Inverse(clientTransform.Value.Transform.Rotation);
                }
                else
                {
                    m_character.PositionComp.SetWorldMatrix(serverPositionAndOrientation.TransformMatrix, null, true);
                    return;
                }

                MyTransformD delta = new MyTransformD();

                delta.Rotation = Quaternion.Identity;

                Vector3D characterDelta = serverPositionAndOrientation.Position - clientPosition;
                Vector3D supportDelta   = serverSupportPos - clientSupportPosition;

                delta.Position = characterDelta - supportDelta;
                m_character.CacheMoveDelta(ref delta.Position);
                m_timestamp.UpdateDeltaPosition(timeStamp, ref delta);
            }
            else
            {
                base.CustomClientRead(timeStamp, ref serverPositionAndOrientation, stream);
            }
        }