private static void ShieldHitReceived(byte[] bytes) { try { if (bytes.Length <= 2) { return; } var data = MyAPIGateway.Utilities.SerializeFromBinary <DataShieldHit>(bytes); // this will throw errors on invalid data MyEntity ent = null; if (MyAPIGateway.Multiplayer.IsServer || data?.ShieldHit == null || !MyEntities.TryGetEntityById(data.EntityId, out ent) || ent.Closed) { Log.Line($"EnforceData Received;; {(ent == null ? "can't find entity" : (ent.Closed ? "found closed entity" : "entity not a shield"))}"); return; } var shield = ent.GameLogic.GetAs <DefenseShields>(); if (shield == null) { return; } var hit = data.ShieldHit; var attacker = MyEntities.GetEntityById(hit.AttackerId); shield.ShieldHits.Add(new ShieldHit(attacker, hit.Amount, MyStringHash.GetOrCompute(hit.DamageType), hit.HitPos)); } catch (Exception ex) { Log.Line($"Exception in ShieldHitReceived: {ex}"); } }
private static void OnTransferItemsBaseMsg(ref TransferItemsBaseMsg msg, MyNetworkClient sender) { MyEntity sourceContainer = MyEntities.GetEntityById(msg.SourceContainerId); MyEntity destinationContainer = MyEntities.GetEntityById(msg.DestinationContainerId); if (sourceContainer == null || destinationContainer == null) { Debug.Fail("Containers/Entities weren't found!"); return; } MyInventoryBase sourceInventory = sourceContainer.GetInventory(msg.SourceInventoryId); MyInventoryBase destinationInventory = destinationContainer.GetInventory(msg.DestinationInventoryId); if (sourceInventory == null || destinationInventory == null) { Debug.Fail("Inventories weren't found!"); return; } var items = sourceInventory.GetItems(); foreach (var item in items) { if (item.ItemId == msg.SourceItemId) { MyInventoryBase.TransferItems(sourceInventory, destinationInventory, item, msg.Amount); return; } } }
private static void InventoryBaseTransferItem_Implementation(MyInventoryTransferEventContent eventParams) { if (!MyEntities.EntityExists(eventParams.DestinationOwnerId) || !MyEntities.EntityExists(eventParams.SourceOwnerId)) { return; } MyEntity sourceOwner = MyEntities.GetEntityById(eventParams.SourceOwnerId); MyInventoryBase source = sourceOwner.GetInventory(eventParams.SourceInventoryId); MyEntity destOwner = MyEntities.GetEntityById(eventParams.DestinationOwnerId); MyInventoryBase dst = destOwner.GetInventory(eventParams.DestinationInventoryId); var items = source.GetItems(); MyPhysicalInventoryItem?foundItem = null; foreach (var item in items) { if (item.ItemId == eventParams.ItemId) { foundItem = item; } } if (foundItem.HasValue) { dst.TransferItemsFrom(source, foundItem, eventParams.Amount); } }
internal bool ServerIsFocused(GridAi ai) { var fd = ai.Construct.Data.Repo.FocusData; fd.HasFocus = false; for (int i = 0; i < fd.Target.Length; i++) { if (fd.Target[i] > 0) { if (MyEntities.GetEntityById(fd.Target[fd.ActiveId]) != null) { fd.HasFocus = true; } else { fd.Target[i] = -1; fd.Locked[i] = LockModes.None; } } if (fd.Target[0] <= 0 && fd.HasFocus) { fd.Target[0] = fd.Target[i]; fd.Locked[0] = fd.Locked[i]; fd.Target[i] = -1; fd.Locked[i] = LockModes.None; fd.ActiveId = 0; } } return(fd.HasFocus); }
private void m_listbox_ItemDoubleClick(object sender, MyGuiControlListboxItemEventArgs eventArgs) { MyEditorGizmo.ClearSelection(); MyEntity entityToSelect = MyEntities.GetEntityById(new MyEntityIdentifier((uint)eventArgs.Key)); MyEditorGizmo.AddEntityToSelection(entityToSelect); }
private static void OnTransferItemsBaseMsg(ref TransferItemsBaseMsg msg, MyNetworkClient sender) { MyEntity sourceContainer = MyEntities.GetEntityById(msg.SourceContainerId); MyEntity destinationContainer = MyEntities.GetEntityById(msg.DestinationContainerId); if (sourceContainer == null || destinationContainer == null) { Debug.Fail("Containers/Entities weren't found!"); return; } // CH: TODO: This breaks the object design, but so far we wouldn't be able to move items between other inventories than MyInventory anyway MyInventory sourceInventory = sourceContainer.GetInventory(msg.SourceInventoryId) as MyInventory; MyInventoryBase destinationInventory = destinationContainer.GetInventory(msg.DestinationInventoryId); if (sourceInventory == null || destinationInventory == null) { Debug.Fail("Inventories weren't found!"); return; } var items = sourceInventory.GetItems(); foreach (var item in items) { if (item.ItemId == msg.SourceItemId) { MyInventoryBase.TransferItems(sourceInventory, destinationInventory, item, msg.Amount); return; } } }
static void OnRemoveItemsSuccess(ref RemoveItemsMsg msg, MyNetworkClient sender) { if (!MyEntities.EntityExists(msg.OwnerEntityId)) { return; } IMyInventoryOwner owner = MyEntities.GetEntityById(msg.OwnerEntityId) as IMyInventoryOwner; MyInventory inv = null; if (owner != null) { inv = owner.GetInventory(msg.InventoryIndex); } else { // NOTE: this should be the default code after we get rid of the inventory owner and should be searched by it's id MyEntity entity = MyEntities.GetEntityById(msg.OwnerEntityId); MyInventoryBase baseInventory; if (entity.Components.TryGet <MyInventoryBase>(out baseInventory)) { inv = baseInventory as MyInventory; } } if (inv != null) { inv.RemoveItemsInternal(msg.itemId, msg.Amount); } else { Debug.Fail("Inventory was not found!"); } }
static void OnRemoveItemsRequest(ref RemoveItemsMsg msg, MyNetworkClient sender) { if (!MyEntities.EntityExists(msg.OwnerEntityId)) { return; } IMyInventoryOwner owner = MyEntities.GetEntityById(msg.OwnerEntityId) as IMyInventoryOwner; MyInventory inv = null; if (owner != null) { inv = owner.GetInventory(msg.InventoryIndex); } else { // NOTE: this should be the default code after we get rid of the inventory owner and should be searched by it's id MyEntity entity = MyEntities.GetEntityById(msg.OwnerEntityId); MyInventoryBase baseInventory; if (entity.Components.TryGet <MyInventoryBase>(out baseInventory)) { inv = baseInventory as MyInventory; } } var item = inv.GetItemByID(msg.itemId); if (!item.HasValue) { return; } inv.RemoveItems(msg.itemId, msg.Amount, spawn: msg.Spawn); }
/// <summary> /// Adds incoming chat event into all players' global chat history. /// </summary> /// <param name="obj"></param> public static void AddChat(ChatManager.ChatEvent obj) { if (!_init) { _init = true; Init(); } Wrapper.GameAction(() => { try { var player = MySession.Static.Players.GetAllPlayers().First(x => x.SteamId == obj.SourceUserId); var characterId = MySession.Static.Players.ControlledEntities.First(x => x.Value.SteamId == obj.SourceUserId).Key; var character = MyEntities.GetEntityById(characterId) as MyCharacter; if (character == null) { //okay, the sending player doesn't have a character. just find any character character = MyEntities.GetEntities().FirstOrDefault(x => (x as MyCharacter) != null) as MyCharacter; if (character == null) { //we gave it our best shot :( return; } } character.SendNewGlobalMessage(player, obj.Message); } catch (Exception ex) { Essentials.Log.Error(ex, "Fail ChatHistory"); } }); }
static void OnAddGps(AddMsg msg) { MyGps gps = new MyGps(); gps.Name = msg.Name; gps.Description = msg.Description; gps.Coords = msg.Coords; gps.ShowOnHud = msg.ShowOnHud; gps.AlwaysVisible = msg.AlwaysVisible; gps.DiscardAt = null; gps.GPSColor = msg.GPSColor; if (!msg.IsFinal) { gps.SetDiscardAt(); } gps.UpdateHash(); if (msg.EntityId > 0) { gps.SetEntity(MyEntities.GetEntityById(msg.EntityId)); } if (MySession.Static.Gpss.AddPlayerGps(msg.IdentityId, ref gps)) {//new entry succesfully added if (gps.ShowOnHud && msg.IdentityId == MySession.Static.LocalPlayerId) { MyHud.GpsMarkers.RegisterMarker(gps); } } var handler = MySession.Static.Gpss.ListChanged; if (handler != null) { handler(msg.IdentityId); } }
private static void AddItemsInternal(AddItemsMsg msg) { IMyInventoryOwner owner = MyEntities.GetEntityById(msg.OwnerEntityId) as IMyInventoryOwner; MyInventory inv = owner.GetInventory(msg.InventoryIndex); inv.AddItemsInternal(msg.Amount, msg.Item, msg.itemIdx); }
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); } }
private void SetEntitiesIndestructible(List <uint> entityIDs) { foreach (uint entityID in entityIDs) { MyEntity entity = MyEntities.GetEntityById(new MyEntityIdentifier(entityID)); MyScriptWrapper.SetEntityDestructible(entity, false); } }
private static void PlayAttackAnimation(long entityId) { if (MyEntities.EntityExists(entityId)) { MyCharacter character = MyEntities.GetEntityById(entityId) as MyCharacter; if (character != null) character.AnimationController.TriggerAction(m_stringIdAttackAction); } }
static void OnAddItemsRequest(ref AddItemsMsg msg, MyNetworkClient sender) { if (!MyEntities.EntityExists(msg.OwnerEntityId)) { return; } IMyInventoryOwner owner = MyEntities.GetEntityById(msg.OwnerEntityId) as IMyInventoryOwner; owner.GetInventory(msg.InventoryIndex).AddItems(msg.Amount, msg.Item, msg.itemIdx); }
public void AcceptGrid(long id, SlimProfilerEntry spe) { if (Type != ProfilerRequestType.Grid) { return; } var grid = MyEntities.GetEntityById(id) as MyCubeGrid; Accept(grid?.DisplayName ?? "Unknown", grid?.PositionComp.WorldAABB.Center, "ID=" + id, spe); }
public void Clear() { MyEntity entity; if ((this.m_hookIdFrom != 0) && MyEntities.TryGetEntityById(this.m_hookIdFrom, out entity, false)) { MyEntities.GetEntityById(this.m_hookIdFrom, false).OnClosing -= this.m_selectedHook_OnClosing; this.m_hookIdFrom = 0L; } }
public void AcceptScript(long id, SlimProfilerEntry spe) { if (Type != ProfilerRequestType.Scripts) { return; } var block = MyEntities.GetEntityById(id) as MyProgrammableBlock; Accept($"{block?.CustomName?.ToString() ?? "Unknown"} on {block?.CubeGrid?.DisplayName ?? "Unknown"}", block?.PositionComp.WorldAABB.Center, "ID=" + id, spe); }
static void OnRemoveItemsSuccess(ref RemoveItemsMsg msg, MyNetworkClient sender) { if (!MyEntities.EntityExists(msg.OwnerEntityId)) { return; } IMyInventoryOwner owner = MyEntities.GetEntityById(msg.OwnerEntityId) as IMyInventoryOwner; MyInventory inv = owner.GetInventory(msg.InventoryIndex); inv.RemoveItemsInternal(msg.itemId, msg.Amount); }
/// <summary> /// Try lock entity and announce to other players (runs only on host) /// </summary> bool TryLockEntity(uint entityId, byte playerId, bool enable) { bool success = true; if (enable) { using (m_lockedEntitiesLock.AcquireExclusiveUsing()) { success = !m_lockedEntities.ContainsKey(entityId); if (success) { m_lockedEntities[entityId] = playerId; MyEntities.GetEntityById(entityId.ToEntityId()).OnClosing += m_unlockOnClosing; } } } else { using (m_lockedEntitiesLock.AcquireExclusiveUsing()) { success = m_lockedEntities.Remove(entityId); MyEntity entity; if (MyEntities.TryGetEntityById(entityId.ToEntityId(), out entity)) { entity.OnClosing -= m_unlockOnClosing; } } } if (success) { // Send lock to all MyEventLock response = new MyEventLock(); response.EntityId = entityId; response.LockType = enable ? MyLockEnum.LOCK : MyLockEnum.UNLOCK; Peers.SendToAll(ref response, NetDeliveryMethod.ReliableOrdered, 0); } if (enable) { // Send response to player MyPlayerRemote player; if (Peers.TryGetPlayer(playerId, out player)) { MyEventLockResult response = new MyEventLockResult(); response.EntityId = entityId; response.IsSuccess = success; Peers.NetworkClient.Send(ref response, player.Connection, NetDeliveryMethod.ReliableOrdered, 0); } } return(success); }
/// <summary> /// Do not use, for interfacing with Water Mod /// </summary> private void ModHandler(object data) { if (data == null) { return; } if (data is byte[]) { Waters = MyAPIGateway.Utilities.SerializeFromBinary <List <Water> >((byte[])data); if (Waters == null) { Waters = new List <Water>(); } else { foreach (var water in Waters) { MyEntity entity = MyEntities.GetEntityById(water.planetID); if (entity != null) { water.planet = MyEntities.GetEntityById(water.planetID) as MyPlanet; } } } int count = Waters.Count; RecievedData?.Invoke(); if (count > Waters.Count) { WaterCreatedEvent?.Invoke(); } if (count < Waters.Count) { WaterRemovedEvent?.Invoke(); } } if (!Registered) { Registered = true; OnRegisteredEvent?.Invoke(); } if (data is int && (int)data != ModAPIVersion) { MyLog.Default.WriteLine("Water API V" + ModAPIVersion + " for " + ModName + " is outdated, expected V" + (int)data); MyAPIGateway.Utilities.ShowMessage(ModName, "Water API V" + ModAPIVersion + " is outdated, expected V" + (int)data); } }
public void CheckPlayers(long id) { string message = ""; MyCubeGrid grid = (MyCubeGrid)MyEntities.GetEntityById(id); MatrixD m = grid.WorldMatrix; message += $"{m.Translation.X} {m.Translation.Y} {m.Translation.Z}"; Context.Respond($"{message}"); }
static void OnAttachToCockpit(MySyncCharacter sync, ref AttachToCockpitMsg msg, MyNetworkClient sender) { MyCharacter character = sync.Entity; MyCockpit cockpit = MyEntities.GetEntityById(msg.CockpitEntityId) as MyCockpit; Debug.Assert(cockpit != null); if (cockpit == null) { return; } cockpit.AttachPilot(character, false); }
public static void AddGrid(long entityId) { using (_entityLock.AcquireSharedUsing()) { var entity = MyEntities.GetEntityById(entityId); if (!(entity is MyCubeGrid grid) || _gridCache.Contains(grid)) { return; } _gridCache.Add(grid); } }
public void EnableProjectors() { foreach (var projector in _projectors.Select(x => MyEntities.GetEntityById(x) as MyProjectorBase)) { if (projector == null) { continue; } projector.Enabled = true; } _projectors.Clear(); }
public MyEntity GetEntityConnectingToParent(MyCubeGrid grid) { MyGroups <MyCubeGrid, MyGridPhysicalHierarchyData> .Node node = base.GetNode(grid); if (node == null) { return(null); } if (node.m_parents.Count == 0) { return(null); } return(MyEntities.GetEntityById(node.m_parents.FirstPair <long, MyGroups <MyCubeGrid, MyGridPhysicalHierarchyData> .Node>().Key, false)); }
private void PbGetSortedThreats(long arg1, object arg2) { GetSortedThreats(MyEntities.GetEntityById(arg1), _tmpTargetList); var dict = (IDictionary <long, float>)arg2; foreach (var i in _tmpTargetList) { dict[i.Item1.EntityId] = i.Item2; } _tmpTargetList.Clear(); }
private IMyEntity GetAiFocus(IMyEntity shooter, int priority = 0) { var shootingGrid = shooter.GetTopMostParent() as MyCubeGrid; if (shootingGrid != null) { GridAi ai; if (_session.GridToMasterAi.TryGetValue(shootingGrid, out ai)) { return(MyEntities.GetEntityById(ai.Construct.Data.Repo.FocusData.Target[priority])); } } return(null); }
static void OnTransferItemsRequest(ref TransferItemsMsg msg, MyNetworkClient sender) { if (!MyEntities.EntityExists(msg.OwnerEntityId) || !MyEntities.EntityExists(msg.DestOwnerEntityId)) { return; } IMyInventoryOwner srcOwner = MyEntities.GetEntityById(msg.OwnerEntityId) as IMyInventoryOwner; IMyInventoryOwner destOwner = MyEntities.GetEntityById(msg.DestOwnerEntityId) as IMyInventoryOwner; MyInventory src = srcOwner.GetInventory(msg.InventoryIndex); MyInventory dst = destOwner.GetInventory(msg.DestInventoryIndex); TransferItemsInternal(src, dst, msg.itemId, msg.Spawn, msg.DestItemIndex, msg.Amount); }
void BeforeDamage(object target, ref MyDamageInformation info) { try { if (info.IsDeformation || info.Amount <= 0 || info.Type != MyDamageType.Grind) { return; } IMySlimBlock block = target as IMySlimBlock; IMyFloatingObject fo = (block == null ? target as IMyFloatingObject : null); if (block == null && fo == null) { return; } MyEntity attacker = MyEntities.GetEntityById(info.AttackerId); IMyAngleGrinder grinder = attacker as IMyAngleGrinder; IMyCharacter attackerChar = (grinder == null ? attacker as IMyCharacter : null); if (grinder == null && attackerChar == null) { return; } ulong attackerSteamId; if (grinder != null) { attackerSteamId = MyAPIGateway.Players.TryGetSteamId(grinder.OwnerIdentityId); } else { attackerSteamId = MyAPIGateway.Players.TryGetSteamId(attackerChar.ControllerInfo.ControllingIdentityId); } if (block != null) { GrindingBlock?.Invoke(block, ref info, grinder, attackerSteamId); } else { GrindingFloatingObject?.Invoke(fo, ref info, attackerSteamId); } } catch (Exception e) { Log.Error(e); } }