public static List<Def> GetResearchRequirements( this RecipeDef recipeDef )
        {
            var researchDefs = new List< Def >();

            if( recipeDef.researchPrerequisite != null )
            {
                // Basic requirement
                researchDefs.Add( recipeDef.researchPrerequisite );

                // Advanced requirement
                var advancedResearchDefs = ResearchController.AdvancedResearch.Where( a => (
                    ( a.IsRecipeToggle )&&
                    ( !a.HideDefs )&&
                    ( a.recipeDefs.Contains( recipeDef ) )
                ) ).ToList();

                if( !advancedResearchDefs.NullOrEmpty() )
                {
                    foreach( var a in advancedResearchDefs )
                    {
                        researchDefs.Add( a );
                    }
                }

            }

            // Get list of things recipe is used on
            var thingsOn = new List< ThingDef >();
            var recipeThings = DefDatabase< ThingDef >.AllDefsListForReading.Where( t => (
                ( t.recipes != null )&&
                ( !t.IsLockedOut() )&&
                ( t.recipes.Contains( recipeDef ) )
            ) ).ToList();

            if( !recipeThings.NullOrEmpty() )
            {
                thingsOn.AddRange( recipeThings );
            }

            // Add those linked via the recipe
            if( !recipeDef.recipeUsers.NullOrEmpty() )
            {
                thingsOn.AddRange( recipeDef.recipeUsers );
            }

            // Make sure they all have hard requirements
            if(
                ( !thingsOn.NullOrEmpty() )&&
                ( thingsOn.All( t => t.HasResearchRequirement() ) )
            )
            {
                foreach( var t in thingsOn )
                {
                    researchDefs.AddRange( t.GetResearchRequirements() );
                }
            }

            // Return the list of research required
            return researchDefs;
        }
Example #2
0
 static Monitor()
 {
     hostilesInRooms = new List<Room>();
     laws = DefDatabase<LawDef>.AllDefsListForReading;
     if( !laws.NullOrEmpty() )
     {
         foreach( var law in laws )
         {
             if( law.lawWorker == null )
             {
                 law.lawWorker = (LawDriver) Activator.CreateInstance( law.lawDriver, new Object[] { law } );
             }
         }
     }
 }
 internal static List<Building_RoomMarker> ContainedMarkers( this Room room, List<Thing> checkList = null )
 {
     if( checkList == null )
     {
         checkList = room.AllContainedThings;
     }
     if( checkList.NullOrEmpty() )
     {
         return null;
     }
     var allContainedMarkers = new List<Building_RoomMarker>();
     foreach( var thing in checkList )
     {
         if( thing is Building_RoomMarker )
         {
             allContainedMarkers.Add( (Building_RoomMarker)thing );
         }
     }
     return allContainedMarkers;
 }
        public override void Init(GraphicRequest req)
        {
            this.data = req.graphicData;
            if (req.path.NullOrEmpty())
            {
                throw new ArgumentNullException("folderPath");
            }
            if (req.shader == null)
            {
                throw new ArgumentNullException("shader");
            }
            this.path     = req.path;
            this.color    = req.color;
            this.colorTwo = req.colorTwo;
            this.drawSize = req.drawSize;
            List <Texture2D> list = (from x in ContentFinder <Texture2D> .GetAllInFolder(req.path)
                                     where !x.name.EndsWith(Graphic_Single.MaskSuffix)
                                     orderby x.name
                                     select x).ToList <Texture2D>();

            if (list.NullOrEmpty <Texture2D>())
            {
                Log.Error("Collection cannot init: No textures found at path " + req.path, false);
                this.subGraphics = new Graphic[]
                {
                    BaseContent.BadGraphic
                };
                return;
            }
            this.subGraphics = new Graphic[list.Count];
            for (int i = 0; i < list.Count; i++)
            {
                string path = req.path + "/" + list[i].name;
                this.subGraphics[i] = GraphicDatabase.Get(typeof(Graphic_Single), path, req.shader, this.drawSize, this.color, this.colorTwo, null, req.shaderParameters);
            }
        }
        public void FriendlyTouched(Pawn p)
        {
            if (crossingPawns.NullOrEmpty())
            {
                crossingPawns = new List <Pawn>();
            }
            if (!crossingPawns.Contains(p))
            {
                crossingPawns.Add(p);
            }
            this.friendlyTouchTicksFactor = 1.0f;
            if (p.CurJob != null)
            {
                switch (p.CurJob.locomotionUrgency)
                {
                case LocomotionUrgency.None:
                case LocomotionUrgency.Amble:
                    friendlyTouchTicksFactor += 1.5f;
                    break;

                case LocomotionUrgency.Walk:
                    friendlyTouchTicksFactor += 0.75f;
                    break;

                case LocomotionUrgency.Jog:
                case LocomotionUrgency.Sprint:
                    break;
                }
            }
            if (p.health.capacities.GetLevel(PawnCapacityDefOf.Moving) is float val && val < 1f)
            {
                //Log.Message("Moving capacity is: " + val);
                friendlyTouchTicksFactor += 1f - val;
            }
            this.lastFriendlyTouchTick = Find.TickManager.TicksGame;
        }
 public static void AvailableNowPostfix(RecipeDef __instance, ref bool __result)
 {
     if (__result)
     {
         if (__instance != null)
         {
             if (__instance.ProducedThingDef != null)
             {
                 if (__instance.ProducedThingDef.comps != null)
                 {
                     if (__instance.ProducedThingDef.GetCompProperties <CompProperties_ExtraPrerequisite>() != null)
                     {
                         if (__instance.ProducedThingDef.GetCompProperties <CompProperties_ExtraPrerequisite>() is CompProperties_ExtraPrerequisite ExtraPrerequisites)
                         {
                             if (!ExtraPrerequisites.ExtraResarchPrerequisites.NullOrEmpty())
                             {
                                 List <ResearchProjectDef> extras = ExtraResarchPrerequisites(ExtraPrerequisites);
                                 if (!extras.NullOrEmpty())
                                 {
                                     foreach (ResearchProjectDef research in extras)
                                     {
                                         __result = research.IsFinished;
                                         if (!__result)
                                         {
                                             break;
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
 }
        public async Task <long> GerarNotaFiscalDevolucao(long codigoIntegracao, List <ElementoItemDetalhes> itensDevolucao)
        {
            string codTipOper = ConfigurationManager.AppSettings["IntegracaoSankhya_CodigoDevolucaoCompra"];

            if (string.IsNullOrEmpty(codTipOper))
            {
                throw new BusinessException("Não foi possível encontrar a configuração para o campo 'codTipOper'");
            }

            string devolucaoXML;

            if (itensDevolucao.NullOrEmpty())
            {
                devolucaoXML = SerializarXML(new DevolucaoTotalXML(codigoIntegracao, codTipOper));
            }
            else
            {
                devolucaoXML = SerializarXML(new DevolucaoParcialXML(codigoIntegracao, codTipOper, itensDevolucao));
            }

            string rootXML = await Instance.ExecutarServicoSankhya(devolucaoXML, "SelecaoDocumentoSP.faturar", "mgecom");

            DevolucaoRespostaXML resposta = DeserializarXML <DevolucaoRespostaXML>(rootXML);

            if (resposta.CorpoResposta == null || resposta.Status != "1" || resposta.CorpoResposta.Notas?.CodigoIntegracao <= 0)
            {
                var erro = DeserializarXML <IntegracaoErroResposta>(rootXML.ToString());

                byte[] erroData      = Convert.FromBase64String(erro.Mensagem);
                string decodedString = Encoding.UTF8.GetString(erroData);

                throw new BusinessException(string.Format("Ocorreu um erro na chamada do serviço 'SelecaoDocumentoSP.faturar' para criação da Nota Fiscal de Devolução. Mensagem de Erro {0}", decodedString));
            }

            return(Convert.ToInt64(resposta.CorpoResposta.Notas.CodigoIntegracao));
        }
 public override string ExplanationPart(StatRequest req)
 {
     if (req.HasThing)
     {
         CompBladelinkWeapon compBladelinkWeapon = req.Thing.TryGetComp <CompBladelinkWeapon>();
         if (compBladelinkWeapon != null)
         {
             StringBuilder         stringBuilder        = new StringBuilder();
             List <WeaponTraitDef> traitsListForReading = compBladelinkWeapon.TraitsListForReading;
             if (!traitsListForReading.NullOrEmpty())
             {
                 for (int i = 0; i < traitsListForReading.Count; i++)
                 {
                     if (traitsListForReading[i].marketValueOffset != 0f)
                     {
                         stringBuilder.AppendLine(traitsListForReading[i].LabelCap + ": " + traitsListForReading[i].marketValueOffset.ToStringByStyle(ToStringStyle.Money, ToStringNumberSense.Offset));
                     }
                 }
             }
             return(stringBuilder.ToString());
         }
     }
     return(null);
 }
Example #9
0
        public static DamageDef PrimaryMeleeWeaponDamageType(List <Tool> tools)
        {
            DamageDef result;

            if (tools.NullOrEmpty <Tool>())
            {
                result = null;
            }
            else
            {
                Tool tool2 = tools.MaxBy((Tool tool) => tool.power);
                List <ManeuverDef> allDefsListForReading = DefDatabase <ManeuverDef> .AllDefsListForReading;
                for (int i = 0; i < allDefsListForReading.Count; i++)
                {
                    ManeuverDef maneuverDef = allDefsListForReading[i];
                    if (tool2.capacities.Contains(maneuverDef.requiredCapacity))
                    {
                        return(maneuverDef.verb.meleeDamageDef);
                    }
                }
                result = null;
            }
            return(result);
        }
 public bool PartIsCoveredByShield(BodyPartRecord part, Pawn pawn)
 {
     if (!shieldCoverage.NullOrEmpty())
     {
         foreach (BodyPartGroupDef group in shieldCoverage)
         {
             if (part.IsInGroup(group))
             {
                 return(true);
             }
         }
     }
     if (!crouchCoverage.NullOrEmpty() && pawn.IsCrouching())
     {
         foreach (BodyPartGroupDef group in crouchCoverage)
         {
             if (part.IsInGroup(group))
             {
                 return(true);
             }
         }
     }
     return(false);
 }
Example #11
0
        public override void PostExposeData()
        {
            Scribe_Values.Look <bool>(ref this.IsInitialized, "IsInitialized", false);
            Scribe_Deep.Look <AbilityData>(ref this.abilityData, "abilityData", new object[]
            {
                this
            });

            if (Scribe.mode == LoadSaveMode.PostLoadInit)
            {
                List <PawnAbility> tempAbilities = new List <PawnAbility>(this.AbilityData.Powers);
                if (!tempAbilities.NullOrEmpty())
                {
                    foreach (PawnAbility pa in tempAbilities)
                    {
                        if (pa.Def.abilityClass != pa.GetType())
                        {
                            RemovePawnAbility(pa.Def);
                            AddPawnAbility(pa.Def);
                        }
                    }
                }
            }
        }
        private static PawnKindDef determinePawnKind(Map map, Predicate <PawnKindDef> isAnimal, float inBiomeWeightNormalized, float outBiomeWeightNormalized, int rndInt, int pawnHandlingLevel, List <string> factionFarmAnimalRestrictions, List <string> factionWildAnimalRestrictions)
        {
            PawnKindDef pawnKindDef = null;



            if (factionWildAnimalRestrictions.NullOrEmpty() && rndInt <= inBiomeWeightNormalized)
            {
                (from a in map.Biome.AllWildAnimals
                 where map.mapTemperature.SeasonAcceptableFor(a.race) &&
                 IsMountableUtility.isAllowedInModOptions(a.defName)
                 select a).TryRandomElementByWeight((PawnKindDef def) => calculateCommonality(def, map, pawnHandlingLevel), out pawnKindDef);
            }
            else if (rndInt <= inBiomeWeightNormalized + outBiomeWeightNormalized)
            {
                (from a in DefDatabase <PawnKindDef> .AllDefs
                 where isAnimal(a) &&
                 a.wildSpawn_spawnWild &&
                 map.mapTemperature.SeasonAcceptableFor(a.race) &&
                 IsMountableUtility.isAllowedInModOptions(a.defName) &&
                 (factionWildAnimalRestrictions.NullOrEmpty() || factionWildAnimalRestrictions.Contains(a.defName))
                 select a).TryRandomElementByWeight((PawnKindDef def) => calculateCommonality(def, map, pawnHandlingLevel), out pawnKindDef);
            }
            else
            {
                (from a in DefDatabase <PawnKindDef> .AllDefs
                 where isAnimal(a) &&
                 !a.wildSpawn_spawnWild &&
                 map.mapTemperature.SeasonAcceptableFor(a.race) &&
                 IsMountableUtility.isAllowedInModOptions(a.defName) &&
                 (factionFarmAnimalRestrictions.NullOrEmpty() || factionFarmAnimalRestrictions.Contains(a.defName))
                 select a).TryRandomElementByWeight((PawnKindDef def) => 1 - def.RaceProps.wildness, out pawnKindDef);
            }

            return(pawnKindDef);
        }
 private static bool TryScribeObjectsValueInternal <T>(ref List <object> values, string label, Type type)
 {
     if (type == typeof(T) && (values.NullOrEmpty() || values.First().GetType() == typeof(T)))
     {
         List <T> list = default(List <T>);
         if (Scribe.mode == LoadSaveMode.Saving)
         {
             if (values != null)
             {
                 list = values.ConvertAll <T>(v => (T)v);
             }
             else
             {
                 list = null;
             }
         }
         Scribe_Collections.Look <T>(ref list, label, LookMode.Value);
         if (Scribe.mode == LoadSaveMode.LoadingVars)
         {
             values = new List <object>();
             if (list != null)
             {
                 foreach (T x in list)
                 {
                     values.Add(x);
                 }
             }
             else
             {
                 values = null;
             }
         }
         return(true);
     }
     return(false);
 }
Example #14
0
 public virtual bool Calculate(List <StatModifier> stats, List <StuffCategoryDef> stuffCategories, out float value)
 {
     value = 0f;
     if (!stuffCategoryDefs.NullOrEmpty())
     {
         if (!stuffCategoryDefs.Any(t => stuffCategories.Contains(t)))
         {
             return(false);
         }
     }
     if (inputs.Any(t => !stats.StatListContains(t)))
     {
         return(false);
     }
     foreach (var arg in args)
     {
         if (stats.FirstOrFallback(t => t.stat.defName == arg.getArgumentName()) is StatModifier modifier)
         {
             arg.setArgumentValue(modifier.value);
         }
     }
     value = (float)expr.calculate();
     return(true);
 }
        private static Thing CalculateDominantIngredient(Job job, List <Thing> ingredients)
        {
            UnfinishedThing uft = job.GetTarget(TargetIndex.B).Thing as UnfinishedThing;

            if (uft != null && uft.def.MadeFromStuff)
            {
                return(uft.ingredients.First((Thing ing) => ing.def == uft.Stuff));
            }
            if (!ingredients.NullOrEmpty())
            {
                if (job.RecipeDef.productHasIngredientStuff)
                {
                    return(ingredients[0]);
                }
                if (job.RecipeDef.products.Any((ThingCountClass x) => x.thingDef.MadeFromStuff))
                {
                    return((from x in ingredients
                            where x.def.IsStuff
                            select x).RandomElementByWeight((Thing x) => (float)x.stackCount));
                }
                return(ingredients.RandomElementByWeight((Thing x) => (float)x.stackCount));
            }
            return(null);
        }
            internal void <> m__0()
            {
                Pawn actor  = this.toil.actor;
                Job  curJob = actor.jobs.curJob;
                List <LocalTargetInfo> targetQueue = curJob.GetTargetQueue(this.ind);

                if (!targetQueue.NullOrEmpty <LocalTargetInfo>())
                {
                    if (this.failIfCountFromQueueTooBig && !curJob.countQueue.NullOrEmpty <int>() && targetQueue[0].HasThing && curJob.countQueue[0] > targetQueue[0].Thing.stackCount)
                    {
                        actor.jobs.curDriver.EndJobWith(JobCondition.Incompletable);
                    }
                    else
                    {
                        curJob.SetTarget(this.ind, targetQueue[0]);
                        targetQueue.RemoveAt(0);
                        if (!curJob.countQueue.NullOrEmpty <int>())
                        {
                            curJob.count = curJob.countQueue[0];
                            curJob.countQueue.RemoveAt(0);
                        }
                    }
                }
            }
Example #17
0
        public override void ExposeData()
        {
            foreach (PawnTableDef type in DefDatabase <PawnTableDef> .AllDefsListForReading.Where(x => x.HasModExtension <DefModExtension_PawnTableDefs>()))
            {
                switch (Scribe.mode)
                {
                case LoadSaveMode.Saving:
                    if (sessionTable.TryGetValue(type, out List <PawnColumnDef> workList))
                    {
                        Scribe_Collections.Look(ref workList, "Numbers_" + type, LookMode.Def);
                        sessionTable[type] = workList;
                    }
                    break;

                case LoadSaveMode.LoadingVars:
                    Scribe_Collections.Look(ref loadList, "Numbers_" + type, LookMode.Def);
                    if (!loadList.NullOrEmpty())
                    {
                        sessionTable[type] = loadList;
                    }
                    break;
                }
            }
        }
Example #18
0
        protected void AddAvailableAmmoFor(ThingWithComps eq)
        {
            if (eq == null || availableDefs == null)
            {
                return;
            }
            CompAmmoUser compAmmo = eq.TryGetComp <CompAmmoUser>();

            if (compAmmo != null && !compAmmo.Props.ammoSet.ammoTypes.NullOrEmpty())
            {
                List <ThingDef> listammo = (from ThingDef g in compAmmo.Props.ammoSet.ammoTypes
                                            where g.canBeSpawningInventory
                                            select g).ToList <ThingDef>();
                if (!listammo.NullOrEmpty())
                {
                    ThingDef randomammo = GenCollection.RandomElement <ThingDef>(listammo);
                    availableDefs.Add(randomammo);
                }
                else
                {
                    return;
                }
            }
        }
Example #19
0
        public Thing FindShip(Pawn pawn)
        {
            List <ShipBase> allShips = DropShipUtility.ShipsOnMap(pawn.Map).FindAll(x => DropShipUtility.HasPassengerSeats(x));

            if (allShips.NullOrEmpty())
            {
                return(null);
            }
            ShipBase ship = null;

            Log.Message(allShips.Count.ToString());
            return(allShips.RandomElement());
            //if (allShips.TryRandomElementByWeight<ShipBase>((ShipBase x) => 100 / x.Position.DistanceToSquared(pawn.Position), out ship))
            //{
            //    Log.Message("Found");
            //    return ship;
            //}
            //else
            //{

            //    Log.Message("NotFoundShips");
            //    return null;
            //}
        }
Example #20
0
        public List <ThingDef> GetThingsUnlocked()
        {
            if (ResearchConsolidator != this)
            {
                return(ResearchConsolidator.GetThingsUnlocked());
            }

            // Buildings it unlocks
            var thingdefs = new List <ThingDef>();

            // Look at this def
            if (
                (!HideDefs) &&
                (IsBuildingToggle)
                )
            {
                thingdefs.AddRangeUnique(thingDefs);
            }

            // Look in matching research
            if (!MatchingAdvancedResearch.NullOrEmpty())
            {
                foreach (var a in MatchingAdvancedResearch)
                {
                    if (
                        (!a.HideDefs) &&
                        (a.IsBuildingToggle)
                        )
                    {
                        thingdefs.AddRangeUnique(a.thingDefs);
                    }
                }
            }

            return(thingdefs);
        }
 public static bool ThinksTheyCanBeSeenByColony( this Pawn pawn, List<Pawn> colonists, List<Building_RoomMarker> markers )
 {
     if( !colonists.NullOrEmpty() )
     {   // Check colonists
         foreach( var colonist in colonists )
         {
             if(
                 ( pawn != colonist )&&
                 ( Data.LineOfSight( colonist.Position, pawn.Position ) )
             )
             {   // Thinks colonist can see them
                 return true;
             }
         }
     }
     if( !markers.NullOrEmpty() )
     {   // Check for remote observable markers
         foreach( var marker in markers )
         {
             if( Data.LineOfSight( marker.Position, pawn.Position, true ) )
             {   // Thinks marker can see them
                 return true;
             }
         }
     }
     return false;
 }
Example #22
0
        public void OutfitSquad(MilSquadFC outfit)
        {
            FactionFC faction = Find.World.GetComponent <FactionFC>();
            int       count   = 0;

            this.outfit     = outfit;
            UsedWeaponList  = new List <ThingWithComps>();
            UsedApparelList = new List <Apparel>();
            animals         = new List <Mercenary>();
            foreach (MilUnitFC loadout in outfit.units)
            {
                try
                {
                    if (mercenaries[count]?.pawn?.kindDef != loadout.pawnKind || mercenaries[count].pawn.Dead)
                    {
                        Mercenary pawn = new Mercenary(true);
                        createNewPawn(ref pawn, loadout.pawnKind);
                        mercenaries.Replace(mercenaries[count], pawn);
                    }

                    StripPawn(mercenaries[count]);
                    HealPawn(mercenaries[count]);
                    if (loadout != null)
                    {
                        //mercenaries[count];
                        //StripPawn(mercenaries[count]);
                        EquipPawn(mercenaries[count], loadout);
                        if (loadout.animal != null)
                        {
                            Mercenary animal = new Mercenary(true);
                            createNewAnimal(ref animal, loadout.animal);
                            animal.handler            = mercenaries[count];
                            mercenaries[count].animal = animal;
                            animals.Add(animal);
                        }

                        mercenaries[count].loadout    = loadout;
                        mercenaries[count].deployable = mercenaries[count].loadout != faction.militaryCustomizationUtil.blankUnit;
                    }

                    if (mercenaries[count].pawn.equipment.AllEquipmentListForReading != null)
                    {
                        UsedWeaponList.AddRange(mercenaries[count].pawn.equipment.AllEquipmentListForReading);

                        //add single check at start of load and mark variable
                    }

                    if (mercenaries[count].pawn.apparel.WornApparel != null)
                    {
                        UsedApparelList.AddRange(mercenaries[count].pawn.apparel.WornApparel);
                    }
                }
                catch (Exception e)
                {
                    Log.Error("Something went wrong when outfitting a squad: " + e.Message);
                    bool isNullOrEmpty = mercenaries.NullOrEmpty();
                    Log.Error("Mercanaries NullOrEmpty: " + isNullOrEmpty);

                    if (isNullOrEmpty)
                    {
                        Log.Error("Number of Mercs: " + mercenaries.Count);
                        Log.Error("Any mercenary or pawn is null: " + mercenaries.Any(mercenary => mercenary?.pawn == null));
                    }
                }
                count++;
            }

            //debugMercenarySquad();
        }
        protected override bool TryExecuteWorker(IncidentParms parms)
        {
            parms.points *= IncidentPointsFactorRange.RandomInRange;
            Caravan caravan         = (Caravan)parms.target;
            bool    factionCanFight = WorldUtility.FactionCanFight((int)parms.points, parms.faction);
            //if (!PawnGroupMakerUtility.TryGetRandomFactionForCombatPawnGroup(parms.points, out parms.faction))
            //{
            //    return false;
            //}
            List <ThingCount> demands = GenerateDemands(caravan);

            if (demands.NullOrEmpty() && parms.faction.HostileTo(caravan.Faction))
            {
                return(false);
            }
            PawnGroupMakerParms defaultPawnGroupMakerParms = IncidentParmsUtility.GetDefaultPawnGroupMakerParms(PawnGroupKindDefOf.Combat, parms);

            defaultPawnGroupMakerParms.generateFightersOnly            = true;
            defaultPawnGroupMakerParms.dontUseSingleUseRocketLaunchers = true;
            List <Pawn> attackers = PawnGroupMakerUtility.GeneratePawns(defaultPawnGroupMakerParms).ToList();

            if (attackers.Count == 0)
            {
                Log.Error("Caravan demand incident couldn't generate any enemies even though min points have been checked. faction=" + defaultPawnGroupMakerParms.faction + "(" + ((defaultPawnGroupMakerParms.faction != null) ? defaultPawnGroupMakerParms.faction.def.ToString() : "null") + ") parms=" + parms);
                return(false);
            }
            CameraJumper.TryJumpAndSelect(caravan);
            DiaNode   diaNode   = new DiaNode(GenerateMessageText(parms.faction, attackers.Count, demands, caravan));
            DiaOption diaOption = new DiaOption("CaravanDemand_Give".Translate());

            diaOption.action = delegate
            {
                ActionGive(caravan, demands, attackers);
                wo.interactable = false;
            };
            if (!wo.Faction.HostileTo(caravan.Faction))
            {
                string str = "RW_CaravanDemand_GiveDisabled".Translate(wo.GetInspectString());
                diaOption.SetText(str);
                diaOption.Disable("");
            }
            diaOption.resolveTree = true;
            diaNode.options.Add(diaOption);
            string fightString = "CaravanDemand_Fight".Translate();

            if (!wo.Faction.HostileTo(caravan.Faction))
            {
                fightString = "RW_Attack_Verbatum".Translate();
            }
            DiaOption diaOption2 = new DiaOption(fightString);

            diaOption2.action = delegate
            {
                ActionFight(caravan, attackers);
                wo.Destroy();
            };
            diaOption2.resolveTree = true;
            diaNode.options.Add(diaOption2);
            DiaOption diaOption3 = new DiaOption("CaravanMeeting_MoveOn".Translate());

            diaOption3.action = delegate
            {
                ActionMoveOn(caravan, attackers);
            };
            if (wo.Faction.HostileTo(caravan.Faction))
            {
                diaOption3.Disable("CaravanMeeting_MoveOn".Translate());
            }
            diaOption3.resolveTree = true;
            diaNode.options.Add(diaOption3);
            TaggedString taggedString = "CaravanDemandTitle".Translate(parms.faction.Name);

            Find.WindowStack.Add(new Dialog_NodeTreeWithFactionInfo(diaNode, parms.faction, true, false, taggedString));
            Find.Archive.Add(new ArchivedDialog(diaNode.text, taggedString, parms.faction));
            return(true);
        }
Example #24
0
        public bool ElectLeader(List <Pawn> toBeIgnored)
        {
            List <Pawn> toBeIgnoredt = toBeIgnored;
            List <Pawn> pawns        = new List <Pawn>();
            List <Pawn> canBeVoted   = new List <Pawn>();
            List <Pawn> tpawns       = new List <Pawn>();
            List <Pawn> votes        = new List <Pawn>();

            pawns.AddRange(getAllColonists());
            canBeVoted.AddRange(getAllColonists());
            List <Pawn> tpawns2 = new List <Pawn>();

            foreach (Pawn current in canBeVoted)
            {
                Hediff h1 = current.health.hediffSet.GetFirstHediffOfDef(HediffDef.Named("leader1"));
                Hediff h2 = current.health.hediffSet.GetFirstHediffOfDef(HediffDef.Named("leader2"));
                Hediff h3 = current.health.hediffSet.GetFirstHediffOfDef(HediffDef.Named("leader3"));
                Hediff h4 = current.health.hediffSet.GetFirstHediffOfDef(HediffDef.Named("leader4"));
                Hediff h5 = current.health.hediffSet.GetFirstHediffOfDef(HediffDef.Named("leaderExpired"));
                if (h1 != null || h2 != null || h3 != null || h4 != null || h5 != null)
                {
                    tpawns2.Add(current);
                }
                if (current.story.WorkTagIsDisabled(WorkTags.Social))
                {
                    tpawns2.Add(current);
                }
            }
            foreach (Pawn current in tpawns2)
            {
                canBeVoted.Remove(current);
            }
            foreach (Pawn current in toBeIgnored)
            {
                canBeVoted.Remove(current);
            }

            List <Pawn> bestOf        = new List <Pawn>();
            Pawn        bestBotanist  = getBestOf(canBeVoted, getBotanistScore);
            Pawn        bestWarrior   = getBestOf(canBeVoted, getWarriorScore);
            Pawn        bestCarpenter = getBestOf(canBeVoted, getCarpenterScore);
            Pawn        bestScientist = getBestOf(canBeVoted, getScientistScore);


            if (bestBotanist != null)
            {
                bestOf.Add(bestBotanist);
            }
            if (bestWarrior != null)
            {
                bestOf.Add(bestWarrior);
            }
            if (bestCarpenter != null)
            {
                bestOf.Add(bestCarpenter);
            }
            if (bestScientist != null)
            {
                bestOf.Add(bestScientist);
            }


            String targetLeader = null;

            if (bestOf.NullOrEmpty() || canBeVoted.NullOrEmpty())
            {
                Messages.Message("NoColonistAbleLeader".Translate(), MessageSound.Negative);
                return(false);
            }

            foreach (Pawn current in pawns)
            {
                Pawn temp        = current;
                int  lastopinion = 0;
                foreach (Pawn p2 in bestOf)
                {
                    if (p2 != current)
                    {
                        int opinion = current.relations.OpinionOf(p2);
                        if (opinion > lastopinion)
                        {
                            lastopinion = opinion;
                            temp        = p2;
                        }
                    }
                }
                votes.Add(temp);
            }

            Pawn most = (from i in votes
                         group i by i into grp
                         orderby grp.Count() descending
                         select grp.Key).First();

            Pawn pawn = most;

            float maxValue = new float[] { getBotanistScore(most), getWarriorScore(most), getCarpenterScore(most), getScientistScore(most) }.Max();

            /*  if (most == bestBotanist && maxValue == getBotanistScore(most)) targetLeader = "leader1";
            *  if (most == bestWarrior && maxValue == getWarriorScore(most)) targetLeader = "leader2";
            *  if (most == bestCarpenter && maxValue == getCarpenterScore(most)) targetLeader = "leader3";
            *  if (most == bestScientist && maxValue == getScientistScore(most)) targetLeader = "leader4";*/

            if (maxValue == getBotanistScore(most))
            {
                targetLeader = "leader1";
            }
            if (maxValue == getWarriorScore(most))
            {
                targetLeader = "leader2";
            }
            if (maxValue == getCarpenterScore(most))
            {
                targetLeader = "leader3";
            }
            if (maxValue == getScientistScore(most))
            {
                targetLeader = "leader4";
            }

            Hediff hediff = HediffMaker.MakeHediff(HediffDef.Named(targetLeader), pawn, null);
            int    count;

            if (toBeIgnored.Contains(pawn))
            {
                Messages.Message("Something bad happened on the election code. Try adding the leaders manually using dev mode.", MessageSound.Negative);
                return(false);
            }

            foreach (Pawn p in currentLeaders(out count))
            {
                if (p.health.hediffSet.GetFirstHediffOfDef(hediff.def) != null)
                {
                    toBeIgnoredt.Add(pawn);
                    ElectLeader(toBeIgnoredt);
                    return(false);
                }
            }
            doElect(pawn, hediff);



            return(true);
        }
Example #25
0
        protected override void FillTab()
        {
            ThingOwner thingOwner = SelTable.GetDirectlyHeldThings();
            CompInnerContainerItemFilter itemFilterComp = SelTable.GetComp <CompInnerContainerItemFilter>();

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

            GUI.BeginGroup(baseRect); // Entire Window

            // DoEnchantBills();

            // Enchantables
            List <Thing> enchantables = new List <Thing>();

            foreach (Thing thing in thingOwner)
            {
                foreach (ThingCategoryDef thingCategoryDef in thing.def.thingCategories)
                {
                    CompStorableByDesignation storableComp = thing.TryGetComp <CompStorableByDesignation>();
                    if (thingCategoryDef == EnchantableCategoryDef && !storableComp.inUseByBill)
                    {
                        enchantables.Add(thing);
                    }
                }
            }

            Rect enchantablesOuterRect = new Rect(0f, 220f, baseRect.width, 116f);
            Rect enchantablesViewRect  = new Rect(
                enchantablesOuterRect.x,
                0f,
                enchantablesOuterRect.width - 16f,
                enchantables.NullOrEmpty() ? enchantablesOuterRect.height : enchantables.Count * EnchantableThingHeight + (enchantables.Count - 1) * EnchantableVerticalGap);

            Rect enchantablesLabelRect = new Rect(enchantablesOuterRect.x, enchantablesOuterRect.y - 30f, enchantablesOuterRect.width, 30f);

            Text.Font   = GameFont.Medium;
            Text.Anchor = TextAnchor.UpperLeft;
            GUI.color   = Color.yellow;
            Widgets.Label(enchantablesLabelRect, "EnchantableItemsLabel".Translate());
            GUI.color = Color.gray;

            Widgets.BeginScrollView(enchantablesOuterRect, ref enchantablesScrollPosition, enchantablesViewRect, true);
            GUI.BeginGroup(enchantablesViewRect);
            if (enchantables.NullOrEmpty())
            {
                Text.Font   = GameFont.Small;
                Text.Anchor = TextAnchor.UpperCenter;
                GUI.color   = Color.white;
                Widgets.Label(enchantablesViewRect, "EnchantableInstructionsTrans".Translate());
            }
            else
            {
                DoEnchantables(thingOwner, enchantablesViewRect, enchantables);
            }

            GUI.EndGroup(); // enchantablesViewRect
            Widgets.EndScrollView();

            // Soul Gems
            List <Thing> soulGems = new List <Thing>();

            foreach (Thing thing in thingOwner)
            {
                foreach (ThingCategoryDef thingCategoryDef in thing.def.thingCategories)
                {
                    CompStorableByDesignation storableComp = thing.TryGetComp <CompStorableByDesignation>();
                    if (thingCategoryDef == SoulGemCategoryDef && !storableComp.inUseByBill)
                    {
                        soulGems.Add(thing);
                    }
                }
            }

            int  maxPerRow         = (int)(baseRect.width / SoulGemWidth) - 1;
            Rect soulGemsOuterRect = new Rect(0f, 370f, baseRect.width, 94f);
            Rect soulGemsViewRect  = new Rect(
                soulGemsOuterRect.x,
                0f,
                soulGemsOuterRect.width - 16f,
                soulGems.NullOrEmpty() ? soulGemsOuterRect.height : (soulGems.Count / maxPerRow) * SoulGemHeight + (soulGems.Count - 1) * SoulGemVerticalGap);

            Rect soulGemsLabelRect = new Rect(soulGemsOuterRect.x, soulGemsOuterRect.y - 30f, soulGemsOuterRect.width, 30f);

            Text.Font   = GameFont.Medium;
            Text.Anchor = TextAnchor.UpperLeft;
            GUI.color   = Color.yellow;
            Widgets.Label(soulGemsLabelRect, "SoulGemsLabel".Translate());
            GUI.color = Color.gray;

            Widgets.BeginScrollView(soulGemsOuterRect, ref soulGemsScrollPosition, soulGemsViewRect, true);
            GUI.BeginGroup(soulGemsViewRect);
            if (soulGems.NullOrEmpty())
            {
                Text.Font   = GameFont.Small;
                Text.Anchor = TextAnchor.UpperCenter;
                GUI.color   = Color.white;
                Widgets.Label(soulGemsViewRect, "SoulGemsInstructionsTrans".Translate());
            }
            else
            {
                DoSoulGems(thingOwner, soulGemsViewRect, soulGems);
            }

            GUI.EndGroup(); // soulGemsViewRect
            Widgets.EndScrollView();

            GUI.EndGroup(); // baseRect
            Text.Anchor = TextAnchor.UpperLeft;
        }
        public static List<ThingDef_FishSpecies> GetFishSpeciesList()
        {
            if (fishSpeciesList.NullOrEmpty())
            {
                fishSpeciesList = new List<ThingDef_FishSpecies>();

                foreach (ThingDef def in DefDatabase<ThingDef>.AllDefsListForReading)
                {
                    if (def is ThingDef_FishSpecies)
                    {
                        fishSpeciesList.Add(def as ThingDef_FishSpecies);
                    }
                }
                if (fishSpeciesList.NullOrEmpty())
                {
                    Log.Warning("FishIndustry: did not found any fish species.");
                }
                //TODO: debug.
                Log.Message("Number of species = " + fishSpeciesList.Count);
            }

            return fishSpeciesList;
        }
 // hidden in vanilla
 public static List<Thing> ProcessedIngredients(Job job, out Thing dominantIngredient)
 {
     var ingredients = new List<Thing>();
     var uft = job.GetTarget(TargetIndex.B).Thing as UnfinishedThing;
     if (uft != null)
     {
         dominantIngredient = uft.def.MadeFromStuff ? uft.ingredients.First(ing => ing.def == uft.Stuff) : null;
         ingredients = uft.ingredients;
         uft.Destroy();
         job.placedThings = null;
         return ingredients;
     }
     if (job.placedThings != null)
     {
         foreach (var thing in job.placedThings.Select(stack => stack.Split()))
         {
             if (ingredients.Contains(thing))
             {
                 Log.Error("Tried to add ingredient from job placed targets twice: " + thing);
             }
             else
             {
                 ingredients.Add(thing);
                 var strippable = thing as IStrippable;
                 strippable?.Strip();
                 if (job.RecipeDef.UsesUnfinishedThing)
                 {
                     Find.DesignationManager.RemoveAllDesignationsOn(thing);
                     if (thing.Spawned)
                     {
                         thing.DeSpawn();
                     }
                 }
                 else
                 {
                     thing.Destroy();
                 }
             }
         }
     }
     job.placedThings = null;
     dominantIngredient = ingredients.NullOrEmpty() ? null : GetDominantIngredient(job.RecipeDef, ingredients);
     return ingredients;
 }
 protected void GetFacingCell(ref Pawn facingPawn, ref IntVec3 facingCell)
 {
     List<Pawn> nearbyPawns = new List<Pawn>();
     foreach (Pawn colonist in Find.MapPawns.FreeColonists)
     {
         if (colonist == this.pawn)
         {
             continue;
         }
         if (colonist.Position.InHorDistOf(this.pawn.Position, 2f))
         {
             nearbyPawns.Add(colonist);
         }
     }
     if (nearbyPawns.NullOrEmpty())
     {
         facingPawn = null;
         facingCell = this.pawn.Position + new IntVec3(0, 0, 1).RotatedBy(new Rot4(Rand.Range(0, 4)));
     }
     else
     {
         facingPawn = nearbyPawns.RandomElement();
         facingCell = facingPawn.Position;
     }
 }
        public static IntVec3 FindStorageCell(Pawn pawn, Thing haulable, List<TargetInfo> targetQueue = null)
        {
            //Find closest cell in queue.
            if (!targetQueue.NullOrEmpty())
                foreach (TargetInfo target in targetQueue)
                    foreach (IntVec3 adjCell in GenAdjFast.AdjacentCells8Way(target))
                        if (!targetQueue.Contains(adjCell) && adjCell.IsValidStorageFor(haulable) && pawn.CanReserve(adjCell))
                            return adjCell;
            /*
            StoragePriority currentPriority = HaulAIUtility.StoragePriorityAtFor(closestHaulable.Position, closestHaulable);
            IntVec3 foundCell;
            if (StoreUtility.TryFindBestBetterStoreCellFor(closestHaulable, pawn, currentPriority, pawn.Faction, out foundCell, true))
                return foundCell;
            */
            //Vanilla code is not worked item on container.
            StoragePriority currentPriority = HaulAIUtility.StoragePriorityAtFor(haulable.Position, haulable);
            foreach (SlotGroup slotGroup in Find.SlotGroupManager.AllGroupsListInPriorityOrder)
            {
                if (slotGroup.Settings.Priority < currentPriority)
                    break;
                foreach (IntVec3 cell in slotGroup.CellsList)
                    if (((!targetQueue.NullOrEmpty() && !targetQueue.Contains(cell)) || targetQueue.NullOrEmpty())
                        && cell.GetStorable() == null
                        && slotGroup.Settings.AllowedToAccept(haulable)
                        && pawn.CanReserve(cell))
                        return cell;
            }

            return IntVec3.Invalid;
        }
Example #30
0
        static void EnsureAtLeastOneMedibayInOutpost()
        {
            List<IntVec2> mediumRoomsList = new List<IntVec2>();

            for (int zoneAbs = 0; zoneAbs < OG_BigOutpost.horizontalZonesNumber; zoneAbs++)
            {
                for (int zoneOrd = 0; zoneOrd < OG_BigOutpost.verticalZonesNumber; zoneOrd++)
                {
                    ZoneType zoneType = zoneMap[zoneOrd, zoneAbs].zoneType;
                    if (zoneType == ZoneType.MediumRoomMedibay)
                    {
                        // Medibay is found.
                        return;
                    }
                    if ((zoneType == ZoneType.MediumRoomBarn)
                        || (zoneType == ZoneType.MediumRoomKitchen)
                        || (zoneType == ZoneType.MediumRoomLaboratory)
                        || (zoneType == ZoneType.MediumRoomPrison)
                        || (zoneType == ZoneType.MediumRoomRecRoom)
                        || (zoneType == ZoneType.MediumRoomWarehouse)
                        || (zoneType == ZoneType.MediumRoomWeaponRoom))
                    {
                        mediumRoomsList.Add(new IntVec2(zoneAbs, zoneOrd));
                    }
                }
            }
            if (mediumRoomsList.NullOrEmpty())
            {
                Log.Warning("MiningCo. Outpost generator: EnsureAtLeastOneMedibayInOutpost did not found any medium room.");
                return;
            }
            IntVec2 roomCoord = mediumRoomsList.RandomElement();
            zoneMap[roomCoord.z, roomCoord.x].zoneType = ZoneType.MediumRoomMedibay;
        }
        private FloatMenu MakeAmmoMenu()
        {
            List <ThingDef> ammoList = new List <ThingDef>();      // List of all ammo types the gun can use and the pawn has in his inventory

            if (compAmmo.turret != null)
            {
                // If we have no inventory available (e.g. manned turret), add all possible ammo types to the selection
                foreach (AmmoLink link in compAmmo.Props.ammoSet.ammoTypes)
                {
                    ammoList.Add(link.ammo);
                }
            }
            else
            {
                // Iterate through all suitable ammo types and check if they're in our inventory
                foreach (AmmoLink curLink in compAmmo.Props.ammoSet.ammoTypes)
                {
                    if (compAmmo.CompInventory.ammoList.Any(x => x.def == curLink.ammo))
                    {
                        ammoList.Add(curLink.ammo);
                    }
                }
            }

            // Append float menu options for every available ammo type
            List <FloatMenuOption> floatOptionList = new List <FloatMenuOption>();

            if (ammoList.NullOrEmpty())
            {
                floatOptionList.Add(new FloatMenuOption("CE_OutOfAmmo".Translate(), null));
            }
            else
            {
                // Append all available ammo types
                foreach (ThingDef curDef in ammoList)
                {
                    AmmoDef ammoDef = (AmmoDef)curDef;
                    floatOptionList.Add(new FloatMenuOption(ammoDef.ammoClass.LabelCap, new Action(delegate {
                        bool shouldReload     = Controller.settings.AutoReloadOnChangeAmmo && (compAmmo.SelectedAmmo != ammoDef || compAmmo.CurMagCount < compAmmo.Props.magazineSize) && compAmmo.turret?.MannableComp == null;
                        compAmmo.SelectedAmmo = ammoDef;
                        if (shouldReload)
                        {
                            if (compAmmo.turret != null)
                            {
                                compAmmo.turret.TryOrderReload();
                            }
                            else
                            {
                                compAmmo.TryStartReload();
                            }
                        }
                    })));
                }
            }
            // Append unload command
            var hasOperator = compAmmo.Wielder != null || (compAmmo.turret?.MannableComp?.MannedNow ?? false);

            if (compAmmo.UseAmmo && hasOperator && compAmmo.HasMagazine && compAmmo.CurMagCount > 0)
            {
                floatOptionList.Add(new FloatMenuOption("CE_UnloadLabel".Translate(), new Action(delegate { compAmmo.TryUnload(); })));
            }
            // Append reload command
            if (compAmmo.HasMagazine && hasOperator)
            {
                floatOptionList.Add(new FloatMenuOption("CE_ReloadLabel".Translate(), new Action(action)));
            }
            return(new FloatMenu(floatOptionList));
        }
Example #32
0
        /// <summary>
        /// Take all defined help sections and calculate 'optimal' column widths.
        /// </summary>
        /// <param name="width">Total width</param>
        private void SetColumnWidths(float width)
        {
            // leave some margin
            width -= 2 * _columnMargin;

            // build lists of all strings in this section
            List <string> prefixes = new List <string>();
            List <string> suffixes = new List <string>();
            List <string> descs    = new List <string>();
            List <Def>    defs     = new List <Def>();

            if (StringDescs != null)
            {
                prefixes.AddRange(StringDescs.Select(s => s.Prefix));
                suffixes.AddRange(StringDescs.Select(s => s.Suffix));
                descs.AddRange(StringDescs.Select(s => s.StringDesc));
            }

            if (KeyDefs != null)
            {
                prefixes.AddRange(KeyDefs.Select(k => k.Prefix));
                suffixes.AddRange(KeyDefs.Select(k => k.Suffix));
                defs.AddRange(KeyDefs.Select(k => k.Def));
            }

            // fetch length of all strings, select largest for each column
            Vector3 requestedWidths = Vector3.zero;

            // make sure wrapping is off so we get a true idea of the length
            bool WW = Text.WordWrap;

            Text.WordWrap = false;
            if (!prefixes.NullOrEmpty())
            {
                requestedWidths.x = prefixes.Select(s => Text.CalcSize(s).x).Max();
            }
            if (!descs.NullOrEmpty())
            {
                requestedWidths.y = descs.Select(s => Text.CalcSize(s).x).Max();
            }
            if (!defs.NullOrEmpty())
            {
                requestedWidths.y = Mathf.Max(requestedWidths.y, defs.Select(d => d.StyledLabelAndIconSize()).Max());
            }
            if (!suffixes.NullOrEmpty())
            {
                requestedWidths.z = suffixes.Select(s => Text.CalcSize(s).x).Max();
            }
            Text.WordWrap = WW;

            if (requestedWidths.Sum() < width)
            {
                // expand right-most column (even if it was zero)
                requestedWidths.z += width - requestedWidths.Sum();

                // done
                ColumnWidths = requestedWidths;
            }
            else
            {
                // if size overflow is < 30% of largest column width, scale that down.
                if (requestedWidths.Sum() - width < .3f * requestedWidths.Max())
                {
                    for (int i = 0; i < 3; i++)
                    {
                        if (requestedWidths[i] == requestedWidths.Max())
                        {
                            requestedWidths[i] -= requestedWidths.Sum() - width;
                            break;
                        }
                    }
                }
                else // scale everything down, with a minimum width of 15% per column
                {
                    Vector3 shrinkableWidth = requestedWidths.Subtract(width * .15f);
                    float   scalingFactor   = width / shrinkableWidth.Sum();
                    for (int i = 0; i < 3; i++)
                    {
                        requestedWidths[i] -= shrinkableWidth[i] * scalingFactor;
                    }
                }

                // done
                ColumnWidths = requestedWidths;
            }

            // set done flag.
            WidthsSet = true;
        }
Example #33
0
        public override void DrawWornExtras()
        {
            base.DrawWornExtras();
            if (!Pauldrons.NullOrEmpty())
            {
                PawnRenderFlags flags      = Wearer.Drawer.renderer.GetDefaultRenderFlags(Wearer);
                Quaternion      quat       = Quaternion.AngleAxis(0, Vector3.up);
                Vector3         vector     = Wearer.Drawer.renderer.GetBodyPos(Wearer.DrawPos, out bool renderBody);
                Rot4            headfacing = Wearer.Rotation;
                Rot4            bodyFacing = Wearer.Rotation;
                bool            portrait   = flags.FlagSet(PawnRenderFlags.Portrait);
                Vector2         size       = (portrait ? MeshPool.humanlikeBodySet.MeshAt(bodyFacing).bounds.size : Wearer.Drawer.renderer.graphics.nakedGraphic.MeshAt(bodyFacing).bounds.size);
                if (AdeptusIntergrationUtility.enabled_AlienRaces)
                {
                    PawnRenderUtility.AlienRacesPatch(Wearer, bodyFacing, out size, portrait);
                }
                else
                {
                    size = new Vector2(1.5f, 1.5f);
                }
                foreach (CompPauldronDrawer Pauldron in Pauldrons)
                {
                    Vector3 center = vector + (quat * Pauldron.GetOffsetFor(bodyFacing, false));
                    if (Pauldron.activeEntries.NullOrEmpty())
                    {
                        Pauldron.Initialize();
                    }
                    foreach (ShoulderPadEntry entry in Pauldron.activeEntries)
                    {
                        //    entry.Drawer = Pauldron;
                        if (entry.apparel == null)
                        {
                            entry.apparel = this;
                        }
                        if (entry.Drawer == null)
                        {
                            Log.Warning("Warning! Drawer null");
                        }
                        if (!entry.ForceDynamicDraw)
                        {
                            continue;
                        }

                        if (entry.ShouldDrawEntry(flags, bodyFacing, size, renderBody, out Graphic pauldronMat, out Mesh pauldronMesh, out Vector3 offset))
                        {
                            if (Pauldron.onHead || renderBody)
                            {
                                Vector3 drawAt = Wearer.Drawer.DrawPos + (quat * Pauldron.GetOffsetFor(bodyFacing, false));

                                /*
                                 * drawAt.y += 0.009687258f;
                                 * drawAt.y += 0.022166021f;
                                 * drawAt.y += 0.028957527f;
                                 * drawAt.y += 0.97f;
                                 */
                                GenDraw.DrawMeshNowOrLater
                                (
                                    // pauldronMesh,
                                    PawnRenderUtility.GetPawnMesh(portrait, Wearer, entry.Props.flipWest && bodyFacing == Rot4.West ? bodyFacing.Opposite : bodyFacing, !Pauldron.onHead),
                                    drawAt + (quat * offset),
                                    quat,
                                    PawnRenderUtility.OverrideMaterialIfNeeded(pauldronMat.MatAt(bodyFacing), Wearer),
                                    flags.FlagSet(PawnRenderFlags.DrawNow)
                                );
                            }
                        }
                    }
                }
            }
            if (!Extras.NullOrEmpty())
            {
                PawnRenderFlags flags      = Wearer.Drawer.renderer.GetDefaultRenderFlags(Wearer);
                Quaternion      quat       = Quaternion.AngleAxis(0, Vector3.up);
                Vector3         vector     = Wearer.DrawPos;
                Rot4            headfacing = Wearer.Rotation;
                Rot4            bodyFacing = Wearer.Rotation;
                bool            portrait   = flags.FlagSet(PawnRenderFlags.Portrait);
                Vector2         size       = (portrait ? MeshPool.humanlikeBodySet.MeshAt(bodyFacing).bounds.size : Wearer.Drawer.renderer.graphics.nakedGraphic.MeshAt(bodyFacing).bounds.size);
                if (AdeptusIntergrationUtility.enabled_AlienRaces)
                {
                    PawnRenderUtility.AlienRacesPatch(Wearer, bodyFacing, out size, portrait);
                }
                else
                {
                    size = new Vector2(1.5f, 1.5f);
                }
                foreach (CompApparelExtraPartDrawer ExtraDrawer in Extras)
                {
                    Vector3 drawAt = Wearer.DrawPos;
                    if (!ExtraDrawer.Props.ExtrasEntries.NullOrEmpty())
                    {
                        bool onHead = ExtraDrawer.onHead || ExtraDrawer.ExtraPartEntry.OnHead || ExtraDrawer.Props.onHead;
                        Rot4 facing = onHead ? headfacing : bodyFacing;
                        if (!ExtraDrawer.ExtraPartEntry.DynamicDraw)
                        {
                            continue;
                        }
                        if (ExtraDrawer.ShouldDrawExtra(Wearer, this, facing, out Material extraMat))
                        {
                            if (onHead || !PawnRenderFlagsExtension.FlagSet(flags, PawnRenderFlags.Invisible))
                            {
                                if (onHead)
                                {
                                    Vector3 v = vector + quat * Wearer.Drawer.renderer.BaseHeadOffsetAt(headfacing);
                                    drawAt = v + quat * new Vector3(ExtraDrawer.GetOffset(bodyFacing, ExtraDrawer.ExtraPartEntry).x *size.x, ExtraDrawer.GetOffset(bodyFacing, ExtraDrawer.ExtraPartEntry).y, ExtraDrawer.GetOffset(bodyFacing, ExtraDrawer.ExtraPartEntry).z *size.y);
                                }
                                else
                                {
                                    drawAt = vector + (quat * new Vector3(ExtraDrawer.GetOffset(bodyFacing, ExtraDrawer.ExtraPartEntry).x *size.x, ExtraDrawer.GetOffset(bodyFacing, ExtraDrawer.ExtraPartEntry).y, ExtraDrawer.GetOffset(bodyFacing, ExtraDrawer.ExtraPartEntry).z *size.y));
                                }

                                /*
                                 * GenDraw.DrawMeshNowOrLater
                                 *  (
                                 *      // pauldronMesh,
                                 *      PawnRenderUtility.GetPawnMesh(portrait, Wearer, facing, !onHead),
                                 *      drawAt,
                                 *      quat,
                                 *      PawnRenderUtility.OverrideMaterialIfNeeded(extraMat, Wearer),
                                 *      ExtraDrawer.ExtraPartEntry.animateExtra
                                 *  );
                                 */
                                Graphics.DrawMesh(
                                    PawnRenderUtility.GetPawnMesh(portrait, Wearer, facing, !onHead),
                                    drawAt,
                                    quat,
                                    PawnRenderUtility.OverrideMaterialIfNeeded(extraMat, Wearer),
                                    0);
                            }
                            //    vector.y += CompApparelExtaDrawer.MinClippingDistance;
                        }
                    }
                }
            }

            if (!Shields.NullOrEmpty())
            {
                foreach (var item in Shields)
                {
                    item.DrawShield();
                }
            }
        }
        public static bool CheckForAddedOrMissingParts(this Pawn pawn)
        {
            // if (!pawn.RaceProps.Humanlike)
            // {
            //     return;
            // }

            //   string log = "Checking for parts on " + pawn.LabelShort + " ...";

            if (!Controller.settings.ShowExtraParts)
            {
                //      log += "\n" + "No extra parts in options, return";
                //      Log.Message(log);
                return(false);
            }

            // no head => no face
            if (!pawn.health.hediffSet.HasHead)
            {
                //      log += "\n" + "No head, return";
                //      Log.Message(log);
                return(false);
            }

            // Reset the stats
            if (pawn.GetCompFace(out CompFace face))
            {
                face.BodyStat.EyeLeft  = PartStatus.Natural;
                face.BodyStat.EyeRight = PartStatus.Natural;
                face.BodyStat.Jaw      = PartStatus.Natural;
            }

            if (pawn.GetCompAnim(out CompBodyAnimator anim))
            {
                anim.BodyStat.HandLeft  = PartStatus.Natural;
                anim.BodyStat.HandRight = PartStatus.Natural;
                anim.BodyStat.FootLeft  = PartStatus.Natural;
                anim.BodyStat.FootRight = PartStatus.Natural;
            }

            List <BodyPartRecord> allParts = pawn.RaceProps?.body?.AllParts;

            if (allParts.NullOrEmpty())
            {
                //     log += "\n" + "All parts null or empty, return";
                //     Log.Message(log);
                return(false);
            }

            List <Hediff> hediffs = pawn.health?.hediffSet?.hediffs.Where(x => !x.def.defName.NullOrEmpty()).ToList();

            if (hediffs.NullOrEmpty())
            {
                // || hediffs.Any(x => x.def == HediffDefOf.MissingBodyPart && x.Part.def == BodyPartDefOf.Head))
                //     log += "\n" + "Hediffs null or empty, return";
                //     Log.Message(log);
                return(false);
            }

            foreach (Hediff diff in hediffs.Where(diff => diff.def == HediffDefOf.MissingBodyPart))
            {
                // Log.Message("Checking missing part "+diff.def.defName);
                CheckPart(allParts, diff, face, anim, true);
            }

            foreach (Hediff diff in hediffs.Where(diff => diff.def.addedPartProps != null))
            {
                //  Log.Message("Checking added part on " + pawn + "--"+diff.def.defName);
                CheckPart(allParts, diff, face, anim, false);
            }

            return(true);
        }
Example #35
0
        /// <summary>
        /// Return a copy of the listToRefresh but remove any destroyed item.
        /// </summary>
        public static List<Thing> RefreshThingList(List<Thing> listToRefresh)
        {
            List<Thing> refreshedList = new List<Thing>();

            if (listToRefresh.NullOrEmpty() == false)
            {
                foreach (Thing thing in listToRefresh)
                {
                    if (thing.Destroyed == false)
                    {
                        refreshedList.Add(thing);
                    }
                }
                return refreshedList;
            }
            else
            {
                return null;
            }
        }
 public ExtraHediffStageProperties GetExtraHediffStagePropertiesAt(int index)
 {
     return(stages.NullOrEmpty() ? ExtraHediffStageProperties.defaultValues : stages[index]);
 }
 public static void DrawPotentialPlacePositions(IntVec3 pylonPosition)
 {
     List<IntVec3> potentialPlacingPositionsList = new List<IntVec3>();
     for (int directionAsInt = 0; directionAsInt < 4; directionAsInt++)
     {
         for (int offset = 1; offset <= 5; offset++)
         {
             string unusedReason = "";
             IntVec3 testedPosition = pylonPosition + new IntVec3(offset, 0, 0).RotatedBy(new Rot4(directionAsInt));
             if (Building_LaserFencePylon.CanPlaceNewPylonHere(testedPosition, out unusedReason))
             {
                 potentialPlacingPositionsList.Add(testedPosition);
             }
         }
         if (potentialPlacingPositionsList.NullOrEmpty() == false)
         {
             GenDraw.DrawFieldEdges(potentialPlacingPositionsList);
         }
     }
 }
Example #38
0
        static IEnumerable <Toil> DoMakeToils(JobDriver_DoBill_Access __instance)
        {
            //normal scenario
            __instance.AddEndCondition(delegate
            {
                Thing thing = __instance.GetActor().jobs.curJob.GetTarget(TargetIndex.A).Thing;
                if (thing is Building && !thing.Spawned)
                {
                    return(JobCondition.Incompletable);
                }
                return(JobCondition.Ongoing);
            });
            __instance.FailOnBurningImmobile(TargetIndex.A);
            __instance.FailOn(delegate()
            {
                if (__instance.job.GetTarget(TargetIndex.A).Thing is Filth)
                {
                    return(false);
                }

                IBillGiver billGiver = __instance.job.GetTarget(TargetIndex.A).Thing as IBillGiver;
                if (billGiver != null)
                {
                    if (__instance.job.bill.DeletedOrDereferenced)
                    {
                        return(true);
                    }
                    if (!billGiver.CurrentlyUsableForBills())
                    {
                        return(true);
                    }
                }
                return(false);
            });

            Toil gotoBillGiver = Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.InteractionCell);

            yield return(new Toil
            {
                initAction = delegate()
                {
                    if (__instance.job.targetQueueB != null && __instance.job.targetQueueB.Count == 1)
                    {
                        UnfinishedThing unfinishedThing = __instance.job.targetQueueB[0].Thing as UnfinishedThing;
                        if (unfinishedThing != null)
                        {
                            unfinishedThing.BoundBill = (Bill_ProductionWithUft)__instance.job.bill;
                        }
                    }
                }
            });

            yield return(Toils_Jump.JumpIf(gotoBillGiver, () => __instance.job.GetTargetQueue(TargetIndex.B).NullOrEmpty()));

            //hauling patch
            if (Settings.adv_haul_all_ings && __instance.pawn.Faction == Faction.OfPlayer)
            {
                Toil checklist = new Toil();
                checklist.initAction = delegate()
                {
                    Pawn actor  = checklist.actor;
                    Job  curJob = actor.jobs.curJob;
                    List <LocalTargetInfo> targetQueue = curJob.GetTargetQueue(TargetIndex.B);
                    if (targetQueue.NullOrEmpty())
                    {
                        actor.jobs.curDriver.EndJobWith(JobCondition.Incompletable);
                    }
                    else
                    {
                        foreach (var target in (targetQueue))
                        {
                            if (target == null || target.Thing.DestroyedOrNull())
                            {
                                actor.jobs.curDriver.EndJobWith(JobCondition.Incompletable);
                                break;
                            }
                        }
                    }
                };

                yield return(checklist);

                Toil extract = new Toil();
                extract.initAction = delegate()
                {
                    Pawn actor  = extract.actor;
                    Job  curJob = actor.jobs.curJob;
                    List <LocalTargetInfo> targetQueue = curJob.GetTargetQueue(TargetIndex.B);
                    if (!curJob.countQueue.NullOrEmpty())
                    {
                        if (curJob.countQueue[0] > targetQueue[0].Thing.stackCount)
                        {
                            actor.jobs.curDriver.EndJobWith(JobCondition.Incompletable);
                        }
                        else
                        {
                            curJob.SetTarget(TargetIndex.B, targetQueue[0]);
                            targetQueue.RemoveAt(0);
                            curJob.count = curJob.countQueue[0];
                            curJob.countQueue.RemoveAt(0);
                        }
                    }
                };

                Toil PickUpThing;
                List <LocalTargetInfo> L = __instance.job.GetTargetQueue(TargetIndex.B);
                if (L.Count < 2 && (L.Count == 0 || L[0].Thing.def.stackLimit < 2))
                {
                    PickUpThing = Toils_Haul.StartCarryThing(TargetIndex.B, true, false, true);
                }
                else
                {
                    PickUpThing            = new Toil();
                    PickUpThing.initAction = delegate()
                    {
                        Pawn  actor  = PickUpThing.actor;
                        Job   curJob = actor.jobs.curJob;
                        Thing thing  = curJob.GetTarget(TargetIndex.B).Thing;
                        List <LocalTargetInfo> targetQueue = curJob.GetTargetQueue(TargetIndex.B);
                        bool InventorySpawned = thing.ParentHolder == actor.inventory;
                        if (InventorySpawned || !Toils_Haul.ErrorCheckForCarry(actor, thing))
                        {
                            if (thing.stackCount < curJob.count)
                            {
                                actor.jobs.curDriver.EndJobWith(JobCondition.Incompletable);
                            }
                            else
                            {
                                Thing splitThing = thing.SplitOff(curJob.count);
                                if (splitThing.ParentHolder != actor.inventory && !actor.inventory.GetDirectlyHeldThings().TryAdd(splitThing, false))
                                {
                                    actor.jobs.curDriver.EndJobWith(JobCondition.Incompletable);
                                }


                                if (!splitThing.Destroyed && splitThing.stackCount != 0)
                                {
                                    targetQueue.Add(splitThing);

                                    if (!InventorySpawned)
                                    {
                                        CompUnloadChecker CUC = splitThing.TryGetComp <CompUnloadChecker>();
                                        if (CUC != null)
                                        {
                                            CUC.ShouldUnload = true;
                                        }
                                    }
                                }

                                if (splitThing != thing && actor.Map.reservationManager.ReservedBy(thing, actor, curJob))
                                {
                                    actor.Map.reservationManager.Release(thing, actor, curJob);
                                }
                            }
                        }
                    };
                }

                Toil TakeToHands = new Toil();
                TakeToHands.initAction = delegate()
                {
                    Pawn actor  = TakeToHands.actor;
                    Job  curJob = actor.jobs.curJob;
                    List <LocalTargetInfo> targetQueue = curJob.GetTargetQueue(TargetIndex.B);
                    if (!targetQueue.NullOrEmpty() && targetQueue[0].Thing.ParentHolder != actor.carryTracker)
                    {
                        actor.inventory.innerContainer.TryTransferToContainer(targetQueue[0].Thing, actor.carryTracker.innerContainer);
                        actor.Reserve(targetQueue[0], curJob);
                        curJob.SetTarget(TargetIndex.B, targetQueue[0]);
                        targetQueue.RemoveAt(0);
                    }
                };

                yield return(extract);

                Toil getToHaulTarget = Toils_Goto.GotoThing(TargetIndex.B, PathEndMode.ClosestTouch).FailOnDespawnedNullOrForbidden(TargetIndex.B).FailOnSomeonePhysicallyInteracting(TargetIndex.B);
                yield return(Toils_Jump.JumpIf(PickUpThing, () => __instance.job.GetTarget(TargetIndex.B).Thing.ParentHolder == __instance.pawn.inventory));

                yield return(getToHaulTarget);

                yield return(PickUpThing);

                yield return(Toils_Jump.JumpIf(extract, () => !__instance.job.countQueue.NullOrEmpty()));

                yield return(TakeToHands);

                yield return(Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.InteractionCell).FailOnDestroyedOrNull(TargetIndex.B));

                Toil findPlaceTarget = Toils_JobTransforms.SetTargetToIngredientPlaceCell(TargetIndex.A, TargetIndex.B, TargetIndex.C);
                yield return(findPlaceTarget);

                yield return(Toils_Haul.PlaceHauledThingInCell(TargetIndex.C, findPlaceTarget, false));

                yield return(Toils_Jump.JumpIfHaveTargetInQueue(TargetIndex.B, TakeToHands));
            }
            else
            {
                Toil extract = Toils_JobTransforms.ExtractNextTargetFromQueue(TargetIndex.B, true);
                yield return(extract);

                Toil getToHaulTarget = Toils_Goto.GotoThing(TargetIndex.B, PathEndMode.ClosestTouch).FailOnDespawnedNullOrForbidden(TargetIndex.B).FailOnSomeonePhysicallyInteracting(TargetIndex.B);
                yield return(getToHaulTarget);

                yield return(Toils_Haul.StartCarryThing(TargetIndex.B, true, false, true));

                yield return(JobDriver_DoBill_Access.JumpToCollectNextIntoHandsForBillCrutch(getToHaulTarget, TargetIndex.B));

                yield return(Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.InteractionCell).FailOnDestroyedOrNull(TargetIndex.B));

                Toil findPlaceTarget = Toils_JobTransforms.SetTargetToIngredientPlaceCell(TargetIndex.A, TargetIndex.B, TargetIndex.C);
                yield return(findPlaceTarget);

                yield return(Toils_Haul.PlaceHauledThingInCell(TargetIndex.C, findPlaceTarget, false));

                yield return(Toils_Jump.JumpIfHaveTargetInQueue(TargetIndex.B, extract));
            }

            yield return(gotoBillGiver); //one line from normal scenario

            //cleaning patch
            if (Settings.adv_cleaning && !Utility.IncapableOfCleaning(__instance.pawn))
            {
                Toil returnToBillGiver = Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.InteractionCell);
                Toil FilthList         = new Toil();
                FilthList.initAction = delegate()
                {
                    Job curJob = FilthList.actor.jobs.curJob;
                    if (curJob.GetTargetQueue(TargetIndex.A).NullOrEmpty())
                    {
                        LocalTargetInfo A = curJob.GetTarget(TargetIndex.A);
                        DoCleanComp     comp;
                        if (!Settings.clean_gizmo || (comp = A.Thing?.TryGetComp <DoCleanComp>()) == null || comp.Active)
                        {
                            IEnumerable <Filth> l = Utility.SelectAllFilth(FilthList.actor, A, Settings.adv_clean_num);
                            Utility.AddFilthToQueue(curJob, TargetIndex.A, l, FilthList.actor);
                            FilthList.actor.ReserveAsManyAsPossible(curJob.GetTargetQueue(TargetIndex.A), curJob);
                        }
                        curJob.targetQueueA.Add(A);
                    }
                };
                yield return(FilthList);

                yield return(Toils_Jump.JumpIf(returnToBillGiver, () => __instance.job.GetTargetQueue(TargetIndex.A).NullOrEmpty()));

                Toil CleanFilthList = Toils_JobTransforms.ClearDespawnedNullOrForbiddenQueuedTargets(TargetIndex.A, null);
                yield return(CleanFilthList);

                yield return(Toils_JobTransforms.ExtractNextTargetFromQueue(TargetIndex.A, true));

                yield return(Toils_Jump.JumpIf(returnToBillGiver, () => __instance.job.GetTargetQueue(TargetIndex.A).NullOrEmpty()));

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

                Toil clean = new Toil();
                clean.initAction = delegate()
                {
                    Filth filth = clean.actor.jobs.curJob.GetTarget(TargetIndex.A).Thing as Filth;
                    __instance.billStartTick             = 0;
                    __instance.ticksSpentDoingRecipeWork = 0;
                    __instance.workLeft = filth.def.filth.cleaningWorkToReduceThickness * filth.thickness;
                };
                clean.tickAction = delegate()
                {
                    Filth filth = clean.actor.jobs.curJob.GetTarget(TargetIndex.A).Thing as Filth;
                    __instance.billStartTick             += 1;
                    __instance.ticksSpentDoingRecipeWork += 1;
                    if (__instance.billStartTick > filth.def.filth.cleaningWorkToReduceThickness)
                    {
                        filth.ThinFilth();
                        __instance.billStartTick = 0;
                        if (filth.Destroyed)
                        {
                            clean.actor.records.Increment(RecordDefOf.MessesCleaned);
                            __instance.ReadyForNextToil();
                            return;
                        }
                    }
                };
                clean.defaultCompleteMode = ToilCompleteMode.Never;
                clean.WithEffect(EffecterDefOf.Clean, TargetIndex.A);
                clean.WithProgressBar(TargetIndex.A, () => __instance.ticksSpentDoingRecipeWork / __instance.workLeft, true, -0.5f);
                clean.PlaySustainerOrSound(() => SoundDefOf.Interact_CleanFilth);
                clean.JumpIfDespawnedOrNullOrForbidden(TargetIndex.A, CleanFilthList);
                clean.JumpIfOutsideHomeArea(TargetIndex.A, CleanFilthList);
                yield return(clean);

                yield return(Toils_Jump.Jump(CleanFilthList));

                yield return(returnToBillGiver);
            }

            //continuation of normal scenario
            yield return(Toils_Recipe.MakeUnfinishedThingIfNeeded());

            yield return(Toils_Recipe.DoRecipeWork().FailOnDespawnedNullOrForbiddenPlacedThings().FailOnCannotTouch(TargetIndex.A, PathEndMode.InteractionCell));

            yield return(Toils_Recipe.FinishRecipeAndStartStoringProduct());

            if (!__instance.job.RecipeDef.products.NullOrEmpty() || !__instance.job.RecipeDef.specialProducts.NullOrEmpty())
            {
                yield return(Toils_Reserve.Reserve(TargetIndex.B, 1, -1, null));

                Toil carryToCell = Toils_Haul.CarryHauledThingToCell(TargetIndex.B);
                yield return(carryToCell);

                yield return(Toils_Haul.PlaceHauledThingInCell(TargetIndex.B, carryToCell, true));

                Toil recount = new Toil();
                recount.initAction = delegate()
                {
                    Bill_Production bill_Production = recount.actor.jobs.curJob.bill as Bill_Production;
                    if (bill_Production != null && bill_Production.repeatMode == BillRepeatModeDefOf.TargetCount)
                    {
                        __instance.MapCrutch().resourceCounter.UpdateResourceCounts();
                    }
                };
                yield return(recount);
            }
            yield break;
        }
Example #39
0
 private void UnlockAllAppropriateDoors()
 {
     var allDoors = Find.ListerBuildings.AllBuildingsColonistOfClass<Building_RestrictedDoor>().Where( (door) =>
     {
         var compLock = door.TryGetComp<CompLockable>();
         if( compLock == null )
         {
             return false;
         }
         return compLock.temporaryLock;
     } ).ToList();
     var doors = new List<Building_RestrictedDoor>();
     if( !hostilesInRooms.NullOrEmpty() )
     {
         foreach( var room in hostilesInRooms )
         {
             foreach( var door in room.Portals() )
             {
                 var restrictedDoor = door as Building_RestrictedDoor;
                 if(
                     ( restrictedDoor != null )&&
                     ( restrictedDoor.TryGetComp<CompLockable>() != null )
                 )
                 {
                     doors.AddUnique( restrictedDoor );
                     allDoors.Remove( restrictedDoor );
                 }
             }
         }
     }
     if( !allDoors.NullOrEmpty() )
     {
         foreach( var door in allDoors )
         {
             //Log.Message( string.Format( "Door {0} is temporarily locked, lifting", door.ThingID ) );
             DoorLockToggle( door.TryGetComp<CompLockable>(), door.TryGetComp<CompPowerTrader>(), false );
         }
     }
     if( !doors.NullOrEmpty() )
     {
         foreach( var door in doors )
         {
             DoorLockToggle( door.TryGetComp<CompLockable>(), door.TryGetComp<CompPowerTrader>(), true );
         }
     }
     hostilesInRooms.Clear();
 }
        /// <summary>
        /// Find an item that should be dropped from the pawn's inventory and how much to drop.
        /// </summary>
        /// <param name="pawn"></param>
        /// <param name="dropThing">The thing which should be dropped.</param>
        /// <param name="dropCount">The amount to drop.</param>
        /// <returns>bool, true indicates that the out variables are filled with something to do work on (drop).</returns>
        // NOTE (ProfoundDarkness): Ended up doing this by nibbling away at the pawn's inventory (or dictionary representation of ThingDefs/Count).
        //  Probably not efficient but was easier to handle atm.
        static public bool GetExcessThing(this Pawn pawn, out Thing dropThing, out int dropCount)
        {
            //(ProfoundDarkness) Thanks to erdelf on the RimWorldMod discord for helping me figure out some dictionary stuff and C# concepts related to 'Primitives' (pass by Value).
            CompInventory     inventory = pawn.TryGetComp <CompInventory>();
            Loadout           loadout   = pawn.GetLoadout();
            List <HoldRecord> records   = LoadoutManager.GetHoldRecords(pawn);

            dropThing = null;
            dropCount = 0;

            if (inventory == null || inventory.container == null || loadout == null || loadout.Slots.NullOrEmpty())
            {
                return(false);
            }

            Dictionary <ThingDef, Integer> listing = GetStorageByThingDef(pawn);

            // iterate over specifics and generics and Chip away at the dictionary.
            foreach (LoadoutSlot slot in loadout.Slots)
            {
                if (slot.thingDef != null && listing.ContainsKey(slot.thingDef))
                {
                    listing[slot.thingDef].value -= slot.count;
                    if (listing[slot.thingDef].value <= 0)
                    {
                        listing.Remove(slot.thingDef);
                    }
                }
                if (slot.genericDef != null)
                {
                    List <ThingDef> killKeys     = new List <ThingDef>();
                    int             desiredCount = slot.count;
                    // find dictionary entries which corespond to covered slot.
                    foreach (ThingDef def in listing.Keys.Where(td => slot.genericDef.lambda(td)))
                    {
                        listing[def].value -= desiredCount;
                        if (listing[def].value <= 0)
                        {
                            desiredCount = 0 - listing[def].value;
                            killKeys.Add(def); // the thing in inventory is exausted, forget about it.
                        }
                        else
                        {
                            break; // we have satisifed this loadout so no need to keep enumerating.
                        }
                    }
                    // cleanup dictionary.
                    foreach (ThingDef def in killKeys)
                    {
                        listing.Remove(def);
                    }
                }
            }

            // if there is something left in the dictionary, that is what is to be dropped.
            // Complicated by the fact that we now consider ammo in guns as part of the inventory...
            if (listing.Any())
            {
                if (records != null && !records.NullOrEmpty())
                {
                    // look at each remaining 'uneaten' thingdef in pawn's inventory.
                    foreach (ThingDef def in listing.Keys)
                    {
                        HoldRecord rec = records.FirstOrDefault(r => r.thingDef == def);
                        if (rec == null)
                        {
                            // the item we have extra of has no HoldRecord, drop it.
                            dropThing = inventory.container.FirstOrDefault(t => t.def == def && !pawn.IsItemQuestLocked(t));
                            if (dropThing != null)
                            {
                                dropCount = listing[def].value > dropThing.stackCount ? dropThing.stackCount : listing[def].value;
                                return(true);
                            }
                        }
                        else if (rec.count < listing[def].value)
                        {
                            // the item we have extra of HAS a HoldRecord but the amount carried is above the limit of the HoldRecord, drop extra.
                            dropThing = pawn.inventory.innerContainer.FirstOrDefault(t => t.def == def && !pawn.IsItemQuestLocked(t));
                            if (dropThing != null)
                            {
                                dropCount = listing[def].value - rec.count;
                                dropCount = dropCount > dropThing.stackCount ? dropThing.stackCount : dropCount;
                                return(true);
                            }
                        }
                    }
                }
                else
                {
                    foreach (ThingDef def in listing.Keys)
                    {
                        dropThing = inventory.container.FirstOrDefault(t => t.GetInnerIfMinified().def == def && !pawn.IsItemQuestLocked(t));
                        if (dropThing != null)
                        {
                            dropCount = listing[def].value > dropThing.stackCount ? dropThing.stackCount : listing[def].value;
                            return(true);
                        }
                    }
                }
            } // else
            return(false);
        }
        public bool CountResourcesInHoppers( List<ResourceAmount> resources )
        {
            //Log.Message( string.Format( "{0}.CompHopperUser.CountResourcesInHoppers( List<ResourceAmount> )", this.parent.ThingID ) );
            if( resources == null )
            {
                return false;
            }
            resources.Clear();

            foreach( var hopper in FindHoppers() )
            {
                foreach( var thing in hopper.GetAllResources( Resources ) )
                {
                    ResourceAmount.AddToList( resources, thing.def, thing.stackCount );
                }
            }
            return !resources.NullOrEmpty();
        }
Example #42
0
        protected override string FormateListThing(List <AnimalWishInfo> things)
        {
            if (things.NullOrEmpty())
            {
                return(base.FormateListThing(things));
            }

            string listingBaseCount  = "";
            string listingOtherCount = "";

            for (int i = 0; i < things.Count; i++)
            {
                if (things[i].amount == Def.specificAmount &&
                    things[i].shouldBeBonded == Def.shouldBeBonded &&
                    things[i].includedStage == Def.includedStage)
                {
                    if (listingBaseCount == "")
                    {
                        if (!Def.countAmountPerInfo && Def.specificAmount < Def.amountNeeded)
                        {
                            listingBaseCount += " x" + Def.specificAmount.ToString();
                        }
                        if (things[i].shouldBeBonded)
                        {
                            listingBaseCount += " (" + PawnRelationDefOf.Bond.LabelCap + ")";
                        }
                        if (!things[i].includedStage.NullOrEmpty())
                        {
                            listingBaseCount += "(";
                            for (int j = 0; j < things[i].includedStage.Count; j++)
                            {
                                listingBaseCount += things[i].animal.race.lifeStageAges[things[i].includedStage[j]].def.LabelCap;
                                listingBaseCount += j == things[i].includedStage.Count - 1 ? ")" : "/";
                            }
                        }
                        listingBaseCount += " => ";
                    }
                    else
                    {
                        listingBaseCount += Def.listing_Separator;
                    }
                    listingBaseCount += things[i].animal.label;
                }
                else
                {
                    listingOtherCount += " x" + things[i].amount.ToString() + " ";
                    listingOtherCount += things[i].animal.label;
                    if (things[i].shouldBeBonded)
                    {
                        listingOtherCount += "(" + PawnRelationDefOf.Bond.LabelCap + ")";
                    }
                    if (!things[i].includedStage.NullOrEmpty())
                    {
                        listingOtherCount += "(";
                        for (int j = 0; j < things[i].includedStage.Count; j++)
                        {
                            listingOtherCount += things[i].animal.race.lifeStageAges[things[i].includedStage[j]].def.LabelCap;
                            listingOtherCount += j == things[i].includedStage.Count - 1 ? ")" : "/";
                        }
                    }
                    if (i != things.Count - 1)
                    {
                        listingOtherCount += def.listing_Separator;
                    }
                }
            }
            if (listingBaseCount != "")
            {
                if (listingOtherCount != "")
                {
                    listingBaseCount += "\n\n" + listingOtherCount;
                }
            }
            else
            {
                listingBaseCount += listingOtherCount;
            }
            return(listingBaseCount);
        }
        private void ProgramHoppersIndividual( List<CompHopper> hoppers )
        {
            //Log.Message( string.Format( "{0}.CompHopperUser.ProgramHoppersIndividual( List<CompHopper> )", this.parent.ThingID ) );
            // Try to find hoppers which match already
            var freeHoppers = new List<CompHopper>();
            foreach( var hopper in hoppers )
            {
                if( !hopper.WasProgrammed )
                {
                    freeHoppers.AddUnique( hopper );
                }
                else
                {
                    var hopperStoreSettings = hopper.GetStoreSettings();
                    bool found = false;
                    foreach( var hopperSetting in hopperSettings )
                    {
                        if( hopperStoreSettings.filter.Matches( hopperSetting.settings.filter ) )
                        {
                            if(
                                ( hopperSetting.HoppersRequired > hopperSetting.hoppers.Count )&&
                                ( hopperSetting.ShouldBeRefrigerated == hopper.IsRefrigerated )
                            )
                            {
                                // Filters match, refrigeration requirements match, now check existing resources
                                var currentResources = hopper.GetAllResources( resourceSettings.filter );
                                if( currentResources.NullOrEmpty() )
                                {
                                    // None here so we can use it for this
                                    found = true;
                                }
                                else
                                {
                                    // Something here, prefer hoppers with resources which are allowed already
                                    foreach( var thing in currentResources )
                                    {
                                        if( hopperSetting.settings.filter.Allows( thing ) )
                                        {
                                            found = true;
                                            break;
                                        }
                                    }
                                }
                                if( found )
                                {
                                    hopperSetting.hoppers.Add( hopper );
                                    break;
                                }
                            }
                        }
                        if( found == true )
                        {
                            break;
                        }
                    }
                    if( !found )
                    {
                        // No matching hopper for this setting
                        hopper.DeprogramHopper();
                        freeHoppers.Add( hopper );
                    }
                }
            }

            // Assign any resources which need hoppers matching refrigeration requirements
            foreach( var hopperSetting in hopperSettings )
            {
                int amountToAssign = hopperSetting.HoppersRequired - hopperSetting.hoppers.Count;
                if( amountToAssign > 0 )
                {
                    for( int index = 0; index < amountToAssign; index++ )
                    {
                        for( int index2 = 0; index2 < freeHoppers.Count; index2++ )
                        {
                            var hopper = freeHoppers[ index2 ];
                            if( hopperSetting.ShouldBeRefrigerated == hopper.IsRefrigerated )
                            {
                                hopperSetting.hoppers.Add( hopper );
                                freeHoppers.Remove( hopper );
                                break;
                            }
                        }
                    }
                }
            }

            // Assign any resources which need hoppers to any hopper regardless of refrigeration requirements
            foreach( var hopperSetting in hopperSettings )
            {
                int amountToAssign = hopperSetting.HoppersRequired - hopperSetting.hoppers.Count;
                if( amountToAssign > 0 )
                {
                    for( int index = 0; index < amountToAssign; index++ )
                    {
                        var hopper = freeHoppers[ 0 ];
                        hopperSetting.hoppers.Add( hopper );
                        freeHoppers.Remove( hopper );
                    }
                }
            }

            // Assign any remaining hoppers to resource settings from most required ingredients to least
            if( !freeHoppers.NullOrEmpty() )
            {
                int nextSetting = 0;
                do
                {
                    var hopper = freeHoppers[ 0 ];
                    bool found = false;
                    bool matchRefrigeration = true;
                    int settingIndex = nextSetting;
                    do
                    {
                        var hopperSetting = hopperSettings[ settingIndex ];
                        if(
                            (
                                ( matchRefrigeration )&&
                                ( hopper.IsRefrigerated == hopperSetting.ShouldBeRefrigerated )
                            )||
                            ( !matchRefrigeration )
                        )
                        {
                            hopperSetting.hoppers.Add( hopper );
                            freeHoppers.Remove( hopper );
                            found = true;
                        }
                        else
                        {
                            settingIndex++;
                            settingIndex %= hopperSettings.Count;
                            if( settingIndex == nextSetting )
                            {
                                matchRefrigeration = false;
                            }
                        }
                    } while ( !found );
                    nextSetting++;
                    nextSetting %= hopperSettings.Count;
                } while ( freeHoppers.Count > 0 );
            }

            // Finally, program the hoppers
            foreach( var hopperSetting in hopperSettings )
            {
                foreach( var hopper in hopperSetting.hoppers )
                {
                    hopper.ProgramHopper( hopperSetting.settings );
                }
            }
        }
Example #44
0
        public static void InferSkillBias(this ResearchProjectDef tech)
        {
            //Log.Warning("InferSkillBias Starting for "+tech.LabelCap);
            //1. check what it unlocks
            List <Pair <Def, string> > unlocks   = ResearchTree_Patches.GetUnlockDefsAndDescs(tech);
            IEnumerable <Def>          defs      = unlocks.Select(x => x.First).AsEnumerable();
            IEnumerable <ThingDef>     thingDefs = from d in defs
                                                   where d is ThingDef
                                                   select d as ThingDef;
            IEnumerable <RecipeDef> recipeDefs = from d in defs
                                                 where d is RecipeDef
                                                 select d as RecipeDef;
            IEnumerable <TerrainDef> terrainDefs = from d in defs
                                                   where d is TerrainDef
                                                   select d as TerrainDef;

            //2. look for skills based on unlocked stuff

            //a. checking by query on the research tree
            //int matches = 0;
            if (tech.Matches("scanner") > 0 | tech.Matches("terraform") > 0)
            {
                miningTag = true;                                                                /*matches++;*/
            }
            ;

            if (tech.Matches("sterile") > 0 | tech.Matches("medical") > 0 | tech.Matches("medicine") > 0 | tech.Matches("cryptosleep") > 0 | tech.Matches("prostheses") > 0 | tech.Matches("implant") > 0 | tech.Matches("organs") > 0 | tech.Matches("surgery") > 0)
            {
                medicineTag = true;                                                                                                                                                                                                                                                         /*matches++;*/
            }
            ;

            if (tech.Matches("irrigation") > 0 | tech.Matches("soil") > 0 | tech.Matches("hydroponic") > 0)
            {
                plantsTag = true;                                                                                               /*matches++;*/
            }
            ;

            if (tech.Matches("tool") > 0)
            {
                craftingTag = true;
            }

            if (tech.Matches("manage") > 0)
            {
                intellectualTag = true;
            }

            //b. checking by unlocked things
            if (thingDefs.Count() > 0)
            {
                foreach (ThingDef t in thingDefs)
                {
                    if (t != null)
                    {
                        InvestigateThingDef(t);
                    }
                }
            }

            //c. checking by unlocked recipes
            if (recipeDefs.Count() > 0)
            {
                foreach (RecipeDef r in recipeDefs)
                {
                    //Log.Message("trying recipe " + r.label);
                    foreach (ThingDef t in r.products.Select(x => x.thingDef))
                    {
                        InvestigateThingDef(t);
                    }
                    if (r.workSkill != null)
                    {
                        AccessTools.Field(typeof(Extension_Research), r.workSkill.defName.ToLower() + "Tag").SetValue(tech, true);
                    }
                }
            }

            //d. checking by unlocked terrainDefs
            if (terrainDefs.Count() > 0)
            {
                foreach (TerrainDef t in terrainDefs)
                {
                    if (!constructionTag && t.designationCategory != null && t.designationCategory.label.Contains("floor"))
                    {
                        constructionTag = true;
                    }
                    else if (!miningTag)
                    {
                        miningTag = true;
                    }
                }
            }

            //e. special cases
            if (HarmonyPatches.RunSpecialCases)
            {
                if (tech.defName.StartsWith("ResearchProject_RotR"))
                {
                    miningTag       = true;
                    constructionTag = true;
                }
                if (tech.defName.StartsWith("BackupPower") || tech.defName.StartsWith("FluffyBreakdowns"))
                {
                    constructionTag = true;
                }
            }

            //3. Figure out Bias.
            //int ThingDefCount = thingDefs.Count();
            //int RecipeDefCount = recipeDefs.Count();
            //int TerrainDefCount = terrainDefs.Count();

            List <SkillDef> relevantSkills = new List <SkillDef>();

            if (shootingTag)
            {
                relevantSkills.Add(SkillDefOf.Shooting);
                shootingTag = false;
            }
            if (meleeTag)
            {
                relevantSkills.Add(SkillDefOf.Melee);
                meleeTag = false;
            }
            if (constructionTag)
            {
                relevantSkills.Add(SkillDefOf.Construction);
                constructionTag = false;
            }
            if (miningTag)
            {
                relevantSkills.Add(SkillDefOf.Mining);
                miningTag = false;
            }
            if (cookingTag)
            {
                relevantSkills.Add(SkillDefOf.Cooking);
                cookingTag = false;
            }
            if (plantsTag)
            {
                relevantSkills.Add(SkillDefOf.Plants);
                plantsTag = false;
            }
            if (animalsTag)
            {
                relevantSkills.Add(SkillDefOf.Animals);
                animalsTag = false;
            }
            if (craftingTag)
            {
                relevantSkills.Add(SkillDefOf.Crafting);
                craftingTag = false;
            }
            if (artisticTag)
            {
                relevantSkills.Add(SkillDefOf.Artistic);
                artisticTag = false;
            }
            if (medicineTag)
            {
                relevantSkills.Add(SkillDefOf.Medicine);
                medicineTag = false;
            }
            if (socialTag)
            {
                relevantSkills.Add(SkillDefOf.Social);
                socialTag = false;
            }
            if (intellectualTag)
            {
                relevantSkills.Add(SkillDefOf.Intellectual);
                intellectualTag = false;
            }

            if (!relevantSkills.NullOrEmpty())
            {
                SkillsByTech.Add(tech, relevantSkills);
                foreach (SkillDef skill in relevantSkills)
                {
                    if (!TechsBySkill.ContainsKey(skill))
                    {
                        TechsBySkill.Add(skill, new List <ResearchProjectDef>()
                        {
                            tech
                        });
                    }
                    else
                    {
                        TechsBySkill[skill].Add(tech);
                    }
                }
            }
            else
            {
                Log.Warning("[HumanResources] No relevant skills could be calculated for " + tech + ". It won't be known by anyone.");
            }
        }
        /// <summary>
        /// Take all defined help sections and calculate 'optimal' column widths.
        /// </summary>
        /// <param name="width">Total width</param>
        private void SetColumnWidths( float width )
        {
            // leave some margin
            width -= 2 * _columnMargin;

            // build lists of all strings in this section
            List<string> prefixes = new List<string>();
            List<string> suffixes = new List<string>();
            List<string> descs = new List<string>();
            List<Def> defs = new List<Def>();

            if ( StringDescs != null )
            {
                prefixes.AddRange( StringDescs.Select( s => s.Prefix ) );
                suffixes.AddRange( StringDescs.Select( s => s.Suffix ) );
                descs.AddRange( StringDescs.Select( s => s.StringDesc ) );
            }

            if ( KeyDefs != null )
            {
                prefixes.AddRange( KeyDefs.Select( k => k.Prefix ) );
                suffixes.AddRange( KeyDefs.Select( k => k.Suffix ) );
                defs.AddRange( KeyDefs.Select( k => k.Def ) );
            }

            // fetch length of all strings, select largest for each column
            Vector3 requestedWidths = Vector3.zero;

            // make sure wrapping is off so we get a true idea of the length
            bool WW = Text.WordWrap;
            Text.WordWrap = false;
            if ( !prefixes.NullOrEmpty() )
            {
                requestedWidths.x = prefixes.Select( s => Text.CalcSize( s ).x ).Max();
            }
            if ( !descs.NullOrEmpty() )
            {
                requestedWidths.y = descs.Select( s => Text.CalcSize( s ).x ).Max();
            }
            if ( !defs.NullOrEmpty() )
            {
                requestedWidths.y = Mathf.Max( requestedWidths.y, defs.Select( d => d.StyledLabelAndIconSize() ).Max() );
            }
            if ( !suffixes.NullOrEmpty() )
            {
                requestedWidths.z = suffixes.Select( s => Text.CalcSize( s ).x ).Max();
            }
            Text.WordWrap = WW;

            if ( requestedWidths.Sum() < width )
            {
                // expand right-most column (even if it was zero)
                requestedWidths.z += width - requestedWidths.Sum();

                // done
                ColumnWidths = requestedWidths;
            }
            else
            {
                // if size overflow is < 30% of largest column width, scale that down.
                if ( requestedWidths.Sum() - width < .3f * requestedWidths.Max() )
                {
                    for ( int i = 0; i < 3; i++ )
                    {
                        if ( requestedWidths[i] == requestedWidths.Max() )
                        {
                            requestedWidths[i] -= requestedWidths.Sum() - width;
                            break;
                        }
                    }
                }
                else // scale everything down, with a minimum width of 15% per column
                {
                    Vector3 shrinkableWidth = requestedWidths.Subtract( width * .15f );
                    float scalingFactor = width / shrinkableWidth.Sum();
                    for( int i = 0; i < 3; i++ )
                    {
                        requestedWidths[i] -= shrinkableWidth[i] * scalingFactor;
                    }
                }

                // done
                ColumnWidths = requestedWidths;
            }

            // set done flag.
            WidthsSet = true;
        }