private void MyGasTank_ContentsChanged(MyInventoryBase obj) { if ((this.m_autoRefill != null) && this.CanRefill()) { this.RefillBottles(); } }
public MyFixedPoint GetItemAmountCombined(MyInventoryBase inventory, MyDefinitionId contentId) { int amount = 0; var group = MyDefinitionManager.Static.GetGroupForComponent(contentId, out amount); if (group == null) { MyComponentSubstitutionDefinition substitutions; if (MyDefinitionManager.Static.TryGetComponentSubstitutionDefinition(contentId, out substitutions)) { foreach (var providingComponent in substitutions.ProvidingComponents) { amount += (int)inventory.GetItemAmount(providingComponent.Key) / providingComponent.Value; } } return(amount + inventory.GetItemAmount(contentId)); } else { Clear(); inventory.CountItems(m_componentCounts); AddItem(group.Id, amount, int.MaxValue); Solve(m_componentCounts); return(GetSolvedItemCount()); } }
void MyGasTank_ContentsChanged(MyInventoryBase obj) { if (m_autoRefill && CanRefill()) { RefillBottles(); } }
public MyFixedPoint GetItemAmountCombined(MyInventoryBase inventory, MyDefinitionId contentId) { int amount = 0; var group = MyDefinitionManager.Static.GetGroupForComponent(contentId, out amount); if (group == null) { MyComponentSubstitutionDefinition substitutions; if (MyDefinitionManager.Static.TryGetComponentSubstitutionDefinition(contentId, out substitutions)) { foreach (var providingComponent in substitutions.ProvidingComponents) { amount += (int)inventory.GetItemAmount(providingComponent.Key) / providingComponent.Value; } return amount; } return inventory.GetItemAmount(contentId); } else { Clear(); inventory.CountItems(m_componentCounts); AddItem(group.Id, amount, int.MaxValue); Solve(m_componentCounts); return GetSolvedItemCount(); } }
/// <summary> /// Search for inventory component with maching index. /// </summary> public static MyInventory GetInventory(this MyEntity thisEntity, int index = 0) { MyInventoryBase foundInventoryBase = thisEntity.GetInventoryBase(index); MyInventory rtnInventory = foundInventoryBase as MyInventory; return(rtnInventory); }
private bool GrinderFull() { if (Globals.UpdateCount < m_nextGrinderCheck) { return(m_grinderFull); } m_nextGrinderCheck = Globals.UpdateCount + 100ul; EnableGrinders(m_enabledGrinders); MyFixedPoint content = 0, capacity = 0; int grinderCount = 0; foreach (IMyShipGrinder grinder in CubeGridCache.GetFor(m_controlBlock.CubeGrid).BlocksOfType(typeof(MyObjectBuilder_ShipGrinder))) { MyInventoryBase grinderInventory = ((MyEntity)grinder).GetInventoryBase(0); content += grinderInventory.CurrentVolume; capacity += grinderInventory.MaxVolume; grinderCount++; } m_grinderFull = capacity <= 0 || (float)content / (float)capacity >= 0.9f; return(m_grinderFull); }
public void SubscribeInventory(MyInventoryBase inventory) { try { if (inventory is MyInventoryAggregate agg) { foreach (MyInventory i in agg.ChildList.Reader) { if (i == null) { continue; } inventories.Add(i); if (MyExternalReplicable.FindByObject(i) is InventoryReplicable replicable) { replicable.Refresh(); } } } else if (inventory is MyInventory i) { inventories.Add(i); if (MyExternalReplicable.FindByObject(i) is InventoryReplicable replicable) { replicable.Refresh(); } } } catch (Exception e) { Plugin.Error("Subscription error", e); } }
public GuidedMissileLauncher(WeaponTargeting weapon) { m_weaponTarget = weapon; m_relayPart = RelayClient.GetOrCreateRelayPart(m_weaponTarget.CubeBlock); this._initialTarget = NoTarget.Instance; MyWeaponBlockDefinition defn = (MyWeaponBlockDefinition)CubeBlock.GetCubeBlockDefinition(); Vector3[] points = new Vector3[3]; Vector3 forwardAdjust = Vector3.Forward * WeaponDescription.GetFor(CubeBlock).MissileSpawnForward; points[0] = CubeBlock.LocalAABB.Min + forwardAdjust; points[1] = CubeBlock.LocalAABB.Max + forwardAdjust; points[2] = CubeBlock.LocalAABB.Min + Vector3.Up * defn.Size.Y * CubeBlock.CubeGrid.GridSize + forwardAdjust; MissileSpawnBox = BoundingBox.CreateFromPoints(points); if (m_weaponTarget.myTurret != null) { Log.TraceLog("original box: " + MissileSpawnBox); MissileSpawnBox.Inflate(CubeBlock.CubeGrid.GridSize * 2f); } Log.TraceLog("MissileSpawnBox: " + MissileSpawnBox); myInventory = ((MyEntity)CubeBlock).GetInventoryBase(0); Registrar.Add(weapon.CubeBlock, this); m_weaponTarget.GuidedLauncher = true; m_gameCooldownTime = TimeSpan.FromSeconds(60d / MyDefinitionManager.Static.GetWeaponDefinition(defn.WeaponDefinitionId).WeaponAmmoDatas[(int)MyAmmoType.Missile].RateOfFire); Log.TraceLog("m_gameCooldownTime: " + m_gameCooldownTime); CubeBlock.AppendingCustomInfo += CubeBlock_AppendingCustomInfo; }
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; } } }
public bool CanContinueBuild(MyInventoryBase inventory, MyConstructionStockpile stockpile) { if (IsFullIntegrity) { return(false); } float topIntegrity = GetTopComponentIntegrity(); if (topIntegrity < m_blockDefinition.Components[m_topGroupIndex].Definition.MaxIntegrity) { return(true); } int nextCompoGroup = m_topGroupIndex; if (m_topComponentIndex == m_blockDefinition.Components[nextCompoGroup].Count - 1) { nextCompoGroup++; } var componentDefinition = m_blockDefinition.Components[nextCompoGroup].Definition; if (stockpile != null && stockpile.GetItemAmount(componentDefinition.Id) > 0) { return(true); } if (inventory != null && MyCubeBuilder.BuildComponent.GetItemAmountCombined(inventory, componentDefinition.Id) > 0) { return(true); } return(false); }
public override void OnAddedToScene() { base.OnAddedToScene(); if (_definition == null) { return; } _inventory = this.Get <MyInventoryBase>(_definition.Inventory) ?? this.Get <MyInventoryBase>(); MrzUtils.ShowNotificationDebug($"InvInteraction::Inventory {_inventory}"); var useObjComp = this.Get <MyUseObjectsComponentBase>(); if (useObjComp == null) { return; } var useObject = useObjComp.GetInteractiveObject("Generic"); _useObj = useObject as MyUseObjectGeneric; if (_useObj == null) { return; } _useObj.Interface = this; }
public static MyInventoryBase GetInventory(this MyEntity entity, MyStringHash inventoryId) { MyInventoryBase inventory = null; inventory = entity.Components.Get <MyInventoryBase>(); if (inventory != null) { if (inventoryId.Equals(MyStringHash.GetOrCompute(inventory.InventoryId.ToString()))) { return(inventory); } } if (inventory is MyInventoryAggregate) { var aggregate = inventory as MyInventoryAggregate; m_tmpList.Clear(); aggregate.GetComponentsFlattened(m_tmpList); foreach (var component in m_tmpList) { var componentInventory = component as MyInventoryBase; if (inventoryId.Equals(MyStringHash.GetOrCompute(componentInventory.InventoryId.ToString()))) { return(componentInventory); } } } return(null); }
private void OnContentsChanged(MyInventoryBase inv, MyPhysicalInventoryItem item, MyFixedPoint amount) { BetterInventoryItem cachedItem; if (!Session.BlockInventoryItems[BlockInventory].TryGetValue(item.ItemId, out cachedItem)) { cachedItem = Session.BetterInventoryItems.Get(); cachedItem.Amount = (int)amount; cachedItem.Content = item.Content; cachedItem.Item = item; Session.BlockInventoryItems[BlockInventory].TryAdd(item.ItemId, cachedItem); } else if (cachedItem.Amount + amount > 0) { cachedItem.Amount += (int)amount; } else if (cachedItem.Amount + amount <= 0) { BetterInventoryItem removedItem; if (Session.BlockInventoryItems[BlockInventory].TryRemove(item.ItemId, out removedItem)) { Session.BetterInventoryItems.Return(removedItem); } } if (Session.IsServer && amount <= 0) { for (int i = 0; i < Platform.Weapons.Length; i++) { Platform.Weapons[i].CheckInventorySystem = true; } } }
private void inventory_OnContentsChanged(MyInventoryBase inv) { if (!this.m_processingLock && Sync.IsServer) { this.m_queueNeedsRebuild = true; } }
public override bool TransferItemsFrom(MyInventoryBase sourceInventory, MyInventoryItem item, int amount) { if (sourceInventory == null || item == null || amount > item.Amount) { return(false); } if (amount == 0) { return(true); } var limitedItem = amount < item.Amount ? item.Clone(amount) : item; if (!CanAddItems(item.DefinitionId, amount) && this != sourceInventory) { return(false); } if (this == sourceInventory) { return(sourceInventory.Remove(item, amount) && Add(limitedItem)); } if (!Add(limitedItem)) { return(false); } if (sourceInventory.Remove(item, amount)) { return(true); } Remove(item, amount); return(false); }
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); } }
public override MyInventoryBase IterateInventory(int searchIndex, int currentIndex) { using (List <MyComponentBase> .Enumerator enumerator = this.ChildList.Reader.GetEnumerator()) { while (true) { if (!enumerator.MoveNext()) { break; } MyInventoryBase current = enumerator.Current as MyInventoryBase; if (current != null) { MyInventoryBase base3 = current.IterateInventory(searchIndex, currentIndex); if (base3 == null) { if (!(current is MyInventory)) { continue; } currentIndex++; continue; } return(base3); } } } return(null); }
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; } } }
public override bool PasteGrid(MyInventoryBase buildInventory = null, bool deactivate = true) { if ((CopiedGrids.Count > 0) && !IsActive) { Activate(); return(true); } if (!m_canBePlaced) { MyGuiAudio.PlaySound(MyGuiSounds.HudUnable); return(false); } if (PreviewGrids.Count == 0) { return(false); } bool result; bool placingOnDynamicGrid = RemoveBlock != null && !RemoveBlock.CubeGrid.IsStatic; if (MyCubeBuilder.Static.DynamicMode || placingOnDynamicGrid) { result = PasteGridsInDynamicMode(buildInventory, deactivate); } else { result = PasteGridsInStaticMode(buildInventory, deactivate); } return(result); }
private void OnContentsChanged(MyInventoryBase inv, MyPhysicalInventoryItem item, MyFixedPoint amount) { if (!Registered) { return; } BetterInventoryItem cachedItem; if (!Session.BlockInventoryItems[BlockInventory].TryGetValue(item.ItemId, out cachedItem)) { cachedItem = Session.BetterInventoryItems.Get(); cachedItem.Amount = (int)amount; cachedItem.Content = item.Content; cachedItem.Item = item; Session.BlockInventoryItems[BlockInventory].TryAdd(item.ItemId, cachedItem); } else if (cachedItem.Amount + amount > 0) { cachedItem.Amount += (int)amount; } else if (cachedItem.Amount + amount <= 0) { BetterInventoryItem removedItem; if (Session.BlockInventoryItems[BlockInventory].TryRemove(item.ItemId, out removedItem)) { Session.BetterInventoryItems.Return(removedItem); } } }
private void Inventory_ContentChangedCallback(MyInventoryBase inventory) { if (Sync.IsServer) { base.NeedsUpdate |= MyEntityUpdateEnum.BEFORE_NEXT_FRAME; } }
private void OutputInventory_ContentsChanged(MyInventoryBase inventory) { if (DisassembleEnabled && RepeatEnabled && Sync.IsServer) { RebuildQueueInRepeatDisassembling(); } }
private bool FindSource() { // don't look for a source if we already have one if (_sourceInventory != null) { return(true); } var grid = _block.GridData; if (grid == null) { return(false); } var hierarchy = grid.Get <MyGridHierarchyComponent>(); if (hierarchy == null) { return(false); } var neighbours = new List <MyBlock>(); grid.GetBlocksInRange(_block.Block.Position - Vector3I.One, _block.Block.Position + Vector3I.One, neighbours); if (neighbours.Count == 0) { return(false); } MyEntity sourceBlock = null; foreach (var entry in neighbours) { sourceBlock = hierarchy.GetBlockEntity(entry.Id); if (sourceBlock == null) { continue; } break; } if (sourceBlock == null) { return(false); } _sourceInventory = sourceBlock.Components.Get <MyInventoryBase>(); if (_sourceInventory == null) { return(false); } _sourceInventory.BeforeRemovedFromContainer += OnBeforeRemovedFromContainer; _sourceInventory.ContentsChanged += OnSourceItemsChanged; return(true); }
protected internal void RemoveItemsCombined(MyInventoryBase inventory, int itemAmount, MyDefinitionId itemDefinitionId) { m_materialList.Clear(); m_materialList.AddMaterial(itemDefinitionId, itemAmount); m_componentCombiner.RemoveItemsCombined(inventory, m_materialList.TotalMaterials); m_materialList.Clear(); return; }
protected override void OnInventoryComponentAdded(MyInventoryBase inventory) { base.OnInventoryComponentAdded(inventory); if (this.GetInventory(0) != null) { this.GetInventory(0).ContentsChanged += new Action <MyInventoryBase>(this.Inventory_ContentChangedCallback); } }
private void inventory_OnContentsChanged(MyInventoryBase inv) { if (m_processingLock) return; if (Sync.IsServer) m_queueNeedsRebuild = true; }
protected override void OnInventoryComponentAdded(MyInventoryBase inventory) { base.OnInventoryComponentAdded(inventory); if ((this.GetInventory(0) != null) && MyPerGameSettings.InventoryMass) { this.GetInventory(0).ContentsChanged += new Action <MyInventoryBase>(this.Inventory_ContentsChanged); } }
private void inventory_OnContentsChanged(MyInventoryBase obj) { RefreshInventoryContents(); if (InventoryContentsChanged != null) { InventoryContentsChanged(this); } }
void InputInventory_ContentsChanged(MyInventoryBase obj) { if (CurrentAssemblerMode == AssemblerMode.Assembling) { RefreshBlueprintGridColors(); } RefreshMaterialsPreview(); }
internal void RemoveItemsCombined(MyInventoryBase inventory, int itemAmount, MyDefinitionId itemDefinitionId) { m_materialList.Clear(); m_materialList.AddMaterial(itemDefinitionId, itemAmount); m_componentCombiner.RemoveItemsCombined(inventory, m_materialList.TotalMaterials); m_materialList.Clear(); return; }
public static void DeconstructStockpile( this MySlimBlock self, float deconstructAmount, MyInventoryBase outputInventory, bool useDefaultDeconstructEfficiency = false) { MethodDelegateInstance(self, deconstructAmount, outputInventory, useDefaultDeconstructEfficiency); }
public static void MoveAllContentsTo(this MyInventory fromInventory, MyInventoryBase toInventory) { foreach (var item in fromInventory.GetItems()) { toInventory.AddItems(item.Amount, item.Content); } fromInventory.Clear(); }
public MyFixedPoint GetItemAmountCombined(MyInventoryBase inventory, MyDefinitionId contentId) { int amount = 0; var group = MyDefinitionManager.Static.GetGroupForComponent(contentId, out amount); if (group == null) { return inventory.GetItemAmount(contentId); } else { Clear(); inventory.CountItems(m_componentCounts); AddItem(group.Id, amount, int.MaxValue); Solve(m_componentCounts); return GetSolvedItemCount(); } }
void InventoryChanged(MyInventoryBase obj) { if (m_clientInventoryUpdate == null) { return; } foreach (var clientData in m_clientInventoryUpdate) { m_clientInventoryUpdate[clientData.Key].Dirty = true; m_clientInventoryUpdate[clientData.Key].MainSendingInfo.StartItemIndex = 0; m_clientInventoryUpdate[clientData.Key].MainSendingInfo.NumItems = 0; //when sending inventory over again don't care about old messages //inventory will be overwritten; m_clientInventoryUpdate[clientData.Key].SendPackets.Clear(); m_clientInventoryUpdate[clientData.Key].FailedIncompletePackets.Clear(); } }
public static void SetBlockComponents(MyHudBlockInfo hudInfo, MySlimBlock block, MyInventoryBase availableInventory = null) { hudInfo.Components.Clear(); for (int i = 0; i < block.ComponentStack.GroupCount; i++) { var groupInfo = block.ComponentStack.GetGroupInfo(i); var componentInfo = new MyHudBlockInfo.ComponentInfo(); componentInfo.DefinitionId = groupInfo.Component.Id; componentInfo.ComponentName = groupInfo.Component.DisplayNameText; componentInfo.Icon = groupInfo.Component.Icon; componentInfo.TotalCount = groupInfo.TotalCount; componentInfo.MountedCount = groupInfo.MountedCount; if (availableInventory != null) componentInfo.AvailableAmount = (int)availableInventory.GetItemAmount(groupInfo.Component.Id); hudInfo.Components.Add(componentInfo); } if (!block.StockpileEmpty) { // For each component foreach (var comp in block.BlockDefinition.Components) { // Get amount in stockpile int amount = block.GetConstructionStockpileItemAmount(comp.Definition.Id); for (int i = 0; amount > 0 && i < hudInfo.Components.Count; i++) { if (block.ComponentStack.GetGroupInfo(i).Component == comp.Definition) { if (block.ComponentStack.IsFullyDismounted) { return; } // Distribute amount in stockpile from bottom to top var info = hudInfo.Components[i]; int space = info.TotalCount - info.MountedCount; int movedItems = Math.Min(space, amount); info.StockpileCount = movedItems; amount -= movedItems; hudInfo.Components[i] = info; } } } } }
public void DecreaseMountLevel(float grinderAmount, MyInventoryBase outputInventory) { if (FatBlock != null) grinderAmount /= FatBlock.DisassembleRatio; else grinderAmount /= BlockDefinition.DisassembleRatio; grinderAmount = grinderAmount * BlockDefinition.IntegrityPointsPerSec; if (MySession.Static.CreativeMode) { ClearConstructionStockpile(outputInventory); } else { EnsureConstructionStockpileExists(); } float oldBuildRatio = m_componentStack.BuildRatio; float newBuildRatio = (BuildIntegrity - grinderAmount) / BlockDefinition.MaxIntegrity; if (BlockDefinition.RatioEnoughForOwnership(BuildLevelRatio) && !BlockDefinition.RatioEnoughForOwnership(newBuildRatio)) { if (FatBlock != null) { FatBlock.OnIntegrityChanged(BuildIntegrity, Integrity, false, MySession.LocalPlayerId); } } long toolOwner = 0; if (outputInventory != null && outputInventory.Entity != null) { var inventoryOwner = outputInventory.Entity; var moduleOwner = inventoryOwner as IMyComponentOwner<MyIDModule>; var character = inventoryOwner as MyCharacter; if (moduleOwner == null) { if (character != null) { Debug.Assert(character.ControllerInfo.Controller != null, "Controller was null on the character in DecreaseMountLevel!"); if (character.ControllerInfo.Controller == null) toolOwner = character.ControllerInfo.ControllingIdentityId; } } else { MyIDModule module; if (moduleOwner.GetComponent(out module)) toolOwner = module.Owner; } } UpdateHackingIndicator(newBuildRatio, oldBuildRatio, toolOwner); if (m_stockpile != null) { m_stockpile.ClearSyncList(); m_componentStack.DecreaseMountLevel(grinderAmount, m_stockpile); CubeGrid.SyncObject.SendStockpileChanged(this, m_stockpile.GetSyncList()); m_stockpile.ClearSyncList(); } else { m_componentStack.DecreaseMountLevel(grinderAmount, null); } bool modelChangeNeeded = BlockDefinition.ModelChangeIsNeeded(m_componentStack.BuildRatio, oldBuildRatio); MyCubeGrid.MyIntegrityChangeEnum integrityChangeType = MyCubeGrid.MyIntegrityChangeEnum.Damage; if (modelChangeNeeded) { UpdateVisual(); if (FatBlock != null) { int buildProgressID = CalculateCurrentModelID(); if ((buildProgressID == -1) || (BuildLevelRatio == 0f)) { integrityChangeType = MyCubeGrid.MyIntegrityChangeEnum.ConstructionEnd; } else if (buildProgressID == BlockDefinition.BuildProgressModels.Length - 1) { integrityChangeType = MyCubeGrid.MyIntegrityChangeEnum.ConstructionBegin; } else { integrityChangeType = MyCubeGrid.MyIntegrityChangeEnum.ConstructionProcess; } } PlayConstructionSound(integrityChangeType, true); CreateConstructionSmokes(); } if (CubeGrid.GridSystems.OxygenSystem != null) { CubeGrid.GridSystems.OxygenSystem.Pressurize(); } if (MyFakes.ENABLE_GENERATED_BLOCKS && !BlockDefinition.IsGeneratedBlock && BlockDefinition.GeneratedBlockDefinitions != null && BlockDefinition.GeneratedBlockDefinitions.Length > 0) { UpdateProgressGeneratedBlocks(oldBuildRatio); } CubeGrid.SyncObject.SendIntegrityChanged(this, integrityChangeType, toolOwner); }
public void IncreaseMountLevel(float welderMountAmount, long welderOwnerPlayerId, MyInventoryBase outputInventory = null, float maxAllowedBoneMovement = 0.0f, bool isHelping = false, MyOwnershipShareModeEnum sharing = MyOwnershipShareModeEnum.Faction) { ProfilerShort.Begin("MySlimBlock.IncreaseMountLevel"); welderMountAmount *= BlockDefinition.IntegrityPointsPerSec; MySession.Static.PositiveIntegrityTotal += welderMountAmount; if (MySession.Static.CreativeMode) { ClearConstructionStockpile(outputInventory); } else { IMyInventoryOwner inventoryOwner = null; if (outputInventory != null && outputInventory.Container != null) inventoryOwner = outputInventory.Container.Entity as IMyInventoryOwner; if (inventoryOwner != null && inventoryOwner.InventoryOwnerType == MyInventoryOwnerTypeEnum.Character) { MoveItemsFromConstructionStockpile(outputInventory, MyItemFlags.Damaged); } } float oldPercentage = m_componentStack.BuildRatio; float oldDamage = CurrentDamage; if (!BlockDefinition.RatioEnoughForOwnership(BuildLevelRatio) && BlockDefinition.RatioEnoughForOwnership((BuildIntegrity + welderMountAmount) / BlockDefinition.MaxIntegrity)) { if (FatBlock != null && outputInventory != null && !isHelping) { FatBlock.OnIntegrityChanged(BuildIntegrity, Integrity, true, welderOwnerPlayerId, sharing); } } if (MyFakes.SHOW_DAMAGE_EFFECTS && FatBlock != null && !BlockDefinition.RationEnoughForDamageEffect((Integrity+welderMountAmount) / MaxIntegrity)) {//stop effect FatBlock.SetDamageEffect(false); } bool removeDecals = false; if (m_stockpile != null) { m_stockpile.ClearSyncList(); m_componentStack.IncreaseMountLevel(welderMountAmount, m_stockpile); CubeGrid.SyncObject.SendStockpileChanged(this, m_stockpile.GetSyncList()); m_stockpile.ClearSyncList(); } else { m_componentStack.IncreaseMountLevel(welderMountAmount, null); } if (m_componentStack.IsFullIntegrity) { ReleaseConstructionStockpile(); removeDecals = true; } ProfilerShort.Begin("ModelChange"); MyCubeGrid.MyIntegrityChangeEnum integrityChangeType = MyCubeGrid.MyIntegrityChangeEnum.Damage; if (BlockDefinition.ModelChangeIsNeeded(oldPercentage, m_componentStack.BuildRatio) || BlockDefinition.ModelChangeIsNeeded(m_componentStack.BuildRatio, oldPercentage)) { removeDecals = true; if (FatBlock != null) { // this needs to be detected here because for cubes the following call to UpdateVisual() set FatBlock to null when the construction is complete if (m_componentStack.IsFunctional) { integrityChangeType = MyCubeGrid.MyIntegrityChangeEnum.ConstructionEnd; } } UpdateVisual(); if (FatBlock != null) { int buildProgressID = CalculateCurrentModelID(); if (buildProgressID == 0) { integrityChangeType = MyCubeGrid.MyIntegrityChangeEnum.ConstructionBegin; } else if (!m_componentStack.IsFunctional) { integrityChangeType = MyCubeGrid.MyIntegrityChangeEnum.ConstructionProcess; } } PlayConstructionSound(integrityChangeType); CreateConstructionSmokes(); if (CubeGrid.GridSystems.OxygenSystem != null) { CubeGrid.GridSystems.OxygenSystem.Pressurize(); } } ProfilerShort.End(); if (HasDeformation) CubeGrid.SetBlockDirty(this); if (removeDecals) CubeGrid.RenderData.RemoveDecals(Position); CubeGrid.SyncObject.SendIntegrityChanged(this, integrityChangeType, 0); if (maxAllowedBoneMovement != 0.0f) FixBones(oldDamage, maxAllowedBoneMovement); if (MyFakes.ENABLE_GENERATED_BLOCKS && !BlockDefinition.IsGeneratedBlock && BlockDefinition.GeneratedBlockDefinitions != null && BlockDefinition.GeneratedBlockDefinitions.Length > 0) { UpdateProgressGeneratedBlocks(oldPercentage); } ProfilerShort.End(); }
public virtual bool PasteGrid(MyInventoryBase buildInventory = null, bool deactivate = true) { return PasteGridInternal(buildInventory, deactivate); }
/*void damageEffect_OnDelete(object sender, EventArgs e) { m_damageEffect = null; }*/ void inventory_ContentsChanged(MyInventoryBase obj) { var before = IsWorking; RefreshRemainingCapacity(); if (!before && IsWorking) OnStartWorking(); else if (before && !IsWorking) OnStopWorking(); }
protected bool PasteGridInternal(MyInventoryBase buildInventory, bool deactivate, List<MyObjectBuilder_CubeGrid> pastedBuilders = null, List<MyCubeGrid> touchingGrids = null, UpdateAfterPasteCallback updateAfterPasteCallback = null) { if (m_copiedGrids.Count == 0) return false; if ((m_copiedGrids.Count > 0) && !IsActive) { Activate(); return true; } if (!CanBePlaced) { MyGuiAudio.PlaySound(MyGuiSounds.HudUnable); return false; } if (m_previewGrids.Count == 0) return false; bool missingBlockDefinitions = !CheckPastedBlocks(); if (missingBlockDefinitions) { AllowSwitchCameraMode = false; var messageBox = MyGuiSandbox.CreateMessageBox( buttonType: MyMessageBoxButtonsType.YES_NO, messageText: MyTexts.Get(MySpaceTexts.MessageBoxTextDoYouWantToPasteGridWithMissingBlocks), messageCaption: MyTexts.Get(MySpaceTexts.MessageBoxCaptionWarning), callback: (result) => { if (result == MyGuiScreenMessageBox.ResultEnum.YES) { PasteInternal(buildInventory, missingBlockDefinitions, deactivate, pastedBuilders, updateAfterPasteCallback: updateAfterPasteCallback); } AllowSwitchCameraMode = true; }); MyGuiSandbox.AddScreen(messageBox); return false; } return PasteInternal(buildInventory, missingBlockDefinitions, deactivate, pastedBuilders: pastedBuilders, touchingGrids: touchingGrids, updateAfterPasteCallback: updateAfterPasteCallback); }
public void MoveUnneededItemsFromConstructionStockpile(MyInventoryBase toInventory) { if (m_stockpile == null) return; Debug.Assert(toInventory != null); if (toInventory == null) return; m_tmpItemList.Clear(); AcquireUnneededStockpileItems(m_tmpItemList); m_stockpile.ClearSyncList(); foreach (var item in m_tmpItemList) { var amount = (int)toInventory.ComputeAmountThatFits(item.Content.GetId()); amount = Math.Min(amount, item.Amount); toInventory.AddItems(amount, item.Content); m_stockpile.RemoveItems(amount, item.Content); } CubeGrid.SyncObject.SendStockpileChanged(this, m_stockpile.GetSyncList()); m_stockpile.ClearSyncList(); }
void m_ammoInventory_ContentsChanged(MyInventoryBase obj) { m_gunBase.RefreshAmmunitionAmount(); }
internal static void SendTransferItemsMessage(MyInventoryBase sourceInventory, MyInventoryBase destinationInventory, IMyInventoryItem item, MyFixedPoint amount) { if (sourceInventory == null || destinationInventory == null || item == null) { Debug.Fail("Invalid parameters!"); return; } Debug.Assert(amount > 0, "Amount is <= 0! Sending meaningless message! Don't call this if transferring amount is 0"); var msg = new TransferItemsBaseMsg(); msg.Amount = amount; msg.SourceContainerId = sourceInventory.Container.Entity.EntityId; msg.DestinationContainerId = destinationInventory.Container.Entity.EntityId; msg.SourceItemId = item.ItemId; msg.SourceInventoryId = MyStringHash.GetOrCompute(sourceInventory.InventoryId.ToString()); msg.DestinationInventoryId = MyStringHash.GetOrCompute(destinationInventory.InventoryId.ToString()); Sync.Layer.SendMessageToServer(ref msg); }
private bool PasteGridsInStaticMode(MyInventoryBase buildInventory, bool deactivate) { MatrixD firstGridMatrix = GetFirstGridOrientationMatrix(); MatrixD inverseFirstGridMatrix = Matrix.Invert(firstGridMatrix); List<MatrixD> previewMatrices = new List<MatrixD>(); foreach (var previewGrid in PreviewGrids) previewMatrices.Add(previewGrid.WorldMatrix); { // First grid is forced static MyObjectBuilder_CubeGrid originalCopiedGrid = CopiedGrids[0]; MatrixD previewGridWorldMatrix = PreviewGrids[0].WorldMatrix; // Convert grid builder to static ConvertGridBuilderToStatic(originalCopiedGrid, previewGridWorldMatrix); PreviewGrids[0].WorldMatrix = MatrixD.CreateTranslation(previewGridWorldMatrix.Translation); } for (int i = 1; i < CopiedGrids.Count; ++i) { if (CopiedGrids[i].IsStatic) { MyObjectBuilder_CubeGrid originalCopiedGrid = CopiedGrids[i]; MatrixD previewGridWorldMatrix = PreviewGrids[i].WorldMatrix; // Convert grid builder to static ConvertGridBuilderToStatic(originalCopiedGrid, previewGridWorldMatrix); PreviewGrids[i].WorldMatrix = MatrixD.CreateTranslation(previewGridWorldMatrix.Translation); } } // All static grids has been reset to default rotation, builders will be set from paste. List<MyObjectBuilder_CubeGrid> pastedBuilders = new List<MyObjectBuilder_CubeGrid>(); bool result = PasteGridInternal(buildInventory: buildInventory, deactivate: true, pastedBuilders: pastedBuilders, touchingGrids: m_touchingGrids, updateAfterPasteCallback: delegate(List<MyObjectBuilder_CubeGrid> pastedBuildersInCallback) { UpdateAfterPaste(deactivate, pastedBuildersInCallback); }); if (result) { UpdateAfterPaste(deactivate, pastedBuilders); } return result; }
private bool PasteGridsInDynamicMode(MyInventoryBase buildInventory, bool deactivate) { bool result; // Remember static grid flag and set it to dynamic List<bool> gridStaticFlags = new List<bool>(); foreach (var copiedGrid in CopiedGrids) { gridStaticFlags.Add(copiedGrid.IsStatic); copiedGrid.IsStatic = false; } result = PasteGridInternal(buildInventory: buildInventory, deactivate: deactivate); // Set static grid flag back for (int i = 0; i < CopiedGrids.Count; ++i) CopiedGrids[i].IsStatic = gridStaticFlags[i]; return result; }
public override bool PasteGrid(MyInventoryBase buildInventory = null, bool deactivate = true) { if ((CopiedGrids.Count > 0) && !IsActive) { Activate(); return true; } if (!m_canBePlaced) { MyGuiAudio.PlaySound(MyGuiSounds.HudUnable); return false; } if (PreviewGrids.Count == 0) return false; bool result; bool isSnappedOnGrid = (m_hitEntity is MyCubeGrid) && IsSnapped && SnapMode == MyGridPlacementSettings.SnapMode.Base6Directions; bool placingDynamicGrid = !CopiedGrids[0].IsStatic && !isSnappedOnGrid; bool placingOnDynamicGrid = (m_hitEntity is MyCubeGrid) && !((MyCubeGrid)m_hitEntity).IsStatic && !MyCubeBuilder.Static.DynamicMode; if (MyCubeBuilder.Static.DynamicMode) { result = PasteGridsInDynamicMode(buildInventory, deactivate); } else if (placingDynamicGrid || placingOnDynamicGrid) { result = PasteGridInternal(buildInventory: buildInventory, deactivate: deactivate); } else { result = PasteGridsInStaticMode(buildInventory, deactivate); } return result; }
public void MoveItemsToConstructionStockpile(MyInventoryBase fromInventory) { if (MySession.Static.CreativeMode || MySession.Static.SimpleSurvival) return; m_tmpComponents.Clear(); GetMissingComponents(m_tmpComponents); if (m_tmpComponents.Count() != 0) { EnsureConstructionStockpileExists(); m_stockpile.ClearSyncList(); foreach (var kv in m_tmpComponents) { var id = new MyDefinitionId(typeof(MyObjectBuilder_Component), kv.Key); int amountAvailable = (int)fromInventory.GetItemAmount(id); int moveAmount = Math.Min(kv.Value, amountAvailable); if (moveAmount > 0) { fromInventory.RemoveItemsOfType(moveAmount, id); m_stockpile.AddItems(moveAmount, new MyDefinitionId(typeof(MyObjectBuilder_Component), kv.Key)); } } CubeGrid.SyncObject.SendStockpileChanged(this, m_stockpile.GetSyncList()); m_stockpile.ClearSyncList(); } }
private void OutputInventory_ContentsChanged(MyInventoryBase inventory) { if (DisassembleEnabled && RepeatEnabled && Sync.IsServer) RebuildQueueInRepeatDisassembling(); }
/// <summary> /// Moves items with the given flags from the construction inventory to the character. /// If the flags are None, all items are moved. /// </summary> public void MoveItemsFromConstructionStockpile(MyInventoryBase toInventory, MyItemFlags flags = MyItemFlags.None) { if (m_stockpile == null) return; Debug.Assert(toInventory != null); if (toInventory == null) return; m_tmpItemList.Clear(); foreach (var item in m_stockpile.GetItems()) { if (flags == MyItemFlags.None || (item.Content.Flags & flags) != 0) m_tmpItemList.Add(item); } m_stockpile.ClearSyncList(); foreach (var item in m_tmpItemList) { var amount = (int)toInventory.ComputeAmountThatFits(item.Content.GetId()); amount = Math.Min(amount, item.Amount); toInventory.AddItems(amount, item.Content); m_stockpile.RemoveItems(amount, item.Content); } CubeGrid.SyncObject.SendStockpileChanged(this, m_stockpile.GetSyncList()); m_stockpile.ClearSyncList(); }
private void inventory_OnContentsChanged(MyInventoryBase obj) { RefreshInventoryContents(); if (InventoryContentsChanged != null) InventoryContentsChanged(this); }
public void ClearConstructionStockpile(MyInventoryBase outputInventory) { if (!StockpileEmpty) { IMyInventoryOwner inventoryOwner = null; if (outputInventory != null && outputInventory.Container != null) inventoryOwner = outputInventory.Container.Entity as IMyInventoryOwner; if (inventoryOwner != null && inventoryOwner.InventoryOwnerType == MyInventoryOwnerTypeEnum.Character) { MoveItemsFromConstructionStockpile(outputInventory); } else { m_stockpile.ClearSyncList(); m_tmpItemList.Clear(); foreach (var item in m_stockpile.GetItems()) { m_tmpItemList.Add(item); } foreach (var item in m_tmpItemList) { RemoveFromConstructionStockpile(item); } CubeGrid.SyncObject.SendStockpileChanged(this, m_stockpile.GetSyncList()); m_stockpile.ClearSyncList(); } } ReleaseConstructionStockpile(); }
void InputInventory_ContentsChanged(MyInventoryBase obj) { if (CurrentAssemblerMode == AssemblerMode.Assembling) RefreshBlueprintGridColors(); RefreshMaterialsPreview(); }
/// <summary> /// Transfers safely given item from inventory given as parameter to this instance. /// </summary> /// <returns>true if items were succesfully transfered, otherwise, false</returns> public override bool TransferItemsFrom(MyInventoryBase sourceInventory, IMyInventoryItem item, MyFixedPoint amount) { if (sourceInventory == null) { System.Diagnostics.Debug.Fail("Source inventory is null!"); return false; } if (item == null) { System.Diagnostics.Debug.Fail("Item is null!"); return false; } if (amount == 0) { return true; } bool transfered = false; if ((ItemsCanBeAdded(amount, item) || this == sourceInventory) && sourceInventory.ItemsCanBeRemoved(amount, item)) { if (Sync.IsServer) { if (this != sourceInventory) { // try to add first and then remove to ensure this items don't disappear if (Add(item, amount)) { if (sourceInventory.Remove(item, amount)) { // successfull transaction return true; } else { // This can happend, that it can't be removed due to some lock, then we need to revert the add. Remove(item, amount); } } } else { // same inventory transfer = splitting amount, need to remove first and add second if (sourceInventory.Remove(item, amount) && Add(item, amount)) { return true; } else { System.Diagnostics.Debug.Fail("Error! Unsuccesfull splitting!"); } } } else { Debug.Assert(sourceInventory != null); MyInventoryTransferEventContent eventParams = new MyInventoryTransferEventContent(); eventParams.Amount = amount; eventParams.ItemId = item.ItemId; eventParams.SourceOwnerId = sourceInventory.Entity.EntityId; eventParams.SourceInventoryId = sourceInventory.InventoryId; eventParams.DestinationOwnerId = Entity.EntityId; MyMultiplayer.RaiseStaticEvent(s => InventoryBaseTransferItem_Implementation, eventParams); } } return transfered; }
void OutputInventory_ContentsChanged(MyInventoryBase obj) { RefreshInventory(); RefreshMaterialsPreview(); }
public void CharacterInventory_OnContentsChanged(MyInventoryBase inventory) { Update(); }
internal MyFixedPoint GetItemAmountCombined(MyInventoryBase availableInventory, MyDefinitionId myDefinitionId) { return m_componentCombiner.GetItemAmountCombined(availableInventory, myDefinitionId); }
private void Inventory_ContentChangedCallback(MyInventoryBase inventory) { if (!Sync.IsServer) return; NeedsUpdate |= MyEntityUpdateEnum.BEFORE_NEXT_FRAME; }
private bool PasteInternal(MyInventoryBase buildInventory, bool missingDefinitions, bool deactivate, List<MyObjectBuilder_CubeGrid> pastedBuilders = null, List<MyCubeGrid> touchingGrids = null, UpdateAfterPasteCallback updateAfterPasteCallback = null) { MyGuiAudio.PlaySound(MyGuiSounds.HudPlaceBlock); MyEntities.RemapObjectBuilderCollection(m_copiedGrids); m_tmpPastedBuilders.Clear(); m_tmpPastedBuilders.Capacity = m_copiedGrids.Count; MyCubeGrid firstPastedGrid = null; bool forceDynamicGrid = IsForcedDynamic() && !m_gridChangeToDynamicDisabled; int i = 0; bool retVal = false; List<MyCubeGrid> pastedGrids = new List<MyCubeGrid>(); foreach (var gridBuilder in m_copiedGrids) { gridBuilder.CreatePhysics = true; gridBuilder.EnableSmallToLargeConnections = true; bool savedStaticFlag = gridBuilder.IsStatic; if (forceDynamicGrid) { gridBuilder.IsStatic = false; } var previousPos = gridBuilder.PositionAndOrientation; gridBuilder.PositionAndOrientation = new MyPositionAndOrientation(m_previewGrids[i].WorldMatrix); var pastedGrid = MyEntities.CreateFromObjectBuilder(gridBuilder) as MyCubeGrid; if (pastedGrid == null) { retVal = true; continue; } if (MySession.Static.EnableStationVoxelSupport && pastedGrid.IsStatic) { pastedGrid.TestDynamic = true; } //pastedGrid.PositionComp.SetPosition(MySector.MainCamera.Position); MyEntities.Add(pastedGrid); if (i == 0) firstPastedGrid = pastedGrid; if (missingDefinitions) pastedGrid.DetectDisconnectsAfterFrame(); //pastedGrid.PositionComp.SetWorldMatrix(m_previewGrids[i].WorldMatrix); i++; if (!pastedGrid.IsStatic && (!MyFakes.ENABLE_BATTLE_SYSTEM || !MySession.Static.Battle)) pastedGrid.Physics.LinearVelocity = m_objectVelocity; if (!pastedGrid.IsStatic && MySession.ControlledEntity != null && MySession.ControlledEntity.Entity.Physics != null && m_calculateVelocity && (!MyFakes.ENABLE_BATTLE_SYSTEM || !MySession.Static.Battle)) { pastedGrid.Physics.AngularVelocity = MySession.ControlledEntity.Entity.Physics.AngularVelocity; } pastedGrids.Add(pastedGrid); gridBuilder.IsStatic = savedStaticFlag; retVal = true; } //Because blocks fills SubBlocks in this method.. //TODO: Create LoadPhase2 MyEntities.UpdateOnceBeforeFrame(); foreach (var pastedGrid in pastedGrids) { var builder = pastedGrid.GetObjectBuilder(); m_tmpPastedBuilders.Add(builder); if (pastedBuilders != null) pastedBuilders.Add((MyObjectBuilder_CubeGrid)builder); } if (IsSnapped && SnapMode == MyGridPlacementSettings.SnapMode.Base6Directions && m_hitEntity is MyCubeGrid && firstPastedGrid != null && ((MyCubeGrid)m_hitEntity).GridSizeEnum == firstPastedGrid.GridSizeEnum) { var hitGrid = m_hitEntity as MyCubeGrid; MatrixI mergingTransform = hitGrid.CalculateMergeTransform(firstPastedGrid, hitGrid.WorldToGridInteger(firstPastedGrid.PositionComp.GetPosition())); MySyncCreate.RequestMergingCopyPaste(m_tmpPastedBuilders, m_hitEntity.EntityId, mergingTransform); } else if (touchingGrids != null && touchingGrids.Count > 0) { // Currently only first grid is supported for merging. MyCubeGrid touchingGrid = touchingGrids[0]; if (touchingGrid != null) { MatrixI mergingTransform = touchingGrid.CalculateMergeTransform(firstPastedGrid, touchingGrid.WorldToGridInteger(firstPastedGrid.PositionComp.GetPosition())); MySyncCreate.RequestMergingCopyPaste(m_tmpPastedBuilders, touchingGrid.EntityId, mergingTransform); } else { //MySyncCreate.RequestEntitiesCreate(m_tmpPastedBuilders); MySyncCreate.SendEntitiesCreated(m_tmpPastedBuilders); } } else { // CH:TODO: This would probably be safer if it was requested from the server as well MySyncCreate.SendEntitiesCreated(m_tmpPastedBuilders); } // CH:TODO: Use only items for grids that were really added to not screw with players if (buildInventory != null) { foreach (var item in m_buildComponents.TotalMaterials) { buildInventory.RemoveItemsOfType(item.Value, item.Key); } } if (deactivate) Deactivate(); if (retVal && updateAfterPasteCallback != null) { updateAfterPasteCallback(pastedBuilders); } return retVal; }
void Inventory_ContentsChanged(MyInventoryBase obj) { CubeGrid.SetInventoryMassDirty(); }