public void Lock(MyEntityIdentifier entityId, bool enable)
        {
            if (IsHost)
            {
                // Host just sends lock to all
                bool success = TryLockEntity(entityId.NumericValue, MyEntityIdentifier.CurrentPlayerId, enable);

                if (success)
                {
                    LogDevelop(MyEntities.GetEntityById(entityId).Name + " " + (enable ? "LOCKED" : "UNLOCKED"));
                }

                MyEntity entity;
                if (enable && MyEntities.TryGetEntityById(entityId, out entity))
                {
                    RaiseLockResponse(entity, success);
                }
            }
            else
            {
                // Send request to host
                MyEventLock msg = new MyEventLock();
                msg.EntityId = entityId.NumericValue;
                msg.LockType = enable ? MyLockEnum.LOCK : MyLockEnum.UNLOCK;

                // Sometimes can be called after host already disconnected (closing screens etc)
                Peers.TrySendHost(ref msg);
            }
        }
        public void Shoot(MyEntity entity, Matrix shooterMatrix, MyMwcObjectBuilder_SmallShip_Weapon_TypesEnum weapon, MyMwcObjectBuilder_SmallShip_Ammo_TypesEnum ammo, MyEntity target, MyEntityIdentifier? projectileId)
        {
            if (!IsControlledByMe(entity))
            {
                return;
            }

            MyEventShoot msg = new MyEventShoot();
            msg.Position = new MyMwcPositionAndOrientation(shooterMatrix);
            msg.ShooterEntityId = entity.EntityId.Value.NumericValue;
            msg.ProjectileEntityId = MyEntityIdentifier.ToNullableInt(projectileId);
            msg.Ammo = ammo;
            msg.TargetEntityId = (target != null && target.EntityId.HasValue) ? target.EntityId.Value.NumericValue : (uint?)null;
            msg.Weapon = weapon;

            Peers.SendToAll(ref msg, NetDeliveryMethod.ReliableUnordered);
        }
Example #3
0
        public virtual void OnOkClick(MyGuiControlButton sender)
        {
            if (HasEntity())
            {
                if (m_idTextbox != null)
                {
                    if (m_entity.EntityId != null)
                    {
                        var newId = new MyEntityIdentifier(Convert.ToUInt32(m_idTextbox.Text));

                        if (newId.NumericValue != m_entity.EntityId.Value.NumericValue && !MyEntityIdentifier.ExistsById(newId))
                        {
                            MyEntityIdentifier.RemoveEntity(m_entity.EntityId.Value);
                            m_entity.EntityId = newId;
                            MyEntityIdentifier.AddEntityWithId(m_entity);
                        }
                    }
                }

                if (IsPositionInput())
                {
                    Vector3 position = GetNewPosition();
                    if (IsValidPositionInput(position))
                    {
                        MyEditorGizmo.MoveAndRotateObject(position, m_entity.GetWorldRotation(), m_entity);
                    }
                }
            }
        }
Example #4
0
 private MyIdentity(string name, long identityId, string model)
 {
     identityId = MyEntityIdentifier.FixObsoleteIdentityType(identityId);
     Init(name, identityId, model);
     MyEntityIdentifier.MarkIdUsed(identityId);
 }
Example #5
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
            };
        }
        protected void CreateRotorGrid(out MyCubeGrid rotorGrid, out MyMotorRotor rotorBlock, long builtBy, MyCubeBlockDefinitionGroup rotorGroup)
        {
            if (rotorGroup == null)
            {
                CreateRotorGridFailed(builtBy, out rotorGrid, out rotorBlock);
                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;
            rotorBlock = (MyMotorRotor)rotorGrid.GetCubeBlock(Vector3I.Zero).FatBlock;
            rotorGrid.PositionComp.SetPosition(rotorGrid.WorldMatrix.Translation - (Vector3D.Transform(rotorBlock.DummyPosLoc, rotorGrid.WorldMatrix) - rotorGrid.WorldMatrix.Translation));

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

            if (Sync.IsServer)
            {
                MyEntities.Add(grid);

                MySyncCreate.SendEntityCreated(grid.GetObjectBuilder());
            }
            else
            {
                grid.Close();
            }
        }
        void OnUpdatePositionFast(ref MyEventUpdatePositionFast msg)
        {
            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("Update position fast");
            MyPlayerRemote player = (MyPlayerRemote)msg.SenderConnection.Tag;
            MyEntityIdentifier entityId = new MyEntityIdentifier(msg.EntityId);

            if (!CheckSenderId(msg, msg.EntityId))
            {
                Alert("Player is updating entity which is not his", msg.SenderEndpoint, msg.EventType);
                return;
            }

            MyEntity entity;
            if (MyEntities.TryGetEntityById(entityId, out entity))
            {
                var m = entity.WorldMatrix;
                m.Translation = msg.Position;
                if (msg.Up != null)
                    m.Up = msg.Up.Value;
                if (msg.Forward != null)
                    m.Forward = msg.Forward.Value;
                entity.WorldMatrix = m;
            }
            else
            {
                Alert("Entity to update not found", msg.SenderEndpoint, msg.EventType);
            }

            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();
        }
        void OnShoot(ref MyEventShoot msg)
        {
            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("Shoot");
            MyEntity parent;

            if (MyEntities.TryGetEntityById(new MyEntityIdentifier(msg.ShooterEntityId), out parent))
            {
                if (parent is MySmallShip)
                {
                    var ship = (MySmallShip)parent;
                    ship.InitGroupMaskIfNeeded();
                    ship.WorldMatrix = msg.Position.GetMatrix();
                    if (msg.TargetEntityId.HasValue)
                    {
                        ship.TargetEntity = MyEntityIdentifier.GetEntityByIdOrNull(new MyEntityIdentifier(msg.TargetEntityId.Value));
                    }
                    var msgWeapon = msg.Weapon;
                    var weapon    = GetWeapon(ship, msgWeapon);
                    if (weapon == null)
                    {
                        weapon = ship.Weapons.AddWeapon(new MyMwcObjectBuilder_SmallShip_Weapon(msg.Weapon));
                    }
                    Debug.Assert(weapon.Parent != null, "Weapon parent is null, something is wrong");
                    weapon.IsDummy = true;
                    weapon.Shot(new MyMwcObjectBuilder_SmallShip_Ammo(msg.Ammo));
                    MyEntity projectile;
                    if (msg.ProjectileEntityId.HasValue && weapon.LastShotId.HasValue && MyEntities.TryGetEntityById(weapon.LastShotId.Value, out projectile))
                    {
                        MyEntityIdentifier.RemoveEntity(weapon.LastShotId.Value);
                        projectile.EntityId = new MyEntityIdentifier(msg.ProjectileEntityId.Value);
                        if (!MyEntityIdentifier.ExistsById(projectile.EntityId.Value))
                        {
                            MyEntityIdentifier.AddEntityWithId(projectile);
                        }
                    }
                }
                else if (parent is MyPrefabLargeWeapon)
                {
                    var gun = ((MyPrefabLargeWeapon)parent).GetGun();
                    if (msg.TargetEntityId.HasValue)
                    {
                        var target = MyEntityIdentifier.GetEntityByIdOrNull(new MyEntityIdentifier(msg.TargetEntityId.Value));
                        gun.SetTarget(target);
                    }

                    gun.GetBarell().IsDummy = true;
                    gun.RotateImmediately(gun.GetPosition() + msg.Position.GetMatrix().Forward * 5000);
                    gun.IsDummy = true;
                    gun.Shot(new MyMwcObjectBuilder_SmallShip_Ammo(msg.Ammo));
                    MyEntity projectile;
                    if (msg.ProjectileEntityId.HasValue && gun.LastShotId.HasValue && MyEntities.TryGetEntityById(gun.LastShotId.Value, out projectile))
                    {
                        MyEntityIdentifier.RemoveEntity(gun.LastShotId.Value);
                        projectile.EntityId = new MyEntityIdentifier(msg.ProjectileEntityId.Value);
                        if (!MyEntityIdentifier.ExistsById(projectile.EntityId.Value))
                        {
                            MyEntityIdentifier.AddEntityWithId(projectile);
                        }
                    }
                }
            }

            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();
        }
        private void AddBlocks()
        {
            HashSet <MyCubeGrid.MyBlockLocation> locations = new HashSet <MyCubeGrid.MyBlockLocation>();

            Quaternion rotation;

            foreach (var loc in m_addLocations)
            {
                loc.Orientation.GetQuaternion(out rotation);
                MyCubeGrid.MyBlockLocation blockLocation = new MyCubeGrid.MyBlockLocation(
                    loc.BlockDefinition.Id, loc.Position, loc.Position, loc.Position, rotation, MyEntityIdentifier.AllocateId(), MySession.LocalPlayerId);

                locations.Add(blockLocation);
            }

            foreach (var location in locations)
            {
                m_grid.BuildGeneratedBlock(location, Vector3I.Zero);
            }
        }
        public override bool HandleCommand(ulong userId, string[] words)
        {
            if (!PluginSettings.Instance.DockingEnabled)
            {
                return(false);
            }

            if (words.Length < 1)
            {
                Communication.SendPrivateInformation(userId, GetHelp());
                return(true);
            }

            if (m_undocking)
            {
                Communication.SendPrivateInformation(userId, "Server is busy, try again");
                return(true);
            }

            m_undocking = true;
            try
            {
                string pylonName = string.Join(" ", words);
                if (PlayerMap.Instance.GetPlayerIdsFromSteamId(userId).Count < 1)
                {
                    Communication.SendPrivateInformation(userId, $"Unable to find player Id: {userId}");
                    return(true);
                }

                long playerId = PlayerMap.Instance.GetPlayerIdsFromSteamId(userId).First( );

                Dictionary <string, List <IMyCubeBlock> > testList;
                List <IMyCubeBlock> beaconList;
                DockingZone.FindByName(pylonName, out testList, out beaconList, playerId);

                if (beaconList.Count == 4)
                {
                    foreach (IMyCubeBlock entity in beaconList)
                    {
                        if (!Entity.CheckOwnership(entity, playerId))
                        {
                            Communication.SendPrivateInformation(userId, $"You do not have permission to use '{pylonName}'.  You must either own all the beacons or they must be shared with faction.");
                            return(true);
                        }
                    }

                    IMyCubeBlock e      = beaconList.First( );
                    IMyCubeGrid  parent = (IMyCubeGrid)e.Parent;

                    long[]             beaconListIds = beaconList.Select(p => p.EntityId).ToArray( );
                    long               ownerId       = beaconList.First( ).OwnerId;
                    List <DockingItem> dockingItems  = Docking.Instance.Find(d => d.PlayerId == ownerId && d.TargetEntityId == parent.EntityId && d.DockingBeaconIds.Intersect(beaconListIds).Count( ) == 4);
                    if (dockingItems.Count < 1)
                    {
                        Communication.SendPrivateInformation(userId, $"You have no ships docked in docking zone '{pylonName}'.");
                        return(true);
                    }

                    DockingItem dockingItem = dockingItems.First( );

                    // Figure out center of docking area, and other distance information
                    double   maxDistance = 99;
                    Vector3D vPos        = new Vector3D(0, 0, 0);
                    foreach (IMyCubeBlock b in beaconList)
                    {
                        Vector3D beaconPos = Entity.GetBlockEntityPosition(b);
                        vPos += beaconPos;
                    }

                    vPos = vPos / 4;
                    foreach (IMyCubeBlock b in beaconList)
                    {
                        Vector3D beaconPos = Entity.GetBlockEntityPosition(b);
                        maxDistance = Math.Min(maxDistance, Vector3D.Distance(vPos, beaconPos));
                    }

                    List <IMySlimBlock> blocks = new List <IMySlimBlock>( );
                    parent.GetBlocks(blocks);
                    foreach (IMySlimBlock slim_cbe in blocks)
                    {
                        if (slim_cbe is IMyCubeBlock)
                        {
                            IMyCubeBlock cbe = slim_cbe.FatBlock;
                            if (cbe.GetObjectBuilderCubeBlock( ) is MyObjectBuilder_Cockpit)
                            {
                                MyObjectBuilder_Cockpit c = (MyObjectBuilder_Cockpit)cbe.GetObjectBuilderCubeBlock( );
                                if (c.Pilot != null)
                                {
                                    Communication.SendPrivateInformation(userId,
                                                                         string.Format(
                                                                             "Carrier ship has a pilot.  The carrier should be unpiloted and fully stopped before undocking.  (Sometimes this can lag a bit.  Wait 10 seconds and try again)",
                                                                             pylonName));
                                    return(true);
                                }
                            }
                        }
                    }

                    string dockedShipFileName = Essentials.PluginPath + $"\\Docking\\docked_{ownerId}_{dockingItem.TargetEntityId}_{dockingItem.DockedEntityId}.sbc";

                    // Load Entity From File and add to game
                    FileInfo fileInfo = new FileInfo(dockedShipFileName);
                    //CubeGridEntity cubeGrid = new CubeGridEntity(fileInfo);

                    MyObjectBuilder_CubeGrid cubeGrid;
                    MyObjectBuilderSerializer.DeserializeXML(dockedShipFileName, out cubeGrid);

                    // Rotate our ship relative to our saved rotation and the new carrier rotation
                    cubeGrid.PositionAndOrientation =
                        new MyPositionAndOrientation(Matrix.CreateFromQuaternion(Quaternion.CreateFromRotationMatrix(parent.Physics.GetWorldMatrix( ).GetOrientation( )) * dockingItem.SaveQuat).GetOrientation( ));
                    // Move our ship relative to the new carrier position and orientation
                    Quaternion newQuat    = Quaternion.CreateFromRotationMatrix(parent.Physics.GetWorldMatrix( ).GetOrientation( ));
                    Vector3D   rotatedPos = Vector3D.Transform(dockingItem.SavePos, newQuat);
                    //cubeGrid.Position = rotatedPos + parent.GetPosition();
                    cubeGrid.PositionAndOrientation = new MyPositionAndOrientation(rotatedPos + parent.GetPosition( ), cubeGrid.PositionAndOrientation.Value.Forward, cubeGrid.PositionAndOrientation.Value.Up);

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

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

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

                    //SectorObjectManager.Instance.AddEntity(cubeGrid);

                    // Remove the docking file
                    File.Delete(dockedShipFileName);
                    Docking.Instance.Remove(dockingItem);

                    Communication.SendPrivateInformation(userId, $"The ship '{dockingItem.DockedName}' has been undocked from docking zone '{pylonName}'");

                    /*
                     * // Queue for cooldown
                     * DockingCooldownItem cItem = new DockingCooldownItem();
                     * cItem.Name = pylonName;
                     * cItem.startTime = DateTime.Now;
                     *
                     * lock (m_cooldownList)
                     *      m_cooldownList.Add(cItem);
                     *
                     * IMyEntity gridEntity = MyAPIGateway.Entities.GetEntityById(dockingItem.DockedEntityId);
                     * IMyCubeGrid cubeGrid = (IMyCubeGrid)gridEntity;
                     *
                     * Quaternion q = Quaternion.CreateFromRotationMatrix(parent.WorldMatrix.GetOrientation()) * dockingItem.SaveQuat;
                     * Quaternion newQuat = Quaternion.CreateFromRotationMatrix(parent.WorldMatrix.GetOrientation());
                     * Vector3 parentPosition = parent.GetPosition();
                     * Vector3 rotatedPos = Vector3.Transform(dockingItem.savePos, newQuat);
                     * Vector3 position = rotatedPos + parentPosition;
                     * Matrix positionMatrix = Matrix.CreateFromQuaternion(q);
                     *
                     * cubeGrid.ChangeGridOwnership(playerId, MyOwnershipShareModeEnum.None);
                     * gridEntity.SetPosition(dockingItem.savePos);
                     *
                     * gridEntity.WorldMatrix = positionMatrix;
                     * gridEntity.SetPosition(position);
                     *
                     * // We need to update again, as this doesn't seem to sync properly?  I set world matrix, and setposition, and it doesn't go where it should, and I
                     * // have to bump into it for it to show up, it's mega weird.
                     *
                     * if (PluginDocking.Settings.DockingItems == null)
                     *      throw new Exception("DockingItems is null");
                     *
                     * // Remove from docked items
                     * PluginDocking.Settings.DockingItems.Remove(dockingItem);
                     *
                     * // Notify user
                     * Communication.SendPrivateInformation(userId, string.Format("The ship '{0}' has been undocked from docking zone '{1}'", gridEntity.DisplayName, pylonName));
                     */
                    // Queue for cooldown

                    /*
                     * DockingCooldownItem cItem = new DockingCooldownItem();
                     * cItem.name = pylonName;
                     * cItem.startTime = DateTime.Now;
                     * PluginDocking.CooldownList.Add(cItem);
                     */
                }
                else if (beaconList.Count > 4)                   // Too many beacons, must be 4
                {
                    Communication.SendPrivateInformation(userId,
                                                         $"Too many beacons with the name or another zone with the name '{pylonName}'.  Place only 4 beacons to create a zone or try a different zone name.");
                }
                else                 // Can't find docking zone
                {
                    Communication.SendPrivateInformation(userId,
                                                         string.Format("Can not locate docking zone '{0}'.  There must be 4 beacons with the name '{0}' to create a docking zone.  Beacons must be fully built!",
                                                                       pylonName));
                }
            }
            catch (NullReferenceException ex)
            {
                Log.Error(ex);
            }
            finally
            {
                m_undocking = false;
            }

            return(true);
        }
        public virtual void OnOkClick(MyGuiControlButton sender)
        {
            if (HasEntity())
            {
                if (m_idTextbox != null)
                {
                    if (m_entity.EntityId != null)
                    {
                        var newId = new MyEntityIdentifier(Convert.ToUInt32(m_idTextbox.Text));

                        if (newId.NumericValue != m_entity.EntityId.Value.NumericValue && !MyEntityIdentifier.ExistsById(newId))
                        {
                            MyEntityIdentifier.RemoveEntity(m_entity.EntityId.Value);
                            m_entity.EntityId = newId;
                            MyEntityIdentifier.AddEntityWithId(m_entity);
                        }
                    }
                }

                if (IsPositionInput())
                {
                    Vector3 position = GetNewPosition();
                    if (IsValidPositionInput(position))
                    {
                        MyEditorGizmo.MoveAndRotateObject(position, m_entity.GetWorldRotation(), m_entity);
                    }
                }
            }            
        }        
Example #12
0
        public static MyEntity Spawn(this MyPhysicalInventoryItem thisItem, MyFixedPoint amount, MatrixD worldMatrix, MyEntity owner = null)
        {
            if (amount < 0)
            {
                return(null);
            }
            if (thisItem.Content == null)
            {
                Debug.Fail("Can not spawn item with null content!");
                return(null);
            }

            if (thisItem.Content is MyObjectBuilder_BlockItem)
            {
                Debug.Assert(MyFixedPoint.IsIntegral(amount), "Spawning fractional number of grids!");
                bool isBlock = typeof(MyObjectBuilder_CubeBlock).IsAssignableFrom(thisItem.Content.GetObjectId().TypeId);
                Debug.Assert(isBlock, "Block item does not contain block!?!?@&*#%!");
                if (!isBlock)
                {
                    return(null);
                }

                var blockItem = thisItem.Content as MyObjectBuilder_BlockItem;
                MyCubeBlockDefinition blockDefinition;
                MyDefinitionManager.Static.TryGetCubeBlockDefinition(blockItem.BlockDefId, out blockDefinition);
                Debug.Assert(blockDefinition != null, "Block definition not found");
                if (blockDefinition == null)
                {
                    return(null);
                }

                var builder = MyObjectBuilderSerializer.CreateNewObject(typeof(MyObjectBuilder_CubeGrid)) as MyObjectBuilder_CubeGrid;
                builder.GridSizeEnum           = blockDefinition.CubeSize;
                builder.IsStatic               = false;
                builder.PersistentFlags       |= MyPersistentEntityFlags2.InScene | MyPersistentEntityFlags2.Enabled;
                builder.PositionAndOrientation = new MyPositionAndOrientation(worldMatrix);

                var block = MyObjectBuilderSerializer.CreateNewObject(blockItem.BlockDefId) as MyObjectBuilder_CubeBlock;
                System.Diagnostics.Debug.Assert(block != null, "Block couldn't been created, maybe wrong definition id? DefID: " + blockItem.BlockDefId);

                if (block != null)
                {
                    block.Min = blockDefinition.Size / 2 - blockDefinition.Size + Vector3I.One;
                    builder.CubeBlocks.Add(block);

                    MyCubeGrid firstGrid = null;
                    for (int i = 0; i < amount; ++i)
                    {
                        builder.EntityId = MyEntityIdentifier.AllocateId();
                        block.EntityId   = MyEntityIdentifier.AllocateId();
                        MyCubeGrid newGrid = MyEntities.CreateFromObjectBuilder(builder) as MyCubeGrid;
                        firstGrid = firstGrid ?? newGrid;
                        MyEntities.Add(newGrid);
                    }
                    return(firstGrid);
                }
                return(null);
            }
            else
            {
                MyPhysicalItemDefinition itemDefinition = null;
                if (MyDefinitionManager.Static.TryGetPhysicalItemDefinition(thisItem.Content.GetObjectId(), out itemDefinition))
                {
                    return(MyFloatingObjects.Spawn(new MyPhysicalInventoryItem(amount, thisItem.Content), worldMatrix, owner != null ? owner.Physics : null));
                }
                return(null);
            }
        }
Example #13
0
        public static MyEntity SpawnInWorldOrLootBag(this MyPhysicalInventoryItem thisItem, MyEntity owner, ref MyEntity lootBagEntity)
        {
            Debug.Assert(Sandbox.Game.Multiplayer.Sync.IsServer);

            MyDefinitionBase itemDefinition = thisItem.GetItemDefinition();

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

            MyEntity spawnedItem = null;

            Vector3 upDir = -MyGravityProviderSystem.CalculateNaturalGravityInPoint(owner.PositionComp.WorldMatrix.Translation);

            if (upDir == Vector3.Zero)
            {
                upDir = Vector3.Up;
            }
            else
            {
                upDir.Normalize();
            }

            if (itemDefinition is MyCubeBlockDefinition)
            {
                MyCubeBlockDefinition blockDef = itemDefinition as MyCubeBlockDefinition;

                if (MyDefinitionManager.Static.GetLootBagDefinition() != null)
                {
                    // New code which tries to spawn item with "MyEntities.FindFreePlace" and if there is no such position then loot bag is spawn and item is moved into it.
                    MyModel     blockModel = MyModels.GetModelOnlyData(blockDef.Model);
                    BoundingBox box        = blockModel.BoundingBox;
                    box.Inflate(0.15f); // Inflate with value that is higher than half size of small grid so it will eliminate problems with block center offsets.
                    float radius            = box.HalfExtents.Max();
                    var   baseSpawnPosition = owner.PositionComp.WorldMatrix.Translation;
                    if (owner is MyCharacter)
                    {
                        baseSpawnPosition += owner.PositionComp.WorldMatrix.Up + owner.PositionComp.WorldMatrix.Forward;
                    }
                    else
                    {
                        baseSpawnPosition += upDir;
                    }

                    for (int gridIndex = 0; gridIndex < thisItem.Amount; ++gridIndex)
                    {
                        Vector3D?spawnPos = null;
                        if (lootBagEntity == null && (spawnPos = MyEntities.FindFreePlace(baseSpawnPosition, radius, maxTestCount: 50, testsPerDistance: 5, stepSize: 0.25f)) != null)
                        {
                            MatrixD transform = owner.PositionComp.WorldMatrix;
                            transform.Translation = spawnPos.Value;

                            var blockBuilder = MyObjectBuilderSerializer.CreateNewObject(blockDef.Id) as MyObjectBuilder_CubeBlock;
                            blockBuilder.Min      = blockDef.Size / 2 - blockDef.Size + Vector3I.One;
                            blockBuilder.EntityId = MyEntityIdentifier.AllocateId();

                            var newGrid = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_CubeGrid>();
                            newGrid.PositionAndOrientation = new MyPositionAndOrientation(transform);
                            newGrid.GridSizeEnum           = blockDef.CubeSize;
                            newGrid.PersistentFlags       |= MyPersistentEntityFlags2.InScene;
                            newGrid.EntityId = MyEntityIdentifier.AllocateId();
                            newGrid.CubeBlocks.Add(blockBuilder);

                            var entity = MyEntities.CreateFromObjectBuilderAndAdd(newGrid);
                            spawnedItem = spawnedItem ?? entity;
                        }
                        else
                        {
                            AddItemToLootBag(owner, new MyPhysicalInventoryItem(1, thisItem.Content), ref lootBagEntity);
                        }
                    }
                }
                else
                {
                    // Old code used in SE (when no loot bag definition is defined).
                    float    spawnRadius = MyUtils.GetRandomFloat(Math.Max(0.25f, ITEM_SPAWN_RADIUS), ITEM_SPAWN_RADIUS);
                    Vector3D randomizer  = MyUtils.GetRandomVector3CircleNormalized() * spawnRadius + Vector3D.Up * 0.25f;

                    int         yOffset = 0;
                    MyModel     m       = MyModels.GetModelOnlyData(blockDef.Model);
                    float       sizeY   = m.BoundingBoxSize.Y + 0.05f;
                    BoundingBox box     = m.BoundingBox;

                    for (int gridIndex = 0; gridIndex < thisItem.Amount; ++gridIndex)
                    {
                        var newGrid = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_CubeGrid>();

                        MatrixD transform = owner.PositionComp.WorldMatrix * MatrixD.CreateTranslation(randomizer + new Vector3D(0, yOffset * sizeY, 0));
                        if (!GetNonPenetratingTransformPosition(ref box, ref transform))
                        {
                            randomizer = MyUtils.GetRandomVector3CircleNormalized() * 0.25f + Vector3D.Up * 0.25f;
                            transform  = owner.PositionComp.WorldMatrix * MatrixD.CreateTranslation(randomizer + new Vector3D(0, yOffset * sizeY, 0));
                        }

                        newGrid.PositionAndOrientation = new MyPositionAndOrientation(transform);
                        newGrid.GridSizeEnum           = blockDef.CubeSize;
                        newGrid.PersistentFlags       |= MyPersistentEntityFlags2.InScene;
                        newGrid.EntityId = MyEntityIdentifier.AllocateId();

                        var newBlock = MyObjectBuilderSerializer.CreateNewObject(blockDef.Id) as MyObjectBuilder_CubeBlock;
                        newBlock.EntityId = MyEntityIdentifier.AllocateId();
                        newGrid.CubeBlocks.Add(newBlock);

                        var entity = MyEntities.CreateFromObjectBuilderAndAdd(newGrid);
                        spawnedItem = spawnedItem ?? entity;

                        if ((gridIndex + 1) % 10 == 0)
                        {
                            spawnRadius = MyUtils.GetRandomFloat(Math.Max(0.25f, ITEM_SPAWN_RADIUS), ITEM_SPAWN_RADIUS);
                            randomizer  = MyUtils.GetRandomVector3CircleNormalized() * spawnRadius + Vector3D.Up * 0.25f;
                            yOffset     = 0;
                        }
                        else
                        {
                            yOffset++;
                        }
                    }
                }
            }
            else if (itemDefinition is MyPhysicalItemDefinition)
            {
                MyPhysicalItemDefinition floatingObjectDefinition = itemDefinition as MyPhysicalItemDefinition;

                MyFixedPoint          amount         = thisItem.Amount;
                bool                  canStack       = thisItem.Content.CanStack(thisItem.Content);
                MyFixedPoint          stackSize      = canStack ? amount : 1;
                MyFixedPoint          maxStackAmount = MyFixedPoint.MaxValue;
                MyComponentDefinition compDef        = null;
                if (MyDefinitionManager.Static.TryGetComponentDefinition(thisItem.Content.GetId(), out compDef))
                {
                    maxStackAmount = compDef.MaxStackAmount;
                    stackSize      = MyFixedPoint.Min(stackSize, maxStackAmount);
                }

                if (MyDefinitionManager.Static.GetLootBagDefinition() != null)
                {
                    // New code which tries to spawn item with "MyEntities.FindFreePlace" and if there is no such position then loot bag is spawn and item is moved into it.
                    MyModel     model             = MyModels.GetModelOnlyData(floatingObjectDefinition.Model);
                    BoundingBox box               = model.BoundingBox;
                    float       radius            = box.HalfExtents.Max();
                    var         baseSpawnPosition = owner.PositionComp.WorldMatrix.Translation;
                    if (owner is MyCharacter)
                    {
                        baseSpawnPosition += owner.PositionComp.WorldMatrix.Up + owner.PositionComp.WorldMatrix.Forward;
                    }
                    else
                    {
                        baseSpawnPosition += upDir;
                    }

                    while (amount > 0)
                    {
                        MyFixedPoint spawnAmount = stackSize;
                        amount -= stackSize;
                        if (amount < 0)
                        {
                            spawnAmount = amount + stackSize;
                        }

                        Vector3D?spawnPos = null;
                        if (lootBagEntity == null && (spawnPos = MyEntities.FindFreePlace(baseSpawnPosition, radius, maxTestCount: 50, testsPerDistance: 5, stepSize: 0.25f)) != null)
                        {
                            MatrixD worldMat = owner.PositionComp.WorldMatrix;
                            worldMat.Translation = spawnPos.Value;
                            var entity = MyFloatingObjects.Spawn(new MyPhysicalInventoryItem(spawnAmount, thisItem.Content), worldMat);
                            spawnedItem = spawnedItem ?? entity;
                        }
                        else
                        {
                            AddItemToLootBag(owner, new MyPhysicalInventoryItem(spawnAmount, thisItem.Content), ref lootBagEntity);
                        }
                    }
                }
                else
                {
                    // Old code used in SE (when no loot bag definition is defined).
                    while (amount > 0)
                    {
                        MyFixedPoint spawnAmount = stackSize;
                        amount -= stackSize;
                        if (amount < 0)
                        {
                            spawnAmount = amount + stackSize;
                        }

                        float    spawnRadius = MyUtils.GetRandomFloat(Math.Max(0.25f, ITEM_SPAWN_RADIUS), ITEM_SPAWN_RADIUS);
                        Vector3D randomizer  = MyUtils.GetRandomVector3CircleNormalized() * spawnRadius + Vector3D.Up * 0.25f;
                        var      worldMat    = owner.PositionComp.WorldMatrix * MatrixD.CreateTranslation(randomizer);

                        var entity = MyFloatingObjects.Spawn(new MyPhysicalInventoryItem(spawnAmount, thisItem.Content), worldMat);
                        spawnedItem = spawnedItem ?? entity;
                    }
                }
            }

            return(spawnedItem);
        }
Example #14
0
        private void AddBlocks()
        {
            Debug.Assert(m_tmpLocationsAndRefBlocks.Count == 0);

            Quaternion rotation;

            foreach (var loc in m_addLocations)
            {
                loc.Orientation.GetQuaternion(out rotation);
                MyCubeGrid.MyBlockLocation blockLocation = new MyCubeGrid.MyBlockLocation(
                    loc.BlockDefinition.Id, loc.Position, loc.Position, loc.Position, rotation, MyEntityIdentifier.AllocateId(), MySession.Static.LocalPlayerId);

                m_tmpLocationsAndRefBlocks.Add(new Tuple <MyCubeGrid.MyBlockLocation, MySlimBlock>(blockLocation, loc.RefBlock));
            }

            foreach (var location in m_tmpLocationsAndRefBlocks)
            {
                var block = m_grid.BuildGeneratedBlock(location.Item1, Vector3I.Zero);
                if (block != null)
                {
                    var compound = block.FatBlock as MyCompoundCubeBlock;
                    if (compound != null)
                    {
                        foreach (var blockInCompound in compound.GetBlocks())
                        {
                            Quaternion q;
                            location.Item1.Orientation.GetQuaternion(out q);
                            MyBlockOrientation r = new MyBlockOrientation(ref q);
                            if (blockInCompound.Orientation == r && blockInCompound.BlockDefinition.Id == location.Item1.BlockDefinition)
                            {
                                block = blockInCompound;
                                break;
                            }
                        }
                    }

                    var refBlock = location.Item2;
                    if (block != null && block.BlockDefinition.IsGeneratedBlock && refBlock != null)
                    {
                        block.SetGeneratedBlockIntegrity(refBlock);
                    }
                }
            }

            m_tmpLocationsAndRefBlocks.Clear();
        }
Example #15
0
 public static bool ValidateEntityType(VRage.MyEntityIdentifier.ID_OBJECT_TYPE type, long id)
 {
     return(MyEntityIdentifier.GetIdObjectType(id) == type);
 }
Example #16
0
        protected void CreateRotorGrid(out MyCubeGrid rotorGrid, out MyMotorRotor 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;
            rotorBlock = (MyMotorRotor)rotorGrid.GetCubeBlock(Vector3I.Zero).FatBlock;
            rotorGrid.PositionComp.SetPosition(rotorGrid.WorldMatrix.Translation - (Vector3D.Transform(rotorBlock.DummyPosLoc, rotorGrid.WorldMatrix) - rotorGrid.WorldMatrix.Translation));

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

            MyEntities.Add(grid);

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

            m_rotorBlockId.Value = new State()
            {
                OtherEntityId = rotorBlock.EntityId, MasterToSlave = masterToSlave
            };
        }
Example #17
0
        protected override void OnAnimationPlay(MyAnimationDefinition animDefinition, MyAnimationCommand command, ref string bonesArea, ref MyFrameOption frameOption, ref bool useFirstPersonVersion)
        {
            var currentMovementState = GetCurrentMovementState();

            if (DefinitionId.Value.SubtypeId == medievelMaleSubtypeId)
            {
                if (command.ExcludeLegsWhenMoving)
                {
                    //In this case, we must stop all upper animations correctly

                    if (currentMovementState == MyCharacterMovementEnum.RotatingLeft ||
                        currentMovementState == MyCharacterMovementEnum.RotatingRight ||
                        currentMovementState == MyCharacterMovementEnum.Standing)
                    {
                        bonesArea = TopBody + " LowerBody";
                    }
                    else
                    {
                        bonesArea = TopBody;
                    }
                    frameOption = frameOption != MyFrameOption.JustFirstFrame ? MyFrameOption.PlayOnce : frameOption;
                }
                else if (m_lastBonesArea == TopBody + " LowerBody")
                {
                    StopLowerCharacterAnimation(0.2f);
                }

                m_lastBonesArea = bonesArea;
            }
            else
            {
                if (currentMovementState != MyCharacterMovementEnum.Standing &&
                    currentMovementState != MyCharacterMovementEnum.RotatingLeft &&
                    currentMovementState != MyCharacterMovementEnum.RotatingRight &&
                    command.ExcludeLegsWhenMoving)
                {
                    //In this case, we must stop all upper animations correctly
                    bonesArea   = TopBody;
                    frameOption = frameOption != MyFrameOption.JustFirstFrame ? MyFrameOption.PlayOnce : frameOption;
                }
            }


            useFirstPersonVersion = IsInFirstPersonView;

            if (animDefinition.AllowWithWeapon)
            {
                if (!UseAnimationForWeapon)
                {
                    StoreWeaponRelativeMatrix();
                    UseAnimationForWeapon       = true;
                    m_resetWeaponAnimationState = true;
                }
            }

            if (!animDefinition.LeftHandItem.TypeId.IsNull)
            {
                if (m_leftHandItem != null)
                {
                    (m_leftHandItem as IMyHandheldGunObject <Sandbox.Game.Weapons.MyDeviceBase>).OnControlReleased();
                    m_leftHandItem.Close();
                }

                // CH: TODO: The entity id is not synced, but it never was in this place. It should be fixed later
                long handItemId      = MyEntityIdentifier.AllocateId();
                uint?inventoryItemId = null;
                var  builder         = GetObjectBuilderForWeapon(animDefinition.LeftHandItem, ref inventoryItemId, handItemId);
                var  leftHandItem    = CreateGun(builder, inventoryItemId);

                if (leftHandItem != null)
                {
                    m_leftHandItem = leftHandItem as MyEntity;
                    leftHandItem.OnControlAcquired(this);
                    UpdateLeftHandItemPosition();

                    MyEntities.Add(m_leftHandItem);
                }
            }
        }
Example #18
0
        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
            };
        }
Example #19
0
        public override void HandleInput()
        {
            if (!m_isActive)
            {
                return;
            }
            if (!(MyScreenManager.GetScreenWithFocus() is MyGuiScreenGamePlay))
            {
                return;
            }

            base.HandleInput();

            if (MyControllerHelper.IsControl(MySpaceBindingCreator.CX_CHARACTER, MyControlsSpace.PRIMARY_TOOL_ACTION, MyControlStateType.NEW_PRESSED))
            {
                m_startTime = MySandboxGame.TotalGamePlayTimeInMilliseconds;
            }

            if (MyControllerHelper.IsControl(MySpaceBindingCreator.CX_CHARACTER, MyControlsSpace.PRIMARY_TOOL_ACTION, MyControlStateType.NEW_RELEASED))
            {
                var gridBuilders = MyPrefabManager.Static.GetGridPrefab(CurrentDefinition.PrefabToThrow);

                Vector3D cameraPos = Vector3D.Zero;
                Vector3D cameraDir = Vector3D.Zero;

                if (USE_SPECTATOR_FOR_THROW)
                {
                    cameraPos = MySpectator.Static.Position;
                    cameraDir = MySpectator.Static.Orientation.Forward;
                }
                else
                {
                    if (MySession.GetCameraControllerEnum() == Common.ObjectBuilders.MyCameraControllerEnum.ThirdPersonSpectator || MySession.GetCameraControllerEnum() == Common.ObjectBuilders.MyCameraControllerEnum.Entity)
                    {
                        if (MySession.ControlledEntity == null)
                        {
                            return;
                        }

                        cameraPos = MySession.ControlledEntity.GetHeadMatrix(true, true).Translation;
                        cameraDir = MySession.ControlledEntity.GetHeadMatrix(true, true).Forward;
                    }
                    else
                    {
                        cameraPos = MySector.MainCamera.Position;
                        cameraDir = MySector.MainCamera.WorldMatrix.Forward;
                    }
                }

                var position = cameraPos + cameraDir;

                float deltaSeconds = (MySandboxGame.TotalGamePlayTimeInMilliseconds - m_startTime) / 1000.0f;
                float velocity     = deltaSeconds / CurrentDefinition.PushTime * CurrentDefinition.MaxSpeed;
                velocity = MathHelper.Clamp(velocity, CurrentDefinition.MinSpeed, CurrentDefinition.MaxSpeed);
                var   linearVelocity = cameraDir * velocity;
                float mass           = 0;
                if (CurrentDefinition.Mass.HasValue)
                {
                    mass = Sandbox.Engine.Physics.MyDestructionHelper.MassToHavok(CurrentDefinition.Mass.Value);
                }

                gridBuilders[0].EntityId = MyEntityIdentifier.AllocateId();
                MySyncThrower.RequestThrow(gridBuilders[0], position, linearVelocity, mass, CurrentDefinition.ThrowSound);

                m_startTime = 0;
            }
        }
        void OnUpdatePosition(ref MyEventUpdatePosition msg)
        {
            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("Update position");
            MyEntityIdentifier entityId = new MyEntityIdentifier(msg.EntityId);

            if (!CheckSenderId(msg, msg.EntityId))
            {
                Alert("Player is updating entity which is not his", msg.SenderEndpoint, MyEventEnum.UPDATE_POSITION);
                return;
            }

            MyEntity entity;
            if (MyEntities.TryGetEntityById(entityId, out entity))
            {
                entity.WorldMatrix = msg.Position.GetMatrix();
                if (entity.Physics != null)
                {
                    entity.Physics.LinearVelocity = msg.Velocity;
                    entity.Physics.LinearAcceleration = msg.Acceleration;
                }
                entity.Physics.AngularVelocity = Vector3.Zero;
                //FixPlayerPosition(entity);
            }
            else
            {
                Alert("Entity to update not found", msg.SenderEndpoint, MyEventEnum.UPDATE_POSITION);
            }

            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();
        }
Example #21
0
        public override void Close()
        {
            GameLogic.Close();
            //doesnt work in parallel update
            //Debug.Assert(MySandboxGame.IsMainThread(), "Entity.Close() called not from Main Thread!");
            Debug.Assert(MyEntities.UpdateInProgress == false, "Do not close entities directly in Update*, use MarkForClose() instead");
            Debug.Assert(MyEntities.CloseAllowed == true, "Use MarkForClose()");
            //Debug.Assert(!Closed, "Close() called twice!");

            //Children has to be cleared after close notification is send
            while (m_entity.Hierarchy.Children.Count > 0)
            {
                MyHierarchyComponentBase compToRemove = m_entity.Hierarchy.Children[m_entity.Hierarchy.Children.Count - 1];
                Debug.Assert(compToRemove.Parent != null, "Entity has no parent but is part of children collection");

                compToRemove.Container.Entity.Close();

                m_entity.Hierarchy.Children.Remove(compToRemove);
            }

            //OnPositionChanged = null;

            CallAndClearOnClosing();

            // hide decals - decals of children are already hidden, see above
            if (m_entity.Render.RenderObjectIDs.Length > 0)
            {
                VRageRender.MyRenderProxy.HideDecals(m_entity.Render.RenderObjectIDs[0], Vector3.Zero, 0);
            }
            MyEntities.RemoveName(m_entity);
            MyEntities.RemoveFromClosedEntities(m_entity);

            if (m_entity.Physics != null)
            {
                m_entity.Physics.Close();
                m_entity.Physics = null;

                m_entity.RaisePhysicsChanged();
            }

            MyEntities.UnregisterForUpdate(m_entity, true);


            if (m_entity.Hierarchy.Parent == null) //only root objects are in entities list
            {
                MyEntities.Remove(m_entity);
            }
            else
            {
                m_entity.Parent.Hierarchy.Children.Remove(m_entity.Hierarchy);

                //remove children first
                if (m_entity.Parent.InScene)
                {
                    m_entity.OnRemovedFromScene(m_entity);
                }

                MyEntities.RaiseEntityRemove(m_entity);
            }

            if (m_entity.EntityId != 0)
            {
                MyEntityIdentifier.RemoveEntity(m_entity.EntityId);
            }

            //this.EntityId = 0;
            Debug.Assert(m_entity.Hierarchy.Children.Count == 0);

            CallAndClearOnClose();

            Closed = true;
        }
        void OnUpdateRotationFast(ref MyEventUpdateRotationFast msg)
        {
            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("Update rotation fast");
            MyPlayerRemote player = (MyPlayerRemote)msg.SenderConnection.Tag;
            MyEntityIdentifier entityId = new MyEntityIdentifier(msg.EntityId);

            if (!CheckSenderId(msg, msg.EntityId))
            {
                Alert("Player is updating entity which is not his", msg.SenderEndpoint, msg.EventType);
                return;
            }

            MyEntity entity;
            if (MyEntities.TryGetEntityById(entityId, out entity))
            {
                if (entity is MyPrefabLargeWeapon)
                {
                    var gun = ((MyPrefabLargeWeapon)entity).GetGun();
                    gun.SetRotationAndElevation(msg.Rotation);
                }
            }
            else
            {
                Alert("Entity to update not found", msg.SenderEndpoint, msg.EventType);
            }

            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();
        }
Example #23
0
        public void Build(MySlimBlock cubeBlock, long owner, long builder)
        {
            Quaternion quat        = Quaternion.Identity;
            var        orientation = cubeBlock.Orientation;

            Matrix local;

            orientation.GetMatrix(out local);
            var gridOrientation = m_clipboard.GetFirstGridOrientationMatrix();

            if (gridOrientation != Matrix.Identity)
            {
                var afterRotation = Matrix.Multiply(local, gridOrientation);
                orientation = new MyBlockOrientation(ref afterRotation);
            }

            Quaternion projQuat = Quaternion.Identity;

            Orientation.GetQuaternion(out projQuat);
            orientation.GetQuaternion(out quat);
            quat = Quaternion.Multiply(projQuat, quat);


            var projectorGrid = CubeGrid;
            var projectedGrid = cubeBlock.CubeGrid;

            Vector3I cubeMin = cubeBlock.FatBlock != null ? cubeBlock.FatBlock.Min : cubeBlock.Position;
            Vector3I cubeMax = cubeBlock.FatBlock != null ? cubeBlock.FatBlock.Max : cubeBlock.Position;

            Vector3I min = projectorGrid.WorldToGridInteger(projectedGrid.GridIntegerToWorld(cubeMin));
            Vector3I max = projectorGrid.WorldToGridInteger(projectedGrid.GridIntegerToWorld(cubeMax));
            Vector3I pos = projectorGrid.WorldToGridInteger(projectedGrid.GridIntegerToWorld(cubeBlock.Position));

            Vector3I projectedMin = new Vector3I(Math.Min(min.X, max.X), Math.Min(min.Y, max.Y), Math.Min(min.Z, max.Z));
            Vector3I projectedMax = new Vector3I(Math.Max(min.X, max.X), Math.Max(min.Y, max.Y), Math.Max(min.Z, max.Z));


            MyCubeGrid.MyBlockLocation location = new MyCubeGrid.MyBlockLocation(cubeBlock.BlockDefinition.Id, projectedMin, projectedMax, pos,
                                                                                 quat, 0, owner);

            MyObjectBuilder_CubeBlock objectBuilder = null;

            //Find original grid builder
            foreach (var blockBuilder in m_originalGridBuilder.CubeBlocks)
            {
                if ((Vector3I)blockBuilder.Min == cubeMin && blockBuilder.GetId() == cubeBlock.BlockDefinition.Id)
                {
                    objectBuilder = (MyObjectBuilder_CubeBlock)blockBuilder.Clone();
                    objectBuilder.SetupForProjector();
                }
            }

            if (objectBuilder == null)
            {
                System.Diagnostics.Debug.Fail("Original object builder could not be found! (AlexFlorea)");
                objectBuilder     = cubeBlock.GetObjectBuilder();
                location.EntityId = MyEntityIdentifier.AllocateId();
            }

            objectBuilder.ConstructionInventory = null;
            bool isAdmin = MySession.Static.IsAdminModeEnabled(Sync.MyId);

            MyMultiplayer.RaiseEvent(projectorGrid, x => x.BuildBlockRequest, cubeBlock.ColorMaskHSV.PackHSVToUint(), location, objectBuilder, builder, isAdmin, owner);
            HideCube(cubeBlock);
        }
Example #24
0
        private void CreateTopGrid(out MyCubeGrid topGrid, out MyPistonTop topBlock, MyCubeBlockDefinitionGroup topGroup)
        {
            if (topGroup == null)
            {
                topGrid  = null;
                topBlock = null;
                return;
            }

            var gridSize = CubeGrid.GridSizeEnum;

            float size   = MyDefinitionManager.Static.GetCubeSize(gridSize);
            var   matrix = MatrixD.CreateWorld(Vector3D.Transform(m_constraintBasePos, Subpart3.WorldMatrix), WorldMatrix.Forward, WorldMatrix.Up);

            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 = Sandbox.Common.ObjectBuilders.Serializer.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 = (MyPistonTop)topGrid.GetCubeBlock(Vector3I.Zero).FatBlock;
            //topGrid.SetPosition(topGrid.WorldMatrix.Translation - (topBlock.WorldMatrix.Translation/*Vector3.Transform(topBlock.DummyPosLoc, topGrid.WorldMatrix) - topGrid.WorldMatrix.Translation*/));

            MyEntities.Add(grid);

            MySyncCreate.SendEntityCreated(grid.GetObjectBuilder());
            m_topBlockId = topBlock.EntityId;
        }
Example #25
0
 public void Init(MyObjectBuilder_GlobalChatItem chatBuilder)
 {
     Text       = chatBuilder.Text;
     IdentityId = MyEntityIdentifier.ConstructId(MyEntityIdentifier.ID_OBJECT_TYPE.IDENTITY, chatBuilder.IdentityIdUniqueNumber);
 }
Example #26
0
 private MyIdentity(string name, MyEntityIdentifier.ID_OBJECT_TYPE identityType, string model = null)
 {
     Debug.Assert(identityType == MyEntityIdentifier.ID_OBJECT_TYPE.IDENTITY, "Trying to create invalid identity type!");
     IdentityId = MyEntityIdentifier.AllocateId(identityType, MyEntityIdentifier.ID_ALLOCATION_METHOD.SERIAL_START_WITH_1);
     Init(name, IdentityId, model);
 }
Example #27
0
 public static long GenerateEntityId(VRage.MyEntityIdentifier.ID_OBJECT_TYPE type)
 {
     return(MyEntityIdentifier.AllocateId(type));
 }
Example #28
0
 private MyIdentity(string name, MyEntityIdentifier.ID_OBJECT_TYPE identityType, string model = null)
 {
     Debug.Assert(identityType == MyEntityIdentifier.ID_OBJECT_TYPE.IDENTITY, "Trying to create invalid identity type!");
     IdentityId = MyEntityIdentifier.AllocateId(identityType, MyEntityIdentifier.ID_ALLOCATION_METHOD.SERIAL_START_WITH_1);
     Init(name, IdentityId, model);
 }
Example #29
0
        public virtual void Start(Vector3 position, Vector3 initialVelocity, Vector3 direction, float impulseMultiplier, MyEntity owner, StringBuilder displayName = null)
        {
            System.Diagnostics.Debug.Assert(Closed);
            Closed = false;
            GuidedInMultiplayer = false;

            if(this.EntityId.HasValue)
            {
                MyEntityIdentifier.RemoveEntity(this.EntityId.Value);
                this.EntityId = null;
            }

            if (this.NeedsId)
            {
                //if(owner.EntityId.HasValue) this.EntityId = MyEntityIdentifier.AllocateId(owner.EntityId.Value.PlayerId);
                //else this.EntityId = MyEntityIdentifier.AllocateId();
                this.EntityId = MyEntityIdentifier.AllocateId();
                MyEntityIdentifier.AddEntityWithId(this);
            }

            if (displayName != null && owner == MySession.PlayerShip)
            {
                DisplayName = displayName.ToString();
                MyHud.AddText(this, displayName, maxDistance: 1000);
            }

            m_isExploded = false;
            m_cascadeExplosionLevel = 0;
            m_origin = position;
            m_previousPosition = position;
            m_initialVelocity = initialVelocity;

            System.Diagnostics.Debug.Assert(owner.EntityId.HasValue, "Shooting entity must have ID");

            m_ownerEntityID = owner.EntityId.Value;
            m_elapsedMiliseconds = 0;



            Matrix ammoWorld = Matrix.CreateWorld(position, direction, owner.WorldMatrix.Up);

            SetWorldMatrix(ammoWorld);

            this.Physics.Clear();
            this.Physics.Enabled = true;
            this.Physics.LinearVelocity = initialVelocity;

            if (owner.Physics != null)
                this.Physics.GroupMask = owner.Physics.GroupMask;
            else
                this.Physics.GroupMask = MyGroupMask.Empty;

            //this.Physics.Enabled = true;

            this.Physics.ApplyImpulse(direction * this.Physics.Mass * impulseMultiplier, position);
            
            MyEntities.Add(this);
            NeedsUpdate = true;
        }