Beispiel #1
0
        public void UnpackFriends()
        {
            MyMwcLog.WriteLine("MyPlayerFriends::UnpackFriends - START");
            MyMwcLog.IncreaseIndent();

            m_helperInventoryItems.Clear();

            MySession.Static.Inventory.GetInventoryItems(ref m_helperInventoryItems, MyMwcObjectBuilderTypeEnum.SmallShip_Bot, null);
            foreach (var inventoryItem in m_helperInventoryItems)
            {
                MyMwcObjectBuilder_SmallShip friendObjectBuilder = (MyMwcObjectBuilder_SmallShip)inventoryItem.GetInventoryItemObjectBuilder(true);

                // We need to removed id's because mothership container could have same entity id in different sector
                friendObjectBuilder.EntityId = null;
                friendObjectBuilder.PositionAndOrientation = new MyMwcPositionAndOrientation(
                    MySession.PlayerShip.GetPosition() + new Vector3(-100, 100, 50),
                    MySession.PlayerShip.WorldMatrix.Forward,
                    MySession.PlayerShip.WorldMatrix.Up);

                var friend = (MySmallShipBot)MyEntities.CreateFromObjectBuilderAndAdd(friendObjectBuilder.DisplayName, friendObjectBuilder,
                                                                                      friendObjectBuilder.PositionAndOrientation.GetMatrix());

                friend.Activate(true, false);
                friend.SpeedModifier = 1.0f;
                friend.Save          = false;
                Add(friend);
                friend.Follow(MySession.PlayerShip);

                MySession.Static.Inventory.RemoveInventoryItem(inventoryItem);
            }

            MyMwcLog.DecreaseIndent();
            MyMwcLog.WriteLine("MyPlayerFriends::UnpackFriends - END");
        }
Beispiel #2
0
        private static void UpdateStartDummy(MyDummyPointFlags flags, Matrix position)
        {
            MyDummyPoint playerStartDummy = null;

            foreach (var entity in MyEntities.GetEntities())
            {
                MyDummyPoint dummy = entity as MyDummyPoint;
                if (dummy != null && (dummy.DummyFlags & flags) > 0)
                {
                    playerStartDummy = dummy;
                    break;
                }
            }

            if (playerStartDummy == null)
            {
                MyMwcObjectBuilder_DummyPoint dummyPointObjectBuilder =
                    MyMwcObjectBuilder_Base.CreateNewObject(MyMwcObjectBuilderTypeEnum.DummyPoint, null) as
                    MyMwcObjectBuilder_DummyPoint;
                playerStartDummy =
                    MyEntities.CreateFromObjectBuilderAndAdd(null, dummyPointObjectBuilder, Matrix.Identity) as MyDummyPoint;
                playerStartDummy.DummyFlags |= flags;
            }

            playerStartDummy.SetWorldMatrix(position);
        }
Beispiel #3
0
        private MyEntity CreateFromObjectBuilder(MyMwcObjectBuilder_Base objectBuilder)
        {
            if (objectBuilder.GetObjectBuilderType() == MyMwcObjectBuilderTypeEnum.VoxelMap)
            {
                MyMwcObjectBuilder_VoxelMap voxelMapObjectBuilder = objectBuilder as MyMwcObjectBuilder_VoxelMap;
                return(MyEntities.CreateFromObjectBuilderAndAdd(null, voxelMapObjectBuilder, Matrix.Identity));
            }
            else if (objectBuilder.GetObjectBuilderType() == MyMwcObjectBuilderTypeEnum.VoxelMap_Neighbour)
            {
                //  Voxel map neighbours are handled in its static classe, so ignore it here
            }
            else
            {
                if (objectBuilder is MyMwcObjectBuilder_Object3dBase || objectBuilder is MyMwcObjectBuilder_InfluenceSphere)
                {
                    MyEntity temporaryEntity = null;
                    Matrix   matrix          = Matrix.Identity;

                    if (objectBuilder is MyMwcObjectBuilder_Object3dBase)
                    {
                        var object3d = objectBuilder as MyMwcObjectBuilder_Object3dBase;

                        matrix = Matrix.CreateWorld(object3d.PositionAndOrientation.Position, object3d.PositionAndOrientation.Forward, object3d.PositionAndOrientation.Up);
                        MyUtils.AssertIsValid(matrix);
                    }

                    temporaryEntity = MyEntities.CreateFromObjectBuilderAndAdd(null, objectBuilder, matrix);

                    MyEntities.TestEntityAfterInsertionForCollision(temporaryEntity);
                    return(temporaryEntity);
                }
            }
            return(null);
        }
        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);
        }
        public override void Accept()
        {
            float        dist         = float.MaxValue;
            MySpawnPoint closestSpawn = null;

            foreach (var spawn in MyEntities.GetEntities().OfType <MySpawnPoint>())
            {
                var d = (this.Location.Entity.GetPosition() - spawn.GetPosition()).LengthSquared();
                if (d < dist)
                {
                    dist         = d;
                    closestSpawn = spawn;
                }
            }

            // Spawnpoint exists and has templates
            if (closestSpawn != null && closestSpawn.GetBotTemplates().Any())
            {
                // HACK: This is little hack (manually adding bot to scene), because spawnpoints are broken
                var template = closestSpawn.GetBotTemplates().First();
                killSubmission.Target = (MySmallShipBot)MyEntities.CreateFromObjectBuilderAndAdd("Assassination target", template.m_builder, closestSpawn.WorldMatrix);
            }

            base.Accept();
        }
Beispiel #6
0
        public void Init(MyMwcObjectBuilder_Player playerObjectBuilder)
        {
            System.Diagnostics.Debug.Assert(playerObjectBuilder != null);

            Health            = playerObjectBuilder.Health;
            Money             = playerObjectBuilder.Money;
            TimeWithoutOxygen = playerObjectBuilder.WithoutOxygen;

            if (playerObjectBuilder.PlayerStatisticsObjectBuilder != null)
            {
                Statistics.Init(playerObjectBuilder.PlayerStatisticsObjectBuilder);
            }

            if (playerObjectBuilder.ShipObjectBuilder != null)
            {
                // because we want generate playership's id after all other entities will be loaded
                //playerObjectBuilder.ShipObjectBuilder.EntityId = null;
                Ship = MyEntities.CreateFromObjectBuilderAndAdd(null,
                                                                playerObjectBuilder.ShipObjectBuilder,
                                                                playerObjectBuilder.ShipObjectBuilder.PositionAndOrientation.GetMatrix()) as MySmallShip;

                if (playerObjectBuilder.ShipConfigObjectBuilder != null)
                {
                    Ship.Config.Init(playerObjectBuilder.ShipConfigObjectBuilder);
                }
            }

            if (MyFakes.ENABLE_REFILL_PLAYER_TO_MAX)
            {
                SetToMax();
            }
        }
        protected override void OnLoad(BitStream stream, Action <MyInventoryBagEntity> loadingDoneHandler)
        {
            MyObjectBuilder_InventoryBagEntity builder = (MyObjectBuilder_InventoryBagEntity)VRage.Serialization.MySerializer.CreateAndRead <MyObjectBuilder_EntityBase>(stream, MyObjectBuilderSerializer.Dynamic);
            var physicsComponent = MyInventoryBagEntity.GetPhysicsComponentBuilder(builder);

            Debug.Assert(physicsComponent != null);
            if (physicsComponent == null)
            {
                return;
            }

            Vector3 velocity = physicsComponent.LinearVelocity;

            velocity /= MyEntityPhysicsStateGroup.EffectiveSimulationRatio;
            physicsComponent.LinearVelocity = velocity;

            velocity  = physicsComponent.AngularVelocity;
            velocity /= MyEntityPhysicsStateGroup.EffectiveSimulationRatio;
            physicsComponent.AngularVelocity = velocity;

            MyInventoryBagEntity entity = (MyInventoryBagEntity)MyEntities.CreateFromObjectBuilderAndAdd(builder);

            entity.DebugCreatedBy = DebugCreatedBy.FromServer;
            loadingDoneHandler(entity);
        }
        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];
            }
        }
        private void OnOldBodClose(MyEntity entity)
        {
            var newBot = MyEntities.CreateFromObjectBuilderAndAdd(null, m_newBotBuilderToInit, m_newBotWorldMatrixToInit);

            newBot.Activate(m_activatedCheckbox.Checked, false);
            MyEditorGizmo.AddEntityToSelection(newBot);
            CloseAndCallOnOk();
        }
Beispiel #10
0
        static void CreateNewPlaceArea(SerializableDefinitionId id, MyPositionAndOrientation positionAndOrientation)
        {
            MyObjectBuilder_AreaMarker objectBuilder = (MyObjectBuilder_AreaMarker)MyObjectBuilderSerializer.CreateNewObject(id);

            objectBuilder.PersistentFlags        = MyPersistentEntityFlags2.Enabled | MyPersistentEntityFlags2.InScene;
            objectBuilder.PositionAndOrientation = positionAndOrientation;

            MyEntities.CreateFromObjectBuilderAndAdd(objectBuilder);
        }
        private static void AddObjectsPrefab(string prefabName)
        {
            var objects = LoadObjectsPrefab(prefabName);

            foreach (var obj in objects)
            {
                MyEntities.CreateFromObjectBuilderAndAdd(obj);
            }
        }
 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);
     }
 }
 private static void RequestSpawnCreative_Implementation(MyObjectBuilder_FloatingObject obj)
 {
     if (MySession.Static.CreativeMode || MyEventContext.Current.IsLocallyInvoked || MySession.Static.HasPlayerAdminRights(MyEventContext.Current.Sender.Value))
     {
         MyEntities.CreateFromObjectBuilderAndAdd(obj);
     }
     else
     {
         MyEventContext.ValidationFailed();
     }
 }
Beispiel #14
0
 private static void RequestSpawnCreative_Implementation(MyObjectBuilder_FloatingObject obj)
 {
     if ((MySession.Static.CreativeMode || MyEventContext.Current.IsLocallyInvoked) || MySession.Static.HasPlayerCreativeRights(MyEventContext.Current.Sender.Value))
     {
         MyEntities.CreateFromObjectBuilderAndAdd(obj, false);
     }
     else
     {
         (MyMultiplayer.Static as MyMultiplayerServerBase).ValidationFailed(MyEventContext.Current.Sender.Value, true, null, true);
     }
 }
Beispiel #15
0
        public void reload() {
            //Delete all registered gates
            int i = 0;
            foreach (var zone in Plugin.zones) {
                foreach (var entity in MyEntities.GetEntities()) {
                    if (entity?.DisplayName?.Contains(zone, StringComparison.CurrentCultureIgnoreCase) ?? false) {
                        i++;
                        entity.Close();
                    }
                }
            }
            IMyPlayer player = Context.Player;
            if (player == null) {
                Context.Respond($"{i} Jumpgates closed!");
            }
            else {
                utils.NotifyMessage($"{i} Jumpgates closed!", Context.Player.SteamUserId);
            }

            //Rebuild all gates
            int gates = 0;
            IEnumerable<string> channelIds = Plugin.Config.Gates;
            string name = "";
            string location = "";
            foreach (string chId in channelIds) {
                name = chId.Split('/')[0];
                location = chId.Split('/')[1];
                location = location.TrimStart('{').TrimEnd('}');
                Vector3D.TryParse(location, out Vector3D gps);
                var ob = new MyObjectBuilder_SafeZone();
                ob.PositionAndOrientation = new MyPositionAndOrientation(gps, Vector3.Forward, Vector3.Up);
                ob.PersistentFlags = MyPersistentEntityFlags2.InScene;
                ob.Shape = MySafeZoneShape.Sphere;
                ob.Radius = Plugin.Config.GateSize;
                ob.Enabled = true;
                ob.DisplayName = $"SM-{gps}";
                ob.AccessTypeGrids = MySafeZoneAccess.Blacklist;
                ob.AccessTypeFloatingObjects = MySafeZoneAccess.Blacklist;
                ob.AccessTypeFactions = MySafeZoneAccess.Blacklist;
                ob.AccessTypePlayers = MySafeZoneAccess.Blacklist;
                var zone = MyEntities.CreateFromObjectBuilderAndAdd(ob, true);
                gates++;
                if (!Plugin.zones.Contains(ob.DisplayName)) {
                    Plugin.zones.Add(ob.DisplayName);
                }
            }
            if (player == null) {
                Context.Respond($"{gates} Jumpgates created!");
            }
            else {
                utils.NotifyMessage($"{gates} Jumpgates created!", Context.Player.SteamUserId);
            }
        }
        internal static MyEntity Spawn(MyInventoryItem item, MatrixD worldMatrix, MyPhysicsComponentBase motionInheritedFrom = null)
        {
            var floatingBuilder = PrepareBuilder(ref item);

            floatingBuilder.PositionAndOrientation = new MyPositionAndOrientation(worldMatrix);
            var thrownEntity = MyEntities.CreateFromObjectBuilderAndAdd(floatingBuilder);

            thrownEntity.Physics.ForceActivate();
            ApplyPhysics(thrownEntity, motionInheritedFrom);
            Debug.Assert(thrownEntity.Save == true, "Thrown item will not be saved. Feel free to ignore this.");
            return(thrownEntity);
        }
Beispiel #17
0
        /// <summary>
        /// Spawn Environment Items instance (e.g. forest) object which can be then used for spawning individual items (e.g. trees).
        /// </summary>
        public static MyEnvironmentItemsSpawnData BeginSpawn(MyEnvironmentItemsDefinition itemsDefinition)
        {
            var builder = MyObjectBuilderSerializer.CreateNewObject(itemsDefinition.Id.TypeId, itemsDefinition.Id.SubtypeName) as MyObjectBuilder_EnvironmentItems;

            builder.PersistentFlags |= MyPersistentEntityFlags2.Enabled | MyPersistentEntityFlags2.InScene | MyPersistentEntityFlags2.CastShadows;
            var envItems = MyEntities.CreateFromObjectBuilderAndAdd(builder) as MyEnvironmentItems;

            MyEnvironmentItemsSpawnData spawnData = new MyEnvironmentItemsSpawnData();

            spawnData.EnvironmentItems = envItems;
            return(spawnData);
        }
Beispiel #18
0
        public void Add()
        {
            Vector3 position;

            if (GetAddPosition(out position))
            {
                Matrix matrix = Matrix.CreateTranslation(position);
                var    cube   = new MyMwcObjectBuilder_MysteriousCube(new CommonLIB.AppCode.Networking.MyMwcPositionAndOrientation(matrix));
                cube.MysteriousCubeType = MyMwcObjectBuilder_MysteriousCube_TypesEnum.Type2;
                MyEntities.CreateFromObjectBuilderAndAdd(null, cube, matrix);
            }
        }
        public override void OnOkClick(MyGuiControlButton sender)
        {
            base.OnOkClick(sender);

            Debug.Assert(m_radiusSlider.GetValue() > 30 || m_bots.Count <= 1, "Spawnpoint radius is too small, you will probably get failed spawn attempts!");

            if (!HasEntity())
            {
                MyMwcObjectBuilder_SpawnPoint builder = MyMwcObjectBuilder_Base.CreateNewObject(MyMwcObjectBuilderTypeEnum.SpawnPoint, null) as MyMwcObjectBuilder_SpawnPoint;
                builder.BoundingRadius = m_radiusSlider.GetValue();

                float cameraDistance = builder.BoundingRadius / (float)Math.Sin(MathHelper.ToRadians(MyCamera.FieldOfViewAngle / 2)) * 1.2f;

                m_spawnPoint = MyEntities.CreateFromObjectBuilderAndAdd(null, builder, Matrix.CreateWorld(MyCamera.Position + cameraDistance * MyCamera.ForwardVector, Vector3.Forward, Vector3.Up)) as MySpawnPoint;
            }

            MyMwcObjectBuilder_FactionEnum shipFaction = (MyMwcObjectBuilder_FactionEnum)
                                                         Enum.ToObject(typeof(MyMwcObjectBuilder_FactionEnum), m_selectShipFactionCombobox.GetSelectedKey());

            List <BotTemplate> templates = new List <BotTemplate>();

            foreach (int key in m_bots.Keys)
            {
                BotTemplate btmp;
                m_bots.TryGetValue(key, out btmp);
                btmp.m_builder.Faction = shipFaction;
                templates.Add(btmp);
            }

            m_spawnPoint.SpawnInGroups   = m_spawnInGroupsCheckbox.Checked;
            m_spawnPoint.LeftToSpawn     = GetSpawnCount();
            m_spawnPoint.MaxSpawnCount   = m_spawnPoint.LeftToSpawn;
            m_spawnPoint.FirstSpawnTimer = m_firstSpawnTimeSlider.GetValue();
            m_spawnPoint.RespawnTimer    = m_respawnTimeSlider.GetValue();

            m_spawnPoint.Faction = shipFaction;
            m_spawnPoint.SetWayPointPath(m_waypointPathCombobox.GetSelectedValue().ToString());
            m_spawnPoint.PatrolMode = (MyPatrolMode)m_patrolModeCombobox.GetSelectedKey();
            m_spawnPoint.ApplyBotTemplates(templates);

            m_spawnPoint.BoundingSphereRadius = m_radiusSlider.GetValue();
            if (m_activeCheckbox.Checked && !m_spawnPoint.IsActive())
            {
                m_spawnPoint.Activate();
            }
            else if (!m_activeCheckbox.Checked && m_spawnPoint.IsActive())
            {
                m_spawnPoint.Deactivate();
            }

            MyGuiManager.CloseAllScreensExcept(MyGuiScreenGamePlay.Static);
        }
        void OnNewEntity(ref MyEventNewEntity msg)
        {
            var entityId = msg.ObjectBuilder.EntityId.ToEntityId();

            if (entityId.HasValue && MyEntities.GetEntityByIdOrNull(entityId.Value) != null)
            {
                return;
            }

            var entity = MyEntities.CreateFromObjectBuilderAndAdd(null, msg.ObjectBuilder, msg.Position.GetMatrix());

            HookEntity(entity);
        }
Beispiel #21
0
        public bool DeserializeGridFromPath(string targetFile, string playername, Vector3D newpos)
        {
            var player = utils.GetPlayerByNameOrId(playername);

            if (MyObjectBuilderSerializer.DeserializeXML(targetFile, out MyObjectBuilder_Definitions myObjectBuilder_Definitions))
            {
                IMyEntity targetEntity = player?.Controller.ControlledEntity.Entity;

                utils.NotifyMessage($"Importing grid from {targetFile}", player.SteamUserId);

                var prefabs = myObjectBuilder_Definitions.Prefabs;

                if (prefabs == null || prefabs.Length != 1)
                {
                    utils.NotifyMessage($"Grid has unsupported format!", player.SteamUserId);
                    return(false);
                }

                var prefab = prefabs[0];
                var grids  = prefab.CubeGrids;

                /* Where do we want to paste the grids? Lets find out. */
                var pos = FindPastePosition(grids, newpos, player.DisplayName);
                if (pos == null)
                {
                    utils.NotifyMessage("No free place.", player.SteamUserId);
                    return(false);
                }

                /* Update GridsPosition if that doesnt work get out of here. */
                if (!UpdateGridsPosition(grids, newpos, player.DisplayName))
                {
                    Log.Error("Failed to update grid position");
                    return(false);
                }

                /* Remapping to prevent any key problems upon paste. */
                MyEntities.RemapObjectBuilderCollection(grids);
                foreach (var grid in grids)
                {
                    if (MyEntities.CreateFromObjectBuilderAndAdd(grid, true) is MyCubeGrid cubeGrid)
                    {
                        FixOwnerAndAuthorShip(cubeGrid, player.DisplayName);
                    }
                }
                utils.NotifyMessage("Grid has been pulled from the void!", player.SteamUserId);
                return(true);
            }

            return(false);
        }
Beispiel #22
0
        protected override void OnLoad(BitStream stream, Action <MyInventoryBagEntity> loadingDoneHandler)
        {
            MyObjectBuilder_InventoryBagEntity builder = (MyObjectBuilder_InventoryBagEntity)VRage.Serialization.MySerializer.CreateAndRead <MyObjectBuilder_EntityBase>(stream, MyObjectBuilderSerializer.Dynamic);
            var physicsComponent = MyInventoryBagEntity.GetPhysicsComponentBuilder(builder);

            Debug.Assert(physicsComponent != null);
            if (physicsComponent == null)
            {
                return;
            }

            MyInventoryBagEntity entity = (MyInventoryBagEntity)MyEntities.CreateFromObjectBuilderAndAdd(builder);

            entity.DebugCreatedBy = DebugCreatedBy.FromServer;
            loadingDoneHandler(entity);
        }
        static void OnMessageSpawnGrid(ref SpawnGridMsg msg, MyNetworkClient sender)
        {
            if (Sync.IsServer)
            {
                var     definition  = Definitions.MyDefinitionManager.Static.GetCubeBlockDefinition(msg.Definition);
                MatrixD worldMatrix = MatrixD.CreateWorld(msg.Position, msg.Forward, msg.Up);

                MyCubeGrid grid = null;

                if (msg.Static)
                {
                    grid = MyCubeBuilder.SpawnStaticGrid(definition, worldMatrix);
                }
                else
                {
                    grid = MyCubeBuilder.SpawnDynamicGrid(definition, worldMatrix);
                }

                if (grid != null)
                {
                    msg.Grid = grid.GetObjectBuilder() as MyObjectBuilder_CubeGrid;
                    MySession.Static.SyncLayer.SendMessageToAll(ref msg);
                }

                if (grid != null && msg.Static)
                {
                    MyCubeBuilder.AfterStaticGridSpawn(grid);
                }
            }
            else
            {
                System.Diagnostics.Debug.Assert(msg.Grid != null, "Client must obtain complete grid from server");

                MyCubeGrid grid = MyEntities.CreateFromObjectBuilderAndAdd(msg.Grid) as MyCubeGrid;

                if (grid != null)
                {
                    if (grid.IsStatic)
                    {
                        MyCubeBuilder.AfterStaticGridSpawn(grid);
                    }
                }
            }
        }
Beispiel #24
0
        public override void Load()
        {
            // HACK: ...adding dead entities (dead by solar wind or anything)
            // These entities probably died after Reichstag A mission was successful, so they were not indestructible, solar wind came and eat them
            var colonel  = MyScriptWrapper.TryGetEntity((uint)EntityID.Bot_WaltherStauffenberg);
            var valkyrie = MyScriptWrapper.TryGetEntity((uint)EntityID.Bot_Disabled_03);

            if (colonel == null || valkyrie == null)
            {
                var sector = MyLocalCache.LoadSector(new MyMwcSectorIdentifier(MyMwcSectorTypeEnum.STORY, null, this.GetCurrentSector(), String.Empty));
                var bots   = sector.SectorObjects.OfType <MyMwcObjectBuilder_SmallShip_Bot>();
                foreach (var bot in bots)
                {
                    if (colonel == null && bot.EntityId == (uint)EntityID.Bot_WaltherStauffenberg ||
                        valkyrie == null && bot.EntityId == (uint)EntityID.Bot_Disabled_03)
                    {
                        MyEntities.CreateFromObjectBuilderAndAdd(bot.DisplayName, bot, bot.PositionAndOrientation.GetMatrix());
                    }
                }
            }

            base.Load();

            MyScriptWrapper.SetFactionRelation(MyMwcObjectBuilder_FactionEnum.FourthReich, MyMwcObjectBuilder_FactionEnum.Rainiers, MyFactions.RELATION_BEST);

            MySmallShipBot FoRrepresentative = (MySmallShipBot)MyScriptWrapper.TryGetEntity((uint)EntityID.Bot_WaltherStauffenberg);

            MyScriptWrapper.ChangeFaction(FoRrepresentative, MyMwcObjectBuilder_FactionEnum.FourthReich);
            FoRrepresentative.IsDestructible = false;
            MySmallShipBot Hans = (MySmallShipBot)MyScriptWrapper.TryGetEntity((uint)EntityID.Bot_Hans);
            MySmallShipBot Karl = (MySmallShipBot)MyScriptWrapper.TryGetEntity((uint)EntityID.Bot_Karl);

            Hans.IsDestructible = false;
            Karl.IsDestructible = false;
            Hans.Follow(FoRrepresentative);
            Karl.Follow(FoRrepresentative);

            MyScriptWrapper.DisableShip(MyScriptWrapper.GetEntity((uint)EntityID.Bot_Disabled_01), true, false);
            MyScriptWrapper.DisableShip(MyScriptWrapper.GetEntity((uint)EntityID.Bot_Disabled_02), true, false);
            MyScriptWrapper.DisableShip(MyScriptWrapper.GetEntity((uint)EntityID.Bot_Disabled_03), true, false);
            MyScriptWrapper.DisableShip(MyScriptWrapper.GetEntity((uint)EntityID.Bot_Disabled_04), true, false);
            MyScriptWrapper.DisableShip(MyScriptWrapper.GetEntity((uint)EntityID.Bot_Disabled_05), true, false);
        }
Beispiel #25
0
        public void Safezone(float radius = -1)
        {
            if (radius == -1)
            {
                radius = (float)Plugin.Config.RadiusGate;
            }
            var entities = MyEntities.GetEntities();

            if (entities != null)
            {
                foreach (MyEntity entity in entities)
                {
                    if (entity != null)
                    {
                        if (entity is MySafeZone)
                        {
                            if (entity.DisplayName.Contains("[NPC-IGNORE]_[Wormhole-SafeZone]"))
                            {
                                entity.Close();
                            }
                        }
                    }
                }
            }
            foreach (var server in Plugin.Config.WormholeGates)
            {
                var ob = new MyObjectBuilder_SafeZone
                {
                    PositionAndOrientation = new MyPositionAndOrientation(new Vector3D(server.X, server.Y, server.Z), Vector3.Forward, Vector3.Up),
                    PersistentFlags        = MyPersistentEntityFlags2.InScene,
                    Shape                     = MySafeZoneShape.Sphere,
                    Radius                    = radius,
                    Enabled                   = true,
                    DisplayName               = "[NPC-IGNORE]_[Wormhole-SafeZone]_" + server.Name,
                    AccessTypeGrids           = MySafeZoneAccess.Blacklist,
                    AccessTypeFloatingObjects = MySafeZoneAccess.Blacklist,
                    AccessTypeFactions        = MySafeZoneAccess.Blacklist,
                    AccessTypePlayers         = MySafeZoneAccess.Blacklist
                };
                MyEntities.CreateFromObjectBuilderAndAdd(ob, true);
            }
            Context.Respond("Deleted all entities with '[NPC-IGNORE]_[Wormhole-SafeZone]' in them and readded Safezones to each Wormhole");
        }
Beispiel #26
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 #27
0
        void confirmButton_OnButtonClick(MyGuiControlButton sender)
        {
            MyContainerDefinition newDefinition = new MyContainerDefinition();

            foreach (var addComp in m_addComponentsListBox.SelectedItems)
            {
                if (addComp.UserData is MyDefinitionId)
                {
                    var defId = (MyDefinitionId)addComp.UserData;

                    MyContainerDefinition.DefaultComponent component = new MyContainerDefinition.DefaultComponent();
                    component.BuilderType = defId.TypeId;
                    component.SubtypeId   = defId.SubtypeId;

                    newDefinition.DefaultComponents.Add(component);
                }
            }

            MyObjectBuilder_EntityBase entityOb = null;

            if (m_replicableEntityCheckBox.IsChecked)
            {
                entityOb         = new MyObjectBuilder_ReplicableEntity();
                newDefinition.Id = new MyDefinitionId(typeof(MyObjectBuilder_ReplicableEntity), "DebugTest");
            }
            else
            {
                entityOb         = new MyObjectBuilder_EntityBase();
                newDefinition.Id = new MyDefinitionId(typeof(MyObjectBuilder_EntityBase), "DebugTest");
            }
            MyDefinitionManager.Static.SetEntityContainerDefinition(newDefinition);

            entityOb.SubtypeName            = newDefinition.Id.SubtypeName;
            entityOb.PositionAndOrientation = new MyPositionAndOrientation(m_position, Vector3.Forward, Vector3.Up);

            MyEntity entity = MyEntities.CreateFromObjectBuilderAndAdd(entityOb);

            Debug.Assert(entity != null, "Entity wasn't created!");

            CloseScreen();
        }
Beispiel #28
0
        public static MyEntity Spawn(MyPhysicalInventoryItem item, MatrixD worldMatrix, MyPhysicsComponentBase motionInheritedFrom = null)
        {
            var floatingBuilder = PrepareBuilder(ref item);

            floatingBuilder.PositionAndOrientation = new MyPositionAndOrientation(worldMatrix);
            var thrownEntity = MyEntities.CreateFromObjectBuilderAndAdd(floatingBuilder);

            if (thrownEntity != null)
            {
                thrownEntity.Physics.ForceActivate();
                ApplyPhysics(thrownEntity, motionInheritedFrom);
                Debug.Assert(thrownEntity.Save == true, "Thrown item will not be saved. Feel free to ignore this.");

                //Visual scripting action
                if (MyVisualScriptLogicProvider.ItemSpawned != null)
                {
                    MyVisualScriptLogicProvider.ItemSpawned(item.Content.TypeId.ToString(), item.Content.SubtypeName, thrownEntity.EntityId, item.Amount.ToIntSafe(), worldMatrix.Translation);
                }
            }
            return(thrownEntity);
        }
Beispiel #29
0
        public static MyMeteor GenerateMeteor(float sizeInMeters, Matrix worldMatrix, Vector3 position, MyMwcVoxelMaterialsEnum material)
        {
            int size = MySectorGenerator.FindAsteroidSize(sizeInMeters, MyMwcObjectBuilder_StaticAsteroid.AsteroidSizes);

            asteroids.Clear();
            MyMwcObjectBuilder_Meteor.GetAsteroids(size, MyStaticAsteroidTypeSetEnum.A, asteroids);
            int rndIndex = MyMwcUtils.GetRandomInt(0, asteroids.Count);

            var builder = new MyMwcObjectBuilder_Meteor(asteroids[rndIndex], material);

            builder.PositionAndOrientation.Position = position;
            builder.PositionAndOrientation.Forward  = MyMwcUtils.GetRandomVector3Normalized();
            builder.PositionAndOrientation.Up       = MyMwcUtils.GetRandomVector3Normalized();

            builder.UseModelTechnique = false;

            MyMeteor meteor = (MyMeteor)MyEntities.CreateFromObjectBuilderAndAdd(null, builder, worldMatrix);

            meteor.m_size = sizeInMeters;

            return(meteor);
        }
Beispiel #30
0
        private void UnpackDrones()
        {
            MyTrace.Send(TraceWindow.Saving, "Player unpacking drones");

            m_heplerInventoryItems.Clear();
            MySession.Static.Inventory.GetInventoryItems(ref m_heplerInventoryItems, MyMwcObjectBuilderTypeEnum.Drone, null);
            foreach (var inventoryItem in m_heplerInventoryItems)
            {
                var droneObjectBuilder = (MyMwcObjectBuilder_Drone)inventoryItem.GetInventoryItemObjectBuilder(true);

                // We need to removed id's because mothership container could have same entity id in different sector
                droneObjectBuilder.EntityId = null;
                droneObjectBuilder.PositionAndOrientation = new MyMwcPositionAndOrientation(
                    MySession.PlayerShip.GetPosition() + new Vector3(-100, 100, 50),
                    MySession.PlayerShip.WorldMatrix.Forward,
                    MySession.PlayerShip.WorldMatrix.Up);

                var drone = MyEntities.CreateFromObjectBuilderAndAdd("Drone", droneObjectBuilder,
                                                                     droneObjectBuilder.PositionAndOrientation.GetMatrix());

                drone.Link();

                /*
                 * MyPrefabContainer container = new MyPrefabContainer();
                 * Matrix worldMatrix = Matrix.CreateTranslation(MySession.PlayerShip.GetPosition() + new Vector3(100, 100, 0));
                 *
                 * container.Init(null, containerObjectBuilder, worldMatrix);
                 *
                 * MyEntities.Add(container);
                 *
                 * //CreateFromObjectBuilderAndAdd(null, largeShipObjectBuilder, Matrix.CreateTranslation(MySession.PlayerShip.GetPosition() + new Vector3(100,100,0)));
                 */

                MySession.Static.Inventory.RemoveInventoryItem(inventoryItem);
            }

            MyTrace.Send(TraceWindow.Saving, "Drones unpacked");
        }