public override void UpdateBeforeSimulation100() { base.UpdateBeforeSimulation100(); IMyInventory inventory = ((Sandbox.ModAPI.IMyTerminalBlock)Entity).GetInventory(0) as IMyInventory; float percent = MathHelper.Clamp((int)Math.Floor(110 - ((float)inventory.CurrentVolume / (float)inventory.MaxVolume * 100f)), 10, 100); terminalBlock.CustomData = "Efficiency: " + percent + "%"; while (new Random().Next(0, 100) < percent) { VRage.MyFixedPoint amount = (VRage.MyFixedPoint)(0.01); inventory.AddItems(amount, new MyObjectBuilder_Ingot() { SubtypeName = "UnstableMatter" }); terminalBlock.RefreshCustomInfo(); percent *= 0.3f; } if (new Random().Next(0, 30000) < 1) { inventory.AddItems((VRage.MyFixedPoint)(1), new MyObjectBuilder_Component() { SubtypeName = "SpecialTech" }); terminalBlock.RefreshCustomInfo(); } }
public void UpdateItemAmount(InventoryItemEntity item, float newAmount) { if (BackingObject != null) { SandboxGameAssemblyWrapper.Instance.GameAction(new Action(delegate() { IMyInventory myInventory = (IMyInventory)BackingObject; if (newAmount == 0) { myInventory.RemoveItems(item.ItemId); } else if (newAmount > item.Amount) { myInventory.AddItems((MyFixedPoint)(newAmount - item.Amount), item.PhysicalContent, (int)item.ItemId); } else if (newAmount < item.Amount) { myInventory.RemoveItemsAt((int)item.ItemId, (MyFixedPoint)(item.Amount - newAmount), true); } })); } /* * InventoryDelta delta = new InventoryDelta(); * delta.item = item; * delta.oldAmount = item.Amount; * delta.newAmount = newAmount; * * m_itemDeltaQueue.Enqueue(delta); * * Action action = InternalUpdateItemAmount; * SandboxGameAssemblyWrapper.Instance.EnqueueMainGameAction(action); */ }
/** * Locates all the Oxygen generator class blocks on the given grid, * then adds 2000 ice if there is room to do so. * * Only call on server. */ public static void FillOxygenGenerators(IMyCubeGrid targetGrid) { List <IMySlimBlock> blockList = new List <IMySlimBlock>(); targetGrid.GetBlocks(blockList, b => b.FatBlock is Sandbox.ModAPI.IMyGasGenerator); foreach (var block in blockList) { IMyGasGenerator gasGenerator = ((IMyGasGenerator)block.FatBlock); if (gasGenerator == null) { continue; } MyDefinitionId definitionId = new MyDefinitionId(typeof(MyObjectBuilder_Ore), "Ice"); MyObjectBuilder_InventoryItem inventoryItem = new MyObjectBuilder_InventoryItem { Amount = AMOUNT_ICE_TO_ADD, Content = (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(definitionId) }; IMyInventory gasGeneratorInv = gasGenerator.GetInventory(0); if (!gasGeneratorInv.CanItemsBeAdded(AMOUNT_ICE_TO_ADD, definitionId)) { continue; } gasGeneratorInv.AddItems(AMOUNT_ICE_TO_ADD, inventoryItem.Content); } }
private void RechargeAmmo() { try { if (Debug.Write($"Weapon heat: {m_heat}/{m_heatMax}", 1, debug) && m_heat > m_heatMax) { return; } var ammoMissing = m_maxAmmo - (int)m_inventory.GetItemAmount(m_chargeDefinitionId); var ammoAdded = 0; while (m_chargeamount >= m_operationalPower && m_inventory != null && ammoAdded < ammoMissing && m_heat <= m_heatMax) { m_chargeTimeout = m_timer + (int)(60 * m_timeoutMult); ammoAdded++; var heat = m_heat + m_heatPerShot; m_heat = heat; var charge = m_chargeamount - m_operationalPower; m_chargeamount = charge; } if (Debug.Write($"Adding {ammoAdded} energy ammo rounds to weapon.", 1, debug) && ammoAdded > 0) { MyAPIGateway.Utilities.InvokeOnGameThread(() => { if (m_inventory != null) { m_inventory.AddItems(ammoAdded, (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(m_magDefId)); } }); } } catch (Exception e) { Debug.HandleException(e); } }
public override void UpdateBeforeSimulation100() { base.UpdateBeforeSimulation100(); if (m_generator.IsWorking) { Frame = frameShift++; if (Frame % 30 != 0) { return; } List <IMyPlayer> players = new List <IMyPlayer>(); MyAPIGateway.Players.GetPlayers(players, x => x.Character != null && !x.IsBot); int count = players.Count; IMyInventory inventory = ((Sandbox.ModAPI.IMyTerminalBlock)Entity).GetInventory(0) as IMyInventory; if (!inventory.ContainItems(Core.Settings.ResourceMax, new MyObjectBuilder_Ingot { SubtypeName = "Coin" })) { inventory.AddItems(Core.Settings.ResourcePerMinute + count * Core.Settings.ResourceIncreasePerPlayerMinute, new MyObjectBuilder_Ingot { SubtypeName = "Coin" }); terminalBlock.RefreshCustomInfo(); } //IMyInventory inventory1 = ((Sandbox.ModAPI.IMyTerminalBlock)Entity).GetInventory(1) as IMyInventory; //if (!inventory1.ContainItems(10, new MyObjectBuilder_AmmoMagazine { SubtypeName = "NATO_25x184mm" })) //{ // inventory1.AddItems(1, new MyObjectBuilder_AmmoMagazine { SubtypeName = "NATO_25x184mm" }); // terminalBlock.RefreshCustomInfo(); //} //List<IMyPlayer> players = new List<IMyPlayer>(); //MyAPIGateway.Players.GetPlayers(players, x => x.Controller != null && x.Controller.ControlledEntity != null); //foreach (IMyPlayer player in players) //{ // if (player.Controller.ControlledEntity is IMyCharacter) // { // MyEntity entity = player.Controller.ControlledEntity.Entity as MyEntity; // if (entity.HasInventory) // { // inventory = entity.GetInventoryBase() as MyInventory; // if (!inventory.ContainItems(10000, new MyObjectBuilder_Ingot { SubtypeName = "Coin" })) // { // inventory.AddItems(5, new MyObjectBuilder_Ingot { SubtypeName = "Coin" }); // terminalBlock.RefreshCustomInfo(); // } // } // } //} } }
public override void UpdateAfterSimulation() { float gridPower; if (TransmissionManager.totalPowerPerGrid.TryGetValue(m_functionalBlock.CubeGrid.EntityId, out gridPower)) { m_running = gridPower > 0f; if (gridPower != m_oldMultiplier) { m_reactor.PowerOutputMultiplier = gridPower; m_oldMultiplier = gridPower; } //MyAPIGateway.Utilities.ShowNotification ("Grid " + Entity.EntityId + m_functionalBlock.CubeGrid.EntityId + ":" + gridPower, 17, MyFontEnum.Green); TransmissionManager.totalPowerPerGrid[m_functionalBlock.CubeGrid.EntityId] = 0f; } else { m_running = false; } //MyAPIGateway.Utilities.ShowNotification ("" + m_running, 17, MyFontEnum.Green); if ((m_running == true) && (m_running != m_runningOld)) { m_inventory.AddItems((MyFixedPoint)1000, m_remoteEnergyBuilder); } else if ((m_running == false) && (m_running != m_runningOld)) { m_inventory.RemoveItemsOfType(m_inventory.GetItemAmount(m_remoteEnergyId), m_remoteEnergyBuilder); } if (m_running) { m_reactor.RequestEnable(true); } else { m_reactor.RequestEnable(false); } m_runningOld = m_running; }
private void addtoParachute(IMyParachute FoundCargoCont, SerializableDefinitionId item, int amount) { IMyInventory inventory = ((Sandbox.ModAPI.Ingame.IMyTerminalBlock)FoundCargoCont).GetInventory(0) as IMyInventory; if (!inventory.CanItemsBeAdded(amount, item)) { return; } MyFixedPoint amount2 = (MyFixedPoint)Math.Min(amount, 9999); inventory.AddItems(amount2, (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(item)); }
private bool AddLoot(IMyCargoContainer container) { bool added = false; bool isLarge = container.CubeGrid.GridSizeEnum == MyCubeSize.Large; IMyInventory inventory = container.GetInventory(); try { if (MyUtils.GetRandomDouble(0, 1) <= (isLarge ? Tech2.chanceLarge : Tech2.chanceSmall)) { int amount = MyUtils.GetRandomInt((isLarge ? Tech2.minItemsLarge : Tech2.minItemsSmall), (isLarge ? Tech2.maxItemsLarge : Tech2.maxItemsSmall)); MyLog.Default.WriteLine("TieredTechBlocks: Added " + amount + "x Common Tech to " + container.CustomName); inventory.AddItems(amount, Tech2.builder); added = true; } if (MyUtils.GetRandomDouble(0, 1) <= (isLarge ? Tech4.chanceLarge : Tech4.chanceSmall)) { int amount = MyUtils.GetRandomInt((isLarge ? Tech4.minItemsLarge : Tech4.minItemsSmall), (isLarge ? Tech4.maxItemsLarge : Tech4.maxItemsSmall)); MyLog.Default.WriteLine("TieredTechBlocks: Added " + amount + "x Rare Tech to " + container.CustomName); inventory.AddItems(amount, Tech4.builder); added = true; } if (MyUtils.GetRandomDouble(0, 1) <= (isLarge ? Tech8.chanceLarge : Tech8.chanceSmall)) { int amount = MyUtils.GetRandomInt((isLarge ? Tech8.minItemsLarge : Tech8.minItemsSmall), (isLarge ? Tech8.maxItemsLarge : Tech8.maxItemsSmall)); MyLog.Default.WriteLine("TieredTechBlocks: Added " + amount + "x Exotic Tech to " + container.CustomName); inventory.AddItems(amount, Tech8.builder); added = true; } } catch (Exception e) { MyLog.Default.WriteLine("TieredTechBlocks: FAILED " + e); } return(added); }
void Recharge() { int chargesInInventory = (int)m_inventory.GetItemAmount(chargeDefinitionIds[damageUpgrades]); if (chargesInInventory < attractorWeaponInfo.keepAtCharge) { if (resourceSink.RequiredInputByType(electricityDefinition) != (attractorWeaponInfo.powerUsage / efficiencyUpgrades)) { resourceSink.SetRequiredInputByType(electricityDefinition, (attractorWeaponInfo.powerUsage / efficiencyUpgrades)); setPowerConsumption = (attractorWeaponInfo.powerUsage / efficiencyUpgrades); powerConsumption = (attractorWeaponInfo.powerUsage / efficiencyUpgrades); } else { if (!functionalBlock.Enabled) { powerConsumption = 0.0001f; } } if (resourceSink.CurrentInputByType(electricityDefinition) == (attractorWeaponInfo.powerUsage / efficiencyUpgrades)) { if (!overheated) { m_inventory.AddItems((MyFixedPoint)(attractorWeaponInfo.keepAtCharge - chargesInInventory), chargeObjectBuilders [damageUpgrades]); } } } else if (chargesInInventory > attractorWeaponInfo.keepAtCharge) { m_inventory.RemoveItemsOfType((MyFixedPoint)(chargesInInventory - attractorWeaponInfo.keepAtCharge), chargeObjectBuilders [damageUpgrades]); } else { if (setPowerConsumption != 0.0001f) { resourceSink.SetRequiredInputByType(electricityDefinition, 0.0001f); setPowerConsumption = 0.0001f; powerConsumption = 0.0001f; } } // terminalBlock.RefreshCustomInfo (); }
public static bool InventoryAdd(IMyInventory inventory, MyFixedPoint amount, MyDefinitionId definitionId) { var content = (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(definitionId); MyObjectBuilder_InventoryItem inventoryItem = new MyObjectBuilder_InventoryItem { Amount = amount, PhysicalContent = content }; if (inventory.CanItemsBeAdded(inventoryItem.Amount, definitionId)) { inventory.AddItems(inventoryItem.Amount, inventoryItem.PhysicalContent, -1); return(true); } // Inventory full. Could not add the item. return(false); }
public override void UpdateBeforeSimulation100() { base.UpdateBeforeSimulation100(); if (m_generator.IsWorking) { if (IsInVoxel(m_generator as Sandbox.ModAPI.IMyTerminalBlock)) { IMyInventory inventory = ((Sandbox.ModAPI.IMyTerminalBlock)Entity).GetInventory(1) as IMyInventory; VRage.MyFixedPoint amount = (VRage.MyFixedPoint)(2000 * (1 + (0.4 * m_generator.UpgradeValues["Productivity"]))); inventory.AddItems(amount, new MyObjectBuilder_Ore() { SubtypeName = "Stone" }); terminalBlock.RefreshCustomInfo(); } } }
public override void UpdateBeforeSimulation() { powerConsumption = resourceSink.CurrentInputByType(electricityDefinition); if (!m_inventory.IsItemAt(0)) { if (!functionalBlock.Enabled) { powerConsumption = 0.0001f; setPowerConsumption = 0.0001f; } else { if (setPowerConsumption != (pulseWeaponInfo.powerUsage / efficiencyUpgrades)) { resourceSink.SetRequiredInputByType(electricityDefinition, (pulseWeaponInfo.powerUsage / efficiencyUpgrades)); setPowerConsumption = (pulseWeaponInfo.powerUsage / efficiencyUpgrades); powerConsumption = resourceSink.CurrentInputByType(electricityDefinition); } charge += powerConsumption; if (charge > (pulseWeaponInfo.energyPerProjectile / efficiencyUpgrades)) { m_inventory.AddItems((MyFixedPoint)pulseWeaponInfo.projectilesPerCharge, chargeObjectBuilders [damageUpgrades]); charge -= (pulseWeaponInfo.energyPerProjectile / efficiencyUpgrades); } } } else { if (setPowerConsumption != 0.0001f) { resourceSink.SetRequiredInputByType(electricityDefinition, 0.0001f); setPowerConsumption = 0.0001f; powerConsumption = resourceSink.CurrentInputByType(electricityDefinition); } } terminalBlock.RefreshCustomInfo(); }
public override void UpdateBeforeSimulation100() { base.UpdateBeforeSimulation100(); IMyInventory inventory = ((Sandbox.ModAPI.IMyTerminalBlock)Entity).GetInventory(0) as IMyInventory; if (inventory.ItemCount < 1) { MyObjectBuilder_AmmoMagazine builder = new MyObjectBuilder_AmmoMagazine() { SubtypeName = "Missile200mm" }; inventory.AddItems((MyFixedPoint)6, builder); } TerminalalBlock.RefreshCustomInfo(); }
public static bool FixUnfinishedBlock(IMyInventory inv, IMySlimBlock slimBlock, long owner) { bool success = true; Dictionary <string, int> missingParts = new Dictionary <string, int>(); slimBlock.GetMissingComponents(missingParts); if (missingParts.Keys.Count == 0) { return(success); } foreach (var part in missingParts.Keys.ToList()) { MyDefinitionId defId = new MyDefinitionId(typeof(MyObjectBuilder_Component), part); var content = (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(defId); MyObjectBuilder_InventoryItem inventoryItem = new MyObjectBuilder_InventoryItem { Amount = 1, Content = content }; while (missingParts[part] > 0) { if (inv.CanItemsBeAdded(1, defId) == true) { inv.AddItems(1, inventoryItem.Content); missingParts[part]--; } else { //Logger.AddMsg("Failed To Add Repair Component To Container", true); success = false; break; } } slimBlock.MoveItemsToConstructionStockpile(inv); slimBlock.IncreaseMountLevel(10000, owner, inv); } return(success); }
public override void UpdateBeforeSimulation100() { base.UpdateBeforeSimulation100(); if (m_generator.IsFunctional) { IMyInventory inventory = ((Sandbox.ModAPI.IMyTerminalBlock)Entity).GetInventory(1) as IMyInventory; VRage.MyFixedPoint amount = 1; if (!inventory.ContainItems(10000, new MyObjectBuilder_Ore { SubtypeName = "Iron" })) { inventory.AddItems(5, new MyObjectBuilder_Ore { SubtypeName = "Iron" }); terminalBlock.RefreshCustomInfo(); } } }
private static double AddToInventory(IMyInventory inventory, MyDefinitionId itemDefinition, double amount) { var content = (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(itemDefinition); MyObjectBuilder_InventoryItem item = new MyObjectBuilder_InventoryItem { Amount = new MyFixedPoint { RawValue = (long)(amount * _multi) }, PhysicalContent = content }; if (!inventory.CanItemsBeAdded(item.Amount, itemDefinition)) { return(0); } inventory.AddItems(item.Amount, item.PhysicalContent); return(amount); }
public override void UpdateBeforeSimulation100() { base.UpdateBeforeSimulation100(); IMyInventory inventory = ((Sandbox.ModAPI.IMyTerminalBlock)Entity).GetInventory(0) as IMyInventory; double targetAmount = 10000; if (TerminalalBlock.CustomData != null && TerminalalBlock.CustomData != "") { try { targetAmount = double.Parse(TerminalalBlock.CustomData); } catch (Exception e) { } } try { for (int i = 0; i < inventory.ItemCount; i++) { MyObjectBuilder_PhysicalObject builder = GetItemBuilder(inventory.GetItemAt(i).Value); if (builder == null) { continue; } double amount = targetAmount - (double)inventory.GetItemAmount(builder); if (amount < 0) { inventory.RemoveItemsOfType((MyFixedPoint)Math.Abs(amount), builder); } else if (amount > 0) { inventory.AddItems((MyFixedPoint)amount, builder); } } } catch (Exception e) { } TerminalalBlock.RefreshCustomInfo(); }
public static void SpawnItems(IMyInventory MyInventory, ref List <MyObjectBuilder_InventoryItem> Items) { MyFixedPoint amount; for (var i = Items.Count - 1; i >= 0; i--) { amount = GetMaxAmountPossible(MyInventory, Items[i]); if (amount > 0) { MyInventory.AddItems(amount, Items[i].PhysicalContent); if ((Items[i].Amount - amount) > 0) { Items[i].Amount -= amount; } else { Items.RemoveAtFast(i); } } } }
public static VRage.MyFixedPoint AddMaxItems(this IMyInventory destInventory, VRage.MyFixedPoint maxNeededFP, MyObjectBuilder_PhysicalObject objectBuilder) { var contentId = objectBuilder.GetObjectId(); if (maxNeededFP <= 0) { return(0); //Amount to small } var maxPossible = destInventory.MaxFractionItemsAddable(maxNeededFP, contentId); if (maxPossible > 0) { destInventory.AddItems(maxPossible, objectBuilder); return(maxPossible); } else { return(0); } }
public override void UpdateBeforeSimulation() { powerConsumption = resourceSink.CurrentInputByType(electricityDefinition); if (!m_inventory.IsItemAt(0)) { if (!functionalBlock.Enabled) { powerConsumption = 0.0001f; setPowerConsumption = 0.0001f; } else { reloadTimer++; if (setPowerConsumption != pulseWeaponInfo.powerUsage) { resourceSink.SetRequiredInputByType(electricityDefinition, pulseWeaponInfo.powerUsage); setPowerConsumption = pulseWeaponInfo.powerUsage; powerConsumption = resourceSink.CurrentInputByType(electricityDefinition); } if (reloadTimer >= 300) { m_inventory.AddItems(pulseWeaponInfo.projectilesPerCharge, chargeObjectBuilders[damageUpgrades]); reloadTimer = 0; } } } else { if (setPowerConsumption != 0.0001f) { resourceSink.SetRequiredInputByType(electricityDefinition, 0.0001f); setPowerConsumption = 0.0001f; powerConsumption = resourceSink.CurrentInputByType(electricityDefinition); } } terminalBlock.RefreshCustomInfo(); }
public bool NewEntry(InventoryItemEntity source) { /* * m_itemManager.AddEntry<InventoryItemEntity>(NextItemId, source); * * NextItemId = NextItemId + 1; * //TODO - Figure out the right way to add new items * //Just updating an item amount doesn't seem to work right * UpdateItemAmount(source, source.Amount * 2); * * RefreshInventory(); */ if (BackingObject != null) { SandboxGameAssemblyWrapper.Instance.GameAction(new Action(delegate() { IMyInventory inventory = (IMyInventory)BackingObject; inventory.AddItems((MyFixedPoint)source.Amount, source.PhysicalContent); })); } return(true); }
public override void UpdateBeforeSimulation100() { w_density = atmoDet.AtmosphereDetectionVaporator(this.Entity); IMyInventory inventory = ((Sandbox.ModAPI.IMyTerminalBlock)Entity).GetInventory(1) as IMyInventory; //check to see if the block is on if (m_vaporator.Enabled && m_vaporator.IsWorking && m_vaporator.IsFunctional) { try { var sink = Entity.Components.Get <MyResourceSinkComponent>(); poweruse = 0.4f * (1f + m_vaporator.UpgradeValues["Productivity"]) * (1f / m_vaporator.UpgradeValues["PowerEfficiency"]); if (sink != null) { sink.SetRequiredInputByType(MyResourceDistributorComponent.ElectricityId, poweruse); } } catch (Exception e) { MyAPIGateway.Utilities.ShowNotification("[ Error in " + GetType().FullName + ": " + e.Message + " ]", 10000, MyFontEnum.Red); MyLog.Default.WriteLine(e); } //m_vaporator.PowerConsumptionMultiplier = 10 * (1f + m_vaporator.UpgradeValues["Productivity"]) * (1f / m_vaporator.UpgradeValues["PowerEfficiency"]); VRage.MyFixedPoint amount = (VRage.MyFixedPoint)(0.2 * (w_density * m_vaporator.UpgradeValues["Effectiveness"]) * (1 + m_vaporator.UpgradeValues["Productivity"])); inventory.AddItems(amount, new MyObjectBuilder_Ore() { SubtypeName = "Ice" }); } terminalBlock.RefreshCustomInfo(); base.UpdateBeforeSimulation100(); }
public static bool InventoryAdd(IMyInventory inventory, MyFixedPoint amount, MyDefinitionId definitionId) { var content = (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(definitionId); var gasContainer = content as MyObjectBuilder_GasContainerObject; if (gasContainer != null) { gasContainer.GasLevel = 1f; } MyObjectBuilder_InventoryItem inventoryItem = new MyObjectBuilder_InventoryItem { Amount = amount, Content = content }; if (inventory.CanItemsBeAdded(inventoryItem.Amount, definitionId)) { inventory.AddItems(inventoryItem.Amount, (MyObjectBuilder_PhysicalObject)inventoryItem.Content, -1); return(true); } // Inventory full. Could not add the item. return(false); }
internal void TakeRequiredComponents() { if (MyAPIGateway.Session.CreativeMode || ComponentsRequired.Count < 1) { return; } List <IMyInventory> removalList = new List <IMyInventory>(); try { foreach (IMyInventory inventory in connectedInventory) { IMyInventory inv = null; IMyInventory constructionInventory = GetConstructionInventory(); if (inventory == null || inventory.CurrentVolume == inventory.MaxVolume) { continue; } if (!GridHelper.IsValidInventoryConnection(constructionInventory, inventory, out inv)) { removalList.Add(inventory); continue; } foreach (var inventoryItem in inventory.GetItems().ToList()) { foreach (var componentNeeded in ComponentsRequired.ToList()) { if (inventoryItem.Content.TypeId != typeof(MyObjectBuilder_Component) || componentNeeded.Value <= 0 || (int)inventoryItem.Amount <= 0f || inventoryItem.Content.SubtypeName != componentNeeded.Key) { continue; } var validAmount = GetMaxComponentAmount(componentNeeded.Key, (float)constructionInventory.MaxVolume - (float)constructionInventory.CurrentVolume); float amount; if (inventoryItem.Amount >= componentNeeded.Value) { amount = Math.Min(componentNeeded.Value, validAmount); } else { amount = Math.Min((float)inventoryItem.Amount, validAmount); } if (!constructionInventory.CanItemsBeAdded((int)amount, new SerializableDefinitionId(typeof(MyObjectBuilder_Component), componentNeeded.Key))) { continue; } MyAPIGateway.Utilities.InvokeOnGameThread(() => { try { inventory.RemoveItemsOfType((int)amount, (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(typeof(MyObjectBuilder_Component), componentNeeded.Key)); constructionInventory.AddItems((int)amount, (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(typeof(MyObjectBuilder_Component), componentNeeded.Key)); if (ComponentsRequired.ContainsKey(componentNeeded.Key)) { ComponentsRequired[componentNeeded.Key] -= (int)amount; } } catch (Exception ex) { Logging.Instance.WriteLine($"Nanite Control Factory: Exception in NaniteConstructionInventory.TakeRequiredComponents:\n{ex.ToString()}"); } }); } } } } catch (InvalidOperationException ex) { Logging.Instance.WriteLine("NaniteConstructionSystem.Extensions.GridHelper.TryMoveToFreeCargo: A list was modified. Aborting.", 1); } catch (Exception ex) when(ex.ToString().Contains("IndexOutOfRangeException")) //because Keen thinks we shouldn't have access to this exception ... { Logging.Instance.WriteLine("NaniteConstructionSystem.Extensions.GridHelper.TryMoveToFreeCargo: A list was modified. Aborting.", 1); } foreach (IMyInventory inv in removalList) { MyAPIGateway.Utilities.InvokeOnGameThread(() => { connectedInventory.Remove(inv); }); } }
public static bool InventoryAdd(IMyInventory inventory, MyFixedPoint amount, MyDefinitionId definitionId) { var content = (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(definitionId); var gasContainer = content as MyObjectBuilder_GasContainerObject; if (gasContainer != null) gasContainer.GasLevel = 1f; MyObjectBuilder_InventoryItem inventoryItem = new MyObjectBuilder_InventoryItem { Amount = amount, Content = content }; if (inventory.CanItemsBeAdded(inventoryItem.Amount, definitionId)) { inventory.AddItems(inventoryItem.Amount, (MyObjectBuilder_PhysicalObject)inventoryItem.Content, -1); return true; } // Inventory full. Could not add the item. return false; }
public void Go() { Players.Clear(); MyAPIGateway.Players.GetPlayers(Players); foreach (IMyPlayer p in Players) { if (p.IsBot) { continue; } IMyEntity entity = p.Controller.ControlledEntity.Entity; entity = Utilities.GetCharacterEntity(entity); PoopPlayer pp; if (Poopers.ContainsKey(p.IdentityId)) { pp = Poopers[p.IdentityId]; } else { pp = new PoopPlayer() { PoopAmount = 0, Player = p }; Poopers.Add(p.IdentityId, pp); } float amount = MyUtils.GetRandomFloat(Config.Instance.PoopAmountPerSecondMin, Config.Instance.PoopAmountPerSecondMax); bool toilet = false; character = p.Character.GetObjectBuilder(false) as MyObjectBuilder_Character; switch (character.MovementState) { case MyCharacterMovementEnum.Sitting: IMyCubeBlock cb = p.Controller.ControlledEntity.Entity as IMyCubeBlock; String seatmodel = cb.DefinitionDisplayNameText.ToLower(); if (seatmodel.Contains("toilet")) { amount *= Config.Instance.PoopMultiplierToilet; toilet = true; } else { amount *= Config.Instance.PoopMultiplierSit; } break; case MyCharacterMovementEnum.Flying: case MyCharacterMovementEnum.Falling: amount *= Config.Instance.PoopMultiplierFly; break; case MyCharacterMovementEnum.Crouching: case MyCharacterMovementEnum.CrouchRotatingRight: case MyCharacterMovementEnum.CrouchRotatingLeft: case MyCharacterMovementEnum.CrouchWalking: case MyCharacterMovementEnum.CrouchBackWalking: case MyCharacterMovementEnum.CrouchStrafingLeft: case MyCharacterMovementEnum.CrouchStrafingRight: case MyCharacterMovementEnum.CrouchWalkingRightFront: case MyCharacterMovementEnum.CrouchWalkingRightBack: case MyCharacterMovementEnum.CrouchWalkingLeftFront: case MyCharacterMovementEnum.CrouchWalkingLeftBack: amount *= Config.Instance.PoopMultiplierCrouch; break; case MyCharacterMovementEnum.Walking: case MyCharacterMovementEnum.BackWalking: case MyCharacterMovementEnum.WalkStrafingLeft: case MyCharacterMovementEnum.WalkStrafingRight: case MyCharacterMovementEnum.WalkingRightFront: case MyCharacterMovementEnum.WalkingRightBack: case MyCharacterMovementEnum.WalkingLeftFront: case MyCharacterMovementEnum.WalkingLeftBack: amount *= Config.Instance.PoopMultiplierWalk; break; case MyCharacterMovementEnum.Running: case MyCharacterMovementEnum.Backrunning: case MyCharacterMovementEnum.RunStrafingLeft: case MyCharacterMovementEnum.RunStrafingRight: case MyCharacterMovementEnum.RunningRightFront: case MyCharacterMovementEnum.RunningRightBack: case MyCharacterMovementEnum.RunningLeftBack: case MyCharacterMovementEnum.RunningLeftFront: case MyCharacterMovementEnum.Sprinting: case MyCharacterMovementEnum.Jump: amount *= Config.Instance.PoopMultiplierSprint; break; case MyCharacterMovementEnum.Died: amount = 0f; break; } pp.PoopAmount += (float)Math.Round(amount, 3); //MyLog.Default.WriteLine("Biogas: Added " + amount + " to " + p.DisplayName + " -> " + pp.PoopAmount); if ((toilet && pp.PoopAmount >= 0.1f) || MyUtils.GetRandomFloat(0, 1) <= Config.Instance.PoopChancePerSecond || pp.PoopAmount >= Config.Instance.PoopAlwaysAt) { IMyInventory inventory = entity.GetInventory(); inventory.AddItems((VRage.MyFixedPoint)Math.Round(pp.PoopAmount, 3), new MyObjectBuilder_Ore() { SubtypeName = "Organic" }); pp.PoopAmount = 0; //MyLog.Default.WriteLine("Biogas: " + p.DisplayName + " pooped"); if (Config.Instance.PoopSounds) { MyVisualScriptLogicProvider.PlaySingleSoundAtPosition("Fart" + MyUtils.GetRandomInt(0, 5), p.GetPosition()); } } } }
public static void AddRandomItem(IMyInventory inventory) { Random ran = new Random(); int num = ran.Next(1, 30); int amount = 500; String type = "SteelPlate"; switch (num) { case 1: amount = amount * 2; type = "Construction"; break; case 2: amount = amount / 5; type = "MetalGrid"; break; case 3: amount = amount * 5; type = "InteriorPlate"; break; case 4: amount = amount * 3; type = "Girder"; break; case 5: amount = amount * 4; type = "SmallTube"; break; case 6: amount = amount / 2; type = "LargeTube"; break; case 7: amount = amount / 2; type = "Motor"; break; case 8: amount = amount / 2; type = "Display"; break; case 9: amount = amount / 3; type = "BulletproofGlass"; break; case 10: amount = amount / 5; type = "Superconductor"; break; case 11: amount = 5000; type = "Computer"; break; case 12: amount = amount / 6; type = "Reactor"; break; //case 13: // amount = 50; // type = "Thrust"; // break; case 14: amount = amount / 10; type = "GravityGenerator"; break; case 15: amount = amount / 40; type = "Medical"; break; case 16: amount = 5; type = "RadioCommunication"; break; case 17: amount = amount / 4; type = "Detector"; break; case 18: amount = amount / 5; type = "Explosives"; break; case 19: amount = amount / 4; type = "SolarCell"; break; case 20: amount = amount / 2; type = "PowerCell"; break; case 21: amount = amount / 8; type = "Canvas"; break; default: break; } inventory.AddItems(ran.Next(1, amount), new MyObjectBuilder_Component { SubtypeName = type }); num = ran.Next(1, 100); if (num < 10) { inventory.AddItems(ran.Next(1, 100), new MyObjectBuilder_Ingot { SubtypeName = "Coin" }); } else if (num < 50) { inventory.AddItems(ran.Next(1, 10), new MyObjectBuilder_Ingot { SubtypeName = "Coin" }); } }
internal void TakeRequiredComponents(MyEntity inventoryOwner) { if (MyAPIGateway.Session.CreativeMode) { return; } if (!inventoryOwner.HasInventory) { return; } // Ignore reactors if (inventoryOwner is Sandbox.ModAPI.Ingame.IMyReactor) { return; } if (inventoryOwner is IMyCubeBlock && ((IMyCubeBlock)inventoryOwner).BlockDefinition.SubtypeName.Contains("Nanite")) { return; } int inventoryIndex = inventoryOwner.InventoryCount - 1; //if (inventoryOwner is Sandbox.ModAPI.Ingame.IMyAssembler) // inventoryIndex = 1; IMyInventory constructionInventory = GetConstructionInventory(); IMyInventory inventory = (IMyInventory)inventoryOwner.GetInventoryBase(inventoryIndex); if (constructionInventory == null || inventory == null) { return; } if (((Sandbox.Game.MyInventory)inventory).GetItemsCount() < 1) { return; } //if (!constructionInventory.IsConnectedTo(inventory)) // return; IMyTerminalBlock terminalOwner = inventoryOwner as IMyTerminalBlock; MyRelationsBetweenPlayerAndBlock relation = ((IMyTerminalBlock)m_constructionBlock).GetUserRelationToOwner(terminalOwner.OwnerId); if (relation == MyRelationsBetweenPlayerAndBlock.Enemies) { return; } foreach (var inventoryItem in inventory.GetItems().ToList()) { foreach (var componentNeeded in ComponentsRequired.ToList()) { if (inventoryItem.Content.TypeId != typeof(MyObjectBuilder_Component)) { continue; } if (componentNeeded.Value <= 0) { continue; } if ((int)inventoryItem.Amount <= 0f) { continue; } if (inventoryItem.Content.SubtypeName == componentNeeded.Key) { if (inventoryItem.Amount >= componentNeeded.Value) { var validAmount = GetMaxComponentAmount(componentNeeded.Key, (float)constructionInventory.MaxVolume - (float)constructionInventory.CurrentVolume); var amount = Math.Min(componentNeeded.Value, validAmount); if (!constructionInventory.CanItemsBeAdded((int)amount, new SerializableDefinitionId(typeof(MyObjectBuilder_Component), componentNeeded.Key))) { continue; } inventory.RemoveItemsOfType((int)amount, (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(typeof(MyObjectBuilder_Component), componentNeeded.Key)); constructionInventory.AddItems((int)amount, (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(typeof(MyObjectBuilder_Component), componentNeeded.Key)); ComponentsRequired[componentNeeded.Key] -= (int)amount; } else { var validAmount = GetMaxComponentAmount(componentNeeded.Key, (float)constructionInventory.MaxVolume - (float)constructionInventory.CurrentVolume); var amount = Math.Min((float)inventoryItem.Amount, validAmount); if (!constructionInventory.CanItemsBeAdded((int)amount, new SerializableDefinitionId(typeof(MyObjectBuilder_Component), componentNeeded.Key))) { continue; } inventory.RemoveItemsOfType((int)amount, (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(typeof(MyObjectBuilder_Component), componentNeeded.Key)); constructionInventory.AddItems((int)amount, (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(typeof(MyObjectBuilder_Component), componentNeeded.Key)); ComponentsRequired[componentNeeded.Key] -= (int)amount; } continue; } } } }
public override void UpdateAfterSimulation10() { if ((Block as MyEntity).IsPreview || !(Block as MyEntity).InScene || !Block.IsFunctional || Block.Transparent || Block.CubeGrid.Physics == null) { return; } if (inventory == null) { inventory = Block.GetInventory(); } if (inventory == null) { return; } if (!isHotTub) { if (Block.BlockDefinition.SubtypeId.Contains("Hottub")) { isHotTub = true; } if (isHotTub) { ((MyInventory)inventory).Constraint = new MyInventoryConstraint(MySpaceTexts.ToolTipItemFilter_AnyOre, null, true).Add(WaterData.IceItem.GetId()); FatBlockStorage.HotTubs.Add(this); FatBlockStorage.HotTubs.ApplyAdditions(); } } if (Block.CubeGrid?.Physics?.Gravity != null) { water = WaterMod.Static.GetClosestWater(Block.PositionComp.GetPosition()); } airtight = Block.CubeGrid.IsRoomAtPositionAirtight(Block.Position) ? true : Block.CubeGrid.IsRoomAtPositionAirtight(Block.Position + (Vector3I)Base6Directions.Directions[(int)Block.Orientation.Up]); Vector3D blockPosition = Block.PositionComp.GetPosition(); float depth = water?.GetDepth(ref blockPosition) ?? 0; underWater = depth < 0; if (water?.collectionRate > 0 && !Block.GetInventory().IsFull&& underWater && !airtight) { if (isHotTub) { inventory.AddItems((int)(Math.Max(depth, 1) * 200), WaterData.IceItem); } else { if (Block.IsWorking) { if (Block.CubeGrid.GridSizeEnum == MyCubeSize.Large) { inventory.AddItems((int)(200 * water.collectionRate), WaterData.IceItem); } else { inventory.AddItems((int)(15 * water.collectionRate), WaterData.IceItem); } } } } if (isHotTub) { if (!airtight && underWater) { return; } if (Block.CubeGrid.Physics != null && !Block.CubeGrid.Physics.IsStatic) { Vector3D acccelDirection = Vector3D.Normalize(Block.CubeGrid.Physics.LinearAcceleration - (Block.CubeGrid.Physics.Gravity * 2)); double dot = Vector3D.Dot(acccelDirection, Block.PositionComp.WorldMatrixRef.Up); //double dot = Vector3D.Dot(water.GetUpDirection(Block.PositionComp.GetPosition()), Block.PositionComp.WorldMatrixRef.Up); if (dot < .5) { if (MyAPIGateway.Session.IsServer) { MyFixedPoint amount = (MyFixedPoint)(dot > 0 ? (1f - Math.Abs(dot)) * 25 : 25); inventory.RemoveItemsAt(0, amount, spawn: true); } } } else { double dot = Vector3D.Dot(water.GetUpDirection(Block.PositionComp.GetPosition()), Block.PositionComp.WorldMatrixRef.Up); if (dot < .75) { if (MyAPIGateway.Session.IsServer) { MyFixedPoint amount = (MyFixedPoint)(dot > 0 ? (1f - Math.Abs(dot)) * 25 : 25); inventory.RemoveItemsAt(0, amount, spawn: true); } } } } }
public override void UpdateBeforeSimulation() { if (!MyAPIGateway.Multiplayer.IsServer || PhysicalFuelObject == null || ModBlock.CurrentOutput == 0 || !ModBlock.IsFunctional || !ModBlock.IsWorking) { return; } float powerRatio = ModBlock.CurrentOutput / ModBlock.MaxOutput; double consumptionAmount = MaxConsumptionPerTick * powerRatio; MyFixedPoint quanity = Inventory.GetItemAmount(DefinitionId); // refill fuel tanks if they are low because keens pulling system for reactors is extremely slow. if (quanity < fuelCheckThreshold && quanity != 0) { // refreshes the tank inventories if new blocks have been added. if (refreshInventory) { fuelTanks.Clear(); ModBlock.CubeGrid.GetBlocks(temp, (b) => { if (b.FatBlock != null && !b.FatBlock.BlockDefinition.IsNull() && FuelStorage.Contains(b.FatBlock.BlockDefinition.SubtypeId)) { fuelTanks.Add(b.FatBlock.GetInventory(0)); } return(false); }); refreshInventory = false; } MyFixedPoint emptySpace = EmptySpace; // no reason to run calculations more than once foreach (IMyInventory inv in fuelTanks) { if (inv == null) { continue; } if (!Inventory.IsConnectedTo(inv)) { continue; } MyFixedPoint value = inv.GetItemAmount(DefinitionId); if (value == null) { continue; } if (value > emptySpace) { inv.RemoveItemsOfType(emptySpace, PhysicalFuelObject, false); Inventory.AddItems(emptySpace, PhysicalFuelObject); break; } else if (value != 0) { inv.RemoveItemsOfType(value, PhysicalFuelObject, false); Inventory.AddItems(value, PhysicalFuelObject); break; } } } if (quanity > (MyFixedPoint)consumptionAmount) { Inventory.RemoveItemsOfType((MyFixedPoint)consumptionAmount, PhysicalFuelObject, false); } }
public override void UpdateBeforeSimulation() { int chargesInInventory = (int)m_inventory.GetItemAmount(chargeDefinitionIds [damageUpgrades]); IMyCubeBlock cube = Entity as IMyCubeBlock; long currentShootTime = ((MyObjectBuilder_InteriorTurret)cube.GetObjectBuilderCubeBlock()).GunBase.LastShootTime; if (currentHeat > 0f) { if ((ticks - lastShootTimeTicks) > beamWeaponInfo.heatDissipationDelay) { currentHeat -= beamWeaponInfo.heatDissipationPerTick; if (currentHeat <= 0f) { currentHeat = 0f; overheated = false; } } } //MyAPIGateway.Utilities.ShowNotification("TIME: " + currentShootTime + " :: " + lastShootTime, 17, MyFontEnum.Red); if (currentShootTime != lastShootTime) { // test hitBool = false; MyEntitySubpart subpart1 = cubeBlock.GetSubpart("InteriorTurretBase1"); MyEntitySubpart subpart2 = subpart1.GetSubpart("InteriorTurretBase2");; //MyAPIGateway.Utilities.ShowNotification("Dif: " + (currentShootTime - lastShootTime), 17, MyFontEnum.Blue); from = subpart2.WorldMatrix.Translation + subpart2.WorldMatrix.Forward * 1.25d; to = subpart2.WorldMatrix.Translation + subpart2.WorldMatrix.Forward * 3000d; LineD testRay = new LineD(from, to); List <MyLineSegmentOverlapResult <MyEntity> > result = new List <MyLineSegmentOverlapResult <MyEntity> >(); MyGamePruningStructure.GetAllEntitiesInRay(ref testRay, result); foreach (var resultItem in result) { IMyCubeGrid grid = resultItem.Element as IMyCubeGrid; IMyDestroyableObject destroyableEntity = resultItem.Element as IMyDestroyableObject; if (grid != null) { IMySlimBlock slimblock; double hitd; Vector3D?resultVec = grid.GetLineIntersectionExactAll(ref testRay, out hitd, out slimblock); if (resultVec != null) { hitBool = true; toTarget = from + subpart2.WorldMatrix.Forward * hitd; if (!MyAPIGateway.Session.CreativeMode) { slimblock.DoDamage(beamWeaponInfo.damage * (currentHeat / beamWeaponInfo.maxHeat + 0.2f), MyStringHash.GetOrCompute("Laser"), false, default(MyHitInfo), cubeBlock.EntityId); } else { slimblock.DoDamage(beamWeaponInfo.damage * 1.2f, MyStringHash.GetOrCompute("Laser"), false, default(MyHitInfo), cubeBlock.EntityId); } //MyAPIGateway.Utilities.ShowNotification("" + s.BlockDefinition.Id.SubtypeId + " ::: " + resultItem.Distance, 17); } } if (destroyableEntity != null) { IMyEntity ent = (IMyEntity)destroyableEntity; double hitd = (from - ent.WorldMatrix.Translation).Length(); toTarget = from + subpart2.WorldMatrix.Forward * hitd; hitBool = true; if (!MyAPIGateway.Session.CreativeMode) { destroyableEntity.DoDamage(beamWeaponInfo.damage * (currentHeat / beamWeaponInfo.maxHeat + 0.2f), MyStringHash.GetOrCompute("Laser"), false, default(MyHitInfo), cubeBlock.EntityId); } else { destroyableEntity.DoDamage(beamWeaponInfo.damage * 1.2f, MyStringHash.GetOrCompute("Laser"), false, default(MyHitInfo), cubeBlock.EntityId); } } } // test lastShootTime = currentShootTime; lastShootTimeTicks = ticks; currentHeat += beamWeaponInfo.heatPerTick; if (currentHeat > beamWeaponInfo.maxHeat) { currentHeat = beamWeaponInfo.maxHeat; overheated = true; } } if (ticks - lastShootTimeTicks < 3) { var beamcolor = Color.DodgerBlue; var beamcolor_aux = Color.LightSkyBlue; var maincolor = new Vector4(beamcolor.X / 30, beamcolor.Y / 30, beamcolor.Z / 30, 1f); var auxcolor = new Vector4(beamcolor_aux.X / 30, beamcolor_aux.Y / 30, beamcolor_aux.Z / 30, 1f); var material = MyStringId.GetOrCompute("WeaponLaser"); if (hitBool == false) { if (!MyAPIGateway.Utilities.IsDedicated) { if (!MyAPIGateway.Session.CreativeMode) { VRage.Game.MySimpleObjectDraw.DrawLine(from, to, material, ref auxcolor, 0.30f); VRage.Game.MySimpleObjectDraw.DrawLine(from, to, material, ref maincolor, 1.0f); } else { VRage.Game.MySimpleObjectDraw.DrawLine(from, to, material, ref auxcolor, 0.30f * 1.2f); VRage.Game.MySimpleObjectDraw.DrawLine(from, to, material, ref maincolor, 1.0f * 1.2f); } } } else { if (!MyAPIGateway.Utilities.IsDedicated) { if (!MyAPIGateway.Session.CreativeMode) { VRage.Game.MySimpleObjectDraw.DrawLine(from, toTarget, material, ref auxcolor, 0.30f); VRage.Game.MySimpleObjectDraw.DrawLine(from, toTarget, material, ref maincolor, 1.0f); } else { VRage.Game.MySimpleObjectDraw.DrawLine(from, toTarget, material, ref auxcolor, 0.30f * 1.2f); VRage.Game.MySimpleObjectDraw.DrawLine(from, toTarget, material, ref maincolor, 1.0f * 1.2f); } } } } if (chargesInInventory < beamWeaponInfo.keepAtCharge) { if (resourceSink.RequiredInputByType(electricityDefinition) != (beamWeaponInfo.powerUsage / efficiencyUpgrades)) { resourceSink.SetRequiredInputByType(electricityDefinition, (beamWeaponInfo.powerUsage / efficiencyUpgrades)); setPowerConsumption = (beamWeaponInfo.powerUsage / efficiencyUpgrades); powerConsumption = (beamWeaponInfo.powerUsage / efficiencyUpgrades); } else { if (!functionalBlock.Enabled) { powerConsumption = 0.0001f; } } if (resourceSink.CurrentInputByType(electricityDefinition) == (beamWeaponInfo.powerUsage / efficiencyUpgrades)) { if (!overheated) { m_inventory.AddItems((MyFixedPoint)(beamWeaponInfo.keepAtCharge - chargesInInventory), chargeObjectBuilders [damageUpgrades]); } } } else if (chargesInInventory > beamWeaponInfo.keepAtCharge) { m_inventory.RemoveItemsOfType((MyFixedPoint)(chargesInInventory - beamWeaponInfo.keepAtCharge), chargeObjectBuilders [damageUpgrades]); } else { if (setPowerConsumption != 0.0001f) { resourceSink.SetRequiredInputByType(electricityDefinition, 0.0001f); setPowerConsumption = 0.0001f; powerConsumption = 0.0001f; } } terminalBlock.RefreshCustomInfo(); ticks++; }