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, substitute: true); } else { Clear(); inventory.CountItems(m_componentCounts); AddItem(group.Id, amount, int.MaxValue); Solve(m_componentCounts); return GetSolvedItemCount(); } }
public GuidedMissileLauncher(WeaponTargeting weapon) { m_weaponTarget = weapon; myLogger = new Logger("GuidedMissileLauncher", CubeBlock); m_relayPart = RelayClient.GetOrCreateRelayPart(m_weaponTarget.CubeBlock); var defn = 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 * CubeBlock.GetCubeBlockDefinition().Size.Y * CubeBlock.CubeGrid.GridSize + forwardAdjust; MissileSpawnBox = BoundingBox.CreateFromPoints(points); if (m_weaponTarget.myTurret != null) { //myLogger.debugLog("original box: " + MissileSpawnBox, "GuidedMissileLauncher()"); MissileSpawnBox.Inflate(CubeBlock.CubeGrid.GridSize * 2f); } //myLogger.debugLog("MissileSpawnBox: " + MissileSpawnBox, "GuidedMissileLauncher()"); myInventory = ((MyEntity)CubeBlock).GetInventoryBase(0); Registrar.Add(weapon.FuncBlock, this); m_weaponTarget.GuidedLauncher = true; }
protected internal void RemoveItemsCombined(MyInventoryBase inventory, int itemAmount, MyDefinitionId itemDefinitionId) { m_materialListCombined.Clear(); m_materialListCombined.AddMaterial(itemDefinitionId, itemAmount); m_componentCombiner.RemoveItemsCombined(inventory, m_materialListCombined.TotalMaterials); m_materialListCombined.Clear(); return; }
void InventoryChanged(MyInventoryBase obj) { if (m_clientInventoryUpdate == null) { return; } foreach (var clientData in m_clientInventoryUpdate) { m_clientInventoryUpdate[clientData.Key].Dirty = true; } }
protected override void OnBeforeInventoryRemovedFromAggregate(Inventory.MyInventoryAggregate aggregate, MyInventoryBase inventory) { if (inventory == InputInventory) { InputInventory.ContentsChanged += inventory_OnContentsChanged; } else if (inventory == OutputInventory) { OutputInventory.ContentsChanged += inventory_OnContentsChanged; } else { Debug.Fail("Added inventory to aggregate, but not input or output invenoty?! This shouldn't happen."); } base.OnBeforeInventoryRemovedFromAggregate(aggregate, inventory); // Base method needs to be called here, cuz it removes the inventories from properties }
void inventory_OnBeforeContentsChanged(MyInventoryBase inventory) { if (this != MySession.Static.LocalCharacter) { return; } if (m_currentWeapon != null && WeaponTakesBuilderFromInventory(m_currentWeapon.DefinitionId) && inventory != null && inventory is MyInventory && (inventory as MyInventory).ContainItems(1, m_currentWeapon.PhysicalObject)) SaveAmmoToWeapon();//because it may be dropped few electrons later }
public void IncreaseMountLevelToDesiredRatio(float desiredIntegrityRatio, long welderOwnerPlayerId, MyInventoryBase outputInventory = null, float maxAllowedBoneMovement = 0.0f, bool isHelping = false, MyOwnershipShareModeEnum sharing = MyOwnershipShareModeEnum.Faction) { float desiredIntegrity = desiredIntegrityRatio * MaxIntegrity; float welderAmount = desiredIntegrity - Integrity; Debug.Assert(welderAmount >= 0f); if (welderAmount <= 0f) return; IncreaseMountLevel(welderAmount / BlockDefinition.IntegrityPointsPerSec, welderOwnerPlayerId, outputInventory: outputInventory, maxAllowedBoneMovement: maxAllowedBoneMovement, isHelping: isHelping, sharing: sharing); }
public void RemoveItemsCombined(MyInventoryBase inventory, DictionaryReader<MyDefinitionId, int> toRemove) { Clear(); foreach (var material in toRemove) // rename material to component { int groupAmount = 0; MyComponentGroupDefinition group = MyDefinitionManager.Static.GetGroupForComponent(material.Key, out groupAmount); // The component does not belong to any component group => we are looking exactly for the given component if (group == null) { if (MySessionComponentEquivalency.Static != null && MySessionComponentEquivalency.Static.HasEquivalents(material.Key)) { var eqGroup = MySessionComponentEquivalency.Static.GetEquivalents(material.Key); if (eqGroup != null) { int amountToRemove = material.Value; foreach (var element in eqGroup) { if (amountToRemove > 0) { var removed = inventory.RemoveItemsOfType(amountToRemove, element); amountToRemove -= (int)removed; } else { break; } } } } else { inventory.RemoveItemsOfType(material.Value, material.Key); continue; } //MyComponentSubstitutionDefinition substitutionDefinition = null; //if (MyDefinitionManager.Static.TryGetComponentSubstitutionDefinition(material.Key, out substitutionDefinition)) //{ // int amountToRemove = material.Value; // foreach (var entry in substitutionDefinition.ProvidingComponents) // { // if (amountToRemove > 0) // { // var removed = inventory.RemoveItemsOfType(amountToRemove * entry.Value, entry.Key); // amountToRemove -= (int)removed; // } // else // { // break; // } // } // if (amountToRemove > 0) // { // var removed = inventory.RemoveItemsOfType(amountToRemove, material.Key); // amountToRemove -= (int)removed; // } //} //else //{ // inventory.RemoveItemsOfType(material.Value, material.Key); // continue; //} } else { AddItem(group.Id, groupAmount, material.Value); } } inventory.CountItems(m_componentCounts); bool success = Solve(m_componentCounts); Debug.Assert(success, "Could not combine required items!"); inventory.ApplyChanges(m_solution); /*CheckUpdate(); m_remainder.Clear(); foreach (var material in toRemove) { m_remainder.Add(material.Key, material.Value); } bool success = true; m_cuttingSolver.Clear(); foreach (var material in m_remainder) { int groupAmount = 0; MyComponentGroupDefinition group = MyDefinitionManager.Static.GetGroupForComponent(material.Key, out groupAmount); // The component does not belong to any component group => we are looking exactly for the given component if (group == null) { success &= RemoveItemsOfTypeInternal(material.Key, material.Value); Debug.Assert(success, "Could not find the required component although we were permitted to build!"); continue; } else { m_cuttingSolver.AddItem(group.Id, groupAmount, material.Value); } m_componentCounts.Clear(); CollectItems(m_componentCounts); success &= m_cuttingSolver.Solve(m_componentCounts); List<MyComponentCombiner.ComponentChange> changes = null; m_cuttingSolver.GetSolution(out changes); foreach (var change in changes) { if (change.IsRemoval()) { success &= RemoveItemsOfTypeInternal(change.ToRemove, change.Amount); Debug.Assert(success, "Could not remove compnents, although the solver told us it should be possible!"); } else if (change.IsChange()) { ComponentInfo cInfo = null; m_componentInfos.TryGetValue(change.ToRemove, out cInfo); Debug.Assert(cInfo != null, "Could not find a component in MyAreaInventory!"); if (cInfo == null) continue; for (int i = 0; i < change.Amount; ++i) { int dummy = 0; long entityId = cInfo.RemoveComponent(1, out dummy); if (entityId == 0) break; var grid = TryGetComponent(entityId); if (grid == null) { break; } SpawnRemainingData spawnData = new SpawnRemainingData(); PrepareSpawnRemainingMaterial(grid, ref spawnData); grid.Physics.Enabled = false; grid.SyncObject.SendCloseRequest(); spawnData.DefId = change.ToAdd; SpawnRemainingMaterial(ref spawnData); } } } } return success;*/ }
// ----------- inventory -------------------- public static bool TryGetInventory(this MyEntity thisEntity, out MyInventoryBase inventoryBase) { inventoryBase = null; return thisEntity.Components.TryGet<MyInventoryBase>(out inventoryBase); }
protected bool PasteGridInternal(MyInventoryBase buildInventory, bool deactivate, List<MyObjectBuilder_CubeGrid> pastedBuilders = null, List<MyCubeGrid> touchingGrids = null, UpdateAfterPasteCallback updateAfterPasteCallback = null, bool multiBlock = false) { 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 (!IsWithinWorldLimits()) { MyGuiAudio.PlaySound(MyGuiSounds.HudUnable); MyHud.Notifications.Add(MyNotificationSingletons.ShipOverLimits); return false; } if (m_previewGrids.Count == 0) return false; foreach (var grid in m_copiedGrids) { foreach (var block in grid.CubeBlocks) { block.BuiltBy = MySession.Static.LocalPlayerId; } } bool missingBlockDefinitions = false; if (ShowModdedBlocksWarning) { missingBlockDefinitions = !CheckPastedBlocks(); } if (missingBlockDefinitions) { AllowSwitchCameraMode = false; var messageBox = MyGuiSandbox.CreateMessageBox( styleEnum: MyMessageBoxStyleEnum.Info, buttonType: MyMessageBoxButtonsType.YES_NO, messageText: MyTexts.Get(MyCommonTexts.MessageBoxTextDoYouWantToPasteGridWithMissingBlocks), messageCaption: MyTexts.Get(MyCommonTexts.MessageBoxCaptionWarning), callback: (result) => { if (result == MyGuiScreenMessageBox.ResultEnum.YES) { PasteInternal(buildInventory, missingBlockDefinitions, deactivate, pastedBuilders, updateAfterPasteCallback: updateAfterPasteCallback, multiBlock: multiBlock); } AllowSwitchCameraMode = true; }); MyGuiSandbox.AddScreen(messageBox); return false; } return PasteInternal(buildInventory, missingBlockDefinitions, deactivate, pastedBuilders: pastedBuilders, touchingGrids: touchingGrids, updateAfterPasteCallback: updateAfterPasteCallback, multiBlock: multiBlock); }
// CH: TODO: This method actually doesn't have a bad internal structure, but it should be refactored BIG TIME (and put to MyHudBlockInfo)! private static void SetBlockComponentsInternal(MyHudBlockInfo hudInfo, MyCubeBlockDefinition blockDefinition, MySlimBlock block, MyInventoryBase availableInventory) { hudInfo.Components.Clear(); if (block != null) { Debug.Assert(block.BlockDefinition == blockDefinition, "The definition given to SetBlockComponnentsInternal was not a definition of the block"); } hudInfo.InitBlockInfo(blockDefinition); hudInfo.ShowAvailable = MyPerGameSettings.AlwaysShowAvailableBlocksOnHud; if (!MyFakes.ENABLE_SMALL_GRID_BLOCK_COMPONENT_INFO && blockDefinition.CubeSize == MyCubeSize.Small) return; if (block != null) { hudInfo.BlockIntegrity = block.Integrity / block.MaxIntegrity; } // CH: TODO: Multiblocks if (block != null && block.IsMultiBlockPart) { var multiBlockInfo = block.CubeGrid.GetMultiBlockInfo(block.MultiBlockId); Debug.Assert(multiBlockInfo != null); if (multiBlockInfo != null) { // Load all block definition components foreach (var blockDefId in multiBlockInfo.MultiBlockDefinition.BlockDefinitions) { MyCubeBlockDefinition blockDef; if (MyDefinitionManager.Static.TryGetCubeBlockDefinition(blockDefId.Id, out blockDef)) { hudInfo.AddComponentsForBlock(blockDef); } } // Merge components from all blocks hudInfo.MergeSameComponents(); // Add mounted counts to components foreach (var multiBlockPart in multiBlockInfo.Blocks) { for (int j = 0; j < multiBlockPart.BlockDefinition.Components.Length; ++j) { var comp = multiBlockPart.BlockDefinition.Components[j]; var groupInfo = multiBlockPart.ComponentStack.GetGroupInfo(j); for (int i = 0; i < hudInfo.Components.Count; i++) { if (hudInfo.Components[i].DefinitionId == comp.Definition.Id) { var c = hudInfo.Components[i]; c.MountedCount += groupInfo.MountedCount; hudInfo.Components[i] = c; break; } } } } // Inventory counts for (int i = 0; i < hudInfo.Components.Count; i++) { if (availableInventory != null) { var c = hudInfo.Components[i]; c.AvailableAmount = (int)MyCubeBuilder.BuildComponent.GetItemAmountCombined(availableInventory, c.DefinitionId); hudInfo.Components[i] = c; } // Get amount in stockpile int amount = 0; foreach (var multiBlockPart in multiBlockInfo.Blocks) { if (!multiBlockPart.StockpileEmpty) amount += multiBlockPart.GetConstructionStockpileItemAmount(hudInfo.Components[i].DefinitionId); } if (amount > 0) { //RKTODO: ??? see below code for non multiblocks /*amount =*/ SetHudInfoComponentAmount(hudInfo, amount, i); } } } } else if (block == null && blockDefinition.MultiBlock != null) { MyDefinitionId defId = new MyDefinitionId(typeof(MyObjectBuilder_MultiBlockDefinition), blockDefinition.MultiBlock); var mbDefinition = MyDefinitionManager.Static.TryGetMultiBlockDefinition(defId); if (mbDefinition != null) { foreach (var blockDefId in mbDefinition.BlockDefinitions) { MyCubeBlockDefinition blockDef; if (MyDefinitionManager.Static.TryGetCubeBlockDefinition(blockDefId.Id, out blockDef)) { hudInfo.AddComponentsForBlock(blockDef); } } // Merge components from all blocks hudInfo.MergeSameComponents(); for (int i = 0; i < hudInfo.Components.Count; ++i) { var component = hudInfo.Components[i]; component.AvailableAmount = (int)MyCubeBuilder.BuildComponent.GetItemAmountCombined(availableInventory, component.DefinitionId); hudInfo.Components[i] = component; } } } else { for (int i = 0; i < blockDefinition.Components.Length; i++) { MyComponentStack.GroupInfo groupInfo = new MyComponentStack.GroupInfo(); if (block != null) { groupInfo = block.ComponentStack.GetGroupInfo(i); } else { var component = blockDefinition.Components[i]; groupInfo.Component = component.Definition; groupInfo.TotalCount = component.Count; groupInfo.MountedCount = 0; groupInfo.AvailableCount = 0; groupInfo.Integrity = 0.0f; groupInfo.MaxIntegrity = component.Count * component.Definition.MaxIntegrity; } AddBlockComponent(hudInfo, groupInfo, availableInventory); } if (block != null && !block.StockpileEmpty) { // For each component foreach (var comp in block.BlockDefinition.Components) { // Get amount in stockpile int amount = block.GetConstructionStockpileItemAmount(comp.Definition.Id); if (amount > 0) { for (int i = 0; i < hudInfo.Components.Count; i++) { if (block.ComponentStack.GetGroupInfo(i).Component == comp.Definition) { if (block.ComponentStack.IsFullyDismounted) { return; } amount = SetHudInfoComponentAmount(hudInfo, amount, i); } } } } } } }
public static void SetBlockComponents(MyHudBlockInfo hudInfo, MyCubeBlockDefinition blockDefinition, MyInventoryBase availableInventory = null) { SetBlockComponentsInternal(hudInfo, blockDefinition, null, availableInventory); }
private void DeconstructStockpile(float deconstructAmount, MyInventoryBase outputInventory, bool useDefaultDeconstructEfficiency = false) { Debug.Assert(Sync.IsServer, "This method is only meant to be called on the server!"); if (MySession.Static.CreativeMode) { ClearConstructionStockpile(outputInventory); } else { EnsureConstructionStockpileExists(); } if (m_stockpile != null) { m_stockpile.ClearSyncList(); m_componentStack.DecreaseMountLevel(deconstructAmount, m_stockpile, useDefaultDeconstructEfficiency: useDefaultDeconstructEfficiency); CubeGrid.SendStockpileChanged(this, m_stockpile.GetSyncList()); m_stockpile.ClearSyncList(); } else { m_componentStack.DecreaseMountLevel(deconstructAmount, null, useDefaultDeconstructEfficiency: useDefaultDeconstructEfficiency); } }
public void DecreaseMountLevel(float grinderAmount, MyInventoryBase outputInventory, bool useDefaultDeconstructEfficiency = false) { Debug.Assert(Sync.IsServer, "This method is only meant to be called on the server!"); if (!Sync.IsServer||m_componentStack.IsFullyDismounted) return; if (FatBlock != null) grinderAmount /= FatBlock.DisassembleRatio; else grinderAmount /= BlockDefinition.DisassembleRatio; grinderAmount = grinderAmount * BlockDefinition.IntegrityPointsPerSec; float oldBuildRatio = m_componentStack.BuildRatio; DeconstructStockpile(grinderAmount, outputInventory, useDefaultDeconstructEfficiency: useDefaultDeconstructEfficiency); float newBuildRatio = (BuildIntegrity - grinderAmount) / BlockDefinition.MaxIntegrity; //Call Integrity Changed if owner is nobody or is not local player if (BlockDefinition.RatioEnoughForDamageEffect(BuildLevelRatio)) { if (FatBlock != null && FatBlock.OwnerId != 0 && FatBlock.OwnerId != MySession.Static.LocalPlayerId) { FatBlock.OnIntegrityChanged(BuildIntegrity, Integrity, false, MySession.Static.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); bool modelChangeNeeded = BlockDefinition.ModelChangeIsNeeded(m_componentStack.BuildRatio, oldBuildRatio); MyIntegrityChangeEnum integrityChangeType = MyIntegrityChangeEnum.Damage; if (modelChangeNeeded) { UpdateVisual(); if (FatBlock != null) { int buildProgressID = CalculateCurrentModelID(); if ((buildProgressID == -1) || (BuildLevelRatio == 0f)) { integrityChangeType = MyIntegrityChangeEnum.ConstructionEnd; } else if (buildProgressID == BlockDefinition.BuildProgressModels.Length - 1) { integrityChangeType = MyIntegrityChangeEnum.ConstructionBegin; } else { integrityChangeType = MyIntegrityChangeEnum.ConstructionProcess; } } PlayConstructionSound(integrityChangeType, true); CreateConstructionSmokes(); } if (CubeGrid.GridSystems.GasSystem != null) { CubeGrid.GridSystems.GasSystem.Pressurize(); } if (MyFakes.ENABLE_GENERATED_BLOCKS && !BlockDefinition.IsGeneratedBlock && BlockDefinition.GeneratedBlockDefinitions != null && BlockDefinition.GeneratedBlockDefinitions.Length > 0) { UpdateProgressGeneratedBlocks(oldBuildRatio); } CubeGrid.SendIntegrityChanged(this, integrityChangeType, toolOwner); CubeGrid.OnIntegrityChanged(this); }
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 { MyEntity inventoryOwner = null; if (outputInventory != null && outputInventory.Container != null) inventoryOwner = outputInventory.Container.Entity as MyEntity; if (inventoryOwner != null && inventoryOwner.InventoryOwnerType() == MyInventoryOwnerTypeEnum.Character) { MoveItemsFromConstructionStockpile(outputInventory, MyItemFlags.Damaged); } } float oldPercentage = m_componentStack.BuildRatio; float oldDamage = CurrentDamage; //Add ownership check in order for the IntegrityChanged not to be called many times if (BlockDefinition.RatioEnoughForOwnership(BuildLevelRatio)) { if (FatBlock != null && FatBlock.OwnerId == 0 && outputInventory != null && !isHelping) { FatBlock.OnIntegrityChanged(BuildIntegrity, Integrity, true, welderOwnerPlayerId, sharing); } } if (MyFakes.SHOW_DAMAGE_EFFECTS && FatBlock != null && !BlockDefinition.RatioEnoughForDamageEffect((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.SendStockpileChanged(this, m_stockpile.GetSyncList()); m_stockpile.ClearSyncList(); } else { m_componentStack.IncreaseMountLevel(welderMountAmount, null); } if (m_componentStack.IsFullIntegrity) { ReleaseConstructionStockpile(); removeDecals = true; } ProfilerShort.Begin("ModelChange"); MyIntegrityChangeEnum integrityChangeType = 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 = MyIntegrityChangeEnum.ConstructionEnd; } } UpdateVisual(); if (FatBlock != null) { int buildProgressID = CalculateCurrentModelID(); if (buildProgressID == 0) { integrityChangeType = MyIntegrityChangeEnum.ConstructionBegin; } else if (!m_componentStack.IsFunctional) { integrityChangeType = MyIntegrityChangeEnum.ConstructionProcess; } } PlayConstructionSound(integrityChangeType); CreateConstructionSmokes(); if (CubeGrid.GridSystems.GasSystem != null) { CubeGrid.GridSystems.GasSystem.Pressurize(); } } ProfilerShort.End(); if (HasDeformation) CubeGrid.SetBlockDirty(this); if (removeDecals) CubeGrid.RenderData.RemoveDecals(Position); CubeGrid.SendIntegrityChanged(this, integrityChangeType, 0); CubeGrid.OnIntegrityChanged(this); 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 void DecreaseMountLevelToDesiredRatio(float desiredIntegrityRatio, MyInventoryBase outputInventory) { float desiredIntegrity = desiredIntegrityRatio * MaxIntegrity; float grinderAmount = Integrity - desiredIntegrity; Debug.Assert(grinderAmount >= 0f); if (grinderAmount <= 0f) return; if (FatBlock != null) grinderAmount *= FatBlock.DisassembleRatio; else grinderAmount *= BlockDefinition.DisassembleRatio; DecreaseMountLevel(grinderAmount / BlockDefinition.IntegrityPointsPerSec, outputInventory, useDefaultDeconstructEfficiency: true); }
public MyGuiScreenBase ShowAggregateInventoryScreen(MyInventoryBase rightSelectedInventory = null) { if (MyPerGameSettings.GUI.InventoryScreen != null) { if (InventoryAggregate != null) { InventoryAggregate.Init(); m_InventoryScreen = MyGuiSandbox.CreateScreen(MyPerGameSettings.GUI.InventoryScreen, InventoryAggregate, rightSelectedInventory); MyGuiSandbox.AddScreen(m_InventoryScreen); m_InventoryScreen.Closed += (scr) => { if (InventoryAggregate != null) { InventoryAggregate.DetachCallbacks(); } m_InventoryScreen = null; }; } } return m_InventoryScreen; }
public virtual bool PasteGrid(MyInventoryBase buildInventory = null, bool deactivate = true) { return PasteGridInternal(buildInventory, deactivate, touchingGrids: m_touchingGrids); }
private static void AddBlockComponent(MyHudBlockInfo hudInfo, MyComponentStack.GroupInfo groupInfo, MyInventoryBase availableInventory) { var componentInfo = new MyHudBlockInfo.ComponentInfo(); componentInfo.DefinitionId = groupInfo.Component.Id; componentInfo.ComponentName = groupInfo.Component.DisplayNameText; componentInfo.Icons = groupInfo.Component.Icons; componentInfo.TotalCount = groupInfo.TotalCount; componentInfo.MountedCount = groupInfo.MountedCount; if (availableInventory != null) componentInfo.AvailableAmount = (int)MyCubeBuilder.BuildComponent.GetItemAmountCombined(availableInventory, groupInfo.Component.Id); hudInfo.Components.Add(componentInfo); }
private bool PasteInternal(MyInventoryBase buildInventory, bool missingDefinitions, bool deactivate, List<MyObjectBuilder_CubeGrid> pastedBuilders = null, List<MyCubeGrid> touchingGrids = null, UpdateAfterPasteCallback updateAfterPasteCallback = null, bool multiBlock = false) { var copiedLocalGrids = new List<MyObjectBuilder_CubeGrid>(); foreach (var gridCopy in m_copiedGrids) { copiedLocalGrids.Add((MyObjectBuilder_CubeGrid)gridCopy.Clone()); } var grid = copiedLocalGrids[0]; bool isMergeNeeded = IsSnapped && SnapMode == SnapMode.Base6Directions && m_hitEntity is MyCubeGrid && grid != null && ((MyCubeGrid)m_hitEntity).GridSizeEnum == grid.GridSizeEnum; if (isMergeNeeded && !IsMergeWithinWorldLimits()) { MyGuiAudio.PlaySound(MyGuiSounds.HudUnable); MyHud.Notifications.Add(MyNotificationSingletons.ShipOverLimits); return false; } MyGuiAudio.PlaySound(MyGuiSounds.HudPlaceBlock); MyCubeGrid hitGrid = null; if(isMergeNeeded) { hitGrid = m_hitEntity as MyCubeGrid; } isMergeNeeded |= touchingGrids != null && touchingGrids.Count > 0; if(hitGrid == null && touchingGrids != null && touchingGrids.Count > 0) { hitGrid = touchingGrids[0]; } int i = 0; foreach (var gridBuilder in copiedLocalGrids) { gridBuilder.CreatePhysics = true; gridBuilder.EnableSmallToLargeConnections = true; gridBuilder.PositionAndOrientation = new MyPositionAndOrientation(m_previewGrids[i].WorldMatrix); gridBuilder.PositionAndOrientation.Value.Orientation.Normalize(); i++; } long inventoryOwnerId = 0; if (buildInventory != null) { if (MyFakes.ENABLE_MEDIEVAL_INVENTORY) { inventoryOwnerId = buildInventory.Entity.EntityId; } else if( buildInventory is MyInventory) { inventoryOwnerId = (buildInventory as MyInventory).Owner.EntityId; } } bool isAdmin = MySession.Static.IsAdminModeEnabled(Sync.MyId); if (isMergeNeeded && hitGrid != null) { hitGrid.PasteBlocksToGrid(copiedLocalGrids, inventoryOwnerId, multiBlock, isAdmin); } //TODO: GZA - This is connected with creational clipboards used to create new grids in space. Should be removed later. else if(CreationMode) { MyMultiplayer.RaiseStaticEvent(s => MyCubeGrid.TryCreateGrid_Implementation, CubeSize, IsStatic, copiedLocalGrids[0].PositionAndOrientation.Value, inventoryOwnerId, isAdmin); CreationMode = false; } else if (MySession.Static.CreativeMode || MySession.Static.HasAdminRights) { bool anyGridInGround = false; bool anyGridIsSmall = false; foreach (var prevGrid in m_previewGrids) { anyGridIsSmall |= prevGrid.GridSizeEnum == MyCubeSize.Small; var settings = m_settings.GetGridPlacementSettings(prevGrid.GridSizeEnum, prevGrid.IsStatic); anyGridInGround |= MyCubeGrid.IsAabbInsideVoxel(prevGrid.PositionComp.WorldMatrix, (BoundingBoxD)prevGrid.PositionComp.LocalAABB, settings); } bool smallInMedieval = false; if (MyPerGameSettings.Game == GameEnum.ME_GAME) { MyCubeGrid hitEntGrid = m_hitEntity as MyCubeGrid; if (hitEntGrid != null) smallInMedieval = anyGridIsSmall && (hitEntGrid.GridSizeEnum == MyCubeSize.Large); } foreach (var gridOb in copiedLocalGrids) { gridOb.IsStatic = smallInMedieval || anyGridInGround || (MySession.Static.EnableConvertToStation && gridOb.IsStatic); } if (!MySandboxGame.IsDedicated) { MyHud.PushRotatingWheelVisible(); } MyMultiplayer.RaiseStaticEvent(s => MyCubeGrid.TryPasteGrid_Implementation, copiedLocalGrids, missingDefinitions, inventoryOwnerId, m_objectVelocity, multiBlock, isAdmin); } if (deactivate) { Deactivate(afterPaste: true); } if (updateAfterPasteCallback != null) { updateAfterPasteCallback(pastedBuilders); } return true; }
public void MoveItemsToConstructionStockpile(MyInventoryBase fromInventory) { if (MySession.Static.CreativeMode) 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)MyCubeBuilder.BuildComponent.GetItemAmountCombined(fromInventory, id); int moveAmount = Math.Min(kv.Value, amountAvailable); if (moveAmount > 0) { MyCubeBuilder.BuildComponent.RemoveItemsCombined(fromInventory, moveAmount, id); m_stockpile.AddItems((int)moveAmount, new MyDefinitionId(typeof(MyObjectBuilder_Component), kv.Key)); } } CubeGrid.SendStockpileChanged(this, m_stockpile.GetSyncList()); m_stockpile.ClearSyncList(); } }
protected virtual void OnInventoryComponentRemoved(MyInventoryBase inventory) { }
public bool CanCombineItems(MyInventoryBase inventory, DictionaryReader<MyDefinitionId, int> items) { bool result = true; Clear(); inventory.CountItems(m_componentCounts); foreach (var item in items) { int itemValue = 0; int neededAmount = item.Value; MyComponentGroupDefinition group = null; group = MyDefinitionManager.Static.GetGroupForComponent(item.Key, out itemValue); if (group == null) { MyFixedPoint itemAmount; if (MySessionComponentEquivalency.Static != null && MySessionComponentEquivalency.Static.HasEquivalents(item.Key)) { if (!MySessionComponentEquivalency.Static.IsProvided(m_componentCounts, item.Key, item.Value)) { result = false; break; } } // Checking if this component is not provided by the group //MyComponentSubstitutionDefinition substitutions; //if (MyDefinitionManager.Static.TryGetComponentSubstitutionDefinition(item.Key, out substitutions)) //{ // int providedAmount; // if (!substitutions.IsProvidedByComponents(m_componentCounts, out providedAmount)) // { // result = false; // break; // } // else if (providedAmount < neededAmount) // { // result = false; // break; // } //} else if (!m_componentCounts.TryGetValue(item.Key, out itemAmount)) { result = false; break; } else if (itemAmount < neededAmount) { result = false; break; } } else { AddItem(group.Id, itemValue, neededAmount); } } if (result) { result &= Solve(m_componentCounts); } if (MyDebugDrawSettings.ENABLE_DEBUG_DRAW) { if (result == false) MyRenderProxy.DebugDrawText2D(new Vector2(0.0f, 0.0f), "Can not build", Color.Red, 1.0f); else { List<MyComponentChange> solution = null; GetSolution(out solution); float yCoord = 0.0f; foreach (var change in solution) { string text = ""; if (change.IsAddition()) { text += "+ " + change.Amount.ToString() + "x" + change.ToAdd.ToString(); MyRenderProxy.DebugDrawText2D(new Vector2(0.0f, yCoord), text, Color.Green, 1.0f); yCoord += 20.0f; } else if (change.IsRemoval()) { text += "- " + change.Amount.ToString() + "x" + change.ToRemove.ToString(); MyRenderProxy.DebugDrawText2D(new Vector2(0.0f, yCoord), text, Color.Red, 1.0f); yCoord += 20.0f; } else { text += "- " + change.Amount.ToString() + "x" + change.ToRemove.ToString(); MyRenderProxy.DebugDrawText2D(new Vector2(0.0f, yCoord), text, Color.Orange, 1.0f); yCoord += 20.0f; text = ""; text += "+ " + change.Amount.ToString() + "x" + change.ToAdd.ToString(); MyRenderProxy.DebugDrawText2D(new Vector2(0.0f, yCoord), text, Color.Orange, 1.0f); yCoord += 20.0f; } } } } return result; }
/// <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 = toInventory.ComputeAmountThatFits(item.Content.GetId()).ToIntSafe(); amount = Math.Min(amount, item.Amount); toInventory.AddItems(amount, item.Content); m_stockpile.RemoveItems(amount, item.Content); } CubeGrid.SendStockpileChanged(this, m_stockpile.GetSyncList()); m_stockpile.ClearSyncList(); }
/// <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 abstract bool TransferItemsFrom(MyInventoryBase sourceInventory, IMyInventoryItem item, MyFixedPoint amount, bool stack);
protected internal MyFixedPoint GetItemAmountCombined(MyInventoryBase availableInventory, MyDefinitionId myDefinitionId) { return m_componentCombiner.GetItemAmountCombined(availableInventory, myDefinitionId); }
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 = toInventory.ComputeAmountThatFits(item.Content.GetId()).ToIntSafe(); amount = Math.Min(amount, item.Amount); toInventory.AddItems(amount, item.Content); m_stockpile.RemoveItems(amount, item.Content); } CubeGrid.SendStockpileChanged(this, m_stockpile.GetSyncList()); m_stockpile.ClearSyncList(); }
private void inventory_OnContentsChanged(MyInventoryBase inv) { if (m_processingLock) return; if (Sync.IsServer) m_queueNeedsRebuild = true; }
public void ClearConstructionStockpile(MyInventoryBase outputInventory) { if (!StockpileEmpty) { MyEntity inventoryOwner = null; if (outputInventory != null && outputInventory.Container != null) inventoryOwner = outputInventory.Container.Entity as MyEntity; 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.SendStockpileChanged(this, m_stockpile.GetSyncList()); m_stockpile.ClearSyncList(); } } ReleaseConstructionStockpile(); }
protected override void OnInventoryAddedToAggregate(Inventory.MyInventoryAggregate aggregate, MyInventoryBase inventory) { base.OnInventoryAddedToAggregate(aggregate, inventory); if (inventory == InputInventory) { InputInventory.ContentsChanged += inventory_OnContentsChanged; } else if (inventory == OutputInventory) { OutputInventory.ContentsChanged += inventory_OnContentsChanged; } else { Debug.Fail("Added inventory to aggregate, but not input or output invenoty?! This shouldn't happen."); } }
void inventory_OnContentsChanged(MyInventoryBase inventory) { if (this != MySession.Static.LocalCharacter) { return; } // Switch away from the weapon if we don't have it; Cube placer is an exception if (m_currentWeapon != null && WeaponTakesBuilderFromInventory(m_currentWeapon.DefinitionId) && inventory != null && inventory is MyInventory && !(inventory as MyInventory).ContainItems(1, m_currentWeapon.PhysicalObject)) SwitchToWeapon(null); // The same needs to be done with the m_leftHandItems, otherwise HandTorch if (LeftHandItem != null && !CanSwitchToWeapon(LeftHandItem.DefinitionId)) { LeftHandItem.OnControlReleased(); m_leftHandItem.Close(); m_leftHandItem = null; } }