protected override void DrawPanelContent(State state)
        {
            base.DrawPanelContent(state);

            IEnumerable <EquipmentSelection> entries = PrepareCarefully.Instance.Equipment.Select((EquipmentSelection equipment) => {
                return(FindEntry(equipment));
            }).Where((EquipmentSelection equipment) => { return(equipment != null); });

            if (table.Selected == null)
            {
                table.Selected = entries.FirstOrDefault();
            }

            table.Draw(entries);

            if (ScrollToEntry != null)
            {
                ScrollTo(ScrollToEntry);
                ScrollToEntry = null;
            }

            if (Widgets.ButtonText(RectRemoveButton, "EdB.PC.Panel.SelectedEquipment.Remove".Translate(), true, false, table.Selected != null))
            {
                SoundDefOf.TickHigh.PlayOneShotOnCamera();
                EquipmentRemoved(table.Selected);
                table.Selected = null;
            }
        }
        /*
         * private SelectedPet RandomPet(ScenPart_StartingAnimal startingAnimal) {
         *  FieldInfo animalKindField = typeof(ScenPart_StartingAnimal).GetField("animalKind", BindingFlags.Instance | BindingFlags.NonPublic);
         *  MethodInfo randomPetsMethod = typeof(ScenPart_StartingAnimal).GetMethod("RandomPets", BindingFlags.Instance | BindingFlags.NonPublic);
         *
         *  PawnKindDef animalKindDef = (PawnKindDef)animalKindField.GetValue(startingAnimal);
         *  if (animalKindDef == null) {
         *      IEnumerable<PawnKindDef> animalKindDefs = (IEnumerable<PawnKindDef>)randomPetsMethod.Invoke(startingAnimal, null);
         *      animalKindDef = animalKindDefs.RandomElementByWeight((PawnKindDef td) => td.RaceProps.petness);
         *  }
         *
         *  List<AnimalRecord> records = PrepareCarefully.Instance.AnimalDatabase.AllAnimals.Where((AnimalRecord r) => {
         *      return r.ThingDef == animalKindDef.race;
         *  }).ToList();
         *  if (records.Count > 0) {
         *      AnimalRecord record = records.RandomElement();
         *      SelectedPet pet = new SelectedPet();
         *      pet.Record = record;
         *
         *      pet.BondedPawn = randomizer.PickBondedPawnForPet(Pawns);
         *
         *      // TODO: We're making an assumption that all pets have single-name names.  Is that a fair assumption?
         *      pet.Pawn = PawnGenerator.GeneratePawn(animalKindDef, Faction.OfPlayer);
         *      pet.Pawn.gender = pet.Record.Gender;
         *      pet.Pawn.Name= PawnBioAndNameGenerator.GeneratePawnName(pet.Pawn, NameStyle.Full, null);
         *      pet.Name = pet.Pawn.Name.ToStringFull;
         *
         *      pet.Id = System.Guid.NewGuid().ToString();
         *      return pet;
         *  }
         *  else {
         *      return null;
         *  }
         * }
         */

        private static EquipmentRecord RandomPet(ScenPart_StartingAnimal startingAnimal)
        {
            FieldInfo  animalKindField  = typeof(ScenPart_StartingAnimal).GetField("animalKind", BindingFlags.Instance | BindingFlags.NonPublic);
            MethodInfo randomPetsMethod = typeof(ScenPart_StartingAnimal).GetMethod("RandomPets", BindingFlags.Instance | BindingFlags.NonPublic);

            PawnKindDef animalKindDef = (PawnKindDef)animalKindField.GetValue(startingAnimal);

            if (animalKindDef == null)
            {
                IEnumerable <PawnKindDef> animalKindDefs = (IEnumerable <PawnKindDef>)randomPetsMethod.Invoke(startingAnimal, null);
                animalKindDef = animalKindDefs.RandomElementByWeight((PawnKindDef td) => td.RaceProps.petness);
            }

            List <EquipmentRecord> entries = PrepareCarefully.Instance.EquipmentDatabase.Animals.FindAll((EquipmentRecord e) => {
                return(e.def == animalKindDef.race);
            });

            if (entries.Count > 0)
            {
                EquipmentRecord entry = entries.RandomElement();
                return(entry);
            }
            else
            {
                return(null);
            }
        }
        protected override void DrawPanelContent(State state)
        {
            base.DrawPanelContent(state);

            IEnumerable <EquipmentSelection> entries = SelectedEquipment;

            if (table.Selected == null)
            {
                table.Selected = entries.FirstOrDefault();
            }

            table.Draw(entries);

            if (ScrollToEntry != null)
            {
                ScrollTo(ScrollToEntry);
                ScrollToEntry = null;
            }

            if (Widgets.ButtonText(RectRemoveButton, "EdB.PC.Panel.SelectedEquipment.Remove".Translate(), true, false, table.Selected != null))
            {
                SoundDefOf.Tick_High.PlayOneShotOnCamera();
                EquipmentRemoved(table.Selected);
                table.Selected = null;
            }
        }
        protected void ScrollTo(EquipmentRecord entry)
        {
            var equipment = GetEquipment();
            int count     = equipment.TakeWhile((EquipmentSelection e) => {
                return(e.Record.def != entry.def || e.Record.stuffDef != entry.stuffDef);
            }).Count();

            if (count < equipment.Count())
            {
                int index = count;

                float min       = table.ScrollView.Position.y;
                float max       = min + table.Rect.height;
                float rowTop    = (float)index * RectRow.height;
                float rowBottom = rowTop + RectRow.height;
                float pos       = (float)index * RectRow.height;
                if (rowTop < min)
                {
                    float amount = min - rowTop;
                    table.ScrollView.Position = new Vector2(table.ScrollView.Position.x, table.ScrollView.Position.y - amount);
                }
                else if (rowBottom > max)
                {
                    float amount = rowBottom - max;
                    table.ScrollView.Position = new Vector2(table.ScrollView.Position.x, table.ScrollView.Position.y + amount);
                }
            }
        }
        public void RemoveEquipment(EquipmentRecord entry)
        {
            EquipmentSelection e = Find(entry);

            if (e != null)
            {
                equipmentToRemove.Add(e);
            }
        }
 public static void Draw(Rect rect, EquipmentRecord entry)
 {
     if (entry.thing == null)
     {
         Draw(rect, entry.def, entry.color);
     }
     else
     {
         Draw(rect, entry.thing, entry.color);
     }
 }
 protected bool AddRecordIfNotThereAlready(EquipmentKey key, EquipmentRecord record)
 {
     if (entries.TryGetValue(key, out EquipmentRecord value))
     {
         return(false);
     }
     else
     {
         entries[key] = record;
         return(true);
     }
 }
 protected void AddThingDef(ThingDef def, EquipmentType type)
 {
     if (def.MadeFromStuff)
     {
         foreach (var s in stuff)
         {
             if (s.stuffProps.CanMake(def))
             {
                 EquipmentKey    key   = new EquipmentKey(def, s);
                 EquipmentRecord entry = CreateEquipmentEntry(def, s, type);
                 if (entry != null)
                 {
                     entries[key] = entry;
                 }
             }
         }
     }
     else if (def.race != null && def.race.Animal)
     {
         if (def.race.hasGenders)
         {
             EquipmentRecord femaleEntry = CreateEquipmentEntry(def, Gender.Female, type);
             if (femaleEntry != null)
             {
                 entries[new EquipmentKey(def, Gender.Female)] = femaleEntry;
             }
             EquipmentRecord maleEntry = CreateEquipmentEntry(def, Gender.Male, type);
             if (maleEntry != null)
             {
                 entries[new EquipmentKey(def, Gender.Male)] = maleEntry;
             }
         }
         else
         {
             EquipmentKey    key   = new EquipmentKey(def, Gender.None);
             EquipmentRecord entry = CreateEquipmentEntry(def, Gender.None, type);
             if (entry != null)
             {
                 entries[key] = entry;
             }
         }
     }
     else
     {
         EquipmentKey    key   = new EquipmentKey(def, null);
         EquipmentRecord entry = CreateEquipmentEntry(def, null, Gender.None, type);
         if (entry != null)
         {
             entries[key] = entry;
         }
     }
 }
 protected void AddThingDef(ThingDef def, EquipmentType type)
 {
     if (def.MadeFromStuff)
     {
         foreach (var s in stuff)
         {
             if (s.stuffProps.CanMake(def))
             {
                 EquipmentKey    key   = new EquipmentKey(def, s);
                 EquipmentRecord entry = CreateEquipmentRecord(def, s, type);
                 if (entry != null)
                 {
                     AddRecordIfNotThereAlready(key, entry);
                 }
             }
         }
     }
     else if (def.race != null && def.race.Animal)
     {
         if (def.race.hasGenders)
         {
             EquipmentRecord femaleEntry = CreateAnimalEquipmentRecord(def, Gender.Female);
             if (femaleEntry != null)
             {
                 AddRecordIfNotThereAlready(new EquipmentKey(def, Gender.Female), femaleEntry);
             }
             EquipmentRecord maleEntry = CreateAnimalEquipmentRecord(def, Gender.Male);
             if (maleEntry != null)
             {
                 AddRecordIfNotThereAlready(new EquipmentKey(def, Gender.Male), maleEntry);
             }
         }
         else
         {
             EquipmentKey    key   = new EquipmentKey(def, Gender.None);
             EquipmentRecord entry = CreateAnimalEquipmentRecord(def, Gender.None);
             if (entry != null)
             {
                 AddRecordIfNotThereAlready(key, entry);
             }
         }
     }
     else
     {
         EquipmentKey    key   = new EquipmentKey(def, null);
         EquipmentRecord entry = CreateEquipmentRecord(def, null, type);
         if (entry != null)
         {
             AddRecordIfNotThereAlready(key, entry);
         }
     }
 }
        public double CalculateEquipmentCost(EquipmentSelection equipment)
        {
            EquipmentRecord entry = PrepareCarefully.Instance.EquipmentDatabase[equipment.Key];

            if (entry != null)
            {
                return((double)equipment.Count * entry.cost);
            }
            else
            {
                return(0);
            }
        }
        public void EquipmentAdded(EquipmentRecord entry)
        {
            EquipmentSelection loadoutRecord = PrepareCarefully.Instance.Find(entry);

            if (loadoutRecord != null)
            {
                table.Selected = loadoutRecord;
                // Mark that we want to scroll to the newly added entry.  We can only scroll to it once
                // it's already been drawn once in the list, so we need to temporarily store a value that
                // we'll use on the next draw pass.
                ScrollToEntry = loadoutRecord.Record;
            }
        }
        protected EquipmentSelection FindEntry(EquipmentSelection equipment)
        {
            ThingDef        def   = equipment.ThingDef;
            EquipmentRecord entry = PrepareCarefully.Instance.EquipmentDatabase[equipment.Key];

            if (entry == null)
            {
                string thing = def != null ? def.defName : "null";
                string stuff = equipment.StuffDef != null ? equipment.StuffDef.defName : "null";
                Log.Warning(string.Format("Could not draw unrecognized resource/equipment.  Invalid item was removed.  This may have been caused by an invalid thing/stuff combination. (thing = {0}, stuff={1})", thing, stuff));
                PrepareCarefully.Instance.RemoveEquipment(equipment);
                return(null);
            }
            return(PrepareCarefully.Instance.Find(entry));
        }
        public bool AddEquipment(EquipmentRecord entry, int count)
        {
            SyncEquipmentRemovals();
            EquipmentSelection e = Find(entry);

            if (e == null)
            {
                equipment.Add(new EquipmentSelection(entry, count));
                return(true);
            }
            else
            {
                e.Count += count;
                return(false);
            }
        }
        public EquipmentRecord AddThingDefWithStuff(ThingDef def, ThingDef stuff, EquipmentType type)
        {
            if (type == null)
            {
                Logger.Warning("Could not add unclassified equipment: " + def);
                return(null);
            }
            EquipmentKey    key   = new EquipmentKey(def, stuff);
            EquipmentRecord entry = CreateEquipmentRecord(def, stuff, type);

            if (entry != null)
            {
                AddRecordIfNotThereAlready(key, entry);
            }
            return(entry);
        }
        public EquipmentRecord AddThingDefWithStuff(ThingDef def, ThingDef stuff, EquipmentType type)
        {
            if (type == null)
            {
                Log.Warning("Prepare Carefully could not add unclassified equipment: " + def);
                return(null);
            }
            EquipmentKey    key   = new EquipmentKey(def, stuff);
            EquipmentRecord entry = CreateEquipmentEntry(def, stuff, type);

            if (entry != null)
            {
                entries[key] = entry;
            }
            return(entry);
        }
Example #16
0
        public bool AddEquipment(EquipmentRecord entry)
        {
            if (entry == null)
            {
                return(false);
            }
            SyncEquipmentRemovals();
            EquipmentSelection e = Find(entry);

            if (e == null)
            {
                equipment.Add(new EquipmentSelection(entry));
                return(true);
            }
            else
            {
                e.Count += entry.stackSize;
                return(false);
            }
        }
Example #17
0
        public bool AddEquipment(EquipmentRecord record, int count)
        {
            if (record == null)
            {
                return(false);
            }
            SyncEquipmentRemovals();
            EquipmentSelection e = Find(record);

            if (e == null)
            {
                equipment.Add(new EquipmentSelection(record, count));
                return(true);
            }
            else
            {
                e.Count += count;
                return(false);
            }
        }
        protected EquipmentRecord CreateAnimalEquipmentRecord(ThingDef def, Gender gender)
        {
            if (def.BaseMarketValue == 0)
            {
                //Logger.Debug("Animal base market value was zero: " + def.defName);
                return(null);
            }
            EquipmentRecord result = new EquipmentRecord()
            {
                type      = TypeAnimals,
                def       = def,
                stuffDef  = null,
                stackSize = 1,
                stacks    = false,
                gear      = false,
                animal    = true,
                cost      = def.BaseMarketValue,
                gender    = gender
            };

            return(result);
        }
Example #19
0
        public bool Load(PrepareCarefully loadout, string presetName)
        {
            SaveRecordPresetV4 preset = new SaveRecordPresetV4();

            Failed = false;
            try {
                Scribe.loader.InitLoading(PresetFiles.FilePathForSavedPreset(presetName));
                preset.ExposeData();

                if (preset.equipment != null)
                {
                    List <EquipmentSelection> equipment = new List <EquipmentSelection>(preset.equipment.Count);
                    foreach (var e in preset.equipment)
                    {
                        ThingDef thingDef = DefDatabase <ThingDef> .GetNamedSilentFail(e.def);

                        if (thingDef == null)
                        {
                            string replacementDefName;
                            if (thingDefReplacements.TryGetValue(e.def, out replacementDefName))
                            {
                                thingDef = DefDatabase <ThingDef> .GetNamedSilentFail(replacementDefName);
                            }
                        }
                        ThingDef stuffDef = null;
                        Gender   gender   = Gender.None;
                        if (!string.IsNullOrEmpty(e.stuffDef))
                        {
                            stuffDef = DefDatabase <ThingDef> .GetNamedSilentFail(e.stuffDef);
                        }
                        if (!string.IsNullOrEmpty(e.gender))
                        {
                            try {
                                gender = (Gender)Enum.Parse(typeof(Gender), e.gender);
                            }
                            catch (Exception) {
                                Log.Warning("Failed to load gender value for animal.");
                                Failed = true;
                                continue;
                            }
                        }
                        if (thingDef != null)
                        {
                            if (string.IsNullOrEmpty(e.stuffDef))
                            {
                                EquipmentKey    key    = new EquipmentKey(thingDef, null, gender);
                                EquipmentRecord record = PrepareCarefully.Instance.EquipmentDatabase.LookupEquipmentRecord(key);
                                if (record != null)
                                {
                                    equipment.Add(new EquipmentSelection(record, e.count));
                                }
                                else
                                {
                                    Log.Warning("Could not find equipment in equipment database: " + key);
                                    Failed = true;
                                    continue;
                                }
                            }
                            else
                            {
                                if (stuffDef != null)
                                {
                                    EquipmentKey    key    = new EquipmentKey(thingDef, stuffDef, gender);
                                    EquipmentRecord record = PrepareCarefully.Instance.EquipmentDatabase.LookupEquipmentRecord(key);
                                    if (record == null)
                                    {
                                        string thing = thingDef != null ? thingDef.defName : "null";
                                        string stuff = stuffDef != null ? stuffDef.defName : "null";
                                        Log.Warning(string.Format("Could not load equipment/resource from the preset.  This may be caused by an invalid thing/stuff combination: " + key));
                                        Failed = true;
                                        continue;
                                    }
                                    else
                                    {
                                        equipment.Add(new EquipmentSelection(record, e.count));
                                    }
                                }
                                else
                                {
                                    Log.Warning("Could not load stuff definition \"" + e.stuffDef + "\" for item \"" + e.def + "\"");
                                    Failed = true;
                                }
                            }
                        }
                        else
                        {
                            Log.Warning("Could not load thing definition \"" + e.def + "\"");
                            Failed = true;
                        }
                    }
                    loadout.Equipment.Clear();
                    foreach (var e in equipment)
                    {
                        loadout.Equipment.Add(e);
                    }
                }
                else
                {
                    Messages.Message("EdB.PC.Dialog.Preset.Error.EquipmentFailed".Translate(), MessageTypeDefOf.ThreatBig);
                    Log.Warning("Failed to load equipment from preset");
                    Failed = true;
                }
            }
            catch (Exception e) {
                Log.Error("Failed to load preset file");
                throw e;
            }
            finally {
                // I don't fully understand how these cross-references and saveables are resolved, but
                // if we don't clear them out, we get null pointer exceptions.
                HashSet <IExposable> saveables = (HashSet <IExposable>)(typeof(PostLoadIniter).GetField("saveablesToPostLoad", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(Scribe.loader.initer));
                if (saveables != null)
                {
                    saveables.Clear();
                }
                List <IExposable> crossReferencingExposables = (List <IExposable>)(typeof(CrossRefHandler).GetField("crossReferencingExposables", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(Scribe.loader.crossRefs));
                if (crossReferencingExposables != null)
                {
                    crossReferencingExposables.Clear();
                }
                Scribe.loader.FinalizeLoading();
            }

            List <CustomPawn> allPawns            = new List <CustomPawn>();
            List <CustomPawn> colonistCustomPawns = new List <CustomPawn>();
            List <CustomPawn> hiddenCustomPawns   = new List <CustomPawn>();

            try {
                foreach (SaveRecordPawnV4 p in preset.pawns)
                {
                    CustomPawn pawn = LoadPawn(p);
                    if (pawn != null)
                    {
                        allPawns.Add(pawn);
                        if (!pawn.Hidden)
                        {
                            colonistCustomPawns.Add(pawn);
                        }
                        else
                        {
                            hiddenCustomPawns.Add(pawn);
                        }
                    }
                    else
                    {
                        Messages.Message("EdB.PC.Dialog.Preset.Error.NoCharacter".Translate(), MessageTypeDefOf.ThreatBig);
                        Log.Warning("Preset was created with the following mods: " + preset.mods);
                    }
                }
            }
            catch (Exception e) {
                Messages.Message("EdB.PC.Dialog.Preset.Error.Failed".Translate(), MessageTypeDefOf.ThreatBig);
                Log.Warning(e.ToString());
                Log.Warning("Preset was created with the following mods: " + preset.mods);
                return(false);
            }

            loadout.ClearPawns();
            foreach (CustomPawn p in colonistCustomPawns)
            {
                loadout.AddPawn(p);
            }
            loadout.RelationshipManager.Clear();
            loadout.RelationshipManager.InitializeWithCustomPawns(colonistCustomPawns.AsEnumerable().Concat(hiddenCustomPawns));

            bool atLeastOneRelationshipFailed          = false;
            List <CustomRelationship> allRelationships = new List <CustomRelationship>();

            if (preset.relationships != null)
            {
                try {
                    foreach (SaveRecordRelationshipV3 r in preset.relationships)
                    {
                        if (string.IsNullOrEmpty(r.source) || string.IsNullOrEmpty(r.target) || string.IsNullOrEmpty(r.relation))
                        {
                            atLeastOneRelationshipFailed = true;
                            Log.Warning("Prepare Carefully failed to load a custom relationship from the preset: " + r);
                            continue;
                        }
                        CustomRelationship relationship = LoadRelationship(r, allPawns);
                        if (relationship == null)
                        {
                            atLeastOneRelationshipFailed = true;
                            Log.Warning("Prepare Carefully failed to load a custom relationship from the preset: " + r);
                        }
                        else
                        {
                            allRelationships.Add(relationship);
                        }
                    }
                }
                catch (Exception e) {
                    Messages.Message("EdB.PC.Dialog.Preset.Error.RelationshipFailed".Translate(), MessageTypeDefOf.ThreatBig);
                    Log.Warning(e.ToString());
                    Log.Warning("Preset was created with the following mods: " + preset.mods);
                    return(false);
                }
                if (atLeastOneRelationshipFailed)
                {
                    Messages.Message("EdB.PC.Dialog.Preset.Error.RelationshipFailed".Translate(), MessageTypeDefOf.ThreatBig);
                }
            }
            loadout.RelationshipManager.AddRelationships(allRelationships);

            if (preset.parentChildGroups != null)
            {
                foreach (var groupRecord in preset.parentChildGroups)
                {
                    ParentChildGroup group = new ParentChildGroup();
                    if (groupRecord.parents != null)
                    {
                        foreach (var id in groupRecord.parents)
                        {
                            CustomPawn parent = FindPawnById(id, colonistCustomPawns, hiddenCustomPawns);
                            if (parent != null)
                            {
                                var pawn = parent;
                                if (pawn != null)
                                {
                                    group.Parents.Add(pawn);
                                }
                                else
                                {
                                    Log.Warning("Prepare Carefully could not load a custom parent relationship because it could not find a matching pawn in the relationship manager.");
                                }
                            }
                            else
                            {
                                Log.Warning("Prepare Carefully could not load a custom parent relationship because it could not find a pawn with the saved identifer.");
                            }
                        }
                    }
                    if (groupRecord.children != null)
                    {
                        foreach (var id in groupRecord.children)
                        {
                            CustomPawn child = FindPawnById(id, colonistCustomPawns, hiddenCustomPawns);
                            if (child != null)
                            {
                                var pawn = child;
                                if (pawn != null)
                                {
                                    group.Children.Add(pawn);
                                }
                                else
                                {
                                    Log.Warning("Prepare Carefully could not load a custom child relationship because it could not find a matching pawn in the relationship manager.");
                                }
                            }
                            else
                            {
                                Log.Warning("Prepare Carefully could not load a custom child relationship because it could not find a pawn with the saved identifer.");
                            }
                        }
                    }
                    loadout.RelationshipManager.ParentChildGroups.Add(group);
                }
            }
            loadout.RelationshipManager.ReassignHiddenPawnIndices();

            if (Failed)
            {
                Messages.Message(preset.mods, MessageTypeDefOf.SilentInput);
                Messages.Message("EdB.PC.Dialog.Preset.Error.ThingDefFailed".Translate(), MessageTypeDefOf.ThreatBig);
                Log.Warning("Preset was created with the following mods: " + preset.mods);
                return(false);
            }

            return(true);
        }
 public EquipmentSelection(EquipmentRecord entry, int count)
 {
     this.count = count;
     record     = entry;
 }
 public EquipmentSelection(EquipmentRecord entry)
 {
     count  = 1;
     record = entry;
 }
        public bool Load(PrepareCarefully loadout, string presetName)
        {
            List <SaveRecordPawnV3>             pawns              = new List <SaveRecordPawnV3>();
            List <SaveRecordPawnV3>             hiddenPawns        = new List <SaveRecordPawnV3>();
            List <SaveRecordRelationshipV3>     savedRelationships = new List <SaveRecordRelationshipV3>();
            List <SaveRecordParentChildGroupV3> parentChildGroups  = new List <SaveRecordParentChildGroupV3>();

            Failed = false;
            int  startingPoints = 0;
            bool usePoints      = false;

            try {
                Scribe.loader.InitLoading(PresetFiles.FilePathForSavedPreset(presetName));

                Scribe_Values.Look <bool>(ref usePoints, "usePoints", true, false);
                Scribe_Values.Look <int>(ref startingPoints, "startingPoints", 0, false);
                Scribe_Values.Look <string>(ref ModString, "mods", "", false);

                try {
                    Scribe_Collections.Look <SaveRecordPawnV3>(ref pawns, "colonists", LookMode.Deep, null);
                }
                catch (Exception e) {
                    Messages.Message("EdB.PC.Dialog.Preset.Error.Failed".Translate(), MessageTypeDefOf.ThreatBig);
                    Log.Warning(e.ToString());
                    Log.Warning("Preset was created with the following mods: " + ModString);
                    return(false);
                }

                try {
                    Scribe_Collections.Look <SaveRecordPawnV3>(ref hiddenPawns, "hiddenPawns", LookMode.Deep, null);
                }
                catch (Exception e) {
                    Messages.Message("EdB.PC.Dialog.Preset.Error.Failed".Translate(), MessageTypeDefOf.ThreatBig);
                    Log.Warning(e.ToString());
                    Log.Warning("Preset was created with the following mods: " + ModString);
                    return(false);
                }

                try {
                    Scribe_Collections.Look <SaveRecordRelationshipV3>(ref savedRelationships, "relationships", LookMode.Deep, null);
                }
                catch (Exception e) {
                    Messages.Message("EdB.PC.Dialog.Preset.Error.Failed".Translate(), MessageTypeDefOf.ThreatBig);
                    Log.Warning(e.ToString());
                    Log.Warning("Preset was created with the following mods: " + ModString);
                    return(false);
                }

                try {
                    Scribe_Collections.Look <SaveRecordParentChildGroupV3>(ref parentChildGroups, "parentChildGroups", LookMode.Deep, null);
                }
                catch (Exception e) {
                    Messages.Message("EdB.PC.Dialog.Preset.Error.Failed".Translate(), MessageTypeDefOf.ThreatBig);
                    Log.Warning(e.ToString());
                    Log.Warning("Preset was created with the following mods: " + ModString);
                    return(false);
                }

                List <SaveRecordEquipmentV3> tempEquipment = new List <SaveRecordEquipmentV3>();
                Scribe_Collections.Look <SaveRecordEquipmentV3>(ref tempEquipment, "equipment", LookMode.Deep, null);
                loadout.Equipment.Clear();
                if (tempEquipment != null)
                {
                    List <EquipmentSelection> equipment = new List <EquipmentSelection>(tempEquipment.Count);
                    foreach (var e in tempEquipment)
                    {
                        ThingDef thingDef = DefDatabase <ThingDef> .GetNamedSilentFail(e.def);

                        if (thingDef == null)
                        {
                            string replacementDefName;
                            if (thingDefReplacements.TryGetValue(e.def, out replacementDefName))
                            {
                                thingDef = DefDatabase <ThingDef> .GetNamedSilentFail(replacementDefName);
                            }
                        }
                        ThingDef stuffDef = null;
                        Gender   gender   = Gender.None;
                        if (!string.IsNullOrEmpty(e.stuffDef))
                        {
                            stuffDef = DefDatabase <ThingDef> .GetNamedSilentFail(e.stuffDef);
                        }
                        if (!string.IsNullOrEmpty(e.gender))
                        {
                            try {
                                gender = (Gender)Enum.Parse(typeof(Gender), e.gender);
                            }
                            catch (Exception) {
                                Log.Warning("Failed to load gender value for animal.");
                                Failed = true;
                                continue;
                            }
                        }
                        if (thingDef != null)
                        {
                            if (string.IsNullOrEmpty(e.stuffDef))
                            {
                                EquipmentKey    key    = new EquipmentKey(thingDef, null, gender);
                                EquipmentRecord record = PrepareCarefully.Instance.EquipmentDatabase.LookupEquipmentRecord(key);
                                if (record != null)
                                {
                                    equipment.Add(new EquipmentSelection(record, e.count));
                                }
                                else
                                {
                                    Log.Warning("Could not find equipment in equipment database: " + key);
                                    Failed = true;
                                    continue;
                                }
                            }
                            else
                            {
                                if (stuffDef != null)
                                {
                                    EquipmentKey    key    = new EquipmentKey(thingDef, stuffDef, gender);
                                    EquipmentRecord record = PrepareCarefully.Instance.EquipmentDatabase.LookupEquipmentRecord(key);
                                    if (record == null)
                                    {
                                        string thing = thingDef != null ? thingDef.defName : "null";
                                        string stuff = stuffDef != null ? stuffDef.defName : "null";
                                        Log.Warning(string.Format("Could not load equipment/resource from the preset.  This may be caused by an invalid thing/stuff combination: " + key));
                                        Failed = true;
                                        continue;
                                    }
                                    else
                                    {
                                        equipment.Add(new EquipmentSelection(record, e.count));
                                    }
                                }
                                else
                                {
                                    Log.Warning("Could not load stuff definition \"" + e.stuffDef + "\" for item \"" + e.def + "\"");
                                    Failed = true;
                                }
                            }
                        }
                        else
                        {
                            Log.Warning("Could not load thing definition \"" + e.def + "\"");
                            Failed = true;
                        }
                    }
                    loadout.Equipment.Clear();
                    foreach (var e in equipment)
                    {
                        loadout.Equipment.Add(e);
                    }
                }
                else
                {
                    Messages.Message("EdB.PC.Dialog.Preset.Error.EquipmentFailed".Translate(), MessageTypeDefOf.ThreatBig);
                    Log.Warning("Failed to load equipment from preset");
                    Failed = true;
                }

                //PrepareCarefully.Instance.Config.pointsEnabled = usePoints;
            }
            catch (Exception e) {
                Log.Error("Failed to load preset file");
                throw e;
            }
            finally {
                PresetLoader.ClearSaveablesAndCrossRefs();
            }

            List <CustomPawn> allPawns            = new List <CustomPawn>();
            List <CustomPawn> colonistCustomPawns = new List <CustomPawn>();

            try {
                foreach (SaveRecordPawnV3 p in pawns)
                {
                    CustomPawn pawn = LoadPawn(p);
                    if (pawn != null)
                    {
                        allPawns.Add(pawn);
                        colonistCustomPawns.Add(pawn);
                    }
                    else
                    {
                        Messages.Message("EdB.PC.Dialog.Preset.Error.NoCharacter".Translate(), MessageTypeDefOf.ThreatBig);
                        Log.Warning("Preset was created with the following mods: " + ModString);
                    }
                }
            }
            catch (Exception e) {
                Messages.Message("EdB.PC.Dialog.Preset.Error.Failed".Translate(), MessageTypeDefOf.ThreatBig);
                Log.Warning(e.ToString());
                Log.Warning("Preset was created with the following mods: " + ModString);
                return(false);
            }

            List <CustomPawn> hiddenCustomPawns = new List <CustomPawn>();

            try {
                if (hiddenPawns != null)
                {
                    foreach (SaveRecordPawnV3 p in hiddenPawns)
                    {
                        CustomPawn pawn = LoadPawn(p);
                        if (pawn != null)
                        {
                            allPawns.Add(pawn);
                            hiddenCustomPawns.Add(pawn);
                        }
                        else
                        {
                            Log.Warning("Prepare Carefully failed to load a hidden character from the preset");
                        }
                    }
                }
            }
            catch (Exception e) {
                Messages.Message("EdB.PC.Dialog.Preset.Error.Failed".Translate(), MessageTypeDefOf.ThreatBig);
                Log.Warning(e.ToString());
                Log.Warning("Preset was created with the following mods: " + ModString);
                return(false);
            }

            loadout.ClearPawns();
            foreach (CustomPawn p in colonistCustomPawns)
            {
                loadout.AddPawn(p);
            }
            loadout.RelationshipManager.Clear();
            loadout.RelationshipManager.InitializeWithCustomPawns(colonistCustomPawns.AsEnumerable().Concat(hiddenCustomPawns));

            bool atLeastOneRelationshipFailed          = false;
            List <CustomRelationship> allRelationships = new List <CustomRelationship>();

            if (savedRelationships != null)
            {
                try {
                    foreach (SaveRecordRelationshipV3 r in savedRelationships)
                    {
                        if (string.IsNullOrEmpty(r.source) || string.IsNullOrEmpty(r.target) || string.IsNullOrEmpty(r.relation))
                        {
                            atLeastOneRelationshipFailed = true;
                            Log.Warning("Prepare Carefully failed to load a custom relationship from the preset: " + r);
                            continue;
                        }
                        CustomRelationship relationship = LoadRelationship(r, allPawns);
                        if (relationship == null)
                        {
                            atLeastOneRelationshipFailed = true;
                            Log.Warning("Prepare Carefully failed to load a custom relationship from the preset: " + r);
                        }
                        else
                        {
                            allRelationships.Add(relationship);
                        }
                    }
                }
                catch (Exception e) {
                    Messages.Message("EdB.PC.Dialog.Preset.Error.RelationshipFailed".Translate(), MessageTypeDefOf.ThreatBig);
                    Log.Warning(e.ToString());
                    Log.Warning("Preset was created with the following mods: " + ModString);
                    return(false);
                }
                if (atLeastOneRelationshipFailed)
                {
                    Messages.Message("EdB.PC.Dialog.Preset.Error.RelationshipFailed".Translate(), MessageTypeDefOf.ThreatBig);
                }
            }
            loadout.RelationshipManager.AddRelationships(allRelationships);

            if (parentChildGroups != null)
            {
                foreach (var groupRecord in parentChildGroups)
                {
                    ParentChildGroup group = new ParentChildGroup();
                    if (groupRecord.parents != null)
                    {
                        foreach (var id in groupRecord.parents)
                        {
                            CustomPawn parent = FindPawnById(id, colonistCustomPawns, hiddenCustomPawns);
                            if (parent != null)
                            {
                                var pawn = parent;
                                if (pawn != null)
                                {
                                    group.Parents.Add(pawn);
                                }
                                else
                                {
                                    Log.Warning("Prepare Carefully could not load a custom parent relationship because it could not find a matching pawn in the relationship manager.");
                                }
                            }
                            else
                            {
                                Log.Warning("Prepare Carefully could not load a custom parent relationship because it could not find a pawn with the saved identifer.");
                            }
                        }
                    }
                    if (groupRecord.children != null)
                    {
                        foreach (var id in groupRecord.children)
                        {
                            CustomPawn child = FindPawnById(id, colonistCustomPawns, hiddenCustomPawns);
                            if (child != null)
                            {
                                var pawn = child;
                                if (pawn != null)
                                {
                                    group.Children.Add(pawn);
                                }
                                else
                                {
                                    Log.Warning("Prepare Carefully could not load a custom child relationship because it could not find a matching pawn in the relationship manager.");
                                }
                            }
                            else
                            {
                                Log.Warning("Prepare Carefully could not load a custom child relationship because it could not find a pawn with the saved identifer.");
                            }
                        }
                    }
                    loadout.RelationshipManager.ParentChildGroups.Add(group);
                }
            }
            loadout.RelationshipManager.ReassignHiddenPawnIndices();

            if (Failed)
            {
                Messages.Message(ModString, MessageTypeDefOf.SilentInput);
                Messages.Message("EdB.PC.Dialog.Preset.Error.ThingDefFailed".Translate(), MessageTypeDefOf.ThreatBig);
                Log.Warning("Preset was created with the following mods: " + ModString);
                return(false);
            }

            return(true);
        }
        protected EquipmentRecord CreateEquipmentRecord(ThingDef def, ThingDef stuffDef, EquipmentType type)
        {
            double baseCost = costs.GetBaseThingCost(def, stuffDef);

            if (baseCost == 0)
            {
                return(null);
            }
            int             stackSize = CalculateStackCount(def, baseCost);
            EquipmentRecord result    = new EquipmentRecord();

            result.type      = type;
            result.def       = def;
            result.stuffDef  = stuffDef;
            result.stackSize = stackSize;
            result.cost      = costs.CalculateStackCost(def, stuffDef, baseCost);
            result.stacks    = true;
            result.gear      = false;
            result.animal    = false;
            if (def.MadeFromStuff && stuffDef != null)
            {
                if (stuffDef.stuffProps.allowColorGenerators && (def.colorGenerator != null || def.colorGeneratorInTraderStock != null))
                {
                    if (def.colorGenerator != null)
                    {
                        result.color = def.colorGenerator.NewRandomizedColor();
                    }
                    else if (def.colorGeneratorInTraderStock != null)
                    {
                        result.color = def.colorGeneratorInTraderStock.NewRandomizedColor();
                    }
                }
                else
                {
                    result.color = stuffDef.stuffProps.color;
                }
            }
            else
            {
                if (def.graphicData != null)
                {
                    result.color = def.graphicData.color;
                }
                else
                {
                    result.color = Color.white;
                }
            }
            if (def.apparel != null)
            {
                result.stacks = false;
                result.gear   = true;
            }
            if (def.weaponTags != null && def.weaponTags.Count > 0)
            {
                result.stacks = false;
                result.gear   = true;
            }

            if (def.thingCategories != null)
            {
                if (def.thingCategories.SingleOrDefault((ThingCategoryDef d) => {
                    return(d.defName == "FoodMeals");
                }) != null)
                {
                    result.gear = true;
                }
                if (def.thingCategories.SingleOrDefault((ThingCategoryDef d) => {
                    return(d.defName == "Medicine");
                }) != null)
                {
                    result.gear = true;
                }
            }

            if (def.defName == "Apparel_PersonalShield")
            {
                result.hideFromPortrait = true;
            }

            return(result);
        }
Example #24
0
        protected void InitializeDefaultEquipment()
        {
            // Go through all of the scenario steps that scatter resources near the player starting location and add
            // them to the resource/equipment list.
            foreach (ScenPart part in Verse.Find.Scenario.AllParts)
            {
                ScenPart_ScatterThingsNearPlayerStart nearPlayerStart = part as ScenPart_ScatterThingsNearPlayerStart;
                if (nearPlayerStart != null)
                {
                    FieldInfo thingDefField = typeof(ScenPart_ScatterThingsNearPlayerStart).GetField("thingDef", BindingFlags.Instance | BindingFlags.NonPublic);
                    FieldInfo stuffDefField = typeof(ScenPart_ScatterThingsNearPlayerStart).GetField("stuff", BindingFlags.Instance | BindingFlags.NonPublic);
                    FieldInfo countField    = typeof(ScenPart_ScatterThingsNearPlayerStart).GetField("count", BindingFlags.Instance | BindingFlags.NonPublic);
                    ThingDef  thingDef      = (ThingDef)thingDefField.GetValue(nearPlayerStart);
                    ThingDef  stuffDef      = (ThingDef)stuffDefField.GetValue(nearPlayerStart);
                    equipmentDatabase.PreloadDefinition(stuffDef);
                    equipmentDatabase.PreloadDefinition(thingDef);
                    int             count  = (int)countField.GetValue(nearPlayerStart);
                    EquipmentKey    key    = new EquipmentKey(thingDef, stuffDef);
                    EquipmentRecord record = equipmentDatabase.LookupEquipmentRecord(key);
                    if (record == null)
                    {
                        Logger.Warning("Couldn't initialize all scenario equipment.  Didn't find an equipment entry for " + thingDef.defName);
                        record = AddNonStandardScenarioEquipmentEntry(key);
                    }
                    if (record != null)
                    {
                        AddEquipment(record, count);
                    }
                }

                // Go through all of the scenario steps that place starting equipment with the colonists and
                // add them to the resource/equipment list.
                ScenPart_StartingThing_Defined startingThing = part as ScenPart_StartingThing_Defined;
                if (startingThing != null)
                {
                    FieldInfo thingDefField = typeof(ScenPart_StartingThing_Defined).GetField("thingDef", BindingFlags.Instance | BindingFlags.NonPublic);
                    FieldInfo stuffDefField = typeof(ScenPart_StartingThing_Defined).GetField("stuff", BindingFlags.Instance | BindingFlags.NonPublic);
                    FieldInfo countField    = typeof(ScenPart_StartingThing_Defined).GetField("count", BindingFlags.Instance | BindingFlags.NonPublic);
                    ThingDef  thingDef      = (ThingDef)thingDefField.GetValue(startingThing);
                    ThingDef  stuffDef      = (ThingDef)stuffDefField.GetValue(startingThing);
                    equipmentDatabase.PreloadDefinition(stuffDef);
                    equipmentDatabase.PreloadDefinition(thingDef);
                    int             count = (int)countField.GetValue(startingThing);
                    EquipmentKey    key   = new EquipmentKey(thingDef, stuffDef);
                    EquipmentRecord entry = equipmentDatabase.LookupEquipmentRecord(key);
                    if (entry == null)
                    {
                        Logger.Warning("Couldn't initialize all scenario equipment.  Didn't find an equipment entry for " + thingDef.defName);
                        entry = AddNonStandardScenarioEquipmentEntry(key);
                    }
                    if (entry != null)
                    {
                        AddEquipment(entry, count);
                    }
                }

                // Go through all of the scenario steps that spawn a pet and add the pet to the equipment/resource
                // list.
                ScenPart_StartingAnimal animal = part as ScenPart_StartingAnimal;
                if (animal != null)
                {
                    FieldInfo animalCountField = typeof(ScenPart_StartingAnimal).GetField("count", BindingFlags.Instance | BindingFlags.NonPublic);
                    int       count            = (int)animalCountField.GetValue(animal);
                    for (int i = 0; i < count; i++)
                    {
                        PawnKindDef animalKindDef = RandomPet(animal);
                        equipmentDatabase.PreloadDefinition(animalKindDef.race);

                        List <EquipmentRecord> entries = PrepareCarefully.Instance.EquipmentDatabase.Animals.FindAll((EquipmentRecord e) => {
                            return(e.def == animalKindDef.race);
                        });
                        EquipmentRecord entry = null;
                        if (entries.Count > 0)
                        {
                            entry = entries.RandomElement();
                        }
                        if (entry != null)
                        {
                            AddEquipment(entry);
                        }
                        else
                        {
                            Logger.Warning("Failed to add the expected scenario animal to list of selected equipment");
                        }
                    }
                }
            }
        }
        protected EquipmentRecord CreateEquipmentEntry(ThingDef def, ThingDef stuffDef, Gender gender, EquipmentType type)
        {
            double baseCost = costs.GetBaseThingCost(def, stuffDef);

            if (baseCost == 0)
            {
                return(null);
            }
            int stackSize = CalculateStackCount(def, baseCost);

            EquipmentRecord result = new EquipmentRecord();

            result.type      = type;
            result.def       = def;
            result.stuffDef  = stuffDef;
            result.stackSize = stackSize;
            result.cost      = costs.CalculateStackCost(def, stuffDef, baseCost);
            result.stacks    = true;
            result.gear      = false;
            result.animal    = false;
            if (def.MadeFromStuff && stuffDef != null)
            {
                if (stuffDef.stuffProps.allowColorGenerators && (def.colorGenerator != null || def.colorGeneratorInTraderStock != null))
                {
                    if (def.colorGenerator != null)
                    {
                        result.color = def.colorGenerator.NewRandomizedColor();
                    }
                    else if (def.colorGeneratorInTraderStock != null)
                    {
                        result.color = def.colorGeneratorInTraderStock.NewRandomizedColor();
                    }
                }
                else
                {
                    result.color = stuffDef.stuffProps.color;
                }
            }
            else
            {
                if (def.graphicData != null)
                {
                    result.color = def.graphicData.color;
                }
                else
                {
                    result.color = Color.white;
                }
            }
            if (def.apparel != null)
            {
                result.stacks = false;
                result.gear   = true;
            }
            if (def.weaponTags != null && def.weaponTags.Count > 0)
            {
                result.stacks = false;
                result.gear   = true;
            }

            if (def.thingCategories != null)
            {
                if (def.thingCategories.SingleOrDefault((ThingCategoryDef d) => {
                    return(d.defName == "FoodMeals");
                }) != null)
                {
                    result.gear = true;
                }
                if (def.thingCategories.SingleOrDefault((ThingCategoryDef d) => {
                    return(d.defName == "Medicine");
                }) != null)
                {
                    result.gear = true;
                }
            }

            if (def.defName == "Apparel_PersonalShield")
            {
                result.hideFromPortrait = true;
            }

            if (def.race != null && def.race.Animal)
            {
                result.animal = true;
                result.gender = gender;
                try {
                    Pawn pawn = CreatePawn(def, stuffDef, gender);
                    if (pawn == null)
                    {
                        return(null);
                    }
                    else
                    {
                        result.thing = pawn;
                    }
                }
                catch (Exception e) {
                    Log.Warning("Prepare Carefully failed to create a pawn for animal equipment entry: " + def.defName);
                    Log.Message("  Exception message: " + e);
                    return(null);
                }
            }

            return(result);
        }
 public void AddEquipment(EquipmentRecord entry)
 {
     PrepareCarefully.Instance.AddEquipment(entry);
 }
        protected void InitializeDefaultEquipment()
        {
            // Go through all of the scenario steps that scatter resources near the player starting location and add
            // them to the resource/equipment list.
            foreach (ScenPart part in Verse.Find.Scenario.AllParts)
            {
                ScenPart_ScatterThingsNearPlayerStart nearPlayerStart = part as ScenPart_ScatterThingsNearPlayerStart;
                if (nearPlayerStart != null)
                {
                    FieldInfo       thingDefField = typeof(ScenPart_ScatterThingsNearPlayerStart).GetField("thingDef", BindingFlags.Instance | BindingFlags.NonPublic);
                    FieldInfo       stuffDefField = typeof(ScenPart_ScatterThingsNearPlayerStart).GetField("stuff", BindingFlags.Instance | BindingFlags.NonPublic);
                    FieldInfo       countField    = typeof(ScenPart_ScatterThingsNearPlayerStart).GetField("count", BindingFlags.Instance | BindingFlags.NonPublic);
                    ThingDef        thingDef      = (ThingDef)thingDefField.GetValue(nearPlayerStart);
                    ThingDef        stuffDef      = (ThingDef)stuffDefField.GetValue(nearPlayerStart);
                    int             count         = (int)countField.GetValue(nearPlayerStart);
                    EquipmentKey    key           = new EquipmentKey(thingDef, stuffDef);
                    EquipmentRecord entry         = equipmentDatabase[key];
                    if (entry == null)
                    {
                        entry = AddNonStandardScenarioEquipmentEntry(key);
                    }
                    if (entry != null)
                    {
                        AddEquipment(entry, count);
                    }
                }

                // Go through all of the scenario steps that place starting equipment with the colonists and
                // add them to the resource/equipment list.
                ScenPart_StartingThing_Defined startingThing = part as ScenPart_StartingThing_Defined;
                if (startingThing != null)
                {
                    FieldInfo       thingDefField = typeof(ScenPart_StartingThing_Defined).GetField("thingDef", BindingFlags.Instance | BindingFlags.NonPublic);
                    FieldInfo       stuffDefField = typeof(ScenPart_StartingThing_Defined).GetField("stuff", BindingFlags.Instance | BindingFlags.NonPublic);
                    FieldInfo       countField    = typeof(ScenPart_StartingThing_Defined).GetField("count", BindingFlags.Instance | BindingFlags.NonPublic);
                    ThingDef        thingDef      = (ThingDef)thingDefField.GetValue(startingThing);
                    ThingDef        stuffDef      = (ThingDef)stuffDefField.GetValue(startingThing);
                    int             count         = (int)countField.GetValue(startingThing);
                    EquipmentKey    key           = new EquipmentKey(thingDef, stuffDef);
                    EquipmentRecord entry         = equipmentDatabase[key];
                    if (entry == null)
                    {
                        entry = AddNonStandardScenarioEquipmentEntry(key);
                    }
                    if (entry != null)
                    {
                        AddEquipment(entry, count);
                    }
                }

                // Go through all of the scenario steps that spawn a pet and add the pet to the pets list.

                /*
                 * ScenPart_StartingAnimal animal = part as ScenPart_StartingAnimal;
                 * if (animal != null) {
                 *  FieldInfo animalCountField = typeof(ScenPart_StartingAnimal).GetField("count", BindingFlags.Instance | BindingFlags.NonPublic);
                 *  int count = (int)animalCountField.GetValue(animal);
                 *  for (int i = 0; i < count; i++) {
                 *      SelectedPet pet = RandomPet(animal);
                 *      if (pet != null) {
                 *          AddPet(pet);
                 *      }
                 *  }
                 * }
                 */

                // Go through all of the scenario steps that spawn a pet and add the pet to the equipment/resource
                // list.
                ScenPart_StartingAnimal animal = part as ScenPart_StartingAnimal;
                if (animal != null)
                {
                    FieldInfo animalCountField = typeof(ScenPart_StartingAnimal).GetField("count", BindingFlags.Instance | BindingFlags.NonPublic);
                    int       count            = (int)animalCountField.GetValue(animal);
                    for (int i = 0; i < count; i++)
                    {
                        AddEquipment(RandomPet(animal));
                    }
                }
            }
        }
        public void CalculatePawnCost(ColonistCostDetails cost, CustomPawn pawn)
        {
            cost.Clear();
            cost.name = pawn.NickName;

            // Start with the market value plus a bit of a mark-up.
            cost.marketValue  = pawn.Pawn.MarketValue;
            cost.marketValue += 300;

            // Calculate passion cost.  Each passion above 8 makes all passions
            // cost more.  Minor passion counts as one passion.  Major passion
            // counts as 3.
            double skillCount           = pawn.currentPassions.Keys.Count();
            double passionLevelCount    = 0;
            double passionLevelCost     = 20;
            double passionateSkillCount = 0;

            foreach (SkillDef def in pawn.currentPassions.Keys)
            {
                Passion passion = pawn.currentPassions[def];
                int     level   = pawn.GetSkillLevel(def);

                if (passion == Passion.Major)
                {
                    passionLevelCount    += 3.0;
                    passionateSkillCount += 1.0;
                }
                else if (passion == Passion.Minor)
                {
                    passionLevelCount    += 1.0;
                    passionateSkillCount += 1.0;
                }
            }
            double levelCost = passionLevelCost;

            if (passionLevelCount > 8)
            {
                double penalty = passionLevelCount - 8;
                levelCost += penalty * 0.4;
            }
            cost.marketValue += levelCost * passionLevelCount;

            // Calculate trait cost.
            if (pawn.TraitCount > Constraints.MaxVanillaTraits)
            {
                int    extraTraitCount = pawn.TraitCount - Constraints.MaxVanillaTraits;
                double extraTraitCost  = 100;
                for (int i = 0; i < extraTraitCount; i++)
                {
                    cost.marketValue += extraTraitCost;
                    extraTraitCost    = Math.Ceiling(extraTraitCost * 2.5);
                }
            }

            // Calculate cost of worn apparel.
            for (int layer = 0; layer < PawnLayers.Count; layer++)
            {
                if (PawnLayers.IsApparelLayer(layer))
                {
                    var def = pawn.GetAcceptedApparel(layer);
                    if (def == null)
                    {
                        continue;
                    }
                    EquipmentKey key = new EquipmentKey();
                    key.ThingDef = def;
                    key.StuffDef = pawn.GetSelectedStuff(layer);
                    EquipmentRecord record = PrepareCarefully.Instance.EquipmentDatabase.Find(key);
                    if (record == null)
                    {
                        continue;
                    }
                    EquipmentSelection selection = new EquipmentSelection(record, 1);
                    double             c         = CalculateEquipmentCost(selection);
                    if (def != null)
                    {
                        // TODO: Discounted materials should be based on the faction, not hard-coded.
                        // TODO: Should we continue with the discounting?
                        if (key.StuffDef != null)
                        {
                            if (key.StuffDef.defName == "Synthread")
                            {
                                if (freeApparel.Contains(key.ThingDef.defName))
                                {
                                    c = 0;
                                }
                                else if (cheapApparel.Contains(key.ThingDef.defName))
                                {
                                    c = c * 0.15d;
                                }
                            }
                        }
                    }
                    cost.apparel += c;
                }
            }

            // Calculate cost for any materials needed for implants.
            OptionsHealth healthOptions = PrepareCarefully.Instance.Providers.Health.GetOptions(pawn);

            foreach (Implant option in pawn.Implants)
            {
                // Check if there are any ancestor parts that override the selection.
                UniqueBodyPart uniquePart = healthOptions.FindBodyPartsForRecord(option.BodyPartRecord);
                if (uniquePart == null)
                {
                    Log.Warning("Prepare Carefully could not find body part record when computing the cost of an implant: " + option.BodyPartRecord.def.defName);
                    continue;
                }
                if (pawn.AtLeastOneImplantedPart(uniquePart.Ancestors.Select((UniqueBodyPart p) => { return(p.Record); })))
                {
                    continue;
                }

                //  Figure out the cost of the part replacement based on its recipe's ingredients.
                if (option.recipe != null)
                {
                    RecipeDef def = option.recipe;
                    foreach (IngredientCount amount in def.ingredients)
                    {
                        int    count     = 0;
                        double totalCost = 0;
                        bool   skip      = false;
                        foreach (ThingDef ingredientDef in amount.filter.AllowedThingDefs)
                        {
                            if (ingredientDef == ThingDefOf.Medicine)
                            {
                                skip = true;
                                break;
                            }
                            count++;
                            EquipmentRecord entry = PrepareCarefully.Instance.EquipmentDatabase[new EquipmentKey(ingredientDef, null)];
                            if (entry != null)
                            {
                                totalCost += entry.cost * (double)amount.GetBaseCount();
                            }
                        }
                        if (skip || count == 0)
                        {
                            continue;
                        }
                        cost.bionics += (int)(totalCost / (double)count);
                    }
                }
            }

            cost.apparel = Math.Ceiling(cost.apparel);
            cost.bionics = Math.Ceiling(cost.bionics);

            // Use a multiplier to balance pawn cost vs. equipment cost.
            // Disabled for now.
            cost.Multiply(1.0);

            cost.ComputeTotal();
        }
 public EquipmentSelection Find(EquipmentRecord entry)
 {
     return(equipment.Find((EquipmentSelection e) => {
         return e.Record == entry;
     }));
 }
 public static void Draw(Rect rect, EquipmentRecord entry)
 {
     Draw(rect, entry.def, entry.color);
 }