Beispiel #1
0
        public static Job HaulToStorageJob(Pawn p, Thing t)
        {
            StoragePriority currentPriority = StoreUtility.CurrentStoragePriorityOf(t);

            if (!StoreUtility.TryFindBestBetterStorageFor(t, p, p.Map, currentPriority, p.Faction, out IntVec3 foundCell, out IHaulDestination haulDestination))
            {
                JobFailReason.Is(NoEmptyPlaceLowerTrans);
                return(null);
            }
            if (haulDestination is ISlotGroupParent)
            {
                return(HaulToCellStorageJob(p, t, foundCell, fitInStoreCell: false));
            }
            Thing thing = haulDestination as Thing;

            if (thing != null && thing.TryGetInnerInteractableThingOwner() != null)
            {
                return(HaulToContainerJob(p, t, thing));
            }
            Log.Error("Don't know how to handle HaulToStorageJob for storage " + haulDestination.ToStringSafe() + ". thing=" + t.ToStringSafe());
            return(null);
        }
Beispiel #2
0
        protected override IEnumerable <Toil> MakeNewToils()
        {
            // Verify processor validity
            this.FailOnDespawnedNullOrForbidden(ProcessorInd);
            this.FailOn(() => !Processor.Finished);

            // Go to the processor
            yield return(Toils_Goto.GotoThing(ProcessorInd, PathEndMode.ClosestTouch));

            // Add delay for collecting items from the processor
            yield return(Toils_General.Wait(Static.GenericWaitDuration)
                         .FailOnDestroyedNullOrForbidden(ProcessorInd)
                         .WithProgressBarToilDelay(ProcessorInd));

            // Collect items
            yield return(new Toil()
            {
                initAction = () =>
                {
                    Thing item = Processor.TakeOutProduct();
                    GenPlace.TryPlaceThing(item, pawn.Position, Map, ThingPlaceMode.Near);
                    StoragePriority storagePriority = StoreUtility.StoragePriorityAtFor(item.Position, item);

                    // Try to find a suitable storage spot for the item
                    if (StoreUtility.TryFindBestBetterStoreCellFor(item, pawn, Map, storagePriority, pawn.Faction, out IntVec3 c))
                    {
                        job.SetTarget(TargetIndex.C, c);
                        job.SetTarget(TargetIndex.B, item);
                        job.count = item.stackCount;
                    }
                    // If there is no spot to store the item, end this job
                    else
                    {
                        EndJobWith(JobCondition.Incompletable);
                    }
                },
                defaultCompleteMode = ToilCompleteMode.Instant
            });
        protected override IEnumerable <Toil> MakeNewToils()
        {
            this.FailOnDespawnedNullOrForbidden(TargetIndex.A);
            this.FailOnBurningImmobile(TargetIndex.A);
            yield return(Toils_Reserve.Reserve(TargetIndex.A, 1));

            yield return(Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.Touch));

            yield return(Toils_General.Wait(200).FailOnDestroyedNullOrForbidden(TargetIndex.A).FailOn(() => !Vat.Fermented).WithProgressBarToilDelay(TargetIndex.A, false, -0.5f));

            yield return(new Toil
            {
                initAction = delegate
                {
                    Thing thing = Vat.TakeOutThing();
                    GenPlace.TryPlaceThing(thing, pawn.Position, Map, ThingPlaceMode.Near, null);
                    StoragePriority currentPriority = StoreUtility.StoragePriorityAtFor(thing.Position, thing);;
                    if (StoreUtility.TryFindBestBetterStoreCellFor(thing, pawn, Map, currentPriority, pawn.Faction, out IntVec3 c, true))
                    {
                        job.SetTarget(TargetIndex.C, c);
                        job.SetTarget(TargetIndex.B, thing);
                        job.count = thing.stackCount;
                    }
        public static bool TryFindBestBetterStoreCellFor(Thing t, Pawn carrier, Map map, StoragePriority currentPriority, Faction faction, out IntVec3 foundCell, bool needAccurateResult = true)
        {
            StoragePriority storagePriority = currentPriority;
            float           num             = 2.14748365E+09f;
            IntVec3         result          = IntVec3.Invalid;

            foreach (var slotGroup in map.haulDestinationManager.AllGroupsListInPriorityOrder)
            {
                StoragePriority priority = slotGroup.Settings.Priority;
                if (priority < storagePriority || priority <= currentPriority)
                {
                    break;
                }
                TryFindBestBetterStoreCellForWorker(t, carrier, map, faction, slotGroup, needAccurateResult, ref result, ref num, ref storagePriority);
            }
            if (!result.IsValid)
            {
                foundCell = IntVec3.Invalid;
                return(false);
            }
            foundCell = result;
            return(true);
        }
        public static bool TryFindBestBetterStorageFor(Thing t, Pawn carrier, Map map, StoragePriority currentPriority, Faction faction, out IntVec3 foundCell, out IHaulDestination haulDestination, bool needAccurateResult = true)
        {
            IntVec3         invalid         = IntVec3.Invalid;
            StoragePriority storagePriority = StoragePriority.Unstored;

            if (StoreUtility.TryFindBestBetterStoreCellFor(t, carrier, map, currentPriority, faction, out invalid, needAccurateResult))
            {
                storagePriority = invalid.GetSlotGroup(map).Settings.Priority;
            }
            IHaulDestination haulDestination2;

            if (!StoreUtility.TryFindBestBetterNonSlotGroupStorageFor(t, carrier, map, currentPriority, faction, out haulDestination2))
            {
                haulDestination2 = null;
            }
            bool result;

            if (storagePriority == StoragePriority.Unstored && haulDestination2 == null)
            {
                foundCell       = IntVec3.Invalid;
                haulDestination = null;
                result          = false;
            }
            else if (haulDestination2 != null && (storagePriority == StoragePriority.Unstored || haulDestination2.GetStoreSettings().Priority > storagePriority))
            {
                foundCell       = IntVec3.Invalid;
                haulDestination = haulDestination2;
                result          = true;
            }
            else
            {
                foundCell       = invalid;
                haulDestination = invalid.GetSlotGroup(map).parent;
                result          = true;
            }
            return(result);
        }
Beispiel #6
0
        public static string Label(this StoragePriority p)
        {
            string result;

            switch (p)
            {
            case StoragePriority.Unstored:
                result = "StoragePriorityUnstored".Translate();
                break;

            case StoragePriority.Low:
                result = "StoragePriorityLow".Translate();
                break;

            case StoragePriority.Normal:
                result = "StoragePriorityNormal".Translate();
                break;

            case StoragePriority.Preferred:
                result = "StoragePriorityPreferred".Translate();
                break;

            case StoragePriority.Important:
                result = "StoragePriorityImportant".Translate();
                break;

            case StoragePriority.Critical:
                result = "StoragePriorityCritical".Translate();
                break;

            default:
                result = "Unknown";
                break;
            }
            return(result);
        }
        public override Job JobOnThing(Pawn pawn, Thing t)
        {
            if (!(t is Corpse))
            {
                return(null);
            }
            Area outpostArea = OG_Util.FindOutpostArea();

            if ((outpostArea != null) &&
                (outpostArea.ActiveCells.Contains(t.Position)))
            {
                // Get potential storage cell and check it is in the outpost area.
                StoragePriority currentPriority = HaulAIUtility.StoragePriorityAtFor(t.Position, t);
                IntVec3         storeCell;
                if (StoreUtility.TryFindBestBetterStoreCellFor(t, pawn, currentPriority, pawn.Faction, out storeCell, true))
                {
                    if (outpostArea.ActiveCells.Contains(storeCell))
                    {
                        return(base.JobOnThing(pawn, t));
                    }
                }
            }
            return(null);
        }
        protected override IEnumerable <Toil> MakeNewToils()
        {
            this.FailOnDespawnedNullOrForbidden(BarrelInd);
            this.FailOnBurningImmobile(BarrelInd);
            yield return(Toils_Goto.GotoThing(BarrelInd, PathEndMode.Touch));

            yield return(Toils_General.Wait(Duration).FailOnDestroyedNullOrForbidden(BarrelInd)
                         .FailOnCannotTouch(BarrelInd, PathEndMode.Touch).FailOn(() => !MeadBarrel.Fermented)
                         .WithProgressBarToilDelay(BarrelInd, false, -0.5f));

            yield return(new Toil
            {
                initAction = delegate
                {
                    Thing thing = MeadBarrel.TakeOutMead();
                    GenPlace.TryPlaceThing(thing, pawn.Position, Map, ThingPlaceMode.Near, null);
                    StoragePriority currentPriority = StoreUtility.CurrentStoragePriorityOf(thing);
                    if (StoreUtility.TryFindBestBetterStoreCellFor(thing,
                                                                   pawn, Map, currentPriority, pawn.Faction, out var c, true))
                    {
                        job.SetTarget(TargetIndex.C, c);
                        job.SetTarget(TargetIndex.B, thing);
                        job.count = thing.stackCount;
                    }
Beispiel #9
0
        private static void TryFindBestBetterStoreCellForWorker(
            Thing t,
            Pawn carrier,
            Map map,
            Faction faction,
            SlotGroup slotGroup,
            bool needAccurateResult,
            ref IntVec3 closestSlot,
            ref float closestDistSquared,
            ref StoragePriority foundPriority)
        {
            if (slotGroup == null || !slotGroup.parent.Accepts(t))
            {
                return;
            }
            IntVec3        intVec3   = t.PositionHeld;    //changed
            List <IntVec3> cellsList = slotGroup.CellsList;
            int            count     = cellsList.Count;
            int            num       = !needAccurateResult ? 0 : Mathf.FloorToInt((float)count * Rand.Range(0.005f, 0.018f));

            for (int index = 0; index < count; ++index)
            {
                IntVec3 c = cellsList[index];
                float   horizontalSquared = (float)(intVec3 - c).LengthHorizontalSquared;
                if ((double)horizontalSquared <= (double)closestDistSquared && StoreUtility.IsGoodStoreCell(c, map, t, carrier, faction))
                {
                    closestSlot        = c;
                    closestDistSquared = horizontalSquared;
                    foundPriority      = slotGroup.Settings.Priority;
                    if (index >= num)
                    {
                        break;
                    }
                }
            }
        }
        public static Job HopperFillFoodJob(Pawn pawn, ISlotGroupParent hopperSgp)
        {
            Building building = (Building)hopperSgp;
            Job      result;

            if (!pawn.CanReserveAndReach(building.Position, PathEndMode.Touch, pawn.NormalMaxDanger(), 1, -1, null, false))
            {
                result = null;
            }
            else
            {
                ThingDef thingDef  = null;
                Thing    firstItem = building.Position.GetFirstItem(building.Map);
                if (firstItem != null)
                {
                    if (Building_NutrientPasteDispenser.IsAcceptableFeedstock(firstItem.def))
                    {
                        thingDef = firstItem.def;
                    }
                    else
                    {
                        if (firstItem.IsForbidden(pawn))
                        {
                            return(null);
                        }
                        return(HaulAIUtility.HaulAsideJobFor(pawn, firstItem));
                    }
                }
                List <Thing> list;
                if (thingDef == null)
                {
                    list = pawn.Map.listerThings.ThingsInGroup(ThingRequestGroup.FoodSourceNotPlantOrTree);
                }
                else
                {
                    list = pawn.Map.listerThings.ThingsOfDef(thingDef);
                }
                bool flag = false;
                for (int i = 0; i < list.Count; i++)
                {
                    Thing thing = list[i];
                    if (thing.def.IsNutritionGivingIngestible)
                    {
                        if (thing.def.ingestible.preferability == FoodPreferability.RawBad || thing.def.ingestible.preferability == FoodPreferability.RawTasty)
                        {
                            if (HaulAIUtility.PawnCanAutomaticallyHaul(pawn, thing, false))
                            {
                                if (pawn.Map.haulDestinationManager.SlotGroupAt(building.Position).Settings.AllowedToAccept(thing))
                                {
                                    StoragePriority storagePriority = StoreUtility.CurrentStoragePriorityOf(thing);
                                    if (storagePriority >= hopperSgp.GetSlotGroup().Settings.Priority)
                                    {
                                        flag = true;
                                        JobFailReason.Is(WorkGiver_CookFillHopper.TheOnlyAvailableFoodIsInStorageOfHigherPriorityTrans, null);
                                    }
                                    else
                                    {
                                        Job job = HaulAIUtility.HaulToCellStorageJob(pawn, thing, building.Position, true);
                                        if (job != null)
                                        {
                                            return(job);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                if (!flag)
                {
                    JobFailReason.Is(WorkGiver_CookFillHopper.NoFoodToFillHopperTrans, null);
                }
                result = null;
            }
            return(result);
        }
Beispiel #11
0
        public static void MakeColony(params ColonyMakerFlag[] flags)
        {
            bool godMode = DebugSettings.godMode;

            DebugSettings.godMode            = true;
            Thing.allowDestroyNonDestroyable = true;
            if (usedCells == null)
            {
                usedCells = new BoolGrid(Map);
            }
            else
            {
                usedCells.ClearAndResizeTo(Map);
            }
            IntVec3 center  = Map.Center;
            int     minX    = center.x - 50;
            IntVec3 center2 = Map.Center;

            overRect = new CellRect(minX, center2.z - 50, 100, 100);
            DeleteAllSpawnedPawns();
            GenDebug.ClearArea(overRect, Find.CurrentMap);
            if (flags.Contains(ColonyMakerFlag.Animals))
            {
                foreach (PawnKindDef item in from k in DefDatabase <PawnKindDef> .AllDefs
                         where k.RaceProps.Animal
                         select k)
                {
                    if (!TryGetFreeRect(6, 3, out CellRect result))
                    {
                        return;
                    }
                    result = result.ContractedBy(1);
                    foreach (IntVec3 item2 in result)
                    {
                        Map.terrainGrid.SetTerrain(item2, TerrainDefOf.Concrete);
                    }
                    GenSpawn.Spawn(PawnGenerator.GeneratePawn(item), result.Cells.ElementAt(0), Map);
                    IntVec3 intVec = result.Cells.ElementAt(1);
                    Pawn    p      = (Pawn)GenSpawn.Spawn(PawnGenerator.GeneratePawn(item), intVec, Map);
                    HealthUtility.DamageUntilDead(p);
                    Corpse       thing        = (Corpse)intVec.GetThingList(Find.CurrentMap).First((Thing t) => t is Corpse);
                    CompRottable compRottable = thing.TryGetComp <CompRottable>();
                    if (compRottable != null)
                    {
                        compRottable.RotProgress += 1200000f;
                    }
                    if (item.RaceProps.leatherDef != null)
                    {
                        GenSpawn.Spawn(item.RaceProps.leatherDef, result.Cells.ElementAt(2), Map);
                    }
                    if (item.RaceProps.meatDef != null)
                    {
                        GenSpawn.Spawn(item.RaceProps.meatDef, result.Cells.ElementAt(3), Map);
                    }
                }
            }
            if (flags.Contains(ColonyMakerFlag.ConduitGrid))
            {
                Designator_Build designator_Build = new Designator_Build(ThingDefOf.PowerConduit);
                for (int i = overRect.minX; i < overRect.maxX; i++)
                {
                    for (int j = overRect.minZ; j < overRect.maxZ; j += 7)
                    {
                        designator_Build.DesignateSingleCell(new IntVec3(i, 0, j));
                    }
                }
                for (int l = overRect.minZ; l < overRect.maxZ; l++)
                {
                    for (int m = overRect.minX; m < overRect.maxX; m += 7)
                    {
                        designator_Build.DesignateSingleCell(new IntVec3(m, 0, l));
                    }
                }
            }
            if (flags.Contains(ColonyMakerFlag.PowerPlants))
            {
                List <ThingDef> list = new List <ThingDef>();
                list.Add(ThingDefOf.SolarGenerator);
                list.Add(ThingDefOf.WindTurbine);
                List <ThingDef> list2 = list;
                for (int n = 0; n < 8; n++)
                {
                    if (TryMakeBuilding(list2[n % list2.Count]) == null)
                    {
                        Log.Message("Could not make solar generator.");
                        break;
                    }
                }
            }
            if (flags.Contains(ColonyMakerFlag.Batteries))
            {
                for (int num = 0; num < 6; num++)
                {
                    Thing thing2 = TryMakeBuilding(ThingDefOf.Battery);
                    if (thing2 == null)
                    {
                        Log.Message("Could not make battery.");
                        break;
                    }
                    ((Building_Battery)thing2).GetComp <CompPowerBattery>().AddEnergy(999999f);
                }
            }
            if (flags.Contains(ColonyMakerFlag.WorkTables))
            {
                IEnumerable <ThingDef> enumerable = from def in DefDatabase <ThingDef> .AllDefs
                                                    where typeof(Building_WorkTable).IsAssignableFrom(def.thingClass)
                                                    select def;
                foreach (ThingDef item3 in enumerable)
                {
                    Thing thing3 = TryMakeBuilding(item3);
                    if (thing3 == null)
                    {
                        Log.Message("Could not make worktable: " + item3.defName);
                        break;
                    }
                    Building_WorkTable building_WorkTable = thing3 as Building_WorkTable;
                    if (building_WorkTable != null)
                    {
                        foreach (RecipeDef allRecipe in building_WorkTable.def.AllRecipes)
                        {
                            building_WorkTable.billStack.AddBill(allRecipe.MakeNewBill());
                        }
                    }
                }
            }
            if (flags.Contains(ColonyMakerFlag.AllBuildings))
            {
                IEnumerable <ThingDef> enumerable2 = from def in DefDatabase <ThingDef> .AllDefs
                                                     where def.category == ThingCategory.Building && def.BuildableByPlayer
                                                     select def;
                foreach (ThingDef item4 in enumerable2)
                {
                    if (item4 != ThingDefOf.PowerConduit)
                    {
                        Thing thing4 = TryMakeBuilding(item4);
                        if (thing4 == null)
                        {
                            Log.Message("Could not make building: " + item4.defName);
                            break;
                        }
                    }
                }
            }
            if (!TryGetFreeRect(33, 33, out CellRect result2))
            {
                Log.Error("Could not get wallable rect");
            }
            result2 = result2.ContractedBy(1);
            if (flags.Contains(ColonyMakerFlag.AllItems))
            {
                List <ThingDef> itemDefs = (from def in DefDatabase <ThingDef> .AllDefs
                                            where DebugThingPlaceHelper.IsDebugSpawnable(def) && def.category == ThingCategory.Item
                                            select def).ToList();
                FillWithItems(result2, itemDefs);
            }
            else if (flags.Contains(ColonyMakerFlag.ItemsRawFood))
            {
                List <ThingDef> list3 = new List <ThingDef>();
                list3.Add(ThingDefOf.RawPotatoes);
                FillWithItems(result2, list3);
            }
            if (flags.Contains(ColonyMakerFlag.Filth))
            {
                foreach (IntVec3 item5 in result2)
                {
                    GenSpawn.Spawn(ThingDefOf.Filth_Dirt, item5, Map);
                }
            }
            if (flags.Contains(ColonyMakerFlag.ItemsWall))
            {
                CellRect         cellRect          = result2.ExpandedBy(1);
                Designator_Build designator_Build2 = new Designator_Build(ThingDefOf.Wall);
                designator_Build2.SetStuffDef(ThingDefOf.WoodLog);
                foreach (IntVec3 edgeCell in cellRect.EdgeCells)
                {
                    designator_Build2.DesignateSingleCell(edgeCell);
                }
            }
            if (flags.Contains(ColonyMakerFlag.ColonistsMany))
            {
                MakeColonists(15, overRect.CenterCell);
            }
            else if (flags.Contains(ColonyMakerFlag.ColonistOne))
            {
                MakeColonists(1, overRect.CenterCell);
            }
            if (flags.Contains(ColonyMakerFlag.Fire))
            {
                if (!TryGetFreeRect(30, 30, out CellRect result3))
                {
                    Log.Error("Could not get free rect for fire.");
                }
                ThingDef plant_TreeOak = ThingDefOf.Plant_TreeOak;
                foreach (IntVec3 item6 in result3)
                {
                    GenSpawn.Spawn(plant_TreeOak, item6, Map);
                }
                foreach (IntVec3 item7 in result3)
                {
                    IntVec3 current9 = item7;
                    if (current9.x % 7 == 0 && current9.z % 7 == 0)
                    {
                        GenExplosion.DoExplosion(current9, Find.CurrentMap, 3.9f, DamageDefOf.Flame, null);
                    }
                }
            }
            if (flags.Contains(ColonyMakerFlag.ColonistsHungry))
            {
                DoToColonists(0.4f, delegate(Pawn col)
                {
                    col.needs.food.CurLevel = Mathf.Max(0f, Rand.Range(-0.05f, 0.05f));
                });
            }
            if (flags.Contains(ColonyMakerFlag.ColonistsTired))
            {
                DoToColonists(0.4f, delegate(Pawn col)
                {
                    col.needs.rest.CurLevel = Mathf.Max(0f, Rand.Range(-0.05f, 0.05f));
                });
            }
            if (flags.Contains(ColonyMakerFlag.ColonistsInjured))
            {
                DoToColonists(0.4f, delegate(Pawn col)
                {
                    DamageDef def2 = (from d in DefDatabase <DamageDef> .AllDefs
                                      where d.ExternalViolenceFor(null)
                                      select d).RandomElement();
                    col.TakeDamage(new DamageInfo(def2, 10f));
                });
            }
            if (flags.Contains(ColonyMakerFlag.ColonistsDiseased))
            {
                foreach (HediffDef item8 in from d in DefDatabase <HediffDef> .AllDefs
                         where d.hediffClass != typeof(Hediff_AddedPart) && (d.HasComp(typeof(HediffComp_Immunizable)) || d.HasComp(typeof(HediffComp_GrowthMode)))
                         select d)
                {
                    Pawn pawn = PawnGenerator.GeneratePawn(Faction.OfPlayer.def.basicMemberKind, Faction.OfPlayer);
                    TryGetFreeRect(1, 1, out CellRect result4);
                    GenSpawn.Spawn(pawn, result4.CenterCell, Map);
                    pawn.health.AddHediff(item8);
                }
            }
            if (flags.Contains(ColonyMakerFlag.Beds))
            {
                IEnumerable <ThingDef> source = from def in DefDatabase <ThingDef> .AllDefs
                                                where def.thingClass == typeof(Building_Bed)
                                                select def;
                int freeColonistsCount = Map.mapPawns.FreeColonistsCount;
                for (int num2 = 0; num2 < freeColonistsCount; num2++)
                {
                    if (TryMakeBuilding(source.RandomElement()) == null)
                    {
                        Log.Message("Could not make beds.");
                        break;
                    }
                }
            }
            if (flags.Contains(ColonyMakerFlag.Stockpiles))
            {
                Designator_ZoneAddStockpile_Resources designator_ZoneAddStockpile_Resources = new Designator_ZoneAddStockpile_Resources();
                IEnumerator enumerator11 = Enum.GetValues(typeof(StoragePriority)).GetEnumerator();
                try
                {
                    while (enumerator11.MoveNext())
                    {
                        StoragePriority priority = (StoragePriority)enumerator11.Current;
                        TryGetFreeRect(7, 7, out CellRect result5);
                        result5 = result5.ContractedBy(1);
                        designator_ZoneAddStockpile_Resources.DesignateMultiCell(result5.Cells);
                        Zone_Stockpile zone_Stockpile = (Zone_Stockpile)Map.zoneManager.ZoneAt(result5.CenterCell);
                        zone_Stockpile.settings.Priority = priority;
                    }
                }
                finally
                {
                    IDisposable disposable;
                    if ((disposable = (enumerator11 as IDisposable)) != null)
                    {
                        disposable.Dispose();
                    }
                }
            }
            if (flags.Contains(ColonyMakerFlag.GrowingZones))
            {
                Zone_Growing dummyZone = new Zone_Growing(Map.zoneManager);
                Map.zoneManager.RegisterZone(dummyZone);
                foreach (ThingDef item9 in from d in DefDatabase <ThingDef> .AllDefs
                         where d.plant != null && PlantUtility.CanSowOnGrower(d, dummyZone)
                         select d)
                {
                    if (!TryGetFreeRect(6, 6, out CellRect result6))
                    {
                        Log.Error("Could not get growing zone rect.");
                    }
                    result6 = result6.ContractedBy(1);
                    foreach (IntVec3 item10 in result6)
                    {
                        Map.terrainGrid.SetTerrain(item10, TerrainDefOf.Soil);
                    }
                    Designator_ZoneAdd_Growing designator_ZoneAdd_Growing = new Designator_ZoneAdd_Growing();
                    designator_ZoneAdd_Growing.DesignateMultiCell(result6.Cells);
                    (Map.zoneManager.ZoneAt(result6.CenterCell) as Zone_Growing)?.SetPlantDefToGrow(item9);
                }
                dummyZone.Delete();
            }
            ClearAllHomeArea();
            FillWithHomeArea(overRect);
            DebugSettings.godMode            = godMode;
            Thing.allowDestroyNonDestroyable = false;
        }
        // duplicated to make changes
        public static bool TryFindBestBetterStoreCellFor(Thing haulable, Pawn carrier, StoragePriority currentPriority, Faction faction, out IntVec3 foundCell, bool needAccurateResult = true)
        {
            List <SlotGroup> allGroupsListInPriorityOrder = Find.SlotGroupManager.AllGroupsListInPriorityOrder;

            if (allGroupsListInPriorityOrder.Count == 0)
            {
                foundCell = IntVec3.Invalid;
                return(false);
            }
            ReservationManager reservations    = Find.Reservations;
            IntVec3            positionHeld    = haulable.PositionHeld;
            StoragePriority    storagePriority = currentPriority;
            float   num    = 2.14748365E+09f;
            IntVec3 intVec = default(IntVec3);
            bool    flag   = false;
            int     count  = allGroupsListInPriorityOrder.Count;

            for (int i = 0; i < count; i++)
            {
                SlotGroup       slotGroup = allGroupsListInPriorityOrder[i];
                StoragePriority priority  = slotGroup.Settings.Priority;
                if (priority < storagePriority || priority <= currentPriority)
                {
                    break;
                }
                if (slotGroup.Settings.AllowedToAccept(haulable))
                {
                    List <IntVec3> cellsList = slotGroup.CellsList;
                    int            count2    = cellsList.Count;
                    int            num2;
                    if (needAccurateResult)
                    {
                        num2 = Mathf.FloorToInt((float)count2 * Rand.Range(0.005f, 0.018f));
                    }
                    else
                    {
                        num2 = 0;
                    }
                    for (int j = 0; j < count2; j++)
                    {
                        IntVec3 intVec2 = cellsList[j];
                        float   lengthHorizontalSquared = (positionHeld - intVec2).LengthHorizontalSquared;
                        if (lengthHorizontalSquared <= num)
                        {
                            if (carrier == null || !intVec2.IsForbidden(carrier))
                            {
                                // call duplicated to make changes
                                if (NoStorageBlockersIn(intVec2, haulable))
                                {
                                    if (!reservations.IsReserved(intVec2, faction))
                                    {
                                        if (!intVec2.ContainsStaticFire())
                                        {
                                            if (carrier == null || haulable.Position.CanReach(slotGroup.CellsList[0], PathEndMode.ClosestTouch, TraverseParms.For(carrier, Danger.Deadly, TraverseMode.ByPawn, false)))
                                            {
                                                flag            = true;
                                                intVec          = intVec2;
                                                num             = lengthHorizontalSquared;
                                                storagePriority = priority;
                                                if (j >= num2)
                                                {
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if (!flag)
            {
                foundCell = IntVec3.Invalid;
                return(false);
            }
            foundCell = intVec;
            return(true);
        }
Beispiel #13
0
        private static Rect viewRect          = new Rect(0, 0, 100f, 10000f); // OMG OMG OMG I got scrollView in Listing_Standard to work!
        public static void DoSettingsWindowContents(Rect inRect)
        {
            Rect outerRect = inRect.ContractedBy(10f);

            Widgets.DrawHighlight(outerRect);
            Listing_Standard l = new Listing_Standard(GameFont.Medium); // my tiny high-resolution monitor :p

            l.BeginScrollView(outerRect, ref scrollPosition, ref viewRect);

            //l.GapLine();  // Who can haul to Deep Storage (robots, animals, etc)
            l.Label("LWMDShaulToStorageExplanation".Translate());
            l.CheckboxLabeled("LWMDSrobotsCanUse".Translate(), ref robotsCanUse, "LWMDSrobotsCanUseDesc".Translate());
            string [] intLabels =
            {
                "LWM_DS_Int_Animal".Translate(),
                "LWM_DS_Int_ToolUser".Translate(),
                "LWM_DS_Int_Humanlike".Translate(),
            };
            // Setting to allow bionic racoons to haul to Deep Storage:
            l.EnumRadioButton <Intelligence>(ref Patch_IsGoodStoreCell.NecessaryIntelligenceToUseDeepStorage, "LWM_DS_IntTitle".Translate(),
                                             "LWM_DS_IntDesc".Translate(), false, intLabels);

            l.GapLine();  //Storing Delay Settings
            l.Label("LWMDSstoringDelaySettings".Translate());
            l.Label("LWMDSstoringDelayExplanation".Translate());
            l.CheckboxLabeled("LWMDSstoringTakesTimeLabel".Translate(),
                              ref storingTakesTime, "LWMDSstoringTakesTimeDesc".Translate());
            l.Label("LWMDSstoringGlobalScale".Translate((storingGlobalScale * 100f).ToString("0.")));
            storingGlobalScale = l.Slider(storingGlobalScale, 0f, 2f);
            l.CheckboxLabeled("LWMDSstoringTimeConsidersStackSize".Translate(),
                              ref storingTimeConsidersStackSize, "LWMDSstoringTimeConsidersStackSizeDesc".Translate());
            // Reset storing delay settings to defaults
            if (l.ButtonText("LWMDSstoringDelaySettings".Translate() + ": " + "ResetBinding".Translate() /*Reset to Default*/))
            {
                storingTakesTime              = true;
                storingGlobalScale            = 1f;
                storingTimeConsidersStackSize = true;
            }
            l.GapLine(); // default Storing Priority
            if (l.ButtonTextLabeled("LWM_DS_defaultStoragePriority".Translate(),
                                    defaultStoragePriority.Label()))
            {
                List <FloatMenuOption> mlist = new List <FloatMenuOption>();
                foreach (StoragePriority p in Enum.GetValues(typeof(StoragePriority)))
                {
                    mlist.Add(new FloatMenuOption(p.Label(), delegate() {
                        defaultStoragePriority = p;
                        foreach (ThingDef d in AllDeepStorageUnits)
                        {
                            d.building.defaultStorageSettings.Priority = p;
                        }
                    }));
                }
                Find.WindowStack.Add(new FloatMenu(mlist));
            }
            l.GapLine();
            l.Label("LWM_DS_userInterface".Translate());
            l.CheckboxLabeled("LWM_DS_useEjectButton".Translate(), ref useEjectButton,
                              "LWM_DS_useEjectButtonDesc".Translate());
            //TODO::
            l.CheckboxLabeled("LWM_DS_useDSRightClick".Translate(), ref useDeepStorageRightClickLogic,
                              "LWM_DS_useDSRightClickDesc".Translate());

            // Architect Menu:
            l.GapLine();  //Architect Menu location

/*
 * //            string archLabel=
 * //            if (archLabel==n
 * //            l.Label("LWMDSarchitectMenuSettings".Translate());
 *          if (architectMenuDesigCatDef==architectMenuDefaultDesigCatDef) {
 * //                if (architectLWM_DS_Storage_DesignationCatDef==null) {
 * //                    Log.Error("LWM.DeepStorage: architectLWM_DS_Storage_DesignationCatDef was null; this should never happen.");
 * //                    tmp="ERROR";
 * //                } else {
 * //                    tmp=architectCurrentDesignationCatDef.LabelCap; // todo: (default)
 * //                }
 *              archLabel+=" ("+
 *          } else {
 *              var x=DefDatabase<DesignationCategoryDef>.GetNamed(architectMenuDesignationCatDefDefName, false);
 *              if (x==null) {
 *                  // TODO
 *              }
 *              tmp=x.LabelCap; // todo: (<menuname>)
 *          }*/
            if (l.ButtonTextLabeled((architectMenuDefaultDesigCatDef + "_ArchitectMenuSettings").Translate(), // Label
                                                                                                              // value of dropdown button:
                                    DefDatabase <DesignationCategoryDef> .GetNamed(architectMenuDesigCatDef)?.LabelCap
                                    ?? "--ERROR--"))                                                          // error display text
//                                     , DefDatabase<DesigarchitectMenuDesigCatDef) ) {
            // Float menu for architect Menu choice:
            {
                List <FloatMenuOption> alist = new List <FloatMenuOption>();
                var arl = DefDatabase <DesignationCategoryDef> .AllDefsListForReading; //all reading list
                //oops:
//                alist.Add(new FloatMenuOption(DefDatabase<DesignationCategoryDef>.GetNamed(architectMenuDefaultDesigCatDef).LabelCap
                alist.Add(new FloatMenuOption(architectMenuActualDef.LabelCap +
                                              " (" + "default".Translate() + " - " + architectMenuActualDef.defName + ")",
                                              delegate() {
                    Utils.Mess(Utils.DBF.Settings, "Architect Menu placement set to default Storage");
                    ArchitectMenu_ChangeLocation(architectMenuDefaultDesigCatDef);
//                                                  architectCurrentDesignationCatDef=architectLWM_DS_Storage_DesignationCatDef;
//                                                  architectMenuDesignationCatDefDefName="LWM_DS_Storage";
//
//                                                  SettingsChanged();
                }, MenuOptionPriority.Default, null, null, 0f, null, null));
                // Architect Menu:  You may remove the "Furniture" references here if you wish
                alist.Add(new FloatMenuOption(DefDatabase <DesignationCategoryDef> .GetNamed("Furniture").LabelCap +
                                              " (Furniture)", // I know what this one's defName is!
                                              delegate() {
                    Utils.Mess(Utils.DBF.Settings, "Architect Menu placement set to Furniture.");
                    ArchitectMenu_ChangeLocation("Furniture");
                }, MenuOptionPriority.Default, null, null, 0f, null, null));
                foreach (var adcd in arl)   //architect designation cat def
                {
                    if (adcd.defName != architectMenuDefaultDesigCatDef && adcd.defName != "Furniture")
                    {
                        alist.Add(new FloatMenuOption(adcd.LabelCap + " (" + adcd.defName + ")",
                                                      delegate() {
                            Utils.Mess(Utils.DBF.Settings, "Architect Menu placement set to " + adcd);
                            ArchitectMenu_ChangeLocation(adcd.defName);
                        }, MenuOptionPriority.Default, null, null, 0f, null, null));
                    }
                }
                Find.WindowStack.Add(new FloatMenu(alist));
            }
            l.CheckboxLabeled((architectMenuDefaultDesigCatDef + "_ArchitectMenuAlwaysShowCategory").Translate(),
                              ref architectMenuAlwaysShowCategory,
                              (architectMenuDefaultDesigCatDef + "_ArchitectMenuAlwaysShowDesc").Translate());
            // Do we always display?  If so, display:
            if (architectMenuAlwaysShowCategory != architectMenuAlwaysShowTmp)
            {
                if (architectMenuAlwaysShowCategory)
                {
                    ArchitectMenu_Show();
                }
                else if (architectMenuDesigCatDef != architectMenuDefaultDesigCatDef)
                {
                    ArchitectMenu_Hide();
                }
                architectMenuAlwaysShowTmp = architectMenuAlwaysShowCategory;
            }
            l.CheckboxLabeled((architectMenuDefaultDesigCatDef + "_ArchitectMenuMoveALL").Translate(),
                              ref architectMenuMoveALLStorageItems,
                              (architectMenuDefaultDesigCatDef + "_ArchitectMenuMoveALLDesc").Translate());
            if (architectMenuMoveALLStorageItems != architectMenuMoveALLTmp)
            {
                //  If turning off "all things in Storage", make sure to
                //    dump all the items into Furniture, to make sure they
                //    can at least be found somewhere.
                string ctmp = architectMenuDesigCatDef;
                if (architectMenuMoveALLStorageItems == false)
                {
                    architectMenuMoveALLStorageItems = true;
                    ArchitectMenu_ChangeLocation("Furniture");
                    architectMenuMoveALLStorageItems = false;
                }
                ArchitectMenu_ChangeLocation(ctmp);
                architectMenuMoveALLTmp = architectMenuMoveALLStorageItems;
            }
            // finished drawing settings for Architect Menu
            // -------------------
            // Allow player to turn of Over-Capacity check.
            //   Turn it off automatically for Project RimFactory and Extended Storage
            //   Note: should turn it off automatically for any other storage mods, too
            l.GapLine();
            Color origColor = GUI.color; // make option gray if ignored
            var   tmpMod    = ModLister.GetActiveModWithIdentifier("spdskatr.projectrimfactory");

            if (tmpMod != null)
            {
                GUI.color = Color.gray;
                // This setting is disabled due to mod Extended Storage
                l.Label("LWMDSignoredDueTo".Translate(tmpMod.Name));
            }
            if ((tmpMod = ModLister.GetActiveModWithIdentifier("Skullywag.ExtendedStorage")) != null)
            {
                GUI.color = Color.gray;
                l.Label("LWMDSignoredDueTo".Translate(tmpMod.Name));
            }
            l.CheckboxLabeled("LWMDSoverCapacityCheck".Translate(), ref checkOverCapacity,
                              "LWMDSoverCapacityCheckDesc".Translate());
            GUI.color = origColor;
            // Per DSU settings - let players change them around...
            l.GapLine();
            if (allowPerDSUSettings)
            {
                if (l.ButtonText("LWMDSperDSUSettings".Translate()))
                {
                    Find.WindowStack.Add(new Dialog_DS_Settings());
                }
            }
            else
            {
                l.CheckboxLabeled("LWMDSperDSUturnOn".Translate(), ref allowPerDSUSettings,
                                  "LWMDSperDSUturnOnDesc".Translate());
            }
            l.GapLine(); // End. Finis. Looks pretty having a line at the end.
            l.EndScrollView(ref viewRect);
        }
        public Job TryOpportunisticJob(Job job)
        {
            Job result;

            if (this.pawn.def.race.intelligence < Intelligence.Humanlike)
            {
                result = null;
            }
            else if (this.pawn.Faction != Faction.OfPlayer)
            {
                result = null;
            }
            else if (this.pawn.Drafted)
            {
                result = null;
            }
            else if (job.playerForced)
            {
                result = null;
            }
            else if (this.pawn.RaceProps.intelligence < Intelligence.Humanlike)
            {
                result = null;
            }
            else if (!job.def.allowOpportunisticPrefix)
            {
                result = null;
            }
            else if (this.pawn.story.WorkTagIsDisabled(WorkTags.ManualDumb | WorkTags.Hauling))
            {
                result = null;
            }
            else if (this.pawn.InMentalState)
            {
                result = null;
            }
            else
            {
                IntVec3 cell = job.targetA.Cell;
                if (!cell.IsValid)
                {
                    result = null;
                }
                else
                {
                    float num = this.pawn.Position.DistanceTo(cell);
                    if (num < AITuning.OpportunisticJobMinDistPawnToDest)
                    {
                        result = null;
                    }
                    else
                    {
                        List <Thing> list = this.pawn.Map.listerHaulables.ThingsPotentiallyNeedingHauling();
                        for (int i = 0; i < list.Count; i++)
                        {
                            Thing thing = list[i];
                            if (this.pawn.Map.reservationManager.FirstRespectedReserver(thing, this.pawn) == null)
                            {
                                float num2 = this.pawn.Position.DistanceTo(thing.Position);
                                if (num2 <= AITuning.OpportunisticJobMaxDistPawnToItem)
                                {
                                    if (num2 <= num * AITuning.OpportunisticJobMaxPickupDistanceFactor)
                                    {
                                        if (num2 + thing.Position.DistanceTo(cell) <= num * AITuning.OpportunisticJobMaxRatioOppHaulDistanceToDestDistance)
                                        {
                                            if (HaulAIUtility.PawnCanAutomaticallyHaulFast(this.pawn, thing, false))
                                            {
                                                StoragePriority currentPriority = StoreUtility.CurrentStoragePriorityOf(thing);
                                                IntVec3         invalid         = IntVec3.Invalid;
                                                if (StoreUtility.TryFindBestBetterStoreCellFor(thing, this.pawn, this.pawn.Map, currentPriority, this.pawn.Faction, out invalid, true))
                                                {
                                                    float num3 = invalid.DistanceTo(cell);
                                                    if (num3 <= AITuning.OpportunisticJobMaxDistDestToDropoff)
                                                    {
                                                        if (num3 <= num * AITuning.OpportunisticJobMaxDistDestToDropoffFactor)
                                                        {
                                                            if (num2 + thing.Position.DistanceTo(invalid) + num3 <= num * AITuning.OpportunisticJobMaxRatioOppHaulDistanceToDestDistance)
                                                            {
                                                                if (num2 + num3 <= num)
                                                                {
                                                                    if (this.pawn.Position.WithinRegions(thing.Position, this.pawn.Map, AITuning.OpportunisticJobMaxPickupRegions, TraverseParms.For(this.pawn, Danger.Deadly, TraverseMode.ByPawn, false), RegionType.Set_Passable))
                                                                    {
                                                                        if (invalid.WithinRegions(cell, this.pawn.Map, AITuning.OpportunisticJobMaxDropoffRegions, TraverseParms.For(this.pawn, Danger.Deadly, TraverseMode.ByPawn, false), RegionType.Set_Passable))
                                                                        {
                                                                            if (DebugViewSettings.drawOpportunisticJobs)
                                                                            {
                                                                                Log.Message("Opportunistic job spawned", false);
                                                                                this.pawn.Map.debugDrawer.FlashLine(this.pawn.Position, thing.Position, 600, SimpleColor.Red);
                                                                                this.pawn.Map.debugDrawer.FlashLine(thing.Position, invalid, 600, SimpleColor.Green);
                                                                                this.pawn.Map.debugDrawer.FlashLine(invalid, cell, 600, SimpleColor.Blue);
                                                                            }
                                                                            return(HaulAIUtility.HaulToCellStorageJob(this.pawn, thing, invalid, false));
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        result = null;
                    }
                }
            }
            return(result);
        }
 public void CopyFrom(StorageSettings other)
 {
     this.Priority = other.Priority;
     this.filter.CopyAllowancesFrom(other.filter);
     this.TryNotifyChanged();
 }
        private Toil Collect()
        {
            Toil toil = new Toil();

            toil.initAction = delegate {
                // Increment the record for how many cells this pawn has mined since this counts as mining
                pawn.records.Increment(RecordDefOf.CellsMined);

                // Start with None to act as a fallback. Rubble will be returned with this parameter
                ResourceRequest req = ResourceRequest.None;

                // Use the mineModeToggle to determine the request
                req = (Quarry.mineModeToggle ? ResourceRequest.Resources : ResourceRequest.Blocks);

                MoteType mote           = MoteType.None;
                bool     singleSpawn    = true;
                bool     eventTriggered = false;
                int      stackCount     = 1;

                // Get the resource from the quarry
                ThingDef def = Quarry.GiveResources(req, out mote, out singleSpawn, out eventTriggered);

                // If something went wrong, bail out
                if (def == null || def.thingClass == null)
                {
                    Log.Warning("Quarry:: Tried to quarry mineable ore, but the ore given was null.");
                    mote        = MoteType.None;
                    singleSpawn = true;
                    // This shouldn't happen at all, but if it does let's add a little reward instead of just giving rubble
                    def = ThingDefOf.ChunkSlagSteel;
                }

                Thing haulableResult = ThingMaker.MakeThing(def);
                if (!singleSpawn && def != ThingDefOf.Component)
                {
                    int sub = (int)(def.BaseMarketValue / 3f);
                    if (sub >= 10)
                    {
                        sub = 9;
                    }

                    stackCount += Mathf.Min(Rand.RangeInclusive(15 - sub, 40 - (sub * 2)), def.stackLimit - 1);
                }

                if (def == ThingDefOf.Component)
                {
                    stackCount += Random.Range(0, 1);
                }

                haulableResult.stackCount = stackCount;

                if (stackCount >= 30)
                {
                    mote = MoteType.LargeVein;
                }

                // Place the resource near the pawn
                GenPlace.TryPlaceThing(haulableResult, pawn.Position, Map, ThingPlaceMode.Near);

                // If the resource had a mote, throw it
                if (mote == MoteType.LargeVein)
                {
                    MoteMaker.ThrowText(haulableResult.DrawPos, Map, Static.TextMote_LargeVein, Color.green, 3f);
                }
                else if (mote == MoteType.Failure)
                {
                    MoteMaker.ThrowText(haulableResult.DrawPos, Map, Static.TextMote_MiningFailed, Color.red, 3f);
                }

                // If the sinkhole event was triggered, damage the pawn and end this job
                // Even if the sinkhole doesn't incapacitate the pawn, they will probably want to seek medical attention
                if (eventTriggered)
                {
                    Messages.Message("QRY_MessageSinkhole".Translate(pawn.NameStringShort), pawn, MessageTypeDefOf.ThreatSmall);
                    DamageInfo dInfo = new DamageInfo(DamageDefOf.Crush, 9, -1f, category: DamageInfo.SourceCategory.Collapse);
                    dInfo.SetBodyRegion(BodyPartHeight.Bottom, BodyPartDepth.Inside);
                    pawn.TakeDamage(dInfo);
                    pawn.TakeDamage(dInfo);

                    EndJobWith(JobCondition.Succeeded);
                }

                // Prevent the colonists from trying to haul rubble, which just makes them visit the platform
                if (haulableResult.def == ThingDefOf.RockRubble)
                {
                    EndJobWith(JobCondition.Succeeded);
                }

                // If this is a chunk or slag, mark it as haulable if allowed to
                if (haulableResult.def.designateHaulable && Quarry.autoHaul)
                {
                    Map.designationManager.AddDesignation(new Designation(haulableResult, DesignationDefOf.Haul));
                }

                // Setup IntVec for assigning
                IntVec3 c;

                // Try to find a suitable storage spot for the resource, removing it from the quarry
                // If there are no platforms with free space, try to haul it to a storage area
                if (Quarry.autoHaul)
                {
                    if (Quarry.HasConnectedPlatform && Quarry.TryFindBestStoreCellFor(haulableResult, pawn, Map, pawn.Faction, out c))
                    {
                        job.SetTarget(TargetIndex.B, haulableResult);
                        job.count = haulableResult.stackCount;
                        job.SetTarget(TargetIndex.C, c);
                    }
                    else
                    {
                        StoragePriority currentPriority = HaulAIUtility.StoragePriorityAtFor(haulableResult.Position, haulableResult);
                        if (StoreUtility.TryFindBestBetterStoreCellFor(haulableResult, pawn, Map, currentPriority, pawn.Faction, out c))
                        {
                            job.SetTarget(TargetIndex.B, haulableResult);
                            job.count = haulableResult.stackCount;
                            job.SetTarget(TargetIndex.C, c);
                        }
                    }
                }
                // If there is no spot to store the resource, end this job
                else
                {
                    EndJobWith(JobCondition.Succeeded);
                }
            };
            toil.defaultCompleteMode = ToilCompleteMode.Instant;

            return(toil);
        }
Beispiel #17
0
        protected override void FillTab()
        {
            IStoreSettingsParent selStoreSettingsParent = this.SelStoreSettingsParent;
            StorageSettings      settings = selStoreSettingsParent.GetStoreSettings();

            Rect position = new Rect(0f, 0f, ITab_Lazy.WinSize.x, ITab_Lazy.WinSize.y).ContractedBy(10f);

            GUI.BeginGroup(position);
            if (this.IsPrioritySettingVisible)
            {
                Text.Font = GameFont.Small;
                Rect rect = new Rect(0f, 0f, 160f, this.TopAreaHeight - 6f);
                if (Widgets.ButtonText(rect, "Priority".Translate() + ": " + settings.Priority.Label(), true, false, true))
                {
                    List <FloatMenuOption> list = new List <FloatMenuOption>();
                    foreach (StoragePriority storagePriority in Enum.GetValues(typeof(StoragePriority)))
                    {
                        if (storagePriority != StoragePriority.Unstored)
                        {
                            StoragePriority localPr = storagePriority;
                            list.Add(new FloatMenuOption(localPr.Label().CapitalizeFirst(), delegate
                            {
                                settings.Priority = localPr;
                            }, MenuOptionPriority.Default, null, null, 0f, null, null));
                        }
                    }
                    Find.WindowStack.Add(new FloatMenu(list));
                }
                UIHighlighter.HighlightOpportunity(rect, "StoragePriority");
            }
            //Lazy button & Threshold Sliders
            {
                Text.Font = GameFont.Small;
                Rect         rect      = new Rect(0f, 35f, 160f, this.TopAreaHeight - 6f);
                LazySettings stockpile = settings as LazySettings;
                if (stockpile == null)
                {
                    Log.Error(string.Format($"Lazy Tab Error: Attempted to load {SelObject} settings as LazySettings, when it was of type {settings.GetType()}"));
                }
                else
                {
                    //Type Button
                    if (Widgets.ButtonText(rect, "Type: " + stockpile.type.ToString(), true, false, true))
                    {
                        List <FloatMenuOption> list = new List <FloatMenuOption>();
                        foreach (LazyType type in Enum.GetValues(typeof(LazyType)))
                        {
                            LazyType localTy = type;
                            list.Add(new FloatMenuOption(type.ToString(), delegate
                            {
                                stockpile.type = type;
                            }, MenuOptionPriority.Default, null, null, 0f, null, null));
                            Find.WindowStack.Add(new FloatMenu(list));
                        }
                    }
                    //Cache Threshold Slider
                    if (stockpile.type == LazyType.Cache)
                    {
                        Rect             sliderRect = new Rect(0f, 66f, WinSize.x - 20f, 70f);
                        Listing_Standard stand      = new Listing_Standard();
                        stand.Begin(sliderRect);
                        stand.Label(string.Format($"Cache Threshold: {stockpile.CacheThreshold * 100:0}%"));
                        stockpile.CacheThreshold = stand.Slider(stockpile.CacheThreshold, 0f, 0.75f);
                        stand.End();
                    }
                    //Buffer Threshold Slider
                    else if (stockpile.type == LazyType.Buffer)
                    {
                        Rect             sliderRect = new Rect(0f, 66f, WinSize.x - 20f, 70f);
                        Listing_Standard stand      = new Listing_Standard();
                        stand.Begin(sliderRect);
                        stand.Label(string.Format($"Buffer Threshold: {stockpile.BufferThreshold * 100:0}%"));
                        stockpile.BufferThreshold = stand.Slider(stockpile.BufferThreshold, 0.25f, 1f);
                        stand.End();
                    }
                }
            }
            ThingFilter parentFilter = null;

            if (selStoreSettingsParent.GetParentStoreSettings() != null)
            {
                parentFilter = selStoreSettingsParent.GetParentStoreSettings().filter;
            }
            Rect rect2 = new Rect(0f, (this.TopAreaHeight * 3) + 5, position.width, position.height - (this.TopAreaHeight * 2));

            ThingFilterUI.DoThingFilterConfigWindow(rect2, ref this.scrollPosition, settings.filter, parentFilter, 8, null, null, null);
            PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.StorageTab, KnowledgeAmount.FrameDisplayed);
            GUI.EndGroup();
        }
Beispiel #18
0
        static bool OverCapacity(Map map, Thing thing, ref StoragePriority storagePriority)
        {
            if (!thing.Spawned)
            {
                return(false);
            }
            if (storagePriority == StoragePriority.Unstored)
            {
                return(false);
            }
            CompDeepStorage cds = (thing.Position.GetSlotGroup(map)?.parent as ThingWithComps)?.GetComp <CompDeepStorage>();
            List <Thing>    l;

            // What if it's a slotGroup put down after someone moved/destroyed a DSU?
            //   Because we CAN still end up with more than one thing on the ground.
            if (cds == null)
            {
                l = map.thingGrid.ThingsListAt(thing.Position);
                for (int i = 0; i < l.Count; i++)
                {
                    if (l[i].def.EverStorable(false))
                    {
                        if (thing == l[i])
                        {
                            return(false);
                        }
                        Utils.Warn(ShouldRemoveFromStorage,
                                   "LWM.DeepStorage: " + thing.stackCount + thing +
                                   " is not in a DSU and there is already a thing at " + thing.Position);
                        storagePriority = StoragePriority.Unstored;
                        return(true);
                    }
                }
            }

            if (cds.limitingFactorForItem > 0f)
            {
                if (thing.GetStatValue(cds.stat) > cds.limitingFactorForItem)
                {
                    Utils.Warn(ShouldRemoveFromStorage,
                               "LWM.DeepStorage: " + thing.stackCount + thing + " is too heavy for DSU at " + thing.Position);
                    storagePriority = StoragePriority.Unstored;
                    return(true);
                }
            }
            float totalWeightStoredHere = 0f;  //mass, or bulk, etc.
            var   stacksStoredHere      = 0;

            l = map.thingGrid.ThingsListAt(thing.Position);
            for (int i = 0; i < l.Count; i++)
            {
                Thing thingInStorage = l[i];
                // TODO: Decide how to handle weight: if thing is stackable, do I want to take some out, if it goes over?
                if (thing == thingInStorage)
                {
                    return(false);                          // it's here, and not over capacity yet!
                }
                if (thingInStorage.def.EverStorable(false)) // an "item" we care about
                {
                    stacksStoredHere++;
                    if (cds.limitingTotalFactorForCell > 0f)
                    {
                        totalWeightStoredHere += thingInStorage.GetStatValue(cds.stat) * thingInStorage.stackCount;
                        if (totalWeightStoredHere > cds.limitingTotalFactorForCell &&
                            stacksStoredHere >= cds.minNumberStacks)
                        {
                            Utils.Warn(ShouldRemoveFromStorage,
                                       "LWM.DeepStorage: " + thing.stackCount + thing + " is over weight capacity at " + thing.Position);
                            storagePriority = StoragePriority.Unstored;
                            return(true);  // this takes us to capacity, and we haven't hit thing
                        }
                    }
                    if (stacksStoredHere >= cds.maxNumberStacks)   // breaks if minNumberStacks > maxNumberStacks. I'm okay with this
                    {
                        Utils.Warn(ShouldRemoveFromStorage,
                                   "LWM.DeepStorage: " + thing.stackCount + thing + " is over capacity at " + thing.Position);
                        storagePriority = StoragePriority.Unstored;
                        return(true);  // this takes us to capacity, and we haven't hit thing
                    }
                } // if storable
            } // end list
            return(false);
        }
        public static bool AddHumanlikeOrders(Vector3 clickPos, Pawn pawn, List <FloatMenuOption> opts)
        {
            IntVec3 c = IntVec3.FromVector3(clickPos);

            foreach (Thing thing in c.GetThingList(pawn.Map))
            {
                Pawn pawn2;
                if ((pawn2 = (thing as Pawn)) != null)
                {
                    Lord lord = pawn2.GetLord();
                    if (lord != null && lord.CurLordToil != null)
                    {
                        IEnumerable <FloatMenuOption> enumerable = lord.CurLordToil.ExtraFloatMenuOptions(pawn2, pawn);
                        if (enumerable != null)
                        {
                            foreach (FloatMenuOption item8 in enumerable)
                            {
                                opts.Add(item8);
                            }
                        }
                    }
                }
            }

            if (pawn.health.capacities.CapableOf(PawnCapacityDefOf.Manipulation))
            {
                foreach (LocalTargetInfo item9 in GenUI.TargetsAt_NewTemp(clickPos, TargetingParameters.ForArrest(pawn), thingsOnly: true))
                {
                    bool flag = item9.HasThing && item9.Thing is Pawn && ((Pawn)item9.Thing).IsWildMan();
                    if (pawn.Drafted || flag)
                    {
                        if (item9.Thing is Pawn && (pawn.InSameExtraFaction((Pawn)item9.Thing, ExtraFactionType.HomeFaction) || pawn.InSameExtraFaction((Pawn)item9.Thing, ExtraFactionType.MiniFaction)))
                        {
                            opts.Add(new FloatMenuOption("CannotArrest".Translate() + ": " + "SameFaction".Translate((Pawn)item9.Thing), null));
                        }
                        else if (!pawn.CanReach(item9, PathEndMode.OnCell, Danger.Deadly))
                        {
                            opts.Add(new FloatMenuOption("CannotArrest".Translate() + ": " + "NoPath".Translate().CapitalizeFirst(), null));
                        }
                        else
                        {
                            Pawn   pTarg2 = (Pawn)item9.Thing;
                            Action action = delegate
                            {
                                Building_Bed building_Bed3 = RestUtility.FindBedFor(pTarg2, pawn, sleeperWillBePrisoner: true, checkSocialProperness: false);
                                if (building_Bed3 == null)
                                {
                                    building_Bed3 = RestUtility.FindBedFor(pTarg2, pawn, sleeperWillBePrisoner: true, checkSocialProperness: false, ignoreOtherReservations: true);
                                }

                                if (building_Bed3 == null)
                                {
                                    Messages.Message("CannotArrest".Translate() + ": " + "NoPrisonerBed".Translate(), pTarg2, MessageTypeDefOf.RejectInput, historical: false);
                                }
                                else
                                {
                                    Job job19 = JobMaker.MakeJob(JobDefOf.Arrest, pTarg2, building_Bed3);
                                    job19.count = 1;
                                    pawn.jobs.TryTakeOrderedJob(job19);
                                    if (pTarg2.Faction != null && ((pTarg2.Faction != Faction.OfPlayer && !pTarg2.Faction.Hidden) || pTarg2.IsQuestLodger()))
                                    {
                                        TutorUtility.DoModalDialogIfNotKnown(ConceptDefOf.ArrestingCreatesEnemies, pTarg2.GetAcceptArrestChance(pawn).ToStringPercent());
                                    }
                                }
                            };
                            opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("TryToArrest".Translate(item9.Thing.LabelCap, item9.Thing, pTarg2.GetAcceptArrestChance(pawn).ToStringPercent()), action, MenuOptionPriority.High, null, item9.Thing), pawn, pTarg2));
                        }
                    }
                }
            }

            foreach (Thing thing2 in c.GetThingList(pawn.Map))
            {
                Thing t = thing2;
                if (t.def.ingestible != null && pawn.RaceProps.CanEverEat(t) && t.IngestibleNow)
                {
                    string text = (!t.def.ingestible.ingestCommandString.NullOrEmpty()) ? string.Format(t.def.ingestible.ingestCommandString, t.LabelShort) : ((string)"ConsumeThing".Translate(t.LabelShort, t));
                    if (!t.IsSociallyProper(pawn))
                    {
                        text = text + ": " + "ReservedForPrisoners".Translate().CapitalizeFirst();
                    }

                    FloatMenuOption floatMenuOption;
                    if (t.def.IsNonMedicalDrug && pawn.IsTeetotaler())
                    {
                        floatMenuOption = new FloatMenuOption(text + ": " + TraitDefOf.DrugDesire.DataAtDegree(-1).GetLabelCapFor(pawn), null);
                    }
                    else if (FoodUtility.InappropriateForTitle(t.def, pawn, allowIfStarving: true))
                    {
                        floatMenuOption = new FloatMenuOption(text + ": " + "FoodBelowTitleRequirements".Translate(pawn.royalty.MostSeniorTitle.def.GetLabelFor(pawn)), null);
                    }
                    else if (!pawn.CanReach(t, PathEndMode.OnCell, Danger.Deadly))
                    {
                        floatMenuOption = new FloatMenuOption(text + ": " + "NoPath".Translate().CapitalizeFirst(), null);
                    }
                    else
                    {
                        MenuOptionPriority priority = (t is Corpse) ? MenuOptionPriority.Low : MenuOptionPriority.Default;
                        int maxAmountToPickup       = FoodUtility.GetMaxAmountToPickup(t, pawn, FoodUtility.WillIngestStackCountOf(pawn, t.def, t.GetStatValue(StatDefOf.Nutrition)));
                        floatMenuOption = FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(text, delegate
                        {
                            int maxAmountToPickup2 = FoodUtility.GetMaxAmountToPickup(t, pawn, FoodUtility.WillIngestStackCountOf(pawn, t.def, t.GetStatValue(StatDefOf.Nutrition)));
                            if (maxAmountToPickup2 != 0)
                            {
                                t.SetForbidden(value: false);
                                Job job18   = JobMaker.MakeJob(JobDefOf.Ingest, t);
                                job18.count = maxAmountToPickup2;
                                pawn.jobs.TryTakeOrderedJob(job18);
                            }
                        }, priority), pawn, t);
                        if (maxAmountToPickup == 0)
                        {
                            floatMenuOption.action = null;
                        }
                    }

                    opts.Add(floatMenuOption);
                }
            }

            foreach (LocalTargetInfo item10 in GenUI.TargetsAt_NewTemp(clickPos, TargetingParameters.ForQuestPawnsWhoWillJoinColony(pawn), thingsOnly: true))
            {
                Pawn            toHelpPawn = (Pawn)item10.Thing;
                FloatMenuOption item4      = pawn.CanReach(item10, PathEndMode.Touch, Danger.Deadly) ? FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(toHelpPawn.IsPrisoner ? "FreePrisoner".Translate() : "OfferHelp".Translate(), delegate
                {
                    pawn.jobs.TryTakeOrderedJob(JobMaker.MakeJob(JobDefOf.OfferHelp, toHelpPawn));
                }, MenuOptionPriority.RescueOrCapture, null, toHelpPawn), pawn, toHelpPawn) : new FloatMenuOption("CannotGoNoPath".Translate(), null);
                opts.Add(item4);
            }

            if (pawn.health.capacities.CapableOf(PawnCapacityDefOf.Manipulation))
            {
                foreach (Thing thing3 in c.GetThingList(pawn.Map))
                {
                    Corpse corpse = thing3 as Corpse;
                    if (corpse != null && corpse.IsInValidStorage())
                    {
                        StoragePriority priority2 = StoreUtility.CurrentHaulDestinationOf(corpse).GetStoreSettings().Priority;
                        if (StoreUtility.TryFindBestBetterNonSlotGroupStorageFor(corpse, pawn, pawn.Map, priority2, Faction.OfPlayer, out IHaulDestination haulDestination, acceptSamePriority: true) && haulDestination.GetStoreSettings().Priority == priority2 && haulDestination is Building_Grave)
                        {
                            Building_Grave grave = haulDestination as Building_Grave;
                            string         label = "PrioritizeGeneric".Translate("Burying".Translate(), corpse.Label);
                            opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(label, delegate
                            {
                                pawn.jobs.TryTakeOrderedJob(HaulAIUtility.HaulToContainerJob(pawn, corpse, grave));
                            }), pawn, new LocalTargetInfo(corpse)));
                        }
                    }
                }

                foreach (LocalTargetInfo item11 in GenUI.TargetsAt_NewTemp(clickPos, TargetingParameters.ForRescue(pawn), thingsOnly: true))
                {
                    Pawn victim3 = (Pawn)item11.Thing;
                    if (!victim3.InBed() && pawn.CanReserveAndReach(victim3, PathEndMode.OnCell, Danger.Deadly, 1, -1, null, ignoreOtherReservations: true) && !victim3.mindState.WillJoinColonyIfRescued)
                    {
                        if (!victim3.IsPrisonerOfColony && (!victim3.InMentalState || victim3.health.hediffSet.HasHediff(HediffDefOf.Scaria)) && (victim3.Faction == Faction.OfPlayer || victim3.Faction == null || !victim3.Faction.HostileTo(Faction.OfPlayer)))
                        {
                            opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("Rescue".Translate(victim3.LabelCap, victim3), delegate
                            {
                                Building_Bed building_Bed2 = RestUtility.FindBedFor(victim3, pawn, sleeperWillBePrisoner: false, checkSocialProperness: false);
                                if (building_Bed2 == null)
                                {
                                    building_Bed2 = RestUtility.FindBedFor(victim3, pawn, sleeperWillBePrisoner: false, checkSocialProperness: false, ignoreOtherReservations: true);
                                }

                                if (building_Bed2 == null)
                                {
                                    string t3 = (!victim3.RaceProps.Animal) ? ((string)"NoNonPrisonerBed".Translate()) : ((string)"NoAnimalBed".Translate());
                                    Messages.Message("CannotRescue".Translate() + ": " + t3, victim3, MessageTypeDefOf.RejectInput, historical: false);
                                }
                                else
                                {
                                    Job job17   = JobMaker.MakeJob(JobDefOf.Rescue, victim3, building_Bed2);
                                    job17.count = 1;
                                    pawn.jobs.TryTakeOrderedJob(job17);
                                    PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.Rescuing, KnowledgeAmount.Total);
                                }
                            }, MenuOptionPriority.RescueOrCapture, null, victim3), pawn, victim3));
                        }

                        if (victim3.RaceProps.Humanlike && (victim3.InMentalState || victim3.Faction != Faction.OfPlayer || (victim3.Downed && (victim3.guilt.IsGuilty || victim3.IsPrisonerOfColony))))
                        {
                            TaggedString taggedString = "Capture".Translate(victim3.LabelCap, victim3);
                            if (victim3.Faction != null && victim3.Faction != Faction.OfPlayer && !victim3.Faction.Hidden && !victim3.Faction.HostileTo(Faction.OfPlayer) && !victim3.IsPrisonerOfColony)
                            {
                                taggedString += ": " + "AngersFaction".Translate().CapitalizeFirst();
                            }

                            opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(taggedString, delegate
                            {
                                Building_Bed building_Bed = RestUtility.FindBedFor(victim3, pawn, sleeperWillBePrisoner: true, checkSocialProperness: false);
                                if (building_Bed == null)
                                {
                                    building_Bed = RestUtility.FindBedFor(victim3, pawn, sleeperWillBePrisoner: true, checkSocialProperness: false, ignoreOtherReservations: true);
                                }

                                if (building_Bed == null)
                                {
                                    Messages.Message("CannotCapture".Translate() + ": " + "NoPrisonerBed".Translate(), victim3, MessageTypeDefOf.RejectInput, historical: false);
                                }
                                else
                                {
                                    Job job16   = JobMaker.MakeJob(JobDefOf.Capture, victim3, building_Bed);
                                    job16.count = 1;
                                    pawn.jobs.TryTakeOrderedJob(job16);
                                    PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.Capturing, KnowledgeAmount.Total);
                                    if (victim3.Faction != null && victim3.Faction != Faction.OfPlayer && !victim3.Faction.Hidden && !victim3.Faction.HostileTo(Faction.OfPlayer) && !victim3.IsPrisonerOfColony)
                                    {
                                        Messages.Message("MessageCapturingWillAngerFaction".Translate(victim3.Named("PAWN")).AdjustedFor(victim3), victim3, MessageTypeDefOf.CautionInput, historical: false);
                                    }
                                }
                            }, MenuOptionPriority.RescueOrCapture, null, victim3), pawn, victim3));
                        }
                    }
                }

                foreach (LocalTargetInfo item12 in GenUI.TargetsAt_NewTemp(clickPos, TargetingParameters.ForRescue(pawn), thingsOnly: true))
                {
                    LocalTargetInfo localTargetInfo = item12;
                    Pawn            victim2         = (Pawn)localTargetInfo.Thing;
                    if (victim2.Downed && pawn.CanReserveAndReach(victim2, PathEndMode.OnCell, Danger.Deadly, 1, -1, null, ignoreOtherReservations: true) && Building_CryptosleepCasket.FindCryptosleepCasketFor(victim2, pawn, ignoreOtherReservations: true) != null)
                    {
                        string text2   = "CarryToCryptosleepCasket".Translate(localTargetInfo.Thing.LabelCap, localTargetInfo.Thing);
                        JobDef jDef    = JobDefOf.CarryToCryptosleepCasket;
                        Action action2 = delegate
                        {
                            Building_CryptosleepCasket building_CryptosleepCasket = Building_CryptosleepCasket.FindCryptosleepCasketFor(victim2, pawn);
                            if (building_CryptosleepCasket == null)
                            {
                                building_CryptosleepCasket = Building_CryptosleepCasket.FindCryptosleepCasketFor(victim2, pawn, ignoreOtherReservations: true);
                            }

                            if (building_CryptosleepCasket == null)
                            {
                                Messages.Message("CannotCarryToCryptosleepCasket".Translate() + ": " + "NoCryptosleepCasket".Translate(), victim2, MessageTypeDefOf.RejectInput, historical: false);
                            }
                            else
                            {
                                Job job15 = JobMaker.MakeJob(jDef, victim2, building_CryptosleepCasket);
                                job15.count = 1;
                                pawn.jobs.TryTakeOrderedJob(job15);
                            }
                        };
                        if (victim2.IsQuestLodger())
                        {
                            text2 += " (" + "CryptosleepCasketGuestsNotAllowed".Translate() + ")";
                            opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(text2, null, MenuOptionPriority.Default, null, victim2), pawn, victim2));
                        }
                        else if (victim2.GetExtraHostFaction() != null)
                        {
                            text2 += " (" + "CryptosleepCasketGuestPrisonersNotAllowed".Translate() + ")";
                            opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(text2, null, MenuOptionPriority.Default, null, victim2), pawn, victim2));
                        }
                        else
                        {
                            opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(text2, action2, MenuOptionPriority.Default, null, victim2), pawn, victim2));
                        }
                    }
                }

                if (ModsConfig.RoyaltyActive)
                {
                    foreach (LocalTargetInfo item13 in GenUI.TargetsAt_NewTemp(clickPos, TargetingParameters.ForShuttle(pawn), thingsOnly: true))
                    {
                        LocalTargetInfo   localTargetInfo2 = item13;
                        Pawn              victim           = (Pawn)localTargetInfo2.Thing;
                        Predicate <Thing> validator        = (Thing thing) => thing.TryGetComp <CompShuttle>()?.IsAllowedNow(victim) ?? false;
                        Thing             shuttleThing     = GenClosest.ClosestThingReachable(victim.Position, victim.Map, ThingRequest.ForDef(ThingDefOf.Shuttle), PathEndMode.ClosestTouch, TraverseParms.For(pawn), 9999f, validator);
                        if (shuttleThing != null && pawn.CanReserveAndReach(victim, PathEndMode.OnCell, Danger.Deadly, 1, -1, null, ignoreOtherReservations: true) && !pawn.WorkTypeIsDisabled(WorkTypeDefOf.Hauling))
                        {
                            string label2  = "CarryToShuttle".Translate(localTargetInfo2.Thing);
                            Action action3 = delegate
                            {
                                CompShuttle compShuttle = shuttleThing.TryGetComp <CompShuttle>();
                                if (!compShuttle.LoadingInProgressOrReadyToLaunch)
                                {
                                    TransporterUtility.InitiateLoading(Gen.YieldSingle(compShuttle.Transporter));
                                }

                                Job job14 = JobMaker.MakeJob(JobDefOf.HaulToTransporter, victim, shuttleThing);
                                job14.ignoreForbidden = true;
                                job14.count           = 1;
                                pawn.jobs.TryTakeOrderedJob(job14);
                            };
                            opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(label2, action3), pawn, victim));
                        }
                    }
                }
            }

            foreach (LocalTargetInfo item14 in GenUI.TargetsAt_NewTemp(clickPos, TargetingParameters.ForStrip(pawn), thingsOnly: true))
            {
                LocalTargetInfo stripTarg = item14;
                FloatMenuOption item5     = pawn.CanReach(stripTarg, PathEndMode.ClosestTouch, Danger.Deadly) ? ((stripTarg.Pawn == null || !stripTarg.Pawn.HasExtraHomeFaction()) ? FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("Strip".Translate(stripTarg.Thing.LabelCap, stripTarg.Thing), delegate
                {
                    stripTarg.Thing.SetForbidden(value: false, warnOnFail: false);
                    pawn.jobs.TryTakeOrderedJob(JobMaker.MakeJob(JobDefOf.Strip, stripTarg));
                    StrippableUtility.CheckSendStrippingImpactsGoodwillMessage(stripTarg.Thing);
                }), pawn, stripTarg) : new FloatMenuOption("CannotStrip".Translate(stripTarg.Thing.LabelCap, stripTarg.Thing) + ": " + "QuestRelated".Translate().CapitalizeFirst(), null)) : new FloatMenuOption("CannotStrip".Translate(stripTarg.Thing.LabelCap, stripTarg.Thing) + ": " + "NoPath".Translate().CapitalizeFirst(), null);
                opts.Add(item5);
            }

            ThingWithComps equipment;

            if (pawn.equipment != null)
            {
                equipment = null;
                List <Thing> thingList = c.GetThingList(pawn.Map);
                for (int i = 0; i < thingList.Count; i++)
                {
                    if (thingList[i].TryGetComp <CompEquippable>() != null)
                    {
                        equipment = (ThingWithComps)thingList[i];
                        break;
                    }
                }

                if (equipment != null)
                {
                    string          labelShort = equipment.LabelShort;
                    FloatMenuOption item6;
                    string          cantReason;
                    if (equipment.def.IsWeapon && pawn.WorkTagIsDisabled(WorkTags.Violent))
                    {
                        item6 = new FloatMenuOption("CannotEquip".Translate(labelShort) + ": " + "IsIncapableOfViolenceLower".Translate(pawn.LabelShort, pawn), null);
                    }
                    else if (!pawn.CanReach(equipment, PathEndMode.ClosestTouch, Danger.Deadly))
                    {
                        item6 = new FloatMenuOption("CannotEquip".Translate(labelShort) + ": " + "NoPath".Translate().CapitalizeFirst(), null);
                    }
                    else if (!pawn.health.capacities.CapableOf(PawnCapacityDefOf.Manipulation))
                    {
                        item6 = new FloatMenuOption("CannotEquip".Translate(labelShort) + ": " + "Incapable".Translate(), null);
                    }
                    else if (equipment.IsBurning())
                    {
                        item6 = new FloatMenuOption("CannotEquip".Translate(labelShort) + ": " + "BurningLower".Translate(), null);
                    }
                    else if (pawn.IsQuestLodger() && !EquipmentUtility.QuestLodgerCanEquip(equipment, pawn))
                    {
                        item6 = new FloatMenuOption("CannotEquip".Translate(labelShort) + ": " + "QuestRelated".Translate().CapitalizeFirst(), null);
                    }
                    else if (!EquipmentUtility.CanEquip_NewTmp(equipment, pawn, out cantReason, checkBonded: false))
                    {
                        item6 = new FloatMenuOption("CannotEquip".Translate(labelShort) + ": " + cantReason.CapitalizeFirst(), null);
                    }
                    else
                    {
                        string text3 = "Equip".Translate(labelShort);
                        if (equipment.def.IsRangedWeapon && pawn.story != null && pawn.story.traits.HasTrait(TraitDefOf.Brawler))
                        {
                            text3 += " " + "EquipWarningBrawler".Translate();
                        }

                        if (EquipmentUtility.AlreadyBondedToWeapon(equipment, pawn))
                        {
                            text3 += " " + "BladelinkAlreadyBonded".Translate();
                            TaggedString dialogText = "BladelinkAlreadyBondedDialog".Translate(pawn.Named("PAWN"), equipment.Named("WEAPON"), pawn.equipment.bondedWeapon.Named("BONDEDWEAPON"));
                            item6 = FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(text3, delegate
                            {
                                Find.WindowStack.Add(new Dialog_MessageBox(dialogText));
                            }, MenuOptionPriority.High), pawn, equipment);
                        }
                        else
                        {
                            item6 = FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(text3, delegate
                            {
                                string personaWeaponConfirmationText = EquipmentUtility.GetPersonaWeaponConfirmationText(equipment, pawn);
                                if (!personaWeaponConfirmationText.NullOrEmpty())
                                {
                                    Find.WindowStack.Add(new Dialog_MessageBox(personaWeaponConfirmationText, "Yes".Translate(), delegate
                                    {
                                        Equip();
                                    }, "No".Translate()));
                                }
                                else
                                {
                                    Equip();
                                }
                            }, MenuOptionPriority.High), pawn, equipment);
                        }
                    }

                    opts.Add(item6);
                }
            }

            foreach (Pair <CompReloadable, Thing> item15 in ReloadableUtility.FindPotentiallyReloadableGear(pawn, c.GetThingList(pawn.Map)))
            {
                CompReloadable comp   = item15.First;
                Thing          second = item15.Second;
                string         text4  = "Reload".Translate(comp.parent.Named("GEAR"), NamedArgumentUtility.Named(comp.AmmoDef, "AMMO")) + " (" + comp.LabelRemaining + ")";
                List <Thing>   chosenAmmo;
                if (!pawn.CanReach(second, PathEndMode.ClosestTouch, Danger.Deadly))
                {
                    opts.Add(new FloatMenuOption(text4 + ": " + "NoPath".Translate().CapitalizeFirst(), null));
                }
                else if (!comp.NeedsReload(allowForcedReload: true))
                {
                    opts.Add(new FloatMenuOption(text4 + ": " + "ReloadFull".Translate(), null));
                }
                else if ((chosenAmmo = ReloadableUtility.FindEnoughAmmo(pawn, second.Position, comp, forceReload: true)) == null)
                {
                    opts.Add(new FloatMenuOption(text4 + ": " + "ReloadNotEnough".Translate(), null));
                }
                else
                {
                    Action action4 = delegate
                    {
                        pawn.jobs.TryTakeOrderedJob(JobGiver_Reload.MakeReloadJob(comp, chosenAmmo));
                    };
                    opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(text4, action4), pawn, second));
                }
            }

            if (pawn.apparel != null)
            {
                if (pawn.Map.thingGrid.ThingAt(c, ThingCategory.Item) is Apparel apparel)
                {
                    string key  = "CannotWear";
                    string key2 = "ForceWear";
                    if (apparel.def.apparel.LastLayer.IsUtilityLayer)
                    {
                        key  = "CannotEquipApparel";
                        key2 = "ForceEquipApparel";
                    }

                    string          cantReason2;
                    FloatMenuOption item7 = (!pawn.CanReach(apparel, PathEndMode.ClosestTouch, Danger.Deadly)) ? new FloatMenuOption(key.Translate(apparel.Label, apparel) + ": " + "NoPath".Translate().CapitalizeFirst(), null) : (apparel.IsBurning() ? new FloatMenuOption(key.Translate(apparel.Label, apparel) + ": " + "Burning".Translate(), null) : (pawn.apparel.WouldReplaceLockedApparel(apparel) ? new FloatMenuOption(key.Translate(apparel.Label, apparel) + ": " + "WouldReplaceLockedApparel".Translate().CapitalizeFirst(), null) : ((!ApparelUtility.HasPartsToWear(pawn, apparel.def)) ? new FloatMenuOption(key.Translate(apparel.Label, apparel) + ": " + "CannotWearBecauseOfMissingBodyParts".Translate(), null) : (EquipmentUtility.CanEquip_NewTmp(apparel, pawn, out cantReason2) ? FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(key2.Translate(apparel.LabelShort, apparel), delegate
                    {
                        apparel.SetForbidden(value: false);
                        Job job13 = JobMaker.MakeJob(JobDefOf.Wear, apparel);
                        pawn.jobs.TryTakeOrderedJob(job13);
                    }, MenuOptionPriority.High), pawn, apparel) : new FloatMenuOption(key.Translate(apparel.Label, apparel) + ": " + cantReason2, null)))));
                    opts.Add(item7);
                }
            }

            if (pawn.IsFormingCaravan())
            {
                Thing item3 = c.GetFirstItem(pawn.Map);
                if (item3 != null && item3.def.EverHaulable && item3.def.canLoadIntoCaravan)
                {
                    Pawn   packTarget = GiveToPackAnimalUtility.UsablePackAnimalWithTheMostFreeSpace(pawn) ?? pawn;
                    JobDef jobDef     = (packTarget == pawn) ? JobDefOf.TakeInventory : JobDefOf.GiveToPackAnimal;
                    if (!pawn.CanReach(item3, PathEndMode.ClosestTouch, Danger.Deadly))
                    {
                        opts.Add(new FloatMenuOption("CannotLoadIntoCaravan".Translate(item3.Label, item3) + ": " + "NoPath".Translate().CapitalizeFirst(), null));
                    }
                    else if (MassUtility.WillBeOverEncumberedAfterPickingUp(packTarget, item3, 1))
                    {
                        opts.Add(new FloatMenuOption("CannotLoadIntoCaravan".Translate(item3.Label, item3) + ": " + "TooHeavy".Translate(), null));
                    }
                    else
                    {
                        LordJob_FormAndSendCaravan lordJob = (LordJob_FormAndSendCaravan)pawn.GetLord().LordJob;
                        float capacityLeft = CaravanFormingUtility.CapacityLeft(lordJob);
                        if (item3.stackCount == 1)
                        {
                            float capacityLeft2 = capacityLeft - item3.GetStatValue(StatDefOf.Mass);
                            opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(CaravanFormingUtility.AppendOverweightInfo("LoadIntoCaravan".Translate(item3.Label, item3), capacityLeft2), delegate
                            {
                                item3.SetForbidden(value: false, warnOnFail: false);
                                Job job12              = JobMaker.MakeJob(jobDef, item3);
                                job12.count            = 1;
                                job12.checkEncumbrance = (packTarget == pawn);
                                pawn.jobs.TryTakeOrderedJob(job12);
                            }, MenuOptionPriority.High), pawn, item3));
                        }
                        else
                        {
                            if (MassUtility.WillBeOverEncumberedAfterPickingUp(packTarget, item3, item3.stackCount))
                            {
                                opts.Add(new FloatMenuOption("CannotLoadIntoCaravanAll".Translate(item3.Label, item3) + ": " + "TooHeavy".Translate(), null));
                            }
                            else
                            {
                                float capacityLeft3 = capacityLeft - (float)item3.stackCount * item3.GetStatValue(StatDefOf.Mass);
                                opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(CaravanFormingUtility.AppendOverweightInfo("LoadIntoCaravanAll".Translate(item3.Label, item3), capacityLeft3), delegate
                                {
                                    item3.SetForbidden(value: false, warnOnFail: false);
                                    Job job11              = JobMaker.MakeJob(jobDef, item3);
                                    job11.count            = item3.stackCount;
                                    job11.checkEncumbrance = (packTarget == pawn);
                                    pawn.jobs.TryTakeOrderedJob(job11);
                                }, MenuOptionPriority.High), pawn, item3));
                            }

                            opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("LoadIntoCaravanSome".Translate(item3.LabelNoCount, item3), delegate
                            {
                                int to3 = Mathf.Min(MassUtility.CountToPickUpUntilOverEncumbered(packTarget, item3), item3.stackCount);
                                Dialog_Slider window3 = new Dialog_Slider(delegate(int val)
                                {
                                    float capacityLeft4 = capacityLeft - (float)val * item3.GetStatValue(StatDefOf.Mass);
                                    return(CaravanFormingUtility.AppendOverweightInfo(string.Format("LoadIntoCaravanCount".Translate(item3.LabelNoCount, item3), val), capacityLeft4));
                                }, 1, to3, delegate(int count)
                                {
                                    item3.SetForbidden(value: false, warnOnFail: false);
                                    Job job10              = JobMaker.MakeJob(jobDef, item3);
                                    job10.count            = count;
                                    job10.checkEncumbrance = (packTarget == pawn);
                                    pawn.jobs.TryTakeOrderedJob(job10);
                                });
                                Find.WindowStack.Add(window3);
                            }, MenuOptionPriority.High), pawn, item3));
                        }
                    }
                }
            }

            if (!pawn.Map.IsPlayerHome && !pawn.IsFormingCaravan())
            {
                Thing item2 = c.GetFirstItem(pawn.Map);
                if (item2 != null && item2.def.EverHaulable)
                {
                    if (!pawn.CanReach(item2, PathEndMode.ClosestTouch, Danger.Deadly))
                    {
                        opts.Add(new FloatMenuOption("CannotPickUp".Translate(item2.Label, item2) + ": " + "NoPath".Translate().CapitalizeFirst(), null));
                    }
                    else if (MassUtility.WillBeOverEncumberedAfterPickingUp(pawn, item2, 1))
                    {
                        opts.Add(new FloatMenuOption("CannotPickUp".Translate(item2.Label, item2) + ": " + "TooHeavy".Translate(), null));
                    }
                    else if (item2.stackCount == 1)
                    {
                        opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("PickUp".Translate(item2.Label, item2), delegate
                        {
                            item2.SetForbidden(value: false, warnOnFail: false);
                            Job job9              = JobMaker.MakeJob(JobDefOf.TakeInventory, item2);
                            job9.count            = 1;
                            job9.checkEncumbrance = true;
                            pawn.jobs.TryTakeOrderedJob(job9);
                        }, MenuOptionPriority.High), pawn, item2));
                    }
                    else
                    {
                        if (MassUtility.WillBeOverEncumberedAfterPickingUp(pawn, item2, item2.stackCount))
                        {
                            opts.Add(new FloatMenuOption("CannotPickUpAll".Translate(item2.Label, item2) + ": " + "TooHeavy".Translate(), null));
                        }
                        else
                        {
                            opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("PickUpAll".Translate(item2.Label, item2), delegate
                            {
                                item2.SetForbidden(value: false, warnOnFail: false);
                                Job job8              = JobMaker.MakeJob(JobDefOf.TakeInventory, item2);
                                job8.count            = item2.stackCount;
                                job8.checkEncumbrance = true;
                                pawn.jobs.TryTakeOrderedJob(job8);
                            }, MenuOptionPriority.High), pawn, item2));
                        }

                        opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("PickUpSome".Translate(item2.LabelNoCount, item2), delegate
                        {
                            int to2 = Mathf.Min(MassUtility.CountToPickUpUntilOverEncumbered(pawn, item2), item2.stackCount);
                            Dialog_Slider window2 = new Dialog_Slider("PickUpCount".Translate(item2.LabelNoCount, item2), 1, to2, delegate(int count)
                            {
                                item2.SetForbidden(value: false, warnOnFail: false);
                                Job job7              = JobMaker.MakeJob(JobDefOf.TakeInventory, item2);
                                job7.count            = count;
                                job7.checkEncumbrance = true;
                                pawn.jobs.TryTakeOrderedJob(job7);
                            });
                            Find.WindowStack.Add(window2);
                        }, MenuOptionPriority.High), pawn, item2));
                    }
                }
            }

            if (!pawn.Map.IsPlayerHome && !pawn.IsFormingCaravan())
            {
                Thing item = c.GetFirstItem(pawn.Map);
                if (item != null && item.def.EverHaulable)
                {
                    Pawn bestPackAnimal = GiveToPackAnimalUtility.UsablePackAnimalWithTheMostFreeSpace(pawn);
                    if (bestPackAnimal != null)
                    {
                        if (!pawn.CanReach(item, PathEndMode.ClosestTouch, Danger.Deadly))
                        {
                            opts.Add(new FloatMenuOption("CannotGiveToPackAnimal".Translate(item.Label, item) + ": " + "NoPath".Translate().CapitalizeFirst(), null));
                        }
                        else if (MassUtility.WillBeOverEncumberedAfterPickingUp(bestPackAnimal, item, 1))
                        {
                            opts.Add(new FloatMenuOption("CannotGiveToPackAnimal".Translate(item.Label, item) + ": " + "TooHeavy".Translate(), null));
                        }
                        else if (item.stackCount == 1)
                        {
                            opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("GiveToPackAnimal".Translate(item.Label, item), delegate
                            {
                                item.SetForbidden(value: false, warnOnFail: false);
                                Job job6   = JobMaker.MakeJob(JobDefOf.GiveToPackAnimal, item);
                                job6.count = 1;
                                pawn.jobs.TryTakeOrderedJob(job6);
                            }, MenuOptionPriority.High), pawn, item));
                        }
                        else
                        {
                            if (MassUtility.WillBeOverEncumberedAfterPickingUp(bestPackAnimal, item, item.stackCount))
                            {
                                opts.Add(new FloatMenuOption("CannotGiveToPackAnimalAll".Translate(item.Label, item) + ": " + "TooHeavy".Translate(), null));
                            }
                            else
                            {
                                opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("GiveToPackAnimalAll".Translate(item.Label, item), delegate
                                {
                                    item.SetForbidden(value: false, warnOnFail: false);
                                    Job job5   = JobMaker.MakeJob(JobDefOf.GiveToPackAnimal, item);
                                    job5.count = item.stackCount;
                                    pawn.jobs.TryTakeOrderedJob(job5);
                                }, MenuOptionPriority.High), pawn, item));
                            }

                            opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("GiveToPackAnimalSome".Translate(item.LabelNoCount, item), delegate
                            {
                                int to = Mathf.Min(MassUtility.CountToPickUpUntilOverEncumbered(bestPackAnimal, item), item.stackCount);
                                Dialog_Slider window = new Dialog_Slider("GiveToPackAnimalCount".Translate(item.LabelNoCount, item), 1, to, delegate(int count)
                                {
                                    item.SetForbidden(value: false, warnOnFail: false);
                                    Job job4   = JobMaker.MakeJob(JobDefOf.GiveToPackAnimal, item);
                                    job4.count = count;
                                    pawn.jobs.TryTakeOrderedJob(job4);
                                });
                                Find.WindowStack.Add(window);
                            }, MenuOptionPriority.High), pawn, item));
                        }
                    }
                }
            }

            if (!pawn.Map.IsPlayerHome && pawn.Map.exitMapGrid.MapUsesExitGrid)
            {
                foreach (LocalTargetInfo item16 in GenUI.TargetsAt_NewTemp(clickPos, TargetingParameters.ForRescue(pawn), thingsOnly: true))
                {
                    Pawn p = (Pawn)item16.Thing;
                    if (p.Faction == Faction.OfPlayer || p.IsPrisonerOfColony || CaravanUtility.ShouldAutoCapture(p, Faction.OfPlayer))
                    {
                        IntVec3 exitSpot;
                        if (!pawn.CanReach(p, PathEndMode.ClosestTouch, Danger.Deadly))
                        {
                            opts.Add(new FloatMenuOption("CannotCarryToExit".Translate(p.Label, p) + ": " + "NoPath".Translate().CapitalizeFirst(), null));
                        }
                        else if (!RCellFinder.TryFindBestExitSpot(pawn, out exitSpot))
                        {
                            opts.Add(new FloatMenuOption("CannotCarryToExit".Translate(p.Label, p) + ": " + "NoPath".Translate().CapitalizeFirst(), null));
                        }
                        else
                        {
                            TaggedString taggedString2 = (p.Faction == Faction.OfPlayer || p.IsPrisonerOfColony) ? "CarryToExit".Translate(p.Label, p) : "CarryToExitAndCapture".Translate(p.Label, p);
                            opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(taggedString2, delegate
                            {
                                Job job3   = JobMaker.MakeJob(JobDefOf.CarryDownedPawnToExit, p, exitSpot);
                                job3.count = 1;
                                job3.failIfCantJoinOrCreateCaravan = true;
                                pawn.jobs.TryTakeOrderedJob(job3);
                            }, MenuOptionPriority.High), pawn, item16));
                        }
                    }
                }
            }

            if (pawn.equipment != null && pawn.equipment.Primary != null && GenUI.TargetsAt_NewTemp(clickPos, TargetingParameters.ForSelf(pawn), thingsOnly: true).Any())
            {
                if (pawn.IsQuestLodger() && !EquipmentUtility.QuestLodgerCanUnequip(pawn.equipment.Primary, pawn))
                {
                    opts.Add(new FloatMenuOption("CannotDrop".Translate(pawn.equipment.Primary.Label, pawn.equipment.Primary) + ": " + "QuestRelated".Translate().CapitalizeFirst(), null));
                }
                else
                {
                    Action action5 = delegate
                    {
                        pawn.jobs.TryTakeOrderedJob(JobMaker.MakeJob(JobDefOf.DropEquipment, pawn.equipment.Primary));
                    };
                    opts.Add(new FloatMenuOption("Drop".Translate(pawn.equipment.Primary.Label, pawn.equipment.Primary), action5, MenuOptionPriority.Default, null, pawn));
                }
            }

            foreach (LocalTargetInfo item17 in GenUI.TargetsAt_NewTemp(clickPos, TargetingParameters.ForTrade(), thingsOnly: true))
            {
                if (!pawn.CanReach(item17, PathEndMode.OnCell, Danger.Deadly))
                {
                    opts.Add(new FloatMenuOption("CannotTrade".Translate() + ": " + "NoPath".Translate().CapitalizeFirst(), null));
                }
                else if (pawn.skills.GetSkill(SkillDefOf.Social).TotallyDisabled)
                {
                    opts.Add(new FloatMenuOption("CannotPrioritizeWorkTypeDisabled".Translate(SkillDefOf.Social.LabelCap), null));
                }
                else if (!pawn.CanTradeWith(((Pawn)item17.Thing).Faction, ((Pawn)item17.Thing).TraderKind))
                {
                    opts.Add(new FloatMenuOption("CannotTradeMissingTitleAbility".Translate(), null));
                }
                else
                {
                    Pawn   pTarg   = (Pawn)item17.Thing;
                    Action action6 = delegate
                    {
                        Job job2 = JobMaker.MakeJob(JobDefOf.TradeWithPawn, pTarg);
                        job2.playerForced = true;
                        pawn.jobs.TryTakeOrderedJob(job2);
                        PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.InteractingWithTraders, KnowledgeAmount.Total);
                    };
                    string t2 = "";
                    if (pTarg.Faction != null)
                    {
                        t2 = " (" + pTarg.Faction.Name + ")";
                    }

                    opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("TradeWith".Translate(pTarg.LabelShort + ", " + pTarg.TraderKind.label) + t2, action6, MenuOptionPriority.InitiateSocial, null, item17.Thing), pawn, pTarg));
                }
            }

            foreach (LocalTargetInfo casket in GenUI.TargetsAt_NewTemp(clickPos, TargetingParameters.ForOpen(pawn), thingsOnly: true))
            {
                if (!pawn.CanReach(casket, PathEndMode.OnCell, Danger.Deadly))
                {
                    opts.Add(new FloatMenuOption("CannotOpen".Translate(casket.Thing) + ": " + "NoPath".Translate().CapitalizeFirst(), null));
                }
                else if (!pawn.health.capacities.CapableOf(PawnCapacityDefOf.Manipulation))
                {
                    opts.Add(new FloatMenuOption("CannotOpen".Translate(casket.Thing) + ": " + "Incapable".Translate(), null));
                }
                else if (casket.Thing.Map.designationManager.DesignationOn(casket.Thing, DesignationDefOf.Open) == null)
                {
                    opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("Open".Translate(casket.Thing), delegate
                    {
                        Job job = JobMaker.MakeJob(JobDefOf.Open, casket.Thing);
                        job.ignoreDesignations = true;
                        pawn.jobs.TryTakeOrderedJob(job);
                    }, MenuOptionPriority.High), pawn, casket.Thing));
                }
            }

            foreach (Thing item18 in pawn.Map.thingGrid.ThingsAt(c))
            {
                foreach (FloatMenuOption floatMenuOption2 in item18.GetFloatMenuOptions(pawn))
                {
                    opts.Add(floatMenuOption2);
                }
            }

            void Equip()
            {
                equipment.SetForbidden(value: false);
                pawn.jobs.TryTakeOrderedJob(JobMaker.MakeJob(JobDefOf.Equip, equipment));
                MoteMaker.MakeStaticMote(equipment.DrawPos, equipment.Map, ThingDefOf.Mote_FeedbackEquip);
                PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.EquippingWeapons, KnowledgeAmount.Total);
            }

            return(false);
        }
        protected override void FillTab()
        {
            IStoreSettingsParent storeSettingsParent = this.SelStoreSettingsParent;
            StorageSettings      settings            = storeSettingsParent.GetStoreSettings();
            Rect position = new Rect(0f, 0f, ITab_Storage.WinSize.x, ITab_Storage.WinSize.y).ContractedBy(10f);

            GUI.BeginGroup(position);
            if (this.IsPrioritySettingVisible)
            {
                Text.Font = GameFont.Small;
                Rect rect = new Rect(0f, 0f, 160f, this.TopAreaHeight - 6f);
                if (Widgets.ButtonText(rect, "Priority".Translate() + ": " + settings.Priority.Label().CapitalizeFirst(), true, false, true))
                {
                    List <FloatMenuOption> list       = new List <FloatMenuOption>();
                    IEnumerator            enumerator = Enum.GetValues(typeof(StoragePriority)).GetEnumerator();
                    try
                    {
                        while (enumerator.MoveNext())
                        {
                            object          obj             = enumerator.Current;
                            StoragePriority storagePriority = (StoragePriority)obj;
                            if (storagePriority != StoragePriority.Unstored)
                            {
                                StoragePriority localPr = storagePriority;
                                list.Add(new FloatMenuOption(localPr.Label().CapitalizeFirst(), delegate()
                                {
                                    settings.Priority = localPr;
                                }, MenuOptionPriority.Default, null, null, 0f, null, null));
                            }
                        }
                    }
                    finally
                    {
                        IDisposable disposable;
                        if ((disposable = (enumerator as IDisposable)) != null)
                        {
                            disposable.Dispose();
                        }
                    }
                    Find.WindowStack.Add(new FloatMenu(list));
                }
                UIHighlighter.HighlightOpportunity(rect, "StoragePriority");
            }
            ThingFilter parentFilter = null;

            if (storeSettingsParent.GetParentStoreSettings() != null)
            {
                parentFilter = storeSettingsParent.GetParentStoreSettings().filter;
            }
            Rect rect2 = new Rect(0f, this.TopAreaHeight, position.width, position.height - this.TopAreaHeight);

            Bill[] first = (from b in BillUtility.GlobalBills()
                            where b is Bill_Production && b.GetStoreZone() == storeSettingsParent && b.recipe.WorkerCounter.CanPossiblyStoreInStockpile((Bill_Production)b, b.GetStoreZone())
                            select b).ToArray <Bill>();
            ThingFilterUI.DoThingFilterConfigWindow(rect2, ref this.scrollPosition, settings.filter, parentFilter, 8, null, null, null, null);
            Bill[] second = (from b in BillUtility.GlobalBills()
                             where b is Bill_Production && b.GetStoreZone() == storeSettingsParent && b.recipe.WorkerCounter.CanPossiblyStoreInStockpile((Bill_Production)b, b.GetStoreZone())
                             select b).ToArray <Bill>();
            IEnumerable <Bill> enumerable = first.Except(second);

            foreach (Bill bill in enumerable)
            {
                Messages.Message("MessageBillValidationStoreZoneInsufficient".Translate(new object[]
                {
                    bill.LabelCap,
                    bill.billStack.billGiver.LabelShort.CapitalizeFirst(),
                    bill.GetStoreZone().label
                }), bill.billStack.billGiver as Thing, MessageTypeDefOf.RejectInput, false);
            }
            PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.StorageTab, KnowledgeAmount.FrameDisplayed);
            GUI.EndGroup();
        }
        private Toil Collect()
        {
            return(new Toil()
            {
                initAction = delegate
                {
                    // Increment the record for how many cells this pawn has mined since this counts as mining
                    // TODO: B19 - change to quarry m3
                    pawn.records.Increment(RecordDefOf.CellsMined);

                    // Start with None to act as a fallback. Rubble will be returned with this parameter
                    ResourceRequest req = ResourceRequest.None;

                    // Use the mineModeToggle to determine the request
                    req = (ResourceRequest)(((int)Quarry.mineModeToggle) + 1);

                    MoteType mote = MoteType.None;
                    int stackCount = 1;

                    // Get the resource from the quarry
                    ThingDef def = Quarry.GiveResources(req, out mote, out bool singleSpawn, out bool eventTriggered);
                    // If something went wrong, bail out
                    if (def == null || def.thingClass == null)
                    {
                        Log.Warning("Quarry:: Tried to quarry mineable ore, but the ore given was null.");
                        mote = MoteType.None;
                        singleSpawn = true;
                        // This shouldn't happen at all, but if it does let's add a little reward instead of just giving rubble
                        def = ThingDefOf.ChunkSlagSteel;
                    }

                    Thing haulableResult = ThingMaker.MakeThing(def);
                    if (!singleSpawn && def != ThingDefOf.ComponentIndustrial)
                    {
                        int sub = (int)(def.BaseMarketValue / 2f);
                        sub = Mathf.Clamp(sub, 0, 10);

                        stackCount += Mathf.Min(Rand.RangeInclusive(15 - sub, 40 - (sub * 2)), def.stackLimit - 1);
                    }

                    if (def == ThingDefOf.ComponentIndustrial)
                    {
                        stackCount += Random.Range(0, 1);
                    }

                    haulableResult.stackCount = stackCount;

                    if (stackCount >= 30)
                    {
                        mote = MoteType.LargeVein;
                    }

                    bool usesQuality = false;
                    // Adjust quality for items that use it
                    if (haulableResult.TryGetComp <CompQuality>() != null)
                    {
                        usesQuality = true;
                        haulableResult.TryGetComp <CompQuality>().SetQuality(QualityUtility.GenerateQualityTraderItem(), ArtGenerationContext.Outsider);
                    }
                    // Adjust hitpoints, this was just mined from under the ground after all
                    if (def.useHitPoints && !def.thingCategories.Contains(QuarryDefOf.StoneChunks) && def != ThingDefOf.ComponentIndustrial)
                    {
                        float minHpThresh = 0.25f;
                        if (usesQuality)
                        {
                            minHpThresh = Mathf.Clamp((float)haulableResult.TryGetComp <CompQuality>().Quality / 10f, 0.1f, 0.7f);
                        }
                        int hp = Mathf.RoundToInt(Rand.Range(minHpThresh, 1f) * haulableResult.MaxHitPoints);
                        hp = Mathf.Max(1, hp);
                        haulableResult.HitPoints = hp;
                    }

                    // Place the resource near the pawn
                    GenPlace.TryPlaceThing(haulableResult, pawn.Position, Map, ThingPlaceMode.Near);

                    // If the resource had a mote, throw it
                    if (mote == MoteType.LargeVein)
                    {
                        MoteMaker.ThrowText(haulableResult.DrawPos, Map, Static.TextMote_LargeVein, Color.green, 3f);
                    }
                    else if (mote == MoteType.Failure)
                    {
                        MoteMaker.ThrowText(haulableResult.DrawPos, Map, Static.TextMote_MiningFailed, Color.red, 3f);
                    }

                    // If the sinkhole event was triggered, damage the pawn and end this job
                    // Even if the sinkhole doesn't incapacitate the pawn, they will probably want to seek medical attention
                    if (eventTriggered)
                    {
                        NamedArgument pawnName = new NamedArgument(0, pawn.NameShortColored);
                        Messages.Message("QRY_MessageSinkhole".Translate(pawnName), pawn, MessageTypeDefOf.NegativeEvent);
                        DamageInfo dInfo = new DamageInfo(DamageDefOf.Crush, 9, category: DamageInfo.SourceCategory.Collapse);
                        dInfo.SetBodyRegion(BodyPartHeight.Bottom, BodyPartDepth.Inside);
                        pawn.TakeDamage(dInfo);

                        EndJobWith(JobCondition.Succeeded);
                    }
                    else
                    {
                        // Prevent the colonists from trying to haul rubble, which just makes them visit the platform
                        if (def == ThingDefOf.Filth_RubbleRock)
                        {
                            EndJobWith(JobCondition.Succeeded);
                        }
                        else
                        {
                            // If this is a chunk or slag, mark it as haulable if allowed to
                            if (def.designateHaulable && Quarry.autoHaul)
                            {
                                Map.designationManager.AddDesignation(new Designation(haulableResult, DesignationDefOf.Haul));
                            }

                            // Try to find a suitable storage spot for the resource, removing it from the quarry
                            // If there are no platforms with free space, or if the resource is a chunk, try to haul it to a storage area
                            if (Quarry.autoHaul)
                            {
                                if (!def.thingCategories.Contains(QuarryDefOf.StoneChunks) && Quarry.HasConnectedPlatform && Quarry.TryFindBestPlatformCell(haulableResult, pawn, Map, pawn.Faction, out IntVec3 c))
                                {
                                    job.SetTarget(TargetIndex.B, haulableResult);
                                    job.count = haulableResult.stackCount;
                                    job.SetTarget(TargetIndex.C, c);
                                }
                                else
                                {
                                    StoragePriority currentPriority = StoreUtility.CurrentStoragePriorityOf(haulableResult);
                                    Job result;
                                    if (!StoreUtility.TryFindBestBetterStorageFor(haulableResult, pawn, Map, currentPriority, pawn.Faction, out c, out IHaulDestination haulDestination, true))
                                    {
                                        JobFailReason.Is("NoEmptyPlaceLower".Translate(), null);
                                    }
                                    else if (haulDestination is ISlotGroupParent)
                                    {
                                        result = HaulAIUtility.HaulToCellStorageJob(pawn, haulableResult, c, false);
                                    }
                                    else
                                    {
                                        job.SetTarget(TargetIndex.B, haulableResult);
                                        job.count = haulableResult.stackCount;
                                        job.SetTarget(TargetIndex.C, c);
                                    }
                                }
                            }
Beispiel #22
0
        public static bool TryFindBestBetterStoreCellFor(Thing t, Pawn carrier, Map map, StoragePriority currentPriority, Faction faction, out IntVec3 foundCell, bool needAccurateResult = true)
        {
            List <SlotGroup> allGroupsListInPriorityOrder = map.haulDestinationManager.AllGroupsListInPriorityOrder;

            if (allGroupsListInPriorityOrder.Count == 0)
            {
                foundCell = IntVec3.Invalid;
                return(false);
            }
            StoragePriority storagePriority = currentPriority;
            float           num             = 2.14748365E+09f;
            IntVec3         invalid         = IntVec3.Invalid;
            int             count           = allGroupsListInPriorityOrder.Count;

            for (int i = 0; i < count; i++)
            {
                SlotGroup       slotGroup = allGroupsListInPriorityOrder[i];
                StoragePriority priority  = slotGroup.Settings.Priority;
                if (priority < storagePriority || priority <= currentPriority)
                {
                    break;
                }
                StoreUtility.TryFindBestBetterStoreCellForWorker(t, carrier, map, faction, slotGroup, needAccurateResult, ref invalid, ref num, ref storagePriority);
            }
            if (!invalid.IsValid)
            {
                foundCell = IntVec3.Invalid;
                return(false);
            }
            foundCell = invalid;
            return(true);
        }
Beispiel #23
0
        public static Job HopperFillFoodJob(Pawn pawn, ISlotGroupParent hopperSgp)
        {
            Building building = hopperSgp as Building;

            if (!pawn.CanReserveAndReach(building.Position, PathEndMode.Touch, pawn.NormalMaxDanger(), 1))
            {
                return(null);
            }
            ThingDef thingDef  = null;
            Thing    firstItem = building.Position.GetFirstItem(pawn.MapHeld);

            if (firstItem != null)
            {
                if (Building_AquacultureBasin.IsAcceptableFeedstock(firstItem.def))
                {
                    thingDef = firstItem.def;
                }
                else
                {
                    if (firstItem.IsForbidden(pawn))
                    {
                        return(null);
                    }
                    return(HaulAIUtility.HaulAsideJobFor(pawn, firstItem));
                }
            }
            List <Thing> list;

            if (thingDef == null)
            {
                list = pawn.MapHeld.listerThings.ThingsInGroup(ThingRequestGroup.FoodSourceNotPlantOrTree);
            }
            else
            {
                list = pawn.MapHeld.listerThings.ThingsOfDef(thingDef);
            }
            for (int i = 0; i < list.Count; i++)
            {
                Thing thing = list[i];
                if (thing.def.IsNutritionGivingIngestible)
                {
                    if (thing.def.ingestible.preferability == FoodPreferability.RawBad || thing.def.ingestible.preferability == FoodPreferability.RawTasty)
                    {
                        if (HaulAIUtility.PawnCanAutomaticallyHaul(pawn, thing))
                        {
                            if (pawn.MapHeld.slotGroupManager.SlotGroupAt(building.Position).Settings.AllowedToAccept(thing))
                            {
                                StoragePriority storagePriority = HaulAIUtility.StoragePriorityAtFor(thing.Position, thing);
                                if (storagePriority < hopperSgp.GetSlotGroup().Settings.Priority)
                                {
                                    Job job = HaulAIUtility.HaulMaxNumToCellJob(pawn, thing, building.Position, true);
                                    if (job != null)
                                    {
                                        return(job);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(null);
        }
Beispiel #24
0
        public static bool TryFindBestBetterStoreCellForIn(Thing t, Pawn carrier, Map map, StoragePriority currentPriority, Faction faction, SlotGroup slotGroup, out IntVec3 foundCell, bool needAccurateResult = true)
        {
            foundCell = IntVec3.Invalid;
            float num = 2.14748365E+09f;

            StoreUtility.TryFindBestBetterStoreCellForWorker(t, carrier, map, faction, slotGroup, needAccurateResult, ref foundCell, ref num, ref currentPriority);
            return(foundCell.IsValid);
        }
Beispiel #25
0
        public static Job HaulWithTools(Pawn pawn, Map map, Thing haulThing = null)
        {
            Trace.stopWatchStart();

            // Job Setting
            bool                useBackpack = false;
            JobDef              jobDef      = null;
            LocalTargetInfo     targetC;
            int                 maxItem;
            int                 thresholdItem;
            int                 reservedMaxItem;
            IEnumerable <Thing> remainingItems;
            bool                shouldDrop;
            //       Thing lastItem = TryGetBackpackLastItem(pawn);
            Apparel_Backpack backpack = TryGetBackpack(pawn);
            //  if (cart == null)
            {
                jobDef  = HaulJobDefOf.HaulWithBackpack;
                targetC = backpack;
                maxItem = backpack.MaxItem;

                // thresholdItem = (int)Math.Ceiling(maxItem * 0.5);
                thresholdItem   = 2;
                reservedMaxItem = backpack.SlotsComp.slots.Count;
                remainingItems  = backpack.SlotsComp.slots;
                shouldDrop      = false;
                useBackpack     = true;
                //       if (lastItem != null)
                //     {
                //         for (int i = 0; i < backpack.slotsComp.slots.Count; i++)
                //         {
                //             if (backpack.slotsComp.slots[i] == lastItem && reservedMaxItem - (i + 1) <= 0)
                //             {
                //                 shouldDrop = false;
                //                 break;
                //             }
                //         }
                //     }
            }


            Job job = new Job(jobDef)
            {
                targetQueueA = new List <LocalTargetInfo>(),
                targetQueueB = new List <LocalTargetInfo>(),
                targetC      = targetC
            };

            if (useBackpack)
            {
                job.countQueue = new List <int>();
            }

            Trace.AppendLine(
                pawn.LabelCap + " In HaulWithTools: " + jobDef.defName + "\n" + "MaxItem: " + maxItem
                + " reservedMaxItem: " + reservedMaxItem);

            // Drop remaining item
            if (shouldDrop)
            {
                Trace.AppendLine("Start Drop remaining item");
                //    bool startDrop = false;
                for (int i = 0; i < remainingItems.Count(); i++)
                {
                    /* if (useBackpack && startDrop == false)
                     * {
                     *   if (remainingItems.ElementAt(i) == lastItem)
                     *   {
                     *       startDrop = true;
                     *   }
                     *   else
                     *   {
                     *       continue;
                     *   }
                     * }
                     */
                    Thing           thing = remainingItems.ElementAt(i);
                    IntVec3         storageCell; //= FindStorageCell(pawn, remainingItems.ElementAt(i), map, job.targetQueueB);
                    StoragePriority currentPriority = HaulAIUtility.StoragePriorityAtFor(thing.Position, thing);
                    if (StoreUtility.TryFindBestBetterStoreCellFor(thing, pawn, pawn.Map, currentPriority, pawn.Faction, out storageCell))
                    {
                        job.targetQueueB.Add(storageCell);
                        break;
                    }
                }

                if (!job.targetQueueB.NullOrEmpty())
                {
                    Trace.AppendLine("Dropping Job is issued");
                    Trace.LogMessage();
                    return(job);
                }

                JobFailReason.Is(NoEmptyPlaceLowerTrans);
                Trace.AppendLine("End Drop remaining item");
                Trace.AppendLine("No Job. Reason: " + JobFailReason.Reason);
                Trace.LogMessage();
                return(null);
            }

            // Collect item
            Trace.AppendLine("Start Collect item");
            IntVec3 searchPos;

            if (haulThing != null)
            {
                searchPos = haulThing.Position;
            }
            else
            {
                searchPos = pawn.Position;
            }

            foreach (SlotGroup slotGroup in map.slotGroupManager.AllGroupsListInPriorityOrder)
            {
                Trace.AppendLine("Start searching slotGroup");
                if (slotGroup.CellsList.Count - slotGroup.HeldThings.Count() < maxItem)
                {
                    continue;
                }

                // Counting valid items
                Trace.AppendLine("Start Counting valid items");
                int thingsCount =
                    map.listerHaulables.ThingsPotentiallyNeedingHauling()
                    .Count(item => slotGroup.Settings.AllowedToAccept(item));

                // Finding valid items
                Trace.AppendLine("Start Finding valid items");

                //ToDo TEST if this works without that line
                if (thingsCount > thresholdItem)
                {
                    Thing thing;
                    if (haulThing == null)
                    {
                        // ClosestThing_Global_Reachable Configuration
                        Predicate <Thing> predicate =
                            item =>
                            !job.targetQueueA.Contains(item) && !item.IsBurning() && !item.IsInAnyStorage() &&
                            (item.def.thingCategories.Exists(
                                 category =>
                                 backpack.SlotsComp.Properties.allowedThingCategoryDefs.Exists(
                                     subCategory =>
                                     subCategory.ThisAndChildCategoryDefs.Contains(category)) &&
                                 !backpack.SlotsComp.Properties.forbiddenSubThingCategoryDefs.Exists(
                                     subCategory =>
                                     subCategory.ThisAndChildCategoryDefs.Contains(category)))) &&
                            slotGroup.Settings.AllowedToAccept(item) &&
                            HaulAIUtility.PawnCanAutomaticallyHaul(pawn, item, true);

                        // && !(item is UnfinishedThing && ((UnfinishedThing)item).BoundBill != null)
                        // && (item.def.IsNutritionSource && !SocialProperness.IsSociallyProper(item, pawn, false, false));
                        thing = GenClosest.ClosestThing_Global_Reachable(
                            searchPos,
                            map,
                            map.listerHaulables.ThingsPotentiallyNeedingHauling(),
                            PathEndMode.ClosestTouch,
                            TraverseParms.For(pawn, pawn.NormalMaxDanger()),
                            9999,
                            predicate);
                        if (thing == null)
                        {
                            continue;
                        }
                    }
                    else
                    {
                        thing = haulThing;
                    }

                    // Find StorageCell
                    IntVec3 storageCell = FindStorageCell(pawn, thing, map, job.targetQueueB);
                    if (storageCell == IntVec3.Invalid)
                    {
                        break;
                    }

                    // Add Queue & Reserve
                    job.targetQueueA.Add(thing);

                    // for backpacks
                    if (useBackpack)
                    {
                        job.countQueue.Add(thing.def.stackLimit);
                    }

                    job.targetQueueB.Add(storageCell);

                    IntVec3 center = thing.Position;

                    // Enqueue SAME items in valid distance
                    Trace.AppendLine("Start Enqueuing SAME items in valid distance");
                    foreach (Thing item in
                             map.listerHaulables.ThingsPotentiallyNeedingHauling()
                             .Where(
                                 item =>
                                 !job.targetQueueA.Contains(item) && !item.IsBurning() && !item.IsInAnyStorage() &&
                                 (item.def.thingCategories.Exists(
                                      category =>
                                      backpack.SlotsComp.Properties.allowedThingCategoryDefs.Exists(
                                          subCategory =>
                                          subCategory.ThisAndChildCategoryDefs.Contains(category)) &&
                                      !backpack.SlotsComp.Properties.forbiddenSubThingCategoryDefs
                                      .Exists(
                                          subCategory =>
                                          subCategory.ThisAndChildCategoryDefs.Contains(
                                              category)))

                                  && slotGroup.Settings.AllowedToAccept(item) &&
                                  HaulAIUtility.PawnCanAutomaticallyHaul(pawn, item, true) &&
                                  center.DistanceToSquared(item.Position) <= ValidDistance)))
                    {
                        job.targetQueueA.Add(item);
                        if (useBackpack)
                        {
                            job.countQueue.Add(item.def.stackLimit);
                        }

                        reservedMaxItem++;

                        if (reservedMaxItem + job.targetQueueA.Count >= maxItem)
                        {
                            break;
                        }
                    }

                    // Find storage cell
                    Trace.AppendLine("Start Finding storage cell");
                    if (reservedMaxItem + job.targetQueueA.Count >= thresholdItem)
                    {
                        StoragePriority currentPriority = HaulAIUtility.StoragePriorityAtFor(thing.Position, thing);
                        IntVec3         storeCell;
                        if (
                            StoreUtility.TryFindBestBetterStoreCellFor(
                                thing,
                                pawn,
                                pawn.Map,
                                currentPriority,
                                pawn.Faction,
                                out storeCell))
                        {
                            job.targetQueueB.Add(storeCell);
                            if (job.targetQueueB.Count >= job.targetQueueA.Count)
                            {
                                break;
                            }
                        }
                    }

                    job.targetQueueA.Clear();
                }
            }

            Trace.AppendLine("Elapsed Time");
            Trace.stopWatchStop();

            // Check job is valid
            if (!job.targetQueueA.NullOrEmpty() && reservedMaxItem + job.targetQueueA.Count > thresholdItem &&
                !job.targetQueueB.NullOrEmpty())
            {
                Trace.AppendLine("Hauling Job is issued");
                Trace.LogMessage();
                return(job);
            }

            if (job.targetQueueA.NullOrEmpty())
            {
                JobFailReason.Is("NoHaulable".Translate());
            }
            else if (reservedMaxItem + job.targetQueueA.Count <= thresholdItem)
            {
                JobFailReason.Is(TooLittleHaulable);
            }
            else if (job.targetQueueB.NullOrEmpty())
            {
                JobFailReason.Is(NoEmptyPlaceLowerTrans);
            }
            Trace.AppendLine("No Job. Reason: " + JobFailReason.Reason);
            Trace.LogMessage();
            return(null);
        }
Beispiel #26
0
        private static void TryFindBestBetterStoreCellForWorker(Thing t, Pawn carrier, Map map, Faction faction, SlotGroup slotGroup, bool needAccurateResult, ref IntVec3 closestSlot, ref float closestDistSquared, ref StoragePriority foundPriority)
        {
            if (!slotGroup.parent.Accepts(t))
            {
                return;
            }
            IntVec3        a         = (!t.SpawnedOrAnyParentSpawned) ? carrier.PositionHeld : t.PositionHeld;
            List <IntVec3> cellsList = slotGroup.CellsList;
            int            count     = cellsList.Count;
            int            num;

            if (needAccurateResult)
            {
                num = Mathf.FloorToInt((float)count * Rand.Range(0.005f, 0.018f));
            }
            else
            {
                num = 0;
            }
            for (int i = 0; i < count; i++)
            {
                IntVec3 intVec = cellsList[i];
                float   num2   = (float)(a - intVec).LengthHorizontalSquared;
                if (num2 <= closestDistSquared)
                {
                    if (StoreUtility.IsGoodStoreCell(intVec, map, t, carrier, faction))
                    {
                        closestSlot        = intVec;
                        closestDistSquared = num2;
                        foundPriority      = slotGroup.Settings.Priority;
                        if (i >= num)
                        {
                            break;
                        }
                    }
                }
            }
        }
Beispiel #27
0
        public static void FillTab(ITab_Storage tab)
        {
            IStoreSettingsParent storeSettingsParent = (IStoreSettingsParent)ITab_Storage_Detour.SelStoreSettingsParent.GetValue(tab, null);

            Debug.Log(storeSettingsParent);
            StorageSettings settings = storeSettingsParent.GetStoreSettings();
            Rect            position = new Rect(0f, 0f, ITab_Storage_Detour.WinSize.x, ITab_Storage_Detour.WinSize.y).ContractedBy(10f);

            GUI.BeginGroup(position);
            Text.Font = GameFont.Small;
            Rect rect = new Rect(0f, 0f, 160f, 29f);

            if (Widgets.ButtonText(rect, "Priority".Translate() + ": " + settings.Priority.Label(), true, false, true))
            {
                List <FloatMenuOption> list = new List <FloatMenuOption>();
                foreach (object current in Enum.GetValues(typeof(StoragePriority)))
                {
                    if ((StoragePriority)current > StoragePriority.Unstored)
                    {
                        StoragePriority localPr = (StoragePriority)current;
                        list.Add(new FloatMenuOption(localPr.Label().CapitalizeFirst(), delegate
                        {
                            settings.Priority = localPr;
                        }, MenuOptionPriority.Default, null, null, 0f, null, null));
                    }
                }
                Find.WindowStack.Add(new FloatMenu(list));
            }
            bool   arg_2B9_0 = Widgets.ButtonImage(new Rect(position.width - 33f, 7.5f, 14f, 14f), Widgets.CheckboxOffTex);
            Rect   arg_204_0 = new Rect(165f, 0f, position.width - 160f - 20f, 29f);
            string text      = (ITab_Storage_Detour.searchText != string.Empty || ITab_Storage_Detour.isFocused) ? ITab_Storage_Detour.searchText : "SearchLabel".Translate();
            bool   flag      = Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape;
            bool   flag2     = !Mouse.IsOver(arg_204_0) && Event.current.type == EventType.MouseDown;

            if (!ITab_Storage_Detour.isFocused)
            {
                GUI.color = new Color(1f, 1f, 1f, 0.6f);
            }
            GUI.SetNextControlName("StorageSearchInput");
            string text2 = Widgets.TextField(arg_204_0, text);

            GUI.color = Color.white;
            if (ITab_Storage_Detour.isFocused)
            {
                ITab_Storage_Detour.searchText = text2;
            }
            if ((GUI.GetNameOfFocusedControl() == "StorageSearchInput" || ITab_Storage_Detour.isFocused) && (flag | flag2))
            {
                GUIUtility.keyboardControl    = 0;
                ITab_Storage_Detour.isFocused = false;
            }
            else if (GUI.GetNameOfFocusedControl() == "StorageSearchInput" && !ITab_Storage_Detour.isFocused)
            {
                ITab_Storage_Detour.isFocused = true;
            }
            if (arg_2B9_0)
            {
                ITab_Storage_Detour.searchText = string.Empty;
            }
            UIHighlighter.HighlightOpportunity(rect, "StoragePriority");
            ThingFilter parentFilter = null;

            if (storeSettingsParent.GetParentStoreSettings() != null)
            {
                parentFilter = storeSettingsParent.GetParentStoreSettings().filter;
            }
            Rect    arg_334_0 = new Rect(0f, 35f, position.width, position.height - 70f);
            Vector2 vector    = (Vector2)ITab_Storage_Detour.ScrollPosition.GetValue(tab);

            HelperThingFilterUI.DoThingFilterConfigWindow(arg_334_0, ref vector, settings.filter, parentFilter, 8, null, null, ITab_Storage_Detour.searchText);
            ITab_Storage_Detour.ScrollPosition.SetValue(tab, vector);
            Rect rect2 = new Rect(0f, position.height - 30f, position.width, 30f);
            StorageSettings_Hysteresis storageSettings_Hysteresis = StorageSettings_Mapping.Get(settings);

            if (storageSettings_Hysteresis == null)
            {
                storageSettings_Hysteresis = new StorageSettings_Hysteresis();
            }
            storageSettings_Hysteresis.FillPercent = Widgets.HorizontalSlider(rect2.LeftPart(0.8f), storageSettings_Hysteresis.FillPercent, 0f, 100f, false, "Refill cells less then", null, null, -1f);
            Widgets.Label(rect2.RightPart(0.2f), storageSettings_Hysteresis.FillPercent.ToString("N0") + "%");
            StorageSettings_Mapping.Set(settings, storageSettings_Hysteresis);
            PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.StorageTab, KnowledgeAmount.FrameDisplayed);
            GUI.EndGroup();
        }
Beispiel #28
0
        public static bool TryFindBestBetterNonSlotGroupStorageFor(Thing t, Pawn carrier, Map map, StoragePriority currentPriority, Faction faction, out IHaulDestination haulDestination)
        {
            List <IHaulDestination> allHaulDestinationsListInPriorityOrder = map.haulDestinationManager.AllHaulDestinationsListInPriorityOrder;
            IntVec3         intVec          = (!t.SpawnedOrAnyParentSpawned) ? carrier.PositionHeld : t.PositionHeld;
            float           num             = 3.40282347E+38f;
            StoragePriority storagePriority = StoragePriority.Unstored;

            haulDestination = null;
            for (int i = 0; i < allHaulDestinationsListInPriorityOrder.Count; i++)
            {
                if (!(allHaulDestinationsListInPriorityOrder[i] is ISlotGroupParent))
                {
                    StoragePriority priority = allHaulDestinationsListInPriorityOrder[i].GetStoreSettings().Priority;
                    if (priority < storagePriority || priority <= currentPriority)
                    {
                        break;
                    }
                    float num2 = (float)intVec.DistanceToSquared(allHaulDestinationsListInPriorityOrder[i].Position);
                    if (num2 <= num)
                    {
                        if (allHaulDestinationsListInPriorityOrder[i].Accepts(t))
                        {
                            Thing thing = allHaulDestinationsListInPriorityOrder[i] as Thing;
                            if (thing == null || thing.Faction == faction)
                            {
                                if (thing != null)
                                {
                                    if (carrier != null)
                                    {
                                        if (thing.IsForbidden(carrier))
                                        {
                                            goto IL_1F3;
                                        }
                                    }
                                    else if (faction != null && thing.IsForbidden(faction))
                                    {
                                        goto IL_1F3;
                                    }
                                }
                                if (thing != null)
                                {
                                    if (carrier != null)
                                    {
                                        if (!carrier.CanReserveNew(thing))
                                        {
                                            goto IL_1F3;
                                        }
                                    }
                                    else if (faction != null && map.reservationManager.IsReservedByAnyoneOf(thing, faction))
                                    {
                                        goto IL_1F3;
                                    }
                                }
                                if (carrier != null)
                                {
                                    if (thing != null)
                                    {
                                        if (!carrier.Map.reachability.CanReach(intVec, thing, PathEndMode.ClosestTouch, TraverseParms.For(carrier, Danger.Deadly, TraverseMode.ByPawn, false)))
                                        {
                                            goto IL_1F3;
                                        }
                                    }
                                    else if (!carrier.Map.reachability.CanReach(intVec, allHaulDestinationsListInPriorityOrder[i].Position, PathEndMode.ClosestTouch, TraverseParms.For(carrier, Danger.Deadly, TraverseMode.ByPawn, false)))
                                    {
                                        goto IL_1F3;
                                    }
                                }
                                num             = num2;
                                storagePriority = priority;
                                haulDestination = allHaulDestinationsListInPriorityOrder[i];
                            }
                        }
                    }
                }
                IL_1F3 :;
            }
            return(haulDestination != null);
        }
Beispiel #29
0
        public static bool TryFindBetterStoreCellInRange(Thing t, Pawn carrier, Map map, int range, StoragePriority currentPriority, Faction faction, out IntVec3 foundCell, bool needAccurateResult = true)
        {
            List <SlotGroup> allGroupsListInPriorityOrder = map.haulDestinationManager.AllGroupsListInPriorityOrder;

            if (allGroupsListInPriorityOrder.Count == 0)
            {
                foundCell = IntVec3.Invalid;
                return(false);
            }
            IntVec3         a = (t.MapHeld == null) ? carrier.PositionHeld : t.PositionHeld;
            StoragePriority storagePriority = currentPriority;
            float           num             = Mathf.Pow(range, 2);
            IntVec3         intVec          = default(IntVec3);
            bool            flag            = false;
            int             count           = allGroupsListInPriorityOrder.Count;

            for (int i = 0; i < count; i++)
            {
                SlotGroup       slotGroup = allGroupsListInPriorityOrder[i];
                StoragePriority priority  = slotGroup.Settings.Priority;
                if (priority < storagePriority || priority <= currentPriority)
                {
                    break;
                }
                if (slotGroup.Settings.AllowedToAccept(t))
                {
                    List <IntVec3> cellsList = slotGroup.CellsList;
                    int            count2    = cellsList.Count;
                    int            num2;
                    if (needAccurateResult)
                    {
                        num2 = Mathf.FloorToInt(count2 * Rand.Range(0.005f, 0.018f));
                    }
                    else
                    {
                        num2 = 0;
                    }
                    for (int j = 0; j < count2; j++)
                    {
                        IntVec3 intVec2 = cellsList[j];
                        float   lengthHorizontalSquared = (a - intVec2).LengthHorizontalSquared;
                        if (lengthHorizontalSquared <= num)
                        {
                            if (StoreUtility.IsGoodStoreCell(intVec2, map, t, carrier, faction))
                            {
                                flag            = true;
                                intVec          = intVec2;
                                num             = lengthHorizontalSquared;
                                storagePriority = priority;
                                if (j >= num2)
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            if (!flag)
            {
                foundCell = IntVec3.Invalid;
                return(false);
            }
            foundCell = intVec;
            return(true);
        }
        protected override IEnumerable <Toil> MakeNewToils()
        {
            CompUniversalFermenter comp = Fermenter.TryGetComp <CompUniversalFermenter>();

            // Verify fermenter validity
            this.FailOn(() => !comp.Fermented);
            this.FailOnDestroyedNullOrForbidden(FermenterInd);

            // Reserve fermenter
            yield return(Toils_Reserve.Reserve(FermenterInd));

            // Go to the fermenter
            yield return(Toils_Goto.GotoThing(FermenterInd, PathEndMode.ClosestTouch));

            // Add delay for collecting product from fermenter, if it is ready
            yield return(Toils_General.Wait(Duration).FailOnDestroyedNullOrForbidden(FermenterInd).WithProgressBarToilDelay(FermenterInd));

            // Collect product
            Toil collect = new Toil();

            collect.initAction = () =>
            {
                Thing product = comp.TakeOutProduct();
                GenPlace.TryPlaceThing(product, pawn.Position, Map, ThingPlaceMode.Near);
                StoragePriority storagePriority = StoreUtility.CurrentStoragePriorityOf(product);
                IntVec3         c;

                // Try to find a suitable storage spot for the product
                if (StoreUtility.TryFindBestBetterStoreCellFor(product, pawn, Map, storagePriority, pawn.Faction, out c))
                {
                    this.job.SetTarget(TargetIndex.B, product);
                    this.job.count = product.stackCount;
                    this.job.SetTarget(TargetIndex.C, c);
                }
                // If there is no spot to store the product, end this job
                else
                {
                    EndJobWith(JobCondition.Incompletable);
                }
            };
            collect.defaultCompleteMode = ToilCompleteMode.Instant;
            yield return(collect);

            // Reserve the product
            yield return(Toils_Reserve.Reserve(ProductToHaulInd));

            // Reserve the storage cell
            yield return(Toils_Reserve.Reserve(StorageCellInd));

            // Go to the product
            yield return(Toils_Goto.GotoThing(ProductToHaulInd, PathEndMode.ClosestTouch));

            // Pick up the product
            yield return(Toils_Haul.StartCarryThing(ProductToHaulInd));

            // Carry the product to the storage cell, then place it down
            Toil carry = Toils_Haul.CarryHauledThingToCell(StorageCellInd);

            yield return(carry);

            yield return(Toils_Haul.PlaceHauledThingInCell(StorageCellInd, carry, true));

            // End the current job
            yield break;
        }