public bool SpawnTrigger() { var dialog = new ValueGetScreenWithCaption("Spawn new Trigger", "", delegate(string text) { var trigger = new MyAreaTriggerComponent(text); var entity = new MyEntity(); trigger.Radius = 2; trigger.Center = MyAPIGateway.Session.Camera.Position; entity.PositionComp.SetPosition(MyAPIGateway.Session.Camera.Position); entity.PositionComp.LocalVolume = new BoundingSphere(Vector3.Zero, 0.5f); entity.EntityId = MyEntityIdentifier.AllocateId(); entity.Components.Remove <MyPhysicsComponentBase>(); entity.Components.Remove <MyRenderComponentBase>(); entity.DisplayName = "TriggerHolder"; MyEntities.Add(entity); if (!entity.Components.Contains(typeof(MyTriggerAggregate))) { entity.Components.Add(typeof(MyTriggerAggregate), new MyTriggerAggregate()); } entity.Components.Get <MyTriggerAggregate>().AddComponent(trigger); if (m_selectedTrigger != null) { m_selectedTrigger.CustomDebugColor = Color.Red; } ; m_selectedTrigger = trigger; m_selectedTrigger.CustomDebugColor = Color.Yellow; return(true); }); MyGuiSandbox.AddScreen(dialog); return(true); }
public MySlimBlock PlaceInGrid( MyDefinitionId blockDefinitionId, MyCubeGrid currentGrid, Vector3I min, Vector3I orientationForward, Vector3I orientationUp, long playerId ) { HashSet <MyCubeGrid.MyBlockLocation> blocksBuildQueue = new HashSet <MyCubeGrid.MyBlockLocation>(); var orientation = Quaternion.CreateFromForwardUp(orientationForward, orientationUp); var myBlockLocation = new MyCubeGrid.MyBlockLocation( blockDefinitionId, min, min, min, orientation, MyEntityIdentifier.AllocateId(), playerId ); blocksBuildQueue.Add(myBlockLocation); var blockIds = currentGrid.CubeBlocks.Select(b => b.UniqueId).ToImmutableHashSet(); currentGrid.BuildBlocks(MyPlayer.SelectedColor, MyStringHash.GetOrCompute(MyPlayer.SelectedArmorSkin), blocksBuildQueue, MySession.Static.LocalCharacterEntityId, MySession.Static.LocalPlayerId); var blockIds2 = currentGrid.CubeBlocks.Select(b => b.UniqueId).ToImmutableHashSet(); var newIds = blockIds2.Except(blockIds); if (newIds.IsEmpty) { throw new InvalidOperationException("Couldn't build the block"); } if (newIds.Count > 1) { throw new InvalidOperationException("Built more than one block!"); } var id = newIds.First(); return(currentGrid.CubeBlocks.First(b => b.UniqueId == id)); }
// Spawn empty entity private void SpawnEntityClicked(MyGuiControlButton myGuiControlButton) { string newEntityName; MyEntity e; do { newEntityName = ENTITY_NAME_PREFIX + m_entityCounter++; } while(MyEntities.TryGetEntityByName(newEntityName, out e)); var entity = new MyEntity { WorldMatrix = MyAPIGateway.Session.Camera.WorldMatrix, EntityId = MyEntityIdentifier.AllocateId(), DisplayName = "Entity", Name = newEntityName }; entity.PositionComp.SetPosition(MyAPIGateway.Session.Camera.Position); entity.Components.Remove <MyPhysicsComponentBase>(); MyEntities.Add(entity); MyEntities.SetEntityName(entity, true); }
public MyEntity Spawn(MyFixedPoint amount, MatrixD worldMatrix, MyEntity owner = null) { if (Content is MyObjectBuilder_BlockItem) { var blockItem = Content as MyObjectBuilder_BlockItem; var builder = Sandbox.Common.ObjectBuilders.Serializer.MyObjectBuilderSerializer.CreateNewObject(typeof(MyObjectBuilder_CubeGrid)) as MyObjectBuilder_CubeGrid; builder.EntityId = MyEntityIdentifier.AllocateId(); builder.GridSizeEnum = MyCubeSize.Small; builder.IsStatic = false; builder.PersistentFlags |= MyPersistentEntityFlags2.InScene | MyPersistentEntityFlags2.Enabled; builder.PositionAndOrientation = new MyPositionAndOrientation(worldMatrix); var block = Sandbox.Common.ObjectBuilders.Serializer.MyObjectBuilderSerializer.CreateNewObject(blockItem.BlockDefId) as MyObjectBuilder_CubeBlock; builder.CubeBlocks.Add(block); var newGrid = MyEntities.CreateFromObjectBuilder(builder) as MyCubeGrid; MyEntities.Add(newGrid); Sandbox.Game.Multiplayer.MySyncCreate.SendEntityCreated(builder); return(newGrid); } else { return(MyFloatingObjects.Spawn(new MyInventoryItem(amount, Content), worldMatrix, owner != null ? owner.Physics : null)); } }
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, MySession.LocalCharacter != null ? MySession.LocalCharacter.EntityId : 0); locations.Add(blockLocation); } foreach (var location in locations) { m_grid.BuildGeneratedBlock(location, Vector3I.Zero); } }
public override bool StartShooting() { MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("MyLargeShipMissileLauncherBarrel::StartShooting"); LastShotId = null; int missileShotInterval = 0; MyLargeShipGunBase.GetMissileAmmoParams(GetAmmoType(), ref missileShotInterval); if ((MyMinerGame.TotalGamePlayTimeInMilliseconds - m_lastTimeShoot) < missileShotInterval) { MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock(); return(false); } m_burstFinish = false; while (!m_burstFinish) { if (!base.StartShooting()) { MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock(); return(false); } if (m_groupMask == null) { MyPhysics.physicsSystem.GetRigidBodyModule().GetGroupMaskManager().GetGroupMask(ref m_groupMask); } MyEntity target = ((MyLargeShipGunBase)Parent).GetTarget(); List <MyModelDummy> muzzles = GetMuzzleFlashMatrix(); m_activeMuzzle = --m_burstToFire; Matrix worldMatrix = WorldMatrix; Vector3 muzzleFlashPosition = MyUtils.GetTransform(muzzles[m_activeMuzzle].Matrix.Translation, ref worldMatrix); if (IsControlledByPlayer()) { //target = MySession.PlayerShip.TargetEntity as MySmallShip; target = MyEnemyTargeting.SwitchNextTarget(true); } if (target != null || IsControlledByPlayer()) { MySoundCue?shootingSound = GetWeaponBase().UnifiedWeaponCueGet(MySoundCuesEnum.WepMissileLaunch3d); if (shootingSound == null || !shootingSound.Value.IsPlaying) { GetWeaponBase().UnifiedWeaponCueSet(Audio.MySoundCuesEnum.WepMissileLaunch3d, MyAudio.AddCue2dOr3d(this.GetWeaponBase().PrefabParent, Audio.MySoundCuesEnum.WepMissileLaunch3d, muzzleFlashPosition, WorldMatrix.Forward, WorldMatrix.Up, Vector3.Zero)); //MyAudio.AddCue2dOr3d(this.GetWeaponBase().PrefabParent, Audio.MySoundCuesEnum.WepMissileLaunch3d, muzzleFlashPosition, WorldMatrix.Forward, WorldMatrix.Up, Vector3.Zero); } Vector3 deviateVector = GetDeviatedVector(MyAmmoConstants.GetAmmoProperties(GetAmmoType())); var missile = MyMissiles.Add(GetAmmoType(), muzzleFlashPosition + 2 * WorldMatrix.Forward, WorldMatrix.Forward * 2.0f, deviateVector, Vector3.Zero, this, target, SearchingDistance, isLightWeight: true); if (missile.GuidedInMultiplayer) { missile.EntityId = MyEntityIdentifier.AllocateId(); MyEntityIdentifier.AddEntityWithId(missile); LastShotId = missile.EntityId; } } if (m_burstToFire <= 0) { m_burstFireTime_ms = MyMinerGame.TotalGamePlayTimeInMilliseconds; m_burstToFire = m_burstFireCount; m_burstFinish = true; } if ((MyMinerGame.TotalGamePlayTimeInMilliseconds - m_burstFireTime_ms) > m_burstFireTimeLoadingIntervalConst_ms) { m_burstFinish = false; } if (!IsControlledByPlayer()) { m_burstFinish = true; } } m_lastTimeShoot = MyMinerGame.TotalGamePlayTimeInMilliseconds; MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock(); return(true); }
private void AddBlocks() { foreach (MyGeneratedBlockLocation location in this.m_addLocations) { Quaternion quaternion; location.Orientation.GetQuaternion(out quaternion); MyCubeGrid.MyBlockLocation location2 = new MyCubeGrid.MyBlockLocation(location.BlockDefinition.Id, location.Position, location.Position, location.Position, quaternion, MyEntityIdentifier.AllocateId(MyEntityIdentifier.ID_OBJECT_TYPE.ENTITY, MyEntityIdentifier.ID_ALLOCATION_METHOD.RANDOM), MySession.Static.LocalPlayerId); m_tmpLocationsAndRefBlocks.Add(new Tuple <MyCubeGrid.MyBlockLocation, MySlimBlock>(location2, location.RefBlock)); } foreach (Tuple <MyCubeGrid.MyBlockLocation, MySlimBlock> tuple in m_tmpLocationsAndRefBlocks) { MySlimBlock block = this.m_grid.BuildGeneratedBlock(tuple.Item1, (Vector3)Vector3I.Zero); if (block != null) { MyCompoundCubeBlock fatBlock = block.FatBlock as MyCompoundCubeBlock; if (fatBlock != null) { foreach (MySlimBlock block4 in fatBlock.GetBlocks()) { Quaternion quaternion2; MyCubeGrid.MyBlockLocation location3 = tuple.Item1; location3.Orientation.GetQuaternion(out quaternion2); MyBlockOrientation orientation2 = new MyBlockOrientation(ref quaternion2); if ((block4.Orientation == orientation2) && (block4.BlockDefinition.Id == tuple.Item1.BlockDefinition)) { block = block4; break; } } } MySlimBlock generatingBlock = tuple.Item2; if (((block != null) && block.BlockDefinition.IsGeneratedBlock) && (generatingBlock != null)) { block.SetGeneratedBlockIntegrity(generatingBlock); } } } m_tmpLocationsAndRefBlocks.Clear(); }
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 = 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 = 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; 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)); } }
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); } }
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 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; }
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); } } }
public override void HandleInput() { if (!m_isActive) { return; } if (!(MyScreenManager.GetScreenWithFocus() is MyGuiScreenGamePlay)) { return; } if (! (VRage.Input.MyInput.Static.ENABLE_DEVELOPER_KEYS || !MySession.Static.SurvivalMode || (MyMultiplayer.Static != null && MyMultiplayer.Static.IsAdmin(MySession.Static.LocalHumanPlayer.Id.SteamId))) ) { 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.Static.GetCameraControllerEnum() == MyCameraControllerEnum.ThirdPersonSpectator || MySession.Static.GetCameraControllerEnum() == MyCameraControllerEnum.Entity) { if (MySession.Static.ControlledEntity == null) { return; } cameraPos = MySession.Static.ControlledEntity.GetHeadMatrix(true, true).Translation; cameraDir = MySession.Static.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 + MySession.Static.ControlledEntity.Entity.Physics.LinearVelocity; float mass = 0; if (CurrentDefinition.Mass.HasValue) { mass = Sandbox.Engine.Physics.MyDestructionHelper.MassToHavok(CurrentDefinition.Mass.Value); } gridBuilders[0].EntityId = MyEntityIdentifier.AllocateId(); MyMultiplayer.RaiseStaticEvent(s => MySessionComponentThrower.OnThrowMessageSuccess, gridBuilders[0], position, linearVelocity, mass, CurrentDefinition.ThrowSound); m_startTime = 0; } }
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(); } }
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 }; }
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; }
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); }
// Every child of this base class must implement Shot() method, which shots projectile or missile. // Method returns true if something was shot. False if not (because interval between two shots didn't pass) public override bool Shot(MyMwcObjectBuilder_SmallShip_Ammo usedAmmo) { LastShotId = null; float missileLauncherShotInterval = float.MaxValue; switch (usedAmmo.AmmoType) { case MyMwcObjectBuilder_SmallShip_Ammo_TypesEnum.Missile_Basic: case MyMwcObjectBuilder_SmallShip_Ammo_TypesEnum.Missile_BioChem: case MyMwcObjectBuilder_SmallShip_Ammo_TypesEnum.Missile_EMP: case MyMwcObjectBuilder_SmallShip_Ammo_TypesEnum.Guided_Missile_Engine_Detection: case MyMwcObjectBuilder_SmallShip_Ammo_TypesEnum.Guided_Missile_Radar_Detection: case MyMwcObjectBuilder_SmallShip_Ammo_TypesEnum.Guided_Missile_Visual_Detection: missileLauncherShotInterval = MyGuidedMissileConstants.MISSILE_LAUNCHER_SHOT_INTERVAL_IN_MILISECONDS; break; default: throw new ArgumentOutOfRangeException(); } if ((MyMinerGame.TotalGamePlayTimeInMilliseconds - m_lastTimeShoot) < missileLauncherShotInterval && !IsDummy) { return(false); } // Throw ship backward (by deviated vector) this.Parent.Physics.AddForce(MyPhysicsForceType.ADD_BODY_FORCE_AND_BODY_TORQUE, MyUtilRandomVector3ByDeviatingVector.GetRandom(Vector3.Backward, MathHelper.ToRadians(5)) * MyMwcUtils.GetRandomFloat(40000, 50000), null, null); // Play missile launch cue (one-time) AddWeaponCue(MySoundCuesEnum.WepMissileLaunch3d); Vector3 forwardVelocity = MyMath.ForwardVectorProjection(this.WorldMatrix.Forward, GetParentMinerShip().Physics.LinearVelocity); // Create and fire missile - but deviate missile direction be random angle Vector3 deviatedVector = GetDeviatedVector(MinerWars.AppCode.Game.Gameplay.MyAmmoConstants.GetAmmoProperties(usedAmmo.AmmoType)); // correct missile start position if it would intersect some entity Vector3 missileStartPosition = m_positionMuzzleInWorldSpace; missileStartPosition = CorrectPosition(missileStartPosition, deviatedVector, Parent); if (MinerWars.AppCode.Game.Managers.Session.MySession.Static.Is2DSector) { forwardVelocity.Y = 0; deviatedVector.Y = 0; } var missile = MyMissiles.Add(usedAmmo.AmmoType, missileStartPosition, forwardVelocity, deviatedVector, LocalMatrix.Translation, Parent, ((MySmallShip)Parent).TargetEntity, isDummy: this.IsDummy); if (missile != null) { missile.EntityId = MyEntityIdentifier.AllocateId(); MyEntityIdentifier.AddEntityWithId(missile); LastShotId = missile.EntityId; GetParentMinerShip().LastMissileFired = missile; } //MyUtilRandomVector3ByDeviatingVector.GetRandom(WorldMatrix.Forward m_lastTimeShoot = MyMinerGame.TotalGamePlayTimeInMilliseconds; m_lastSmokePosition = GetSmokePosition(); if (SysUtils.MyMwcFinalBuildConstants.ENABLE_TRAILER_SAVE) { MinerWars.AppCode.Game.Trailer.MyTrailerSave.UpdateGunShot(this.Parent, Trailer.MyTrailerGunsShotTypeEnum.MISSILE); } // We shot one missile return(true); }
public static long GenerateEntityId(VRage.MyEntityIdentifier.ID_OBJECT_TYPE type) { return(MyEntityIdentifier.AllocateId(type)); }
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(); }
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 }; }
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); }
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); }