public int UseISR2G()
        {
            var result   = 0;
            var settings = LoadedModManager.GetMod <RoadsOfTheRim>().GetSettings <RoadsOfTheRimSettings>();

            // Setting the caravan to use ISR2G or AISR2G if present and settings allow it
            // TO DO : I can do better than hardcode
            if (!settings.useISR2G)
            {
                return(result);
            }

            foreach (var aThing in CaravanInventoryUtility.AllInventoryItems(GetCaravan()))
            {
                if (result < 1 && aThing.GetInnerIfMinified().def.defName == "RotR_ISR2GNew")
                {
                    result = 1;
                }

                if (aThing.GetInnerIfMinified().def.defName != "RotR_AISR2GNew")
                {
                    continue;
                }

                result = 2;
                return(result);
            }

            return(result);
        }
        public static bool PlayerOrItemStashHas(ThingDef thingDef)
        {
            List <Map> maps = Find.Maps;

            for (int i = 0; i < maps.Count; i++)
            {
                if (maps[i].listerThings.ThingsOfDef(thingDef).Count > 0)
                {
                    return(true);
                }
            }
            List <Caravan> caravans = Find.WorldObjects.Caravans;

            for (int j = 0; j < caravans.Count; j++)
            {
                if (caravans[j].IsPlayerControlled)
                {
                    List <Thing> list = CaravanInventoryUtility.AllInventoryItems(caravans[j]);
                    for (int k = 0; k < list.Count; k++)
                    {
                        if (list[k].def == thingDef)
                        {
                            return(true);
                        }
                    }
                }
            }
            return(PlayerItemAccessibilityUtility.ItemStashHas(thingDef));
        }
Exemplo n.º 3
0
        private void ResolveTradedItems()
        {
            List <Thing> itemList    = CaravanInventoryUtility.AllInventoryItems(this.landedShip);
            List <Thing> tmpToRemove = new List <Thing>();

            if (itemList != null)
            {
                for (int i = 0; i < landedShip.ships.Count; i++)
                {
                    ThingOwner container = landedShip.ships[i].GetDirectlyHeldThings();
                    tmpToRemove.Clear();
                    for (int k = 0; k < container.Count; k++)
                    {
                        if (!itemList.Contains(container[k]))
                        {
                            Pawn pawn = container[k] as Pawn;
                            if (pawn != null)
                            {
                                if (!pawn.IsColonist)
                                {
                                    tmpToRemove.Add(container[k]);
                                }
                            }
                            else
                            {
                                tmpToRemove.Add(container[k]);
                            }
                        }
                    }
                    container.RemoveAll(x => tmpToRemove.Contains(x));
                }
            }
            this.LoadNewCargo();
        }
Exemplo n.º 4
0
        // I had to take into account the old defs of ISR2G that used to be buildings, and replace them with new ISR2G defs that are craftable items
        public void OldDefsCleanup()
        {
            int     newISRG2  = 0;
            int     newAISRG2 = 0;
            Caravan caravan   = this.GetCaravan();

            foreach (Thing aThing in CaravanInventoryUtility.AllInventoryItems(caravan))
            {
                if (aThing.GetInnerIfMinified().def.defName == "RotR_ISR2G")
                {
                    newISRG2++;
                    aThing.Destroy();
                }
                else if (aThing.GetInnerIfMinified().def.defName == "RotR_AISR2G")
                {
                    newAISRG2++;
                    aThing.Destroy();
                }
            }
            for (int i = newISRG2; i > 0; i--)
            {
                Thing newThing = ThingMaker.MakeThing(ThingDef.Named("RotR_ISR2GNew"));
                CaravanInventoryUtility.GiveThing(caravan, newThing);
                RoadsOfTheRim.DebugLog("Replacing an ISR2G in caravan " + caravan.ToString());
            }
            for (int j = newAISRG2; j > 0; j--)
            {
                Thing newThing = ThingMaker.MakeThing(ThingDef.Named("RotR_AISR2GNew"));
                CaravanInventoryUtility.GiveThing(caravan, newThing);
                RoadsOfTheRim.DebugLog("Replacing an AISR2G in caravan " + caravan.ToString());
            }
        }
Exemplo n.º 5
0
        public static bool PlayerHasWithQuality(ThingDef thingDef, QualityCategory quality, out int total, int count = 1)
        {
            if (count <= 0)
            {
                total = 0;
                return(true);
            }
            int        num  = 0;
            List <Map> maps = Find.Maps;

            for (int i = 0; i < maps.Count; i++)
            {
                List <Thing> thingsList = maps[i].listerThings.ThingsOfDef(thingDef);
                foreach (Thing thing in thingsList)
                {
                    //Log.Message("Cheese found");
                    if (thing.TryGetComp <CompQuality>() is CompQuality qualityComp &&
                        qualityComp.Quality == quality)
                    {
                        //Log.Message("Quality is "+ qualityComp.Quality);
                        num += thing.stackCount;
                    }
                }

                if (num >= count)
                {
                    total = num;
                    return(true);
                }
            }
            total = num;
            List <Caravan> caravans = Find.WorldObjects.Caravans;

            for (int j = 0; j < caravans.Count; j++)
            {
                if (caravans[j].IsPlayerControlled)
                {
                    List <Thing> list = CaravanInventoryUtility.AllInventoryItems(caravans[j]);
                    for (int k = 0; k < list.Count; k++)
                    {
                        if (list[k].def == thingDef)
                        {
                            if (list[k].TryGetComp <CompQuality>() is CompQuality qualityComp &&
                                qualityComp.Quality == quality)
                            {
                                num   += list[k].stackCount;
                                total += num;
                            }

                            if (num >= count)
                            {
                                return(true);
                            }
                        }
                    }
                }
            }
            return(total >= count);
        }
Exemplo n.º 6
0
        public static bool PlayerOrQuestRewardHas(ThingDef thingDef)
        {
            List <Map> maps = Find.Maps;

            for (int i = 0; i < maps.Count; i++)
            {
                if (maps[i].listerThings.ThingsOfDef(thingDef).Count > 0)
                {
                    return(true);
                }
            }
            List <Caravan> caravans = Find.WorldObjects.Caravans;

            for (int j = 0; j < caravans.Count; j++)
            {
                if (caravans[j].IsPlayerControlled)
                {
                    List <Thing> list = CaravanInventoryUtility.AllInventoryItems(caravans[j]);
                    for (int k = 0; k < list.Count; k++)
                    {
                        if (list[k].def == thingDef)
                        {
                            return(true);
                        }
                    }
                }
            }
            List <Site> sites = Find.WorldObjects.Sites;

            for (int l = 0; l < sites.Count; l++)
            {
                ItemStashContentsComp component = sites[l].GetComponent <ItemStashContentsComp>();
                if (component != null)
                {
                    ThingOwner contents = component.contents;
                    for (int m = 0; m < contents.Count; m++)
                    {
                        if (contents[m].def == thingDef)
                        {
                            return(true);
                        }
                    }
                }
                DefeatAllEnemiesQuestComp component2 = sites[l].GetComponent <DefeatAllEnemiesQuestComp>();
                if (component2 != null)
                {
                    ThingOwner rewards = component2.rewards;
                    for (int n = 0; n < rewards.Count; n++)
                    {
                        if (rewards[n].def == thingDef)
                        {
                            return(true);
                        }
                    }
                }
            }
            return(false);
        }
Exemplo n.º 7
0
        private void AddItemsToTransferables()
        {
            List <Thing> list = CaravanInventoryUtility.AllInventoryItems(this.caravan);

            foreach (Thing t in list)
            {
                this.AddToTransferables(t);
            }
        }
Exemplo n.º 8
0
        private static void AddItemsToTransferables(Caravan caravan, List <TransferableOneWay> transferables)
        {
            List <Thing> list = CaravanInventoryUtility.AllInventoryItems(caravan);

            for (int i = 0; i < list.Count; i++)
            {
                AddToTransferables(list[i], transferables);
            }
        }
Exemplo n.º 9
0
        public static List <Thing> GetAllThings(Caravan caravan)
        {
            var goods = CaravanInventoryUtility.AllInventoryItems(caravan).ToList().Concat(
                caravan.PawnsListForReading
                .Cast <Thing>()
                ).ToList();

            return(goods);
        }
Exemplo n.º 10
0
        public bool AnyPawnOutOfFood(out string malnutritionHediff)
        {
            tmpInvFood.Clear();
            List <Thing> list = CaravanInventoryUtility.AllInventoryItems(caravan);

            for (int i = 0; i < list.Count; i++)
            {
                if (list[i].def.IsNutritionGivingIngestible)
                {
                    tmpInvFood.Add(list[i]);
                }
            }
            List <Pawn> pawnsListForReading = caravan.PawnsListForReading;

            for (int j = 0; j < pawnsListForReading.Count; j++)
            {
                Pawn pawn = pawnsListForReading[j];
                if (!pawn.RaceProps.EatsFood || VirtualPlantsUtility.CanEatVirtualPlantsNow(pawn))
                {
                    continue;
                }
                bool flag = false;
                for (int k = 0; k < tmpInvFood.Count; k++)
                {
                    if (CaravanPawnsNeedsUtility.CanEatForNutritionEver(tmpInvFood[k].def, pawn))
                    {
                        flag = true;
                        break;
                    }
                }
                if (flag)
                {
                    continue;
                }
                int    num  = -1;
                string text = null;
                for (int l = 0; l < pawnsListForReading.Count; l++)
                {
                    Hediff firstHediffOfDef = pawnsListForReading[l].health.hediffSet.GetFirstHediffOfDef(HediffDefOf.Malnutrition);
                    if (firstHediffOfDef != null && (text == null || firstHediffOfDef.CurStageIndex > num))
                    {
                        num  = firstHediffOfDef.CurStageIndex;
                        text = firstHediffOfDef.LabelCap;
                    }
                }
                malnutritionHediff = text;
                tmpInvFood.Clear();
                return(true);
            }
            malnutritionHediff = null;
            tmpInvFood.Clear();
            return(false);
        }
        public static bool PlayerOrItemStashHas(ThingFilter thingFilter)
        {
            ThingRequest bestThingRequest = thingFilter.BestThingRequest;
            List <Map>   maps             = Find.Maps;

            for (int i = 0; i < maps.Count; i++)
            {
                List <Thing> list = maps[i].listerThings.ThingsMatching(bestThingRequest);
                for (int j = 0; j < list.Count; j++)
                {
                    if (thingFilter.Allows(list[j]))
                    {
                        return(true);
                    }
                }
            }
            List <Caravan> caravans = Find.WorldObjects.Caravans;

            for (int k = 0; k < caravans.Count; k++)
            {
                if (caravans[k].IsPlayerControlled)
                {
                    List <Thing> list2 = CaravanInventoryUtility.AllInventoryItems(caravans[k]);
                    for (int l = 0; l < list2.Count; l++)
                    {
                        if (thingFilter.Allows(list2[l]))
                        {
                            return(true);
                        }
                    }
                }
            }
            List <Site> sites = Find.WorldObjects.Sites;

            for (int m = 0; m < sites.Count; m++)
            {
                ItemStashContentsComp component = sites[m].GetComponent <ItemStashContentsComp>();
                if (component != null)
                {
                    ThingOwner contents = component.contents;
                    for (int n = 0; n < contents.Count; n++)
                    {
                        if (thingFilter.Allows(contents[n]))
                        {
                            return(true);
                        }
                    }
                }
            }
            return(false);
        }
Exemplo n.º 12
0
 private static void TrySatisfyPowerNeed(Pawn pawn, Caravan caravan)
 {
     try
     {
         var charger = ChargeSourceUtility
                       .FindSources(CaravanInventoryUtility.AllInventoryItems(caravan), true)
                       .Where(source => source.Available)
                       .OrderByDescending(source => source.RateAvailable)
                       .First();
         charger.Charge(pawn);
     }
     catch (InvalidOperationException)
     {
     }
 }
        /// <summary>
        /// Get all items from Player's home inventory
        /// </summary>
        /// <param name="thingDef"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public static bool PlayerHas(ThingDef thingDef, out int total, int count = 1)
        {
            if (count <= 0)
            {
                total = 0;
                return(true);
            }
            int        num  = 0;
            List <Map> maps = Find.Maps;

            for (int i = 0; i < maps.Count; i++)
            {
                num += maps[i].listerThings.ThingsOfDef(thingDef).Sum(t => t.stackCount);
                if (num >= count)
                {
                    total = num;
                    return(true);
                }
            }
            total = num;
            List <Caravan> caravans = Find.WorldObjects.Caravans;

            for (int j = 0; j < caravans.Count; j++)
            {
                if (caravans[j].IsPlayerControlled)
                {
                    List <Thing> list = CaravanInventoryUtility.AllInventoryItems(caravans[j]);
                    for (int k = 0; k < list.Count; k++)
                    {
                        if (list[k].def == thingDef)
                        {
                            num   += list[k].stackCount;
                            total += num;
                            if (num >= count)
                            {
                                return(true);
                            }
                        }
                    }
                }
            }
            return(total >= count);
        }
Exemplo n.º 14
0
        private void SetupPlayerCaravanVariables()
        {
            Caravan caravan = TradeSession.playerNegotiator.GetCaravan();

            if (caravan != null)
            {
                this.playerIsCaravan = true;
                this.playerCaravanAllPawnsAndItems = new List <Thing>();
                List <Pawn> pawnsListForReading = caravan.PawnsListForReading;
                for (int i = 0; i < pawnsListForReading.Count; i++)
                {
                    this.playerCaravanAllPawnsAndItems.Add(pawnsListForReading[i]);
                }
                this.playerCaravanAllPawnsAndItems.AddRange(CaravanInventoryUtility.AllInventoryItems(caravan));
            }
            else
            {
                this.playerIsCaravan = false;
            }
        }
Exemplo n.º 15
0
        public static bool TryGetBestWater(Caravan caravan, Pawn forPawn, out Thing water, out Pawn owner)
        {
            var   inventoryThings = CaravanInventoryUtility.AllInventoryItems(caravan);
            Thing foundThing      = null;
            var   bestScore       = float.MinValue;

            // キャラバンの全所持品をチェック
            foreach (var thing in inventoryThings)
            {
                // それが飲めるものかどうか
                if (!CanNowGetWater(thing, forPawn))
                {
                    continue;
                }

                var waterScore = GetWaterScore(thing);

                // 今まで見つけたベストスコアを超えたか
                if (bestScore >= waterScore)
                {
                    continue;
                }

                foundThing = thing;
                bestScore  = waterScore;
            }

            if (foundThing != null)
            {
                // 何かしらの水が見つかった
                water = foundThing;

                // 水が個人の所持品に含まれている場合は持ち主が誰かを調べておく
                owner = CaravanInventoryUtility.GetOwnerOf(caravan, foundThing);
                return(true);
            }

            water = null;
            owner = null;
            return(false);
        }
        private void CallShuttleToCaravan(Pawn caller, Faction faction, bool free)
        {
            Caravan caravan           = caller.GetCaravan();
            int     maxLaunchDistance = ThingDefOf.Shuttle.GetCompProperties <CompProperties_Launchable>().fixedLaunchDistanceMax;

            CameraJumper.TryJump(CameraJumper.GetWorldTarget(caravan));
            Find.WorldSelector.ClearSelection();
            int caravanTile = caravan.Tile;

            Find.WorldTargeter.BeginTargeting_NewTemp(ChoseWorldTarget, canTargetTiles: true, CompLaunchable.TargeterMouseAttachment, closeWorldTabWhenFinished: false, delegate
            {
                GenDraw.DrawWorldRadiusRing(caravanTile, maxLaunchDistance);
            }, (GlobalTargetInfo target) => CompLaunchable.TargetingLabelGetter(target, caravanTile, maxLaunchDistance, Gen.YieldSingle(caravan), Launch, null));
            bool ChoseWorldTarget(GlobalTargetInfo target)
            {
                return(CompLaunchable.ChoseWorldTarget(target, caravan.Tile, Gen.YieldSingle(caravan), maxLaunchDistance, Launch, null));
            }

            void Launch(int tile, TransportPodsArrivalAction arrivalAction)
            {
                ActiveDropPodInfo activeDropPodInfo = new ActiveDropPodInfo();

                activeDropPodInfo.innerContainer.TryAddRangeOrTransfer(CaravanInventoryUtility.AllInventoryItems(caravan));
                activeDropPodInfo.innerContainer.TryAddRangeOrTransfer(caravan.GetDirectlyHeldThings());
                caravan.Destroy();
                TravelingTransportPods travelingTransportPods = (TravelingTransportPods)WorldObjectMaker.MakeWorldObject(WorldObjectDefOf.TravelingShuttle);

                travelingTransportPods.Tile = caravan.Tile;
                travelingTransportPods.SetFaction(Faction.OfPlayer);
                travelingTransportPods.destinationTile = tile;
                travelingTransportPods.arrivalAction   = arrivalAction;
                travelingTransportPods.AddPod(activeDropPodInfo, justLeftTheMap: true);
                Find.WorldObjects.Add(travelingTransportPods);
                Find.WorldTargeter.StopTargeting();
                caller.royalty.GetPermit(def, faction).Notify_Used();
                if (!free)
                {
                    caller.royalty.TryRemoveFavor(faction, def.royalAid.favorCost);
                }
            }
        }
Exemplo n.º 17
0
        public static bool TryGetBestArt(Caravan caravan, out Thing thing, out Pawn owner)
        {
            thing = null;
            List <Thing> list = CaravanInventoryUtility.AllInventoryItems(caravan);
            float        num  = 0f;

            foreach (Thing current in list)
            {
                if (current.GetInnerIfMinified().GetStatValue(StatDefOf.Beauty) > num && (current.GetInnerIfMinified().TryGetComp <CompArt>()?.Props?.canBeEnjoyedAsArt ?? false))
                {
                    thing = current;
                }
            }
            if (thing != null)
            {
                owner = CaravanInventoryUtility.GetOwnerOf(caravan, thing);
                return(true);
            }
            owner = null;
            return(false);
        }
Exemplo n.º 18
0
        public static void CheckIfCaravanOverWeight(Caravan caravan)
        {
            if (CaravanOverWeight(caravan))
            {
                List <Thing> items = CaravanInventoryUtility.AllInventoryItems(caravan);

                for (int i = 0; i < 1000; i++)
                {
                    if (items.Count == 0)
                    {
                        return;
                    }

                    if (!CaravanOverWeight(caravan))
                    {
                        return;
                    }

                    items.RemoveLast();
                }
            }
        }
        // I had to take into account the old defs of ISR2G that used to be buildings, and replace them with new ISR2G defs that are craftable items
        private void OldDefsCleanup()
        {
            var newISRG2  = 0;
            var newAISRG2 = 0;
            var caravan   = GetCaravan();

            foreach (var aThing in CaravanInventoryUtility.AllInventoryItems(caravan))
            {
                switch (aThing.GetInnerIfMinified().def.defName)
                {
                case "RotR_ISR2G":
                    newISRG2++;
                    aThing.Destroy();
                    break;

                case "RotR_AISR2G":
                    newAISRG2++;
                    aThing.Destroy();
                    break;
                }
            }

            for (var i = newISRG2; i > 0; i--)
            {
                var newThing = ThingMaker.MakeThing(ThingDef.Named("RotR_ISR2GNew"));
                CaravanInventoryUtility.GiveThing(caravan, newThing);
                RoadsOfTheRim.DebugLog("Replacing an ISR2G in caravan " + caravan);
            }

            for (var j = newAISRG2; j > 0; j--)
            {
                var newThing = ThingMaker.MakeThing(ThingDef.Named("RotR_AISR2GNew"));
                CaravanInventoryUtility.GiveThing(caravan, newThing);
                RoadsOfTheRim.DebugLog("Replacing an AISR2G in caravan " + caravan);
            }
        }
Exemplo n.º 20
0
        public static void Postfix(Caravan __instance, ref IEnumerable <Gizmo> __result)
        {
            float masss = 0.0f;

            foreach (Pawn pawn in __instance.pawns.InnerListForReading)
            {
                for (int index = 0; index < pawn.inventory.innerContainer.Count; ++index)
                {
                    if (pawn.inventory.innerContainer[index].def.defName != "Building_Helicopter")
                    {
                        masss += pawn.inventory.innerContainer[index].def.BaseMass * (float)pawn.inventory.innerContainer[index].stackCount;
                    }
                }
            }
            foreach (Pawn pawn in __instance.pawns.InnerListForReading)
            {
                Pawn_InventoryTracker pinv = pawn.inventory;
                for (int i = 0; i < pinv.innerContainer.Count; i++)
                {
                    if (pinv.innerContainer[i].def.defName == "Building_Helicopter")
                    {
                        Command_Action commandAction1 = new Command_Action();
                        commandAction1.defaultLabel = "CommandLaunchGroup".Translate();
                        commandAction1.defaultDesc  = "CommandLaunchGroupDesc".Translate();
                        commandAction1.icon         = ContentFinder <Texture2D> .Get("UI/Commands/LaunchShip", true);

                        commandAction1.alsoClickIfOtherInGroupClicked = false;
                        commandAction1.action = (Action)(() =>
                        {
                            float massCapacity = pinv.innerContainer[i].TryGetComp <CompTransporter>().Props.massCapacity;
                            if ((double)masss <= (double)massCapacity)
                            {
                                pinv.innerContainer[i].TryGetComp <CompLaunchableHelicopter>().WorldStartChoosingDestination(__instance);
                            }
                            else
                            {
                                Messages.Message("TooBigTransportersMassUsage".Translate() + "(" + (object)(float)((double)massCapacity - (double)masss) + "KG)", MessageTypeDefOf.RejectInput, false);
                            }
                        });
                        List <Gizmo> list = __result.ToList <Gizmo>();
                        list.Add((Gizmo)commandAction1);
                        Command_Action commandAction2 = new Command_Action();
                        commandAction2.defaultLabel = "CommandAddFuel".Translate();
                        commandAction2.defaultDesc  = "CommandAddFuelDesc".Translate();
                        commandAction2.icon         = ContentFinder <Texture2D> .Get("Things/Item/Resource/Chemfuel", true);

                        commandAction2.alsoClickIfOtherInGroupClicked = false;
                        commandAction2.action = (Action)(() =>
                        {
                            bool flag = false;
                            int count = 0;
                            CompRefuelable comp = pinv.innerContainer[i].TryGetComp <CompRefuelable>();
                            List <Thing> thingList = CaravanInventoryUtility.AllInventoryItems(__instance);
                            for (int index = 0; index < thingList.Count; ++index)
                            {
                                if (thingList[index].def == ThingDefOf.Chemfuel)
                                {
                                    count = thingList[index].stackCount;
                                    Pawn ownerOf = CaravanInventoryUtility.GetOwnerOf(__instance, thingList[index]);
                                    float num = comp.Props.fuelCapacity - comp.Fuel;
                                    if ((double)num < 1.0 && (double)num > 0.0)
                                    {
                                        count = 1;
                                    }
                                    if ((double)count * 1.0 >= (double)num)
                                    {
                                        count = (int)num;
                                    }
                                    if ((double)thingList[index].stackCount * 1.0 <= (double)count)
                                    {
                                        thingList[index].stackCount -= count;
                                        Thing thing = thingList[index];
                                        ownerOf.inventory.innerContainer.Remove(thing);
                                        thing.Destroy(DestroyMode.Vanish);
                                    }
                                    else if ((uint)count > 0U)
                                    {
                                        thingList[index].SplitOff(count).Destroy(DestroyMode.Vanish);
                                    }
                                    comp.GetType().GetField("fuel", BindingFlags.Instance | BindingFlags.NonPublic).SetValue((object)comp, (object)(float)((double)comp.Fuel + (double)count));
                                    flag = true;
                                    break;
                                }
                            }
                            if (flag)
                            {
                                Messages.Message("AddFuelDoneMsg".Translate((object)count, (object)comp.Fuel), MessageTypeDefOf.PositiveEvent, false);
                            }
                            else
                            {
                                Messages.Message("NonOilMsg".Translate(), MessageTypeDefOf.RejectInput, false);
                            }
                        });
                        list.Add((Gizmo)commandAction2);
                        Gizmo_MapRefuelableFuelStatus refuelableFuelStatus = new Gizmo_MapRefuelableFuelStatus()
                        {
                            nowFuel   = pinv.innerContainer[i].TryGetComp <CompRefuelable>().Fuel,
                            maxFuel   = pinv.innerContainer[i].TryGetComp <CompRefuelable>().Props.fuelCapacity,
                            compLabel = pinv.innerContainer[i].TryGetComp <CompRefuelable>().Props.FuelGizmoLabel
                        };
                        list.Add((Gizmo)refuelableFuelStatus);
                        __result = (IEnumerable <Gizmo>)list;
                        return;
                    }
                }
            }
        }
Exemplo n.º 21
0
    public static IEnumerable<Gizmo> LaunchAndBombGizmosPassthrough(IEnumerable<Gizmo> __result, Caravan __instance)
    {
      IEnumerator<Gizmo> enumerator = __result.GetEnumerator();
      while (enumerator.MoveNext())
      {
        var element = enumerator.Current;
        yield return element;
        if ((element as Command_Action)?.defaultLabel == "CommandSettle".Translate() && __instance.PawnsListForReading.Any(x => x.inventory.innerContainer.Any(y => y.TryGetComp<CompLaunchableSRTS>() != null)))
        {
          float massUsage = 0f;
          Thing srts = null;
          foreach (Pawn p in __instance.PawnsListForReading)
          {
            foreach (Thing t in p.inventory?.innerContainer)
            {
              if (t.TryGetComp<CompLaunchableSRTS>() != null)
                srts = t;
              else
              {
                massUsage += t.GetStatValue(StatDefOf.Mass, true) * t.stackCount;
              }
            }
            massUsage += p.GetStatValue(StatDefOf.Mass, true);
            massUsage -= MassUtility.InventoryMass(p) * p.stackCount;
          }
          yield return new Command_Action
          {
            defaultLabel = "CommandLaunchGroup".Translate(),
            defaultDesc = "CommandLaunchGroupDesc".Translate(),
            icon = Tex2D.LaunchSRTS,
            alsoClickIfOtherInGroupClicked = false,
            action = delegate ()
            {
              if (massUsage > SRTSMod.GetStatFor<float>(srts.def.defName, StatName.massCapacity))
                Messages.Message("TooBigTransportersMassUsage".Translate(), MessageTypeDefOf.RejectInput, false);
              else
                srts.TryGetComp<CompLaunchableSRTS>().WorldStartChoosingDestination(__instance);
            }
          };
          /* Not Yet Implemented */
          /*yield return new Command_Action
          {
              defaultLabel = "BombTarget".Translate(),
              defaultDesc = "BombTargetDesc".Translate(),
              icon = TexCommand.Attack,
              action = delegate ()
              {
                  if(SRTSMod.mod.settings.passengerLimits)
                  {
                      if(__instance.PawnsListForReading.Count < SRTSMod.GetStatFor<int>(srts.def.defName, StatName.minPassengers))
                      {
                          Messages.Message("NotEnoughPilots".Translate(), MessageTypeDefOf.RejectInput, false);
                          return;
                      }
                      else if(__instance.PawnsListForReading.Count > SRTSMod.GetStatFor<int>(srts.def.defName, StatName.maxPassengers))
                      {
                          Messages.Message("TooManyPilots".Translate(), MessageTypeDefOf.RejectInput, false);
                          return;
                      }
                  }

                  FloatMenuOption carpetBombing = new FloatMenuOption("CarpetBombing".Translate(), delegate ()
                  {
                      srts.TryGetComp<CompBombFlyer>().bombType = BombingType.carpet;
                      srts.TryGetComp<CompBombFlyer>().StartChoosingWorldDestinationBomb(__instance);
                  });
                  FloatMenuOption preciseBombing = new FloatMenuOption("PreciseBombing".Translate(), delegate ()
                  {
                      srts.TryGetComp<CompBombFlyer>().bombType = BombingType.precise;
                      srts.TryGetComp<CompBombFlyer>().StartChoosingWorldDestinationBomb(__instance);
                  });
                  Find.WindowStack.Add(new FloatMenuGizmo(new List<FloatMenuOption>() { carpetBombing, preciseBombing }, srts, srts.LabelCap, UI.MouseMapPosition()));
              }
          };*/

          Command_Action RefuelSRTS = new Command_Action()
          {
            defaultLabel = "CommandAddFuelSRTS".Translate(srts.TryGetComp<CompRefuelable>().parent.Label),
            defaultDesc = "CommandAddFuelDescSRTS".Translate(),
            icon = Tex2D.FuelSRTS,
            alsoClickIfOtherInGroupClicked = false,
            action = delegate ()
            {
              bool flag = false;
              int count = 0;
              List<Thing> thingList = CaravanInventoryUtility.AllInventoryItems(__instance);
              for (int index = 0; index < thingList.Count; ++index)
              {
                if (thingList[index].def == ThingDefOf.Chemfuel)
                {
                  count = thingList[index].stackCount;
                  Pawn ownerOf = CaravanInventoryUtility.GetOwnerOf(__instance, thingList[index]);
                  float num = srts.TryGetComp<CompRefuelable>().Props.fuelCapacity - srts.TryGetComp<CompRefuelable>().Fuel;
                  if ((double)num < 1.0 && (double)num > 0.0)
                    count = 1;
                  if ((double)count * 1.0 >= (double)num)
                    count = (int)num;
                  if ((double)thingList[index].stackCount * 1.0 <= (double)count)
                  {
                    thingList[index].stackCount -= count;
                    Thing thing = thingList[index];
                    ownerOf.inventory.innerContainer.Remove(thing);
                    thing.Destroy(DestroyMode.Vanish);
                  }
                  else if ((uint)count > 0U)
                    thingList[index].SplitOff(count).Destroy(DestroyMode.Vanish);
                  srts.TryGetComp<CompRefuelable>().GetType().GetField("fuel", BindingFlags.Instance | BindingFlags.NonPublic).SetValue((object)srts.TryGetComp<CompRefuelable>(), (object)(float)((double)srts.TryGetComp<CompRefuelable>().Fuel + (double)count));
                  flag = true;
                  break;
                }
              }
              if (flag)
                Messages.Message("AddFuelSRTSCaravan".Translate(count, srts.LabelCap), MessageTypeDefOf.PositiveEvent, false);
              else
                Messages.Message("NoFuelSRTSCaravan".Translate(), MessageTypeDefOf.RejectInput, false);
            }
          };
          if (srts.TryGetComp<CompRefuelable>().IsFull)
            RefuelSRTS.Disable();
          yield return RefuelSRTS;
          yield return new Gizmo_MapRefuelableFuelStatus
          {

            nowFuel = srts.TryGetComp<CompRefuelable>().Fuel,
            maxFuel = srts.TryGetComp<CompRefuelable>().Props.fuelCapacity,
            compLabel = srts.TryGetComp<CompRefuelable>().Props.FuelGizmoLabel
          };
        }
      }
    }
        public static bool PlayerOrQuestRewardHas(ThingFilter thingFilter)
        {
            ThingRequest bestThingRequest = thingFilter.BestThingRequest;
            List <Map>   maps             = Find.Maps;

            for (int i = 0; i < maps.Count; i++)
            {
                List <Thing> list = maps[i].listerThings.ThingsMatching(bestThingRequest);
                for (int j = 0; j < list.Count; j++)
                {
                    if (thingFilter.Allows(list[j]))
                    {
                        return(true);
                    }
                }
            }
            List <Caravan> caravans = Find.WorldObjects.Caravans;

            for (int k = 0; k < caravans.Count; k++)
            {
                if (!caravans[k].IsPlayerControlled)
                {
                    continue;
                }
                List <Thing> list2 = CaravanInventoryUtility.AllInventoryItems(caravans[k]);
                for (int l = 0; l < list2.Count; l++)
                {
                    if (thingFilter.Allows(list2[l]))
                    {
                        return(true);
                    }
                }
            }
            List <Site> sites = Find.WorldObjects.Sites;

            for (int m = 0; m < sites.Count; m++)
            {
                for (int n = 0; n < sites[m].parts.Count; n++)
                {
                    SitePart sitePart = sites[m].parts[n];
                    if (sitePart.things == null)
                    {
                        continue;
                    }
                    for (int num = 0; num < sitePart.things.Count; num++)
                    {
                        if (thingFilter.Allows(sitePart.things[num]))
                        {
                            return(true);
                        }
                    }
                }
                DefeatAllEnemiesQuestComp component = sites[m].GetComponent <DefeatAllEnemiesQuestComp>();
                if (component == null)
                {
                    continue;
                }
                ThingOwner rewards = component.rewards;
                for (int num2 = 0; num2 < rewards.Count; num2++)
                {
                    if (thingFilter.Allows(rewards[num2]))
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
        public static bool PlayerOrQuestRewardHas(ThingDef thingDef, int count = 1)
        {
            if (count <= 0)
            {
                return(true);
            }
            int        num  = 0;
            List <Map> maps = Find.Maps;

            for (int i = 0; i < maps.Count; i++)
            {
                if (count == 1)
                {
                    if (maps[i].listerThings.ThingsOfDef(thingDef).Count > 0)
                    {
                        return(true);
                    }
                    continue;
                }
                num += Mathf.Max(maps[i].resourceCounter.GetCount(thingDef), maps[i].listerThings.ThingsOfDef(thingDef).Count);
                if (num >= count)
                {
                    return(true);
                }
            }
            List <Caravan> caravans = Find.WorldObjects.Caravans;

            for (int j = 0; j < caravans.Count; j++)
            {
                if (!caravans[j].IsPlayerControlled)
                {
                    continue;
                }
                List <Thing> list = CaravanInventoryUtility.AllInventoryItems(caravans[j]);
                for (int k = 0; k < list.Count; k++)
                {
                    if (list[k].def == thingDef)
                    {
                        num += list[k].stackCount;
                        if (num >= count)
                        {
                            return(true);
                        }
                    }
                }
            }
            List <Site> sites = Find.WorldObjects.Sites;

            for (int l = 0; l < sites.Count; l++)
            {
                for (int m = 0; m < sites[l].parts.Count; m++)
                {
                    SitePart sitePart = sites[l].parts[m];
                    if (sitePart.things == null)
                    {
                        continue;
                    }
                    for (int n = 0; n < sitePart.things.Count; n++)
                    {
                        if (sitePart.things[n].def == thingDef)
                        {
                            num += sitePart.things[n].stackCount;
                            if (num >= count)
                            {
                                return(true);
                            }
                        }
                    }
                }
                DefeatAllEnemiesQuestComp component = sites[l].GetComponent <DefeatAllEnemiesQuestComp>();
                if (component == null)
                {
                    continue;
                }
                ThingOwner rewards = component.rewards;
                for (int num2 = 0; num2 < rewards.Count; num2++)
                {
                    if (rewards[num2].def == thingDef)
                    {
                        num += rewards[num2].stackCount;
                        if (num >= count)
                        {
                            return(true);
                        }
                    }
                }
            }
            return(false);
        }
        public static void Postfix(Caravan __instance, ref IEnumerable <Gizmo> __result)
        {
            float masss = 0;

            foreach (Pawn pawn in __instance.pawns.InnerListForReading)
            {
                for (int j = 0; j < pawn.inventory.innerContainer.Count; j++)
                {
                    if (pawn.inventory.innerContainer[j].def != USCMDefOf.RRY_USCM_DropshipUD4L)
                    {
                        masss += (pawn.inventory.innerContainer[j].def.BaseMass * pawn.inventory.innerContainer[j].stackCount);
                    }
                }
            }

            foreach (Pawn pawn in __instance.pawns.InnerListForReading)
            {
                Pawn_InventoryTracker pinv = pawn.inventory;
                for (int i = 0; i < pinv.innerContainer.Count; i++)
                {
                    if (pinv.innerContainer[i].def == USCMDefOf.RRY_USCM_DropshipUD4L)
                    {
                        Command_Action launch = new Command_Action();
                        launch.defaultLabel = "CommandSendShuttle".Translate();
                        launch.defaultDesc  = "CommandSendShuttleDesc".Translate();
                        launch.icon         = ContentFinder <Texture2D> .Get("UI/Commands/LaunchShip", true);

                        launch.alsoClickIfOtherInGroupClicked = false;
                        launch.action = delegate
                        {
                            float maxmass = pinv.innerContainer[i].TryGetComp <CompTransporter>().Props.massCapacity;
                            if (masss <= maxmass)
                            {
                                pinv.innerContainer[i].TryGetComp <CompUSCMDropship>().WorldStartChoosingDestination(__instance);
                            }
                            else
                            {
                                Messages.Message("TooBigTransportersMassUsage".Translate() + "(" + (maxmass - masss) + "KG)", MessageTypeDefOf.RejectInput, false);
                            }
                        };

                        List <Gizmo> newr = __result.ToList();
                        newr.Add(launch);

                        Command_Action addFuel = new Command_Action();
                        addFuel.defaultLabel = "USCM_Dropship_CommandAddFuel".Translate();
                        addFuel.defaultDesc  = "USCM_Dropship_CommandAddFuelDesc".Translate();
                        addFuel.icon         = ContentFinder <Texture2D> .Get("Things/Item/Resource/Chemfuel", true);

                        addFuel.alsoClickIfOtherInGroupClicked = false;
                        addFuel.action = delegate
                        {
                            bool           hasAddFuel = false;
                            int            fcont      = 0;
                            CompRefuelable comprf     = pinv.innerContainer[i].TryGetComp <CompRefuelable>();
                            List <Thing>   list       = CaravanInventoryUtility.AllInventoryItems(__instance);
                            //pinv.innerContainer.Count
                            for (int j = 0; j < list.Count; j++)
                            {
                                if (list[j].def == ThingDefOf.Chemfuel)
                                {
                                    fcont = list[j].stackCount;
                                    Pawn  ownerOf = CaravanInventoryUtility.GetOwnerOf(__instance, list[j]);
                                    float need    = comprf.Props.fuelCapacity - comprf.Fuel;

                                    if (need < 1f && need > 0)
                                    {
                                        fcont = 1;
                                    }
                                    if (fcont * 1f >= need)
                                    {
                                        fcont = (int)need;
                                    }



                                    // Log.Warning("f&n is "+fcont+"/"+need);
                                    if (list[j].stackCount * 1f <= fcont)
                                    {
                                        list[j].stackCount -= fcont;
                                        Thing thing = list[j];
                                        ownerOf.inventory.innerContainer.Remove(thing);
                                        thing.Destroy(DestroyMode.Vanish);
                                    }
                                    else
                                    {
                                        if (fcont != 0)
                                        {
                                            list[j].SplitOff(fcont).Destroy(DestroyMode.Vanish);
                                        }
                                    }


                                    Type      crtype = comprf.GetType();
                                    FieldInfo finfo  = crtype.GetField("fuel", BindingFlags.NonPublic | BindingFlags.Instance);
                                    finfo.SetValue(comprf, comprf.Fuel + fcont);
                                    hasAddFuel = true;
                                    break;
                                }
                            }
                            if (hasAddFuel)
                            {
                                Messages.Message("USCM_Dropship_AddFuelDoneMsg".Translate(fcont, comprf.Fuel), MessageTypeDefOf.PositiveEvent, false);
                            }
                            else
                            {
                                Messages.Message("USCM_Dropship_NoFuelMsg".Translate(), MessageTypeDefOf.RejectInput, false);
                            }
                        };

                        newr.Add(addFuel);

                        Gizmo_MapRefuelableFuelStatus fuelStat = new Gizmo_MapRefuelableFuelStatus
                        {
                            nowFuel   = pinv.innerContainer[i].TryGetComp <CompRefuelable>().Fuel,
                            maxFuel   = pinv.innerContainer[i].TryGetComp <CompRefuelable>().Props.fuelCapacity,
                            compLabel = pinv.innerContainer[i].TryGetComp <CompRefuelable>().Props.FuelGizmoLabel
                        };


                        newr.Add(fuelStat);

                        __result = newr;
                        return;
                    }
                }
            }
        }
        public override void Arrived(Caravan caravan)
        {
            if (mode == "exchangeOfGoods")
            {
                //Pawn bestNegotiator = CaravanVisitUtility.BestNegotiator(caravan);
                ThingOwner <Thing> сontainer = new ThingOwner <Thing>();
                Dialog_TradeOnline form      = null;
                if (сaravanOnline.OnlineWObject == null)
                {
                    Log.Error("OCity_Caravan_LOGNoData".Translate());
                    return;
                }

                var goods = CaravanInventoryUtility.AllInventoryItems(caravan).ToList().Concat(
                    caravan.PawnsListForReading
                    .Cast <Thing>()
                    ).ToList();

                form = new Dialog_TradeOnline(goods
                                              , сaravanOnline.OnlinePlayerLogin
                                              , сaravanOnline.OnlineWObject.FreeWeight
                                              , () =>
                {
                    var select            = form.GetSelect();
                    bool selectAllCaravan = caravan.PawnsListForReading.Count == select.Count(s => s.Key is Pawn);
                    if (selectAllCaravan)
                    {
                        Log.Message("OCity_Caravan_LOGSwap".Translate());
                        select = new Dictionary <Thing, int>();
                        foreach (var pawn in caravan.PawnsListForReading)
                        {
                            foreach (var item in pawn.inventory.innerContainer.ToDictionary(t => t, t => t.stackCount))
                            {
                                select.Add(item.Key, item.Value);
                            }
                            select.Add(pawn, 1);
                            pawn.inventory.innerContainer.Clear();
                        }
                    }
                    //передаем выбранные товары из caravan к другому игроку в сaravanOnline
                    var sendThings = new List <ThingEntry>();
                    foreach (var pair in select)
                    {
                        var thing     = pair.Key;
                        var numToTake = pair.Value;
                        if (thing is Pawn)
                        {
                            var pawn = thing as Pawn;
                            //если отдали пешку, то выкладываем все другим и удаляемся из каравана
                            var things = pawn.inventory.innerContainer.ToList();
                            pawn.inventory.innerContainer.Clear();
                            GameUtils.DeSpawnSetupOnCaravan(caravan, pawn);
                            foreach (var thin in things)
                            {
                                var p = CaravanInventoryUtility.FindPawnToMoveInventoryTo(thin, caravan.PawnsListForReading, null);
                                if (p != null)
                                {
                                    p.inventory.innerContainer.TryAdd(thin, true);
                                }
                            }
                        }
                        sendThings.Add(new ThingEntry(thing, numToTake));
                    }
                    SessionClientController.Command((connect) =>
                    {
                        connect.SendThings(sendThings
                                           , SessionClientController.My.Login
                                           , сaravanOnline.OnlinePlayerLogin
                                           , сaravanOnline.OnlineWObject.ServerId
                                           , сaravanOnline.Tile
                                           );
                    });

                    if (selectAllCaravan)
                    {
                        //удаляем пешку из игры
                        foreach (var pawn in caravan.PawnsListForReading)
                        {
                            pawn.Destroy(DestroyMode.Vanish);
                        }

                        Find.WorldObjects.Remove(caravan);
                    }
                    else
                    {
                        foreach (var pair in select)
                        {
                            var thing     = pair.Key;
                            var numToTake = pair.Value;
                            if (thing is Pawn)
                            {
                                var pawn = thing as Pawn;
                                //удаляем пешку из игры
                                pawn.Destroy(DestroyMode.Vanish);
                                //Find.WorldPawns.RemovePawn(pawn); не проверенное не полное удаление, если её вернут назад
                            }
                            else
                            {
                                //если отдали вешь, то находим кто её тащит и убираем с него
                                Pawn ownerOf = CaravanInventoryUtility.GetOwnerOf(caravan, thing);
                                ownerOf.inventory.innerContainer.TryTransferToContainer(thing, сontainer, numToTake);
                            }
                        }
                    }
                });
                Find.WindowStack.Add(form);
            }
        }
Exemplo n.º 26
0
        /*
         * Based on the Caravan's resources, Pawns & the road's cost (modified by terrain) :
         * - Determine the amount of work done in a tick
         * - Consume the caravan's resources
         * - Return whether or not the Caravan must now stop because it ran out of resources
         * - NOTE : Does this need to be here ? Maybe better in Mod.cs
         * Returns TRUE if work finished
         * CALLED FROM : CompTick() of WorldObjectComp_Caravan
         */
        public static bool DoSomeWork(Caravan caravan, RoadConstructionSite site, out bool noMoreResources)
        {
            var caravanComp = caravan.GetComponent <WorldObjectComp_Caravan>();
            var siteComp    = site.GetComponent <WorldObjectComp_ConstructionSite>();

            _ = site.roadDef.GetModExtension <DefModExtension_RotR_RoadDef>();
            noMoreResources = false;
            var   useISR2G    = caravanComp.UseISR2G();
            var   available   = new Dictionary <string, int>();
            var   needed      = new Dictionary <string, int>();
            var   ratio       = new Dictionary <string, float>();
            float ratio_final = 1;

            //RoadsOfTheRim.DebugLog("[RotR] DEBUG ========== doSomeWork() ==========");
            //RoadsOfTheRim.DebugLog("[RotR] DEBUG ISR2G set to "+useISR2G);

            if (DebugSettings.godMode)
            {
                return(siteComp.FinishWork(caravan));
            }

            if (caravanComp.CaravanCurrentState() != CaravanState.ReadyToWork)
            {
                DebugLog("[RotR] DEBUG : doSomeWork() failed because the caravan can't work.");
                return(false);
            }

            // Percentage of total work that can be done in this batch, might be 0 if no pawn was found with enough skill
            var amountOfWork = caravanComp.AmountOfWork(true);

            // Work was 0 (not enough skill)
            if (Math.Abs(amountOfWork) < double.Epsilon)
            {
                Messages.Message("RoadsOfTheRim_CaravanNoWork".Translate(caravan.Name, site.roadDef.label),
                                 MessageTypeDefOf.RejectInput);
                caravanComp.StopWorking();
                return(false);
            }

            // calculate material present in the caravan
            foreach (var resourceName in DefModExtension_RotR_RoadDef.allResources)
            {
                available[resourceName] = 0;
            }

            foreach (var aThing in CaravanInventoryUtility.AllInventoryItems(caravan))
            {
                foreach (var resourceName in DefModExtension_RotR_RoadDef.allResources)
                {
                    if (IsThis(aThing.def, resourceName))
                    {
                        available[resourceName] += aThing.stackCount;
                    }
                }
            }

            // What percentage of work will remain after amountOfWork is done ?
            var percentOfWorkLeftToDoAfter = (siteComp.GetLeft("Work") - amountOfWork) / siteComp.GetCost("Work");

            // The amount of each resource left to spend in total is : percentOfWorkLeftToDoAfter * {this resource cost}
            // Materials that would be needed to do that much work
            foreach (var resourceName in DefModExtension_RotR_RoadDef.allResources)
            {
                needed[resourceName] = (int)Math.Round(siteComp.GetLeft(resourceName) -
                                                       (percentOfWorkLeftToDoAfter * siteComp.GetCost(resourceName)));
                // Check if there's enough material to go through this batch. Materials with a cost of 0 are always OK
                // Don't check when ISR2G is in use for this resource, don't check for work
                if (DefModExtension_RotR_RoadDef.GetInSituModifier(resourceName, useISR2G) || resourceName == "Work")
                {
                    continue;
                }

                ratio[resourceName] = needed[resourceName] == 0
                    ? 1f
                    : Math.Min(available[resourceName] / (float)needed[resourceName], 1f);
                if (ratio[resourceName] < ratio_final)
                {
                    ratio_final = ratio[resourceName];
                }
            }

            // The caravan didn't have enough resources for a full batch of work. Use as much as we can then stop working
            if (ratio_final < 1f)
            {
                Messages.Message("RoadsOfTheRim_CaravanNoResource".Translate(caravan.Name, site.roadDef.label),
                                 MessageTypeDefOf.RejectInput);
                foreach (var resourceName in DefModExtension_RotR_RoadDef.allResources)
                {
                    needed[resourceName] = (int)(needed[resourceName] * ratio_final);
                }

                caravanComp.StopWorking();
            }
            //RoadsOfTheRim.DebugLog("[RotR] ISR2G DEBUG ratio final = " + ratio_final);

            // Consume resources from the caravan
            _ = site.roadDef.defName ==
                "DirtPathBuilt"; // Always consider resources have been consumed when the road is a dirt path
            foreach (var aThing in CaravanInventoryUtility.AllInventoryItems(caravan))
            {
                foreach (var resourceName in DefModExtension_RotR_RoadDef.allResources)
                {
                    if (!DefModExtension_RotR_RoadDef.GetInSituModifier(resourceName, useISR2G))
                    {
                        if (needed[resourceName] <= 0 || !IsThis(aThing.def, resourceName))
                        {
                            continue;
                            //RoadsOfTheRim.DebugLog("[RotR] ISR2G consumption DEBUG =" + resourceName + " Qty consumed = " + amountUsed);
                        }

                        var amountUsed = aThing.stackCount > needed[resourceName]
                            ? needed[resourceName]
                            : aThing.stackCount;
                        aThing.stackCount -= amountUsed;
                        // Reduce how much of this resource is needed
                        needed[resourceName] -= amountUsed;
                        siteComp.ReduceLeft(resourceName, amountUsed);
                    }
                    else
                    {
                        if (needed[resourceName] <= 0)
                        {
                            continue;
                        }

                        //RoadsOfTheRim.DebugLog("[RotR] ISR2G consumption DEBUG =" + resourceName + " Qty freely awarded = " + needed[resourceName]);
                        siteComp.ReduceLeft(resourceName, needed[resourceName]);
                        needed[resourceName] = 0;
                    }
                }

                if (aThing.stackCount == 0)
                {
                    aThing.Destroy();
                }
            }

            caravanComp.TeachPawns(ratio_final); // Pawns learn some construction
            // HARDCODED : ISR2G divides work done by 4 , AISR2G by 2 for all roads except dirt path
            if (useISR2G > 0 && site.roadDef.defName != "DirtPathBuilt")
            {
                amountOfWork = amountOfWork * 0.25f * useISR2G;
            }

            // Update amountOfWork based on the actual ratio worked & finally reducing the work & resources left
            amountOfWork = ratio_final * amountOfWork;
            return(siteComp.UpdateProgress(amountOfWork, caravan));
        }
Exemplo n.º 27
0
        private static bool AnyPawnOutOfWater(Caravan c, out string worstDehydrationText)
        {
            // キャラバンの全所持品の水アイテムリスト作成
            var tmpInvWater = CaravanInventoryUtility.AllInventoryItems(c).FindAll(t => t.CanGetWater());

            var allFoundWaterItem = true;

            // キャラバン内の全ポーンをチェック
            foreach (var pawn in c.PawnsListForReading)
            {
                // 水分要求なし→水不要
                if (pawn.needs.Water() == null)
                {
                    continue;
                }

                // 心情ステータス無し、キャラバンの地形に水がある→アイテムがなくても水は飲める
                if (pawn.needs.mood == null && c.GetWaterTerrainType() != WaterTerrainType.NoWater)
                {
                    continue;
                }

                // そのポーンが飲める水があるなら良し
                if (tmpInvWater.Exists(t => CanEverGetWater(t.def)))
                {
                    continue;
                }

                // 適切な水アイテムを見つけられなかったポーンがいる
                allFoundWaterItem = false;
                break;
            }

            if (allFoundWaterItem)
            {
                // 全ポーンが水アイテムを見つけた
                // →脱水症状のテキストは不要
                worstDehydrationText = null;
                return(false);
            }

            // 適切なアイテムを見つけられなかったポーンがいる
            // →全ポーンの脱水症状をチェックして最悪の状態を調査、そのテキストを取得
            var    maxHediffStageIndex = -1;
            string maxHediffText       = null;

            foreach (var pawn in c.PawnsListForReading)
            {
                // 脱水症状の健康状態を持っているか
                var hediff = pawn.health.hediffSet.GetFirstHediffOfDef(MizuDef.Hediff_Dehydration);
                if (hediff == null)
                {
                    continue;
                }

                if (maxHediffText != null && maxHediffStageIndex >= hediff.CurStageIndex)
                {
                    continue;
                }

                // 最悪状態なら更新
                maxHediffStageIndex = hediff.CurStageIndex;
                maxHediffText       = hediff.LabelCap;
            }

            // 最悪の脱水症状テキストを返す
            worstDehydrationText = maxHediffText;
            return(true);
        }
        public static void CheckVision(Pawn pawn)
        {
            // Basically a copy of the function in PawnObserver
            if (!pawn.health.capacities.CapableOf(PawnCapacityDefOf.Sight) || pawn.needs.mood == null)
            {
                return;
            }
            // caravans have some different management
            Caravan caravan = pawn.GetCaravan();

            if (caravan != null)
            {
                // inside caravan
                // see other
                foreach (Pawn potentialOther in caravan.PawnsListForReading)
                {
                    Find.World.GetComponent <FriendshipMemoryGlobalTracker>().Notify_PhysicalSightOccured(pawn, potentialOther);
                }
                // see dead
                foreach (Thing thing in CaravanInventoryUtility.AllInventoryItems(caravan))
                {
                    Corpse potentialCorpse = thing as Corpse;
                    if (potentialCorpse != null)
                    {
                        Pawn deadPawn = potentialCorpse.InnerPawn;
                        Find.World.GetComponent <FriendshipMemoryGlobalTracker>().Notify_PhysicalSightOfCorpseOccured(pawn, deadPawn);
                    }
                }
                return;
            }
            Map map = pawn.Map;

            if (map == null)
            {
                return;
            }
            MapPawns pawns        = pawn.Map.mapPawns;
            IntVec3  selfPosition = pawn.Position;

            // seen alive
            foreach (Pawn potentialOther in pawns.AllPawnsSpawned)
            {
                if (GenSight.LineOfSight(selfPosition, potentialOther.Position, map, skipFirstCell: true))
                {
                    // can see!
                    float distanceSq = selfPosition.DistanceToSquared(potentialOther.Position);
                    if (distanceSq > 25)
                    {
                        // distance radius > 5, excluded
                        continue;
                    }
                    Find.World.GetComponent <FriendshipMemoryGlobalTracker>().Notify_PhysicalSightOccured(pawn, potentialOther);
                }
            }
            // seen corpse
            for (int i = 0; (float)i < 100f; i++)
            {
                IntVec3 intVec = pawn.Position + GenRadial.RadialPattern[i];
                if (!intVec.InBounds(map) || !GenSight.LineOfSight(intVec, pawn.Position, map, skipFirstCell: true))
                {
                    continue;
                }
                List <Thing> thingList = intVec.GetThingList(map);
                for (int j = 0; j < thingList.Count; j++)
                {
                    Corpse potentialCorpse = thingList[j] as Corpse;
                    if (potentialCorpse != null)
                    {
                        Pawn deadPawn = potentialCorpse.InnerPawn;
                        Find.World.GetComponent <FriendshipMemoryGlobalTracker>().Notify_PhysicalSightOfCorpseOccured(pawn, deadPawn);
                    }
                }
            }
            // tick the stuff
            Find.World.GetComponent <FriendshipMemoryGlobalTracker>().GetFriendshipMemoryTrackerForSubject(pawn)?.Notify_TickOnce(TickIntervalVision);
        }
Exemplo n.º 29
0
 public static IEnumerable <IChargeSource> FindSources(Caravan caravan)
 {
     return(FindSources(CaravanInventoryUtility.AllInventoryItems(caravan), true));
 }