Пример #1
0
        private static void FixTransferAmount(MyInventory src, MyInventory dst, MyPhysicalInventoryItem?srcItem, bool spawn, ref MyFixedPoint remove, ref MyFixedPoint add)
        {
            Debug.Assert(Sync.IsServer);
            if (srcItem.Value.Amount < remove)
            {
                remove = srcItem.Value.Amount;
                add    = remove;
            }

            if (!MySession.Static.CreativeMode && !src.Equals(dst))
            {
                MyFixedPoint space = dst.ComputeAmountThatFits(srcItem.Value.Content.GetId());
                if (space < remove)
                {
                    if (spawn)
                    {
                        MyEntity e = (dst.Owner as MyEntity);
                        Matrix   m = e.WorldMatrix;
                        MyFloatingObjects.Spawn(new MyPhysicalInventoryItem(remove - space, srcItem.Value.Content), e.PositionComp.GetPosition() + m.Forward + m.Up, m.Forward, m.Up, e.Physics);
                    }
                    else
                    {
                        remove = space;
                    }
                    add = space;
                }
            }
        }
        private static void SpawnIntoContainer_Implementation(long amount, SerializableDefinitionId item, long entityId, long playerId)
        {
            if (!MyEventContext.Current.IsLocallyInvoked && !MySession.Static.HasPlayerCreativeRights(MyEventContext.Current.Sender.Value))
            {
                MyEventContext.ValidationFailed();
                return;
            }

            MyEntity entity;

            if (!MyEntities.TryGetEntityById(entityId, out entity))
            {
                return;
            }

            if (!entity.HasInventory || !((MyTerminalBlock)entity).HasPlayerAccess(playerId))
            {
                return;
            }

            MyInventory inventory = entity.GetInventory();

            if (!inventory.CheckConstraint(item))
            {
                return;
            }

            MyFixedPoint itemAmt = (MyFixedPoint)Math.Min(amount, (decimal)inventory.ComputeAmountThatFits(item));

            inventory.AddItems(itemAmt, (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(item));
        }
        private float GetNaniteInventoryAmountThatFits(IMyEntity target, MyCubeBlock block)
        {
            if (!block.HasInventory)
            {
                return(0f);
            }

            MyFloatingObject floating = (MyFloatingObject)target;

            var          def        = MyDefinitionManager.Static.GetPhysicalItemDefinition(new VRage.Game.MyDefinitionId(floating.Item.Content.TypeId, floating.Item.Content.SubtypeId));
            MyInventory  inventory  = block.GetInventory();
            MyFixedPoint amountFits = inventory.ComputeAmountThatFits(new VRage.Game.MyDefinitionId(floating.Item.Content.TypeId, floating.Item.Content.SubtypeId));

            //Logging.Instance.WriteLine(string.Format("AmountFits: {0} - {1}", amountFits, def.Volume));
            //float amount;

            /*
             * if (amountFits * def.Volume > 1)
             * {
             *  amount = 1f / def.Volume;
             * }
             * else
             *  amount = (float)amountFits;
             */

            return((float)amountFits);
        }
Пример #4
0
        public void SpawnRandomCargo()
        {
            if (m_containerType == null)
            {
                return;
            }

            MyContainerTypeDefinition containerDefinition = MyDefinitionManager.Static.GetContainerTypeDefinition(m_containerType);

            if (containerDefinition != null && containerDefinition.Items.Count() > 0)
            {
                int itemNumber = MyUtils.GetRandomInt(containerDefinition.CountMin, containerDefinition.CountMax);
                for (int i = 0; i < itemNumber; ++i)
                {
                    MyContainerTypeDefinition.ContainerTypeItem item = containerDefinition.SelectNextRandomItem();
                    MyFixedPoint amount = (MyFixedPoint)MyRandom.Instance.NextFloat((float)item.AmountMin, (float)item.AmountMax);

                    if (MyDefinitionManager.Static.GetPhysicalItemDefinition(item.DefinitionId).HasIntegralAmounts)
                    {
                        amount = MyFixedPoint.Ceiling(amount); // Use ceiling to avoid amounts equal to 0
                    }

                    amount = MyFixedPoint.Min(m_inventory.ComputeAmountThatFits(item.DefinitionId), amount);
                    if (amount > 0)
                    {
                        var inventoryItem = (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(item.DefinitionId);
                        m_inventory.AddItems(amount, inventoryItem);
                    }
                }
                containerDefinition.DeselectAll();
            }
        }
Пример #5
0
 private static bool ComputeFloatingObjectAmount(MyFloatingObject obj, ref MyFixedPoint amount, MyInventory inv)
 {
     amount = obj.Item.Amount;
     if (!MySession.Static.CreativeMode)
     {
         amount = MyFixedPoint.Min(amount, inv.ComputeAmountThatFits(obj.Item.Content.GetId()));
     }
     if (amount <= 0) // does not fit into inventory
     {
         return(false);
     }
     return(true);
 }
Пример #6
0
        private float GetNaniteInventoryAmountThatFits(IMyEntity target, MyCubeBlock block)
        {
            if (!block.HasInventory)
            {
                return(0f);
            }

            var def = MyDefinitionManager.Static.GetPhysicalItemDefinition
                          (new VRage.Game.MyDefinitionId(((MyFloatingObject)target).Item.Content.TypeId, ((MyFloatingObject)target).Item.Content.SubtypeId));
            MyInventory  inventory  = block.GetInventory();
            MyFixedPoint amountFits = inventory.ComputeAmountThatFits
                                          (new VRage.Game.MyDefinitionId(((MyFloatingObject)target).Item.Content.TypeId, ((MyFloatingObject)target).Item.Content.SubtypeId));

            return((float)amountFits);
        }
        private static bool FillInventoryWithIron()
        {
            IMyInventoryOwner invObject = MySession.ControlledEntity as IMyInventoryOwner;

            if (invObject != null)
            {
                MyFixedPoint amount = 20000;

                var         oreBuilder = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Ore>("Iron");
                MyInventory inventory  = invObject.GetInventory(0);
                amount = inventory.ComputeAmountThatFits(oreBuilder.GetId());

                inventory.AddItems(amount, oreBuilder);
            }

            return(true);
        }
        private static bool FillInventoryWithIron()
        {
            var invObject = MySession.Static.ControlledEntity as MyEntity;

            if (invObject != null && invObject.HasInventory)
            {
                MyFixedPoint amount = 20000;

                var oreBuilder = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Ore>("Iron");
                System.Diagnostics.Debug.Assert(invObject.GetInventory(0) as MyInventory != null, "Null or unexpected inventory type returned!");
                MyInventory inventory = invObject.GetInventory(0) as MyInventory;
                amount = inventory.ComputeAmountThatFits(oreBuilder.GetId());

                inventory.AddItems(amount, oreBuilder);
            }

            return(true);
        }
Пример #9
0
        public void Fill(MyInventory target, MyDefinitionId itemId)
        {
            if (target == null)
            {
                return;
            }

            MyFixedPoint ammoNeeded = target.ComputeAmountThatFits(itemId);

            foreach (MyInventory source in Inventories)
            {
                if (ammoNeeded == 0)
                {
                    return;
                }

                var item = source.FindItem(itemId);

                if (!item.HasValue || item.Value.Amount == 0)
                {
                    continue;
                }

                if (!((IMyInventory)source).IsConnectedTo(target))
                {
                    continue;
                }

                int index = source.GetItemIndexById(item.Value.ItemId);
                if (item.Value.Amount > ammoNeeded)
                {
                    target.TransferItemFrom(source, index, null, true, ammoNeeded);
                    break;
                }
                else
                {
                    target.TransferItemFrom(source, index, null, true, item.Value.Amount);
                    ammoNeeded -= item.Value.Amount;
                }
            }
        }
Пример #10
0
        private void TransferFromTarget(MyCubeBlock target)
        {
            MyInventory targetInventory = ((MyCubeBlock)m_constructionBlock.ConstructionBlock).GetInventory();
            MyInventory sourceInventory = target.GetInventory();

            foreach (var item in sourceInventory.GetItems().ToList())
            {
                if (targetInventory.ItemsCanBeAdded(item.Amount, item))
                {
                    targetInventory.TransferItemsFrom(sourceInventory, item, item.Amount);
                }
                else
                {
                    int amountFits = (int)targetInventory.ComputeAmountThatFits(new MyDefinitionId(item.Content.TypeId, item.Content.SubtypeId));
                    if (amountFits > 0f)
                    {
                        targetInventory.TransferItemsFrom(sourceInventory, item, amountFits);
                    }
                }
            }

            if (sourceInventory.GetItems().Count < 1)
            {
                return;
            }

            if (GridHelper.FindFreeCargo(target, (MyCubeBlock)m_constructionBlock.ConstructionBlock))
            {
                return;
            }

            // We have left over inventory, drop it
            foreach (var item in sourceInventory.GetItems().ToList())
            {
                sourceInventory.RemoveItems(item.ItemId, item.Amount, spawn: true);
            }
        }
        void confirmButton_OnButtonClick(MyGuiControlButton sender)
        {
            MyEntity invObject = MySession.Static.ControlledEntity as MyEntity;

            if (invObject != null && invObject.HasInventory)
            {
                double amountDec = 0;
                double.TryParse(m_amountTextbox.Text, out amountDec);
                m_lastAmount = amountDec;

                MyFixedPoint amount = (MyFixedPoint)amountDec;

                if (m_items.GetSelectedKey() < 0 || (int)m_items.GetSelectedKey() >= m_physicalItemDefinitions.Count)
                {
                    return;
                }

                var itemId = m_physicalItemDefinitions[(int)m_items.GetSelectedKey()].Id;
                m_lastSelectedItem = (int)m_items.GetSelectedKey();
                MyInventory inventory = invObject.GetInventory(0) as MyInventory;
                System.Diagnostics.Debug.Assert(inventory != null, "Null or other inventory type!");

                if (inventory != null)
                {
                    if (!MySession.Static.CreativeMode)
                    {
                        amount = MyFixedPoint.Min(inventory.ComputeAmountThatFits(itemId), amount);
                    }

                    var builder = (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(itemId);
                    inventory.DebugAddItems(amount, builder);
                }
            }

            CloseScreen();
        }
        void confirmButton_OnButtonClick(MyGuiControlButton sender)
        {
            IMyInventoryOwner invObject = MySession.ControlledEntity as IMyInventoryOwner;

            if (invObject != null)
            {
                double amountDec = 0;
                double.TryParse(m_amountTextbox.Text, out amountDec);

                MyFixedPoint amount = (MyFixedPoint)amountDec;

                var         itemId    = m_physicalItemDefinitions[(int)m_items.GetSelectedKey()].Id;
                MyInventory inventory = invObject.GetInventory(0);
                if (!MySession.Static.CreativeMode)
                {
                    amount = MyFixedPoint.Min(inventory.ComputeAmountThatFits(itemId), amount);
                }

                var builder = (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(itemId);
                inventory.DebugAddItems(amount, builder);
            }

            CloseScreen();
        }
Пример #13
0
        public void MoveUnneededItemsFromConstructionStockpile(MyInventory 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();
        }
Пример #14
0
        /// <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(MyInventory 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();
        }
Пример #15
0
        public static bool FindFreeCargo(MyCubeBlock target, MyCubeBlock startBlock, bool ignoreOtherFactories = false)
        {
            var list = Conveyor.GetConveyorListFromEntity(startBlock);

            if (list == null)
            {
                return(false);
            }

            List <MyInventory> inventoryList = new List <MyInventory>();

            foreach (var item in list)
            {
                IMyEntity entity;
                if (MyAPIGateway.Entities.TryGetEntityById(item, out entity))
                {
                    if (!(entity is IMyCubeBlock))
                    {
                        continue;
                    }

                    if (target == (MyCubeBlock)entity)
                    {
                        continue;
                    }

                    if (entity is Ingame.IMyRefinery || entity is Ingame.IMyAssembler)
                    {
                        continue;
                    }

                    if (ignoreOtherFactories && ((IMyCubeBlock)entity).BlockDefinition.SubtypeName == "LargeNaniteFactory")
                    {
                        continue;
                    }

                    MyCubeBlock block = (MyCubeBlock)entity;
                    if (!block.HasInventory)
                    {
                        continue;
                    }

                    inventoryList.Add(block.GetInventory());
                }
            }

            MyInventory sourceInventory = target.GetInventory();
            MyInventory targetInventory = null;

            foreach (var item in inventoryList.OrderByDescending(x => (float)x.MaxVolume - (float)x.CurrentVolume))
            {
                targetInventory = item;

                foreach (var subItem in sourceInventory.GetItems().ToList())
                {
                    if (targetInventory.ItemsCanBeAdded(subItem.Amount, subItem))
                    {
                        targetInventory.TransferItemsFrom(sourceInventory, subItem, subItem.Amount);
                    }
                    else
                    {
                        int amountFits = (int)targetInventory.ComputeAmountThatFits(new MyDefinitionId(subItem.Content.TypeId, subItem.Content.SubtypeId));
                        if (amountFits > 0f)
                        {
                            targetInventory.TransferItemsFrom(sourceInventory, subItem, amountFits);
                        }
                    }
                }
            }

            if (sourceInventory.GetItems().Count < 1)
            {
                return(true);
            }

            return(false);
        }
Пример #16
0
 private static bool ComputeFloatingObjectAmount(MyFloatingObject obj, ref MyFixedPoint amount, MyInventory inv)
 {
     amount = obj.Item.Amount;
     if (!MySession.Static.CreativeMode)
         amount = MyFixedPoint.Min(amount, inv.ComputeAmountThatFits(obj.Item.Content.GetId()));
     if (amount <= 0) // does not fit into inventory
         return false;
     return true;
 }
Пример #17
0
        private static void FixTransferAmount(MyInventory src, MyInventory dst, MyInventoryItem? srcItem, bool spawn, ref MyFixedPoint remove, ref MyFixedPoint add)
        {
            Debug.Assert(Sync.IsServer);
            if (srcItem.Value.Amount < remove)
            {
                remove = srcItem.Value.Amount;
                add = remove;
            }

            if (!MySession.Static.CreativeMode && !src.Equals(dst))
            {
                MyFixedPoint space = dst.ComputeAmountThatFits(srcItem.Value.Content.GetId());
                if (space < remove)
                {
                    if (spawn)
                    {
                        MyEntity e = (dst.Owner as MyEntity);
                        Matrix m = e.WorldMatrix;
                        MyFloatingObjects.Spawn(new MyInventoryItem(remove - space, srcItem.Value.Content), e.PositionComp.GetPosition() + m.Forward + m.Up, m.Forward, m.Up, e.Physics);
                    }
                    else
                    {
                        remove = space;
                    }
                    add = space;
                }
            }
        }
Пример #18
0
        public static bool PullAllRequest(IMyConveyorEndpointBlock start, MyInventory destinationInventory, long playerId, MyInventoryConstraint requestedTypeIds)
        {
            MyCubeBlock startingBlock = start as MyCubeBlock;
            if (startingBlock == null) return false;

            m_tmpRequestedItemSet.Set(requestedTypeIds);

            // Try and get the block from the cache
            MyGridConveyorSystem conveyorSystem = startingBlock.CubeGrid.GridSystems.ConveyorSystem;
            MyGridConveyorSystem.ConveyorEndpointMapping endpoints = conveyorSystem.GetConveyorEndpointMapping(start);
            if (endpoints.pullElements != null)
            {
                bool didTransfer = false;

                // Iterate to the other elements, see if we can collect some amount of items to pull
                for (int i = 0; i < endpoints.pullElements.Count; i++)
                {
                    MyCubeBlock sourceBlock = endpoints.pullElements[i] as MyCubeBlock;
                    if (sourceBlock == null) continue;

                    int inventoryCount = sourceBlock.InventoryCount;
                    for (int inventoryIndex = 0; inventoryIndex < inventoryCount; inventoryIndex++)
                    {
                        MyInventory inventory = sourceBlock.GetInventory(inventoryIndex);
                        if ((inventory.GetFlags() & MyInventoryFlags.CanSend) == 0)
                            continue;

                        if (inventory == destinationInventory)
                            continue;

                        m_tmpInventoryItems.Clear();
                        foreach (var item in inventory.GetItems())
                        {
                            m_tmpInventoryItems.Add(item);
                        }

                        foreach (var item in m_tmpInventoryItems)
                        {
                            if (destinationInventory.VolumeFillFactor >= 1.0f)
                            {
                                m_tmpInventoryItems.Clear();
                                return true;
                            }

                            var itemId = item.Content.GetId();

                            if (requestedTypeIds != null && !m_tmpRequestedItemSet.Contains(itemId))
                                continue;

                            // Verify that this item can, in fact, make it past sorters, etc
                            if (!CanTransfer(start, endpoints.pullElements[i], itemId, false))
                                continue;

                            var transferedAmount = item.Amount;

                            var oxygenBottle = item.Content as Sandbox.Common.ObjectBuilders.Definitions.MyObjectBuilder_GasContainerObject;
                            if (oxygenBottle != null && oxygenBottle.GasLevel >= 1f)
                                continue;

                            if (!MySession.Static.CreativeMode)
                            {
                                var fittingAmount = destinationInventory.ComputeAmountThatFits(item.Content.GetId());
                                if (item.Content.TypeId != typeof(MyObjectBuilder_Ore) &&
                                    item.Content.TypeId != typeof(MyObjectBuilder_Ingot))
                                {
                                    fittingAmount = MyFixedPoint.Floor(fittingAmount);
                                }
                                transferedAmount = MyFixedPoint.Min(fittingAmount, transferedAmount);
                            }
                            if (transferedAmount == 0)
                                continue;

                            didTransfer = true;
                            MyInventory.Transfer(inventory, destinationInventory, item.Content.GetId(), MyItemFlags.None, transferedAmount);

                            if (destinationInventory.CargoPercentage >= 0.99f)
                                break;
                        }

                        if (destinationInventory.CargoPercentage >= 0.99f)
                            break;
                    }

                    if (destinationInventory.CargoPercentage >= 0.99f)
                        break;
                }

                return didTransfer;
            }

            else
            {
                // Cache may need to be recomputed
                if (!conveyorSystem.m_isRecomputingGraph)
                    conveyorSystem.RecomputeConveyorEndpoints();
            }

            return false;
        }
Пример #19
0
        private static bool ItemPullAll(IMyConveyorEndpointBlock start, MyInventory destinationInventory)
        {
            MyCubeBlock startingBlock = start as MyCubeBlock;
            if (startingBlock == null) return false;

            bool itemsPulled = false;

            // Try and get the block from the cache
            MyGridConveyorSystem conveyorSystem = startingBlock.CubeGrid.GridSystems.ConveyorSystem;
            MyGridConveyorSystem.ConveyorEndpointMapping endpoints = conveyorSystem.GetConveyorEndpointMapping(start);
            if (endpoints.pullElements != null)
            {
                // Iterate to the other elements, see if we can collect some amount of items to pull
                for (int i = 0; i < endpoints.pullElements.Count; i++)
                {
                    MyCubeBlock sourceBlock = endpoints.pullElements[i] as MyCubeBlock;
                    if (sourceBlock == null) continue;

                    int inventoryCount = sourceBlock.InventoryCount;
                    for (int inventoryIndex = 0; inventoryIndex < inventoryCount; inventoryIndex++)
                    {
                        MyInventory inventory = sourceBlock.GetInventory(inventoryIndex);
                        if ((inventory.GetFlags() & MyInventoryFlags.CanSend) == 0)
                            continue;

                        if (inventory == destinationInventory)
                            continue;

                        var items = inventory.GetItems().ToArray();
                        for (int itemIndex = 0; itemIndex < items.Length; itemIndex++)
                        {
                            var item = items[itemIndex];
                            var itemId = item.GetDefinitionId();

                            var amountThatFits = destinationInventory.ComputeAmountThatFits(itemId);
                            if (amountThatFits <= 0)
                                continue;

                            // Verify that this item can, in fact, make it past sorters, etc
                            if (!CanTransfer(start, endpoints.pullElements[i], itemId, false))
                                continue;

                            var availableAmount = inventory.GetItemAmount(itemId);
                            var transferAmount = MyFixedPoint.Min(availableAmount, amountThatFits);

                            MyInventory.Transfer(inventory, destinationInventory, itemId, MyItemFlags.None, transferAmount);
                            itemsPulled = true;

                            if (destinationInventory.CargoPercentage >= 0.99f)
                                break;
                        }

                        if (destinationInventory.CargoPercentage >= 0.99f)
                            break;
                    }

                    if (destinationInventory.CargoPercentage >= 0.99f)
                        break;
                }
            }

            else
            {
                // Cache may need to be recomputed
                if (!conveyorSystem.m_isRecomputingGraph)
                    conveyorSystem.RecomputeConveyorEndpoints();
            }
            return itemsPulled;
        }
Пример #20
0
        private static void ItemPullAllInternal(MyInventory destinationInventory, PullRequestItemSet requestedTypeIds, bool onlySmall)
        {
            SetTraversalInventoryItemDefinitionId();
            Debug.Assert(m_tmpPullRequests.Count == 0, "m_tmpPullRequests is not empty!");
            using (var invertedConductivity = new MyConveyorLine.InvertedConductivity())
            {
                foreach (var conveyorEndpoint in MyGridConveyorSystem.Pathfinding)
                {
                    IMyInventoryOwner owner = conveyorEndpoint.CubeBlock as IMyInventoryOwner;
                    if (owner == null) continue;

                    for (int i = 0; i < owner.InventoryCount; ++i)
                    {
                        var inventory = owner.GetInventory(i);
                        if ((inventory.GetFlags() & MyInventoryFlags.CanSend) == 0)
                            continue;

                        if (inventory == destinationInventory)
                            continue;

                        m_tmpInventoryItems.Clear();
                        foreach (var item in inventory.GetItems())
                        {
                            m_tmpInventoryItems.Add(item);
                        }

                        foreach (var item in m_tmpInventoryItems)
                        {
                            if (destinationInventory.VolumeFillFactor >= 1.0f)
                            {
                                m_tmpInventoryItems.Clear();
                                return;
                            }

                            var itemId = item.Content.GetId();

                            if (requestedTypeIds != null && !requestedTypeIds.Contains(itemId))
                                continue;

                            if (onlySmall && NeedsLargeTube(itemId))
                                continue;

                            var transferedAmount = item.Amount;

                            var oxygenBottle = item.Content as Sandbox.Common.ObjectBuilders.Definitions.MyObjectBuilder_OxygenContainerObject;
                            if (oxygenBottle != null && oxygenBottle.OxygenLevel == 1f)
                                continue;

                            if (!MySession.Static.CreativeMode)
                            {
                                var fittingAmount = destinationInventory.ComputeAmountThatFits(item.Content.GetId());
                                if (item.Content.TypeId != typeof(MyObjectBuilder_Ore) &&
                                    item.Content.TypeId != typeof(MyObjectBuilder_Ingot))
                                {
                                    fittingAmount = MyFixedPoint.Floor(fittingAmount);
                                }
                                transferedAmount = MyFixedPoint.Min(fittingAmount, transferedAmount);
                            }
                            if (transferedAmount == 0)
                                continue;

                            // SK: this is mental
                            m_tmpPullRequests.Add(new MyTuple<IMyConveyorEndpointBlock, MyPhysicalInventoryItem>(m_startingEndpoint.CubeBlock as IMyConveyorEndpointBlock, item));
                            //MyInventory.Transfer(inventory, destinationInventory, item.Content.GetId(), MyItemFlags.None, transferedAmount);
                        }
                    }
                }
            }

            foreach (var tuple in m_tmpPullRequests)
            {
                if (destinationInventory.VolumeFillFactor >= 1.0f)
                {
                    m_tmpPullRequests.Clear();
                    return;
                }

                var start = tuple.Item1;
                var item = tuple.Item2;

                var transferedAmount = item.Amount;
                var fittingAmount = destinationInventory.ComputeAmountThatFits(item.Content.GetId());
                if (item.Content.TypeId != typeof(MyObjectBuilder_Ore) &&
                    item.Content.TypeId != typeof(MyObjectBuilder_Ingot))
                {
                    fittingAmount = MyFixedPoint.Floor(fittingAmount);
                }
                transferedAmount = MyFixedPoint.Min(fittingAmount, transferedAmount);

                if (transferedAmount == 0)
                    continue;

                var itemId = item.Content.GetId();

                SetTraversalInventoryItemDefinitionId(itemId);
                ItemPullRequest(start, destinationInventory, m_playerIdForAccessiblePredicate, itemId, transferedAmount);
            }

            m_tmpPullRequests.Clear();
        }
Пример #21
0
        public static bool FindFreeCargo(MyCubeBlock target, MyCubeBlock startBlock, bool ignoreOtherFactories = false)
        {
            var list = Conveyor.GetConveyorListFromEntity(startBlock);

            if (list == null)
            {
                return(false);
            }

            List <MyInventory> inventoryList = new List <MyInventory>();

            foreach (var item in list)
            {
                IMyEntity entity;
                if (MyAPIGateway.Entities.TryGetEntityById(item, out entity))
                {
                    if (!(entity is IMyCubeBlock))
                    {
                        continue;
                    }

                    if (target == (MyCubeBlock)entity)
                    {
                        continue;
                    }

                    if (entity is Ingame.IMyRefinery || entity is Ingame.IMyAssembler)
                    {
                        continue;
                    }

                    if (ignoreOtherFactories && ((IMyCubeBlock)entity).BlockDefinition.SubtypeName == "LargeNaniteFactory")
                    {
                        continue;
                    }

                    MyCubeBlock block = (MyCubeBlock)entity;
                    if (!block.HasInventory)
                    {
                        continue;
                    }

                    inventoryList.Add(block.GetInventory());
                }
            }

            MyInventory sourceInventory = target.GetInventory();
            MyInventory targetInventory = null;

            foreach (var item in inventoryList.OrderByDescending(x => (float)x.MaxVolume - (float)x.CurrentVolume))
            {
                targetInventory = item;
                List <VRage.Game.Entity.MyPhysicalInventoryItem> items = sourceInventory.GetItems();
                for (int i = 0; i < items.Count; i++)
                {
                    IMyInventoryItem subItem = items[i] as IMyInventoryItem;
                    if (subItem == null)
                    {
                        VRage.Utils.MyLog.Default.WriteLineAndConsole("WARNING: IMyInventoryItem subItem was NULL: NaniteConstructionSystem.Extensions.GridHelper.TryMoveToFreeCargo");
                        continue;
                    }
                    if (targetInventory.ItemsCanBeAdded(subItem.Amount, subItem))
                    {
                        targetInventory.TransferItemFrom(sourceInventory, i, null, null, subItem.Amount);
                    }
                    else
                    {
                        int amountFits = (int)targetInventory.ComputeAmountThatFits(new MyDefinitionId(subItem.Content.TypeId, subItem.Content.SubtypeId));
                        if (amountFits > 0f)
                        {
                            targetInventory.TransferItemFrom(sourceInventory, i, null, null, amountFits);
                        }
                    }
                }
            }

            if (sourceInventory.GetItems().Count < 1)
            {
                return(true);
            }

            return(false);
        }
        public static void TryMoveToFreeCargo(MyCubeBlock source, List <IMyInventory> connectedInventory, bool ignoreOtherFactories = false)
        {
            try
            {
                List <IMyInventory> removalList     = new List <IMyInventory>();
                MyInventory         sourceInventory = source.GetInventory();
                foreach (IMyInventory inv in connectedInventory.OrderByDescending(x => (float)x.MaxVolume - (float)x.CurrentVolume))
                {
                    MyInventory  targetInventory = inv as MyInventory;
                    IMyInventory outinv          = null;
                    if (!IsValidInventoryConnection(sourceInventory, targetInventory, out outinv))
                    {
                        removalList.Add(inv);
                        continue;
                    }

                    if ((IMyEntity)(targetInventory.Owner) is IMyProductionBlock)
                    {
                        continue; // Dont push to assembler inventories
                    }
                    List <VRage.Game.Entity.MyPhysicalInventoryItem> items = sourceInventory.GetItems();
                    for (int i = 0; i < items.Count; i++)
                    {
                        IMyInventoryItem subItem = items[i] as IMyInventoryItem;
                        if (subItem == null)
                        {
                            continue;
                        }

                        MyAPIGateway.Utilities.InvokeOnGameThread(() =>
                        {
                            try
                            {
                                if (subItem == null || targetInventory == null || sourceInventory == null)
                                {
                                    return;
                                }

                                MyFixedPoint amountFits = targetInventory.ComputeAmountThatFits(new MyDefinitionId(subItem.Content.TypeId, subItem.Content.SubtypeId));
                                amountFits = (amountFits > subItem.Amount) ? subItem.Amount : amountFits;

                                if (amountFits > (MyFixedPoint)0f && sourceInventory.Remove(subItem, amountFits))
                                {
                                    targetInventory.Add(subItem, amountFits);
                                }
                            }
                            catch (Exception e)
                            { Logging.Instance.WriteLine($"NaniteConstructionSystem.Extensions.GridHelper.TryMoveToFreeCargo:\n{e.ToString()}"); }
                        });
                    }
                }
                foreach (IMyInventory inv in removalList)
                {
                    MyAPIGateway.Utilities.InvokeOnGameThread(() =>
                                                              { connectedInventory.Remove(inv); });
                }
            }
            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);
            }
        }
Пример #23
0
        public static bool PullAny(this MyInventory inventory, HashSet <IMyTerminalBlock> sourceInventories, Dictionary <string, int> toPull)
        {
            bool result = false;

            foreach (KeyValuePair <string, int> entry in toPull)
            {
                int remainingAmount = entry.Value;
                //Logging.Instance.WriteDebug(entry.Key + entry.Value);
                foreach (IMyTerminalBlock block in sourceInventories)
                {
                    if (block == null || block.Closed)
                    {
                        continue;
                    }

                    MyInventory sourceInventory;
                    //get the output inventory for production blocks
                    if (((MyEntity)block).InventoryCount > 1)
                    {
                        sourceInventory = ((MyEntity)block).GetInventory(1);
                    }
                    else
                    {
                        sourceInventory = ((MyEntity)block).GetInventory();
                    }

                    List <MyPhysicalInventoryItem> sourceItems = sourceInventory.GetItems();
                    if (sourceItems.Count == 0)
                    {
                        continue;
                    }

                    var toMove = new List <KeyValuePair <MyPhysicalInventoryItem, int> >();
                    foreach (MyPhysicalInventoryItem item in sourceItems)
                    {
                        if (item.Content.SubtypeName == entry.Key)
                        {
                            if (item.Amount <= 0) //KEEEN
                            {
                                continue;
                            }

                            if (item.Amount >= remainingAmount)
                            {
                                toMove.Add(new KeyValuePair <MyPhysicalInventoryItem, int>(item, remainingAmount));
                                remainingAmount = 0;
                                result          = true;
                            }
                            else
                            {
                                remainingAmount -= (int)item.Amount;
                                toMove.Add(new KeyValuePair <MyPhysicalInventoryItem, int>(item, (int)item.Amount));
                                result = true;
                            }
                        }
                    }

                    foreach (KeyValuePair <MyPhysicalInventoryItem, int> itemEntry in toMove)
                    {
                        if (inventory.ComputeAmountThatFits(itemEntry.Key.Content.GetId()) < itemEntry.Value)
                        {
                            return(false);
                        }

                        sourceInventory.Remove(itemEntry.Key, itemEntry.Value);
                        inventory.Add(itemEntry.Key, itemEntry.Value);
                    }

                    if (remainingAmount == 0)
                    {
                        break;
                    }
                }
            }

            return(result);
        }
        private static bool ItemPullAllInternal(MyInventory destinationInventory, PullRequestItemSet requestedTypeIds, bool onlySmall)
        {
            bool pullCreated = false;

            SetTraversalInventoryItemDefinitionId();
            Debug.Assert(m_tmpPullRequests.Count == 0, "m_tmpPullRequests is not empty!");
            using (var invertedConductivity = new MyConveyorLine.InvertedConductivity())
            {
                foreach (var conveyorEndpoint in MyGridConveyorSystem.Pathfinding)
                {
                    MyCubeBlock owner = (conveyorEndpoint.CubeBlock != null && conveyorEndpoint.CubeBlock.HasInventory) ? conveyorEndpoint.CubeBlock : null;
                    if (owner == null)
                    {
                        continue;
                    }

                    for (int i = 0; i < owner.InventoryCount; ++i)
                    {
                        var inventory = owner.GetInventory(i) as MyInventory;
                        System.Diagnostics.Debug.Assert(inventory != null, "Null or other inventory type!");

                        if ((inventory.GetFlags() & MyInventoryFlags.CanSend) == 0)
                        {
                            continue;
                        }

                        if (inventory == destinationInventory)
                        {
                            continue;
                        }

                        m_tmpInventoryItems.Clear();
                        foreach (var item in inventory.GetItems())
                        {
                            m_tmpInventoryItems.Add(item);
                        }

                        foreach (var item in m_tmpInventoryItems)
                        {
                            if (destinationInventory.VolumeFillFactor >= 1.0f)
                            {
                                m_tmpInventoryItems.Clear();
                                return(pullCreated);
                            }

                            var itemId = item.Content.GetId();

                            if (requestedTypeIds != null && !requestedTypeIds.Contains(itemId))
                            {
                                continue;
                            }

                            if (onlySmall && NeedsLargeTube(itemId))
                            {
                                continue;
                            }

                            var transferedAmount = item.Amount;

                            var oxygenBottle = item.Content as Sandbox.Common.ObjectBuilders.Definitions.MyObjectBuilder_GasContainerObject;
                            if (oxygenBottle != null && oxygenBottle.GasLevel == 1f)
                            {
                                continue;
                            }

                            if (!MySession.Static.CreativeMode)
                            {
                                var fittingAmount = destinationInventory.ComputeAmountThatFits(item.Content.GetId());
                                if (item.Content.TypeId != typeof(MyObjectBuilder_Ore) &&
                                    item.Content.TypeId != typeof(MyObjectBuilder_Ingot))
                                {
                                    fittingAmount = MyFixedPoint.Floor(fittingAmount);
                                }
                                transferedAmount = MyFixedPoint.Min(fittingAmount, transferedAmount);
                            }
                            if (transferedAmount == 0)
                            {
                                continue;
                            }

                            // SK: this is mental
                            m_tmpPullRequests.Add(new MyTuple <IMyConveyorEndpointBlock, MyPhysicalInventoryItem>(m_startingEndpoint.CubeBlock as IMyConveyorEndpointBlock, item));
                            //MyInventory.Transfer(inventory, destinationInventory, item.Content.GetId(), MyItemFlags.None, transferedAmount);
                        }
                    }
                }
            }

            foreach (var tuple in m_tmpPullRequests)
            {
                if (destinationInventory.VolumeFillFactor >= 1.0f)
                {
                    m_tmpPullRequests.Clear();
                    return(pullCreated);
                }

                var start = tuple.Item1;
                var item  = tuple.Item2;

                var transferedAmount = item.Amount;
                var fittingAmount    = destinationInventory.ComputeAmountThatFits(item.Content.GetId());
                if (item.Content.TypeId != typeof(MyObjectBuilder_Ore) &&
                    item.Content.TypeId != typeof(MyObjectBuilder_Ingot))
                {
                    fittingAmount = MyFixedPoint.Floor(fittingAmount);
                }
                transferedAmount = MyFixedPoint.Min(fittingAmount, transferedAmount);

                if (transferedAmount == 0)
                {
                    continue;
                }

                var itemId = item.Content.GetId();

                SetTraversalInventoryItemDefinitionId(itemId);
                ItemPullRequest(start, destinationInventory, m_playerIdForAccessiblePredicate, itemId, transferedAmount);
                pullCreated = true;
            }

            m_tmpPullRequests.Clear();
            return(pullCreated);
        }