Beispiel #1
0
 public static T ItemFromXmlString <T>(string xmlContent, string filePath, bool resolveCrossRefs = true) where T : new()
 {
     if (resolveCrossRefs && DirectXmlCrossRefLoader.LoadingInProgress)
     {
         Log.Error("Cannot call ItemFromXmlString with resolveCrossRefs=true while loading is already in progress (forgot to resolve or clear cross refs from previous loading?).");
     }
     try
     {
         XmlDocument xmlDocument = new XmlDocument();
         xmlDocument.LoadXml(xmlContent);
         T result = DirectXmlToObject.ObjectFromXml <T>(xmlDocument.DocumentElement, doPostLoad: false);
         if (resolveCrossRefs)
         {
             try
             {
                 DirectXmlCrossRefLoader.ResolveAllWantedCrossReferences(FailMode.LogErrors);
             }
             finally
             {
                 DirectXmlCrossRefLoader.Clear();
             }
         }
         return(result);
     }
     catch (Exception ex)
     {
         Log.Error("Exception loading file at " + filePath + ". Loading defaults instead. Exception was: " + ex.ToString());
         return(new T());
     }
 }
        public static T ItemFromXmlFile <T>(string filePath, bool resolveCrossRefs = true) where T : new()
        {
            if (resolveCrossRefs && DirectXmlCrossRefLoader.LoadingInProgress)
            {
                Log.Error("Cannot call ItemFromXmlFile with resolveCrossRefs=true while loading is already in progress.");
            }
            FileInfo fileInfo = new FileInfo(filePath);

            if (!fileInfo.Exists)
            {
                return(Activator.CreateInstance <T>());
            }
            T result;

            try
            {
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.LoadXml(File.ReadAllText(fileInfo.FullName));
                T t = DirectXmlToObject.ObjectFromXml <T>(xmlDocument.DocumentElement, false);
                if (resolveCrossRefs)
                {
                    DirectXmlCrossRefLoader.ResolveAllWantedCrossReferences(FailMode.LogErrors);
                }
                result = t;
            }
            catch (Exception ex)
            {
                Log.Error("Exception loading file at " + filePath + ". Loading defaults instead. Exception was: " + ex.ToString());
                result = Activator.CreateInstance <T>();
            }
            return(result);
        }
Beispiel #3
0
        private static List <T> ListFromXml <T>(XmlNode listRootNode) where T : new()
        {
            List <T> list = new List <T>();

            try
            {
                bool flag = typeof(Def).IsAssignableFrom(typeof(T));
                foreach (XmlNode xmlNode in listRootNode.ChildNodes)
                {
                    if (DirectXmlToObject.ValidateListNode(xmlNode, listRootNode, typeof(T)))
                    {
                        if (flag)
                        {
                            DirectXmlCrossRefLoader.RegisterListWantsCrossRef <T>(list, xmlNode.InnerText);
                        }
                        else
                        {
                            list.Add(DirectXmlToObject.ObjectFromXml <T>(xmlNode, true));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(string.Concat(new object[]
                {
                    "Exception loading list from XML: ",
                    ex,
                    "\nXML:\n",
                    listRootNode.OuterXml
                }));
            }
            return(list);
        }
Beispiel #4
0
 public void LoadDataFromXmlCustom(XmlNode xmlRoot)
 {
     if (xmlRoot.ChildNodes.Count != 1)
     {
         Log.Error("Misconfigured SkillGain: " + xmlRoot.OuterXml, false);
         return;
     }
     DirectXmlCrossRefLoader.RegisterObjectWantsCrossRef(this, "skill", xmlRoot.Name);
     this.xp = (int)ParseHelper.FromString(xmlRoot.FirstChild.Value, typeof(int));
 }
 public void LoadDataFromXmlCustom(XmlNode xmlRoot)
 {
     if (xmlRoot.ChildNodes.Count != 1)
     {
         Log.Error("Misconfigured ThingDefCountClass: " + xmlRoot.OuterXml);
         return;
     }
     DirectXmlCrossRefLoader.RegisterObjectWantsCrossRef(this, "thingDef", xmlRoot.Name);
     count = ParseHelper.FromString <int>(xmlRoot.FirstChild.Value);
 }
Beispiel #6
0
 public void LoadDataFromXmlCustom(XmlNode xmlRoot)
 {
     if (xmlRoot.ChildNodes.Count != 1)
     {
         Log.Error("Misconfigured ThingOption: " + xmlRoot.OuterXml);
         return;
     }
     DirectXmlCrossRefLoader.RegisterObjectWantsCrossRef(this, "thingDef", xmlRoot.Name);
     this.weight = (float)ParseHelper.FromString(xmlRoot.FirstChild.Value, typeof(float));
 }
 public void LoadDataFromXmlCustom(XmlNode xmlRoot)
 {
     if (xmlRoot.ChildNodes.Count != 1)
     {
         Log.Error("Misconfigured ThingDefCountRangeClass: " + xmlRoot.OuterXml, false);
         return;
     }
     DirectXmlCrossRefLoader.RegisterObjectWantsCrossRef(this, "thingDef", xmlRoot.Name);
     this.countRange = (IntRange)ParseHelper.FromString(xmlRoot.FirstChild.Value, typeof(IntRange));
 }
 public static void LoadAllPlayData(bool recovering = false)
 {
     if (PlayDataLoader.loadedInt)
     {
         Log.Error("Loading play data when already loaded. Call ClearAllPlayData first.");
     }
     else
     {
         DeepProfiler.Start("LoadAllPlayData");
         try
         {
             PlayDataLoader.DoPlayLoad();
         }
         catch (Exception arg)
         {
             if (!Prefs.ResetModsConfigOnCrash)
             {
                 throw;
             }
             if (recovering)
             {
                 Log.Warning("Could not recover from errors loading play data. Giving up.");
                 throw;
             }
             IEnumerable <ModMetaData> activeModsInLoadOrder = ModsConfig.ActiveModsInLoadOrder;
             if (activeModsInLoadOrder.Count() == 1 && activeModsInLoadOrder.First().IsCoreMod)
             {
                 throw;
             }
             Log.Warning("Caught exception while loading play data but there are active mods other than Core. Resetting mods config and trying again.\nThe exception was: " + arg);
             try
             {
                 PlayDataLoader.ClearAllPlayData();
             }
             catch
             {
                 Log.Warning("Caught exception while recovering from errors and trying to clear all play data. Ignoring it.\nThe exception was: " + arg);
             }
             ModsConfig.Reset();
             DirectXmlCrossRefLoader.Clear();
             PlayDataLoader.LoadAllPlayData(true);
             return;
         }
         finally
         {
             DeepProfiler.End();
         }
         PlayDataLoader.loadedInt = true;
         if (recovering)
         {
             Log.Message("Successfully recovered from errors and loaded play data.");
             DelayedErrorWindowRequest.Add("RecoveredFromErrorsText".Translate(), "RecoveredFromErrorsDialogTitle".Translate());
         }
     }
 }
            public override bool TryResolve(FailMode failReportMode)
            {
                failReportMode = FailMode.LogErrors;
                bool flag  = typeof(Def).IsAssignableFrom(typeof(K));
                bool flag2 = typeof(Def).IsAssignableFrom(typeof(V));
                List <Pair <K, V> > list = new List <Pair <K, V> >();

                foreach (XmlNode xmlNode in this.wantedDictRefs)
                {
                    XmlNode xmlNode2 = xmlNode["key"];
                    XmlNode xmlNode3 = xmlNode["value"];
                    K       first;
                    if (flag)
                    {
                        first = DirectXmlCrossRefLoader.TryResolveDef <K>(xmlNode2.InnerText, failReportMode, this.debugWanterInfo);
                    }
                    else
                    {
                        first = DirectXmlToObject.ObjectFromXml <K>(xmlNode2, true);
                    }
                    V second;
                    if (flag2)
                    {
                        second = DirectXmlCrossRefLoader.TryResolveDef <V>(xmlNode3.InnerText, failReportMode, this.debugWanterInfo);
                    }
                    else
                    {
                        second = DirectXmlToObject.ObjectFromXml <V>(xmlNode3, true);
                    }
                    list.Add(new Pair <K, V>(first, second));
                }
                Dictionary <K, V> dictionary = (Dictionary <K, V>) this.wanter;

                dictionary.Clear();
                foreach (Pair <K, V> pair in list)
                {
                    try
                    {
                        dictionary.Add(pair.First, pair.Second);
                    }
                    catch
                    {
                        Log.Error(string.Concat(new object[]
                        {
                            "Failed to load key/value pair: ",
                            pair.First,
                            ", ",
                            pair.Second
                        }), false);
                    }
                }
                return(true);
            }
        private static List <T> ListFromXml <T>(XmlNode listRootNode) where T : new()
        {
            List <T> list = new List <T>();

            try
            {
                bool        flag       = typeof(Def).IsAssignableFrom(typeof(T));
                IEnumerator enumerator = listRootNode.ChildNodes.GetEnumerator();
                try
                {
                    while (enumerator.MoveNext())
                    {
                        object  obj     = enumerator.Current;
                        XmlNode xmlNode = (XmlNode)obj;
                        if (DirectXmlToObject.ValidateListNode(xmlNode, listRootNode, typeof(T)))
                        {
                            if (flag)
                            {
                                DirectXmlCrossRefLoader.RegisterListWantsCrossRef <T>(list, xmlNode.InnerText, listRootNode.Name);
                            }
                            else
                            {
                                list.Add(DirectXmlToObject.ObjectFromXml <T>(xmlNode, true));
                            }
                        }
                    }
                }
                finally
                {
                    IDisposable disposable;
                    if ((disposable = (enumerator as IDisposable)) != null)
                    {
                        disposable.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(string.Concat(new object[]
                {
                    "Exception loading list from XML: ",
                    ex,
                    "\nXML:\n",
                    listRootNode.OuterXml
                }), false);
            }
            return(list);
        }
Beispiel #11
0
        public void LoadDataFromXmlCustom(XmlNode xmlRoot)
        {
            if (xmlRoot.ChildNodes.Count != 1)
            {
                Log.Error("Misconfigured DefHyperlink: " + xmlRoot.OuterXml);
                return;
            }
            Type typeInAnyAssembly = GenTypes.GetTypeInAnyAssembly(xmlRoot.Name);

            if (typeInAnyAssembly == null)
            {
                Log.Error("Misconfigured DefHyperlink. Could not find def of type " + xmlRoot.Name);
            }
            else
            {
                DirectXmlCrossRefLoader.RegisterObjectWantsCrossRef(this, "def", xmlRoot.FirstChild.Value, null, typeInAnyAssembly);
            }
        }
Beispiel #12
0
        private static Dictionary <K, V> DictionaryFromXml <K, V>(XmlNode dictRootNode) where K : new() where V : new()
        {
            Dictionary <K, V> dictionary = new Dictionary <K, V>();

            try
            {
                bool flag  = typeof(Def).IsAssignableFrom(typeof(K));
                bool flag2 = typeof(Def).IsAssignableFrom(typeof(V));
                if (!flag && !flag2)
                {
                    foreach (XmlNode xmlNode in dictRootNode.ChildNodes)
                    {
                        if (DirectXmlToObject.ValidateListNode(xmlNode, dictRootNode, typeof(KeyValuePair <K, V>)))
                        {
                            K key   = DirectXmlToObject.ObjectFromXml <K>(xmlNode["key"], true);
                            V value = DirectXmlToObject.ObjectFromXml <V>(xmlNode["value"], true);
                            dictionary.Add(key, value);
                        }
                    }
                }
                else
                {
                    foreach (XmlNode xmlNode2 in dictRootNode.ChildNodes)
                    {
                        if (DirectXmlToObject.ValidateListNode(xmlNode2, dictRootNode, typeof(KeyValuePair <K, V>)))
                        {
                            DirectXmlCrossRefLoader.RegisterDictionaryWantsCrossRef <K, V>(dictionary, xmlNode2);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(string.Concat(new object[]
                {
                    "Malformed dictionary XML. Node: ",
                    dictRootNode.OuterXml,
                    ".\n\nException: ",
                    ex
                }));
            }
            return(dictionary);
        }
Beispiel #13
0
        private static List <T> ListFromXml <T>(XmlNode listRootNode) where T : new()
        {
            List <T> list = new List <T>();

            try
            {
                bool        flag       = typeof(Def).IsAssignableFrom(typeof(T));
                IEnumerator enumerator = listRootNode.ChildNodes.GetEnumerator();
                try
                {
                    while (enumerator.MoveNext())
                    {
                        XmlNode xmlNode = (XmlNode)enumerator.Current;
                        if (ValidateListNode(xmlNode, listRootNode, typeof(T)))
                        {
                            if (flag)
                            {
                                DirectXmlCrossRefLoader.RegisterListWantsCrossRef(list, xmlNode.InnerText, listRootNode.Name);
                            }
                            else
                            {
                                list.Add(ObjectFromXml <T>(xmlNode, doPostLoad: true));
                            }
                        }
                    }
                    return(list);
                }
                finally
                {
                    IDisposable disposable;
                    if ((disposable = (enumerator as IDisposable)) != null)
                    {
                        disposable.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error("Exception loading list from XML: " + ex + "\nXML:\n" + listRootNode.OuterXml);
                return(list);
            }
        }
            public override bool TryResolve(FailMode failReportMode)
            {
                bool flag = false;

                for (int i = 0; i < this.defNames.Count; i++)
                {
                    T t = DirectXmlCrossRefLoader.TryResolveDef <T>(this.defNames[i], failReportMode, this.debugWanterInfo);
                    if (t != null)
                    {
                        ((List <T>) this.wanter).Add(t);
                        this.defNames.RemoveAt(i);
                        i--;
                    }
                    else
                    {
                        flag = true;
                    }
                }
                return(!flag);
            }
Beispiel #15
0
        private static List <T> ListFromXml <T>(XmlNode listRootNode)
        {
            List <T> list = new List <T>();

            try
            {
                bool flag = typeof(Def).IsAssignableFrom(typeof(T));
                foreach (XmlNode childNode in listRootNode.ChildNodes)
                {
                    if (ValidateListNode(childNode, listRootNode, typeof(T)))
                    {
                        XmlAttribute xmlAttribute = childNode.Attributes["MayRequire"];
                        if (flag)
                        {
                            DirectXmlCrossRefLoader.RegisterListWantsCrossRef(list, childNode.InnerText, listRootNode.Name, xmlAttribute?.Value);
                        }
                        else
                        {
                            try
                            {
                                if (xmlAttribute == null || xmlAttribute.Value.NullOrEmpty() || ModsConfig.IsActive(xmlAttribute.Value))
                                {
                                    list.Add(ObjectFromXml <T>(childNode, doPostLoad: true));
                                }
                            }
                            catch (Exception ex)
                            {
                                Log.Error("Exception loading list element from XML: " + ex + "\nXML:\n" + listRootNode.OuterXml);
                            }
                        }
                    }
                }
                return(list);
            }
            catch (Exception ex2)
            {
                Log.Error("Exception loading list from XML: " + ex2 + "\nXML:\n" + listRootNode.OuterXml);
                return(list);
            }
        }
        private static Dictionary <K, V> DictionaryFromXml <K, V>(XmlNode dictRootNode)
        {
            Dictionary <K, V> dictionary = new Dictionary <K, V>();

            try
            {
                bool num  = typeof(Def).IsAssignableFrom(typeof(K));
                bool flag = typeof(Def).IsAssignableFrom(typeof(V));
                if (!num && !flag)
                {
                    foreach (XmlNode childNode in dictRootNode.ChildNodes)
                    {
                        if (ValidateListNode(childNode, dictRootNode, typeof(KeyValuePair <K, V>)))
                        {
                            K key   = ObjectFromXml <K>(childNode["key"], doPostLoad: true);
                            V value = ObjectFromXml <V>(childNode["value"], doPostLoad: true);
                            dictionary.Add(key, value);
                        }
                    }
                    return(dictionary);
                }
                foreach (XmlNode childNode2 in dictRootNode.ChildNodes)
                {
                    if (ValidateListNode(childNode2, dictRootNode, typeof(KeyValuePair <K, V>)))
                    {
                        DirectXmlCrossRefLoader.RegisterDictionaryWantsCrossRef(dictionary, childNode2, dictRootNode.Name);
                    }
                }
                return(dictionary);
            }
            catch (Exception ex)
            {
                Log.Error("Malformed dictionary XML. Node: " + dictRootNode.OuterXml + ".\n\nException: " + ex);
                return(dictionary);
            }
        }
Beispiel #17
0
        private static Dictionary <K, V> DictionaryFromXml <K, V>(XmlNode dictRootNode) where K : new()where V : new()
        {
            Dictionary <K, V> dictionary = new Dictionary <K, V>();

            try
            {
                bool flag  = typeof(Def).IsAssignableFrom(typeof(K));
                bool flag2 = typeof(Def).IsAssignableFrom(typeof(V));
                if (!flag && !flag2)
                {
                    IEnumerator enumerator = dictRootNode.ChildNodes.GetEnumerator();
                    try
                    {
                        while (enumerator.MoveNext())
                        {
                            XmlNode xmlNode = (XmlNode)enumerator.Current;
                            if (ValidateListNode(xmlNode, dictRootNode, typeof(KeyValuePair <K, V>)))
                            {
                                K key   = ObjectFromXml <K>(xmlNode["key"], doPostLoad: true);
                                V value = ObjectFromXml <V>(xmlNode["value"], doPostLoad: true);
                                dictionary.Add(key, value);
                            }
                        }
                        return(dictionary);
                    }
                    finally
                    {
                        IDisposable disposable;
                        if ((disposable = (enumerator as IDisposable)) != null)
                        {
                            disposable.Dispose();
                        }
                    }
                }
                IEnumerator enumerator2 = dictRootNode.ChildNodes.GetEnumerator();
                try
                {
                    while (enumerator2.MoveNext())
                    {
                        XmlNode xmlNode2 = (XmlNode)enumerator2.Current;
                        if (ValidateListNode(xmlNode2, dictRootNode, typeof(KeyValuePair <K, V>)))
                        {
                            DirectXmlCrossRefLoader.RegisterDictionaryWantsCrossRef(dictionary, xmlNode2, dictRootNode.Name);
                        }
                    }
                    return(dictionary);
                }
                finally
                {
                    IDisposable disposable2;
                    if ((disposable2 = (enumerator2 as IDisposable)) != null)
                    {
                        disposable2.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error("Malformed dictionary XML. Node: " + dictRootNode.OuterXml + ".\n\nException: " + ex);
                return(dictionary);
            }
        }
Beispiel #18
0
        private static void DoPlayLoad()
        {
            DeepProfiler.Start("GraphicDatabase.Clear()");
            try
            {
                GraphicDatabase.Clear();
            }
            finally
            {
                DeepProfiler.End();
            }
            DeepProfiler.Start("Load all active mods.");
            try
            {
                LoadedModManager.LoadAllActiveMods();
            }
            finally
            {
                DeepProfiler.End();
            }
            DeepProfiler.Start("Load language metadata.");
            try
            {
                LanguageDatabase.InitAllMetadata();
            }
            finally
            {
                DeepProfiler.End();
            }
            LongEventHandler.SetCurrentEventText("LoadingDefs".Translate());
            DeepProfiler.Start("Copy all Defs from mods to global databases.");
            try
            {
                foreach (Type item in typeof(Def).AllSubclasses())
                {
                    GenGeneric.InvokeStaticMethodOnGenericType(typeof(DefDatabase <>), item, "AddAllInMods");
                }
            }
            finally
            {
                DeepProfiler.End();
            }
            DeepProfiler.Start("Resolve cross-references between non-implied Defs.");
            try
            {
                DirectXmlCrossRefLoader.ResolveAllWantedCrossReferences(FailMode.Silent);
            }
            finally
            {
                DeepProfiler.End();
            }
            DeepProfiler.Start("Rebind defs (early).");
            try
            {
                DefOfHelper.RebindAllDefOfs(earlyTryMode: true);
            }
            finally
            {
                DeepProfiler.End();
            }
            DeepProfiler.Start("TKeySystem.BuildMappings()");
            try
            {
                TKeySystem.BuildMappings();
            }
            finally
            {
                DeepProfiler.End();
            }
            DeepProfiler.Start("Inject selected language data into game data (early pass).");
            try
            {
                LanguageDatabase.activeLanguage.InjectIntoData_BeforeImpliedDefs();
            }
            finally
            {
                DeepProfiler.End();
            }
            DeepProfiler.Start("Generate implied Defs (pre-resolve).");
            try
            {
                DefGenerator.GenerateImpliedDefs_PreResolve();
            }
            finally
            {
                DeepProfiler.End();
            }
            DeepProfiler.Start("Resolve cross-references between Defs made by the implied defs.");
            try
            {
                DirectXmlCrossRefLoader.ResolveAllWantedCrossReferences(FailMode.LogErrors);
            }
            finally
            {
                DirectXmlCrossRefLoader.Clear();
                DeepProfiler.End();
            }
            DeepProfiler.Start("Rebind DefOfs (final).");
            try
            {
                DefOfHelper.RebindAllDefOfs(earlyTryMode: false);
            }
            finally
            {
                DeepProfiler.End();
            }
            DeepProfiler.Start("Other def binding, resetting and global operations (pre-resolve).");
            try
            {
                PlayerKnowledgeDatabase.ReloadAndRebind();
                LessonAutoActivator.Reset();
                CostListCalculator.Reset();
                Pawn.ResetStaticData();
                PawnApparelGenerator.Reset();
                RestUtility.Reset();
                ThoughtUtility.Reset();
                ThinkTreeKeyAssigner.Reset();
                ThingCategoryNodeDatabase.FinalizeInit();
                TrainableUtility.Reset();
                HaulAIUtility.Reset();
                GenConstruct.Reset();
                MedicalCareUtility.Reset();
                InspectPaneUtility.Reset();
                GraphicDatabaseHeadRecords.Reset();
                DateReadout.Reset();
                ResearchProjectDef.GenerateNonOverlappingCoordinates();
                BaseGen.Reset();
                ResourceCounter.ResetDefs();
                ApparelProperties.ResetStaticData();
                WildPlantSpawner.ResetStaticData();
                PawnGenerator.Reset();
                TunnelHiveSpawner.ResetStaticData();
                Hive.ResetStaticData();
                ExpectationsUtility.Reset();
                WealthWatcher.ResetStaticData();
                SkillUI.Reset();
                QuestNode_GetThingPlayerCanProduce.ResetStaticData();
                Pawn_PsychicEntropyTracker.ResetStaticData();
                ColoredText.ResetStaticData();
                QuestNode_GetRandomNegativeGameCondition.ResetStaticData();
                RoyalTitleUtility.ResetStaticData();
                RewardsGenerator.ResetStaticData();
                WorkGiver_FillFermentingBarrel.ResetStaticData();
                WorkGiver_DoBill.ResetStaticData();
                WorkGiver_InteractAnimal.ResetStaticData();
                WorkGiver_Warden_DoExecution.ResetStaticData();
                WorkGiver_GrowerSow.ResetStaticData();
                WorkGiver_Miner.ResetStaticData();
                WorkGiver_FixBrokenDownBuilding.ResetStaticData();
                WorkGiver_ConstructDeliverResources.ResetStaticData();
            }
            finally
            {
                DeepProfiler.End();
            }
            DeepProfiler.Start("Resolve references.");
            try
            {
                DeepProfiler.Start("ThingCategoryDef resolver");
                try
                {
                    DefDatabase <ThingCategoryDef> .ResolveAllReferences();
                }
                finally
                {
                    DeepProfiler.End();
                }
                DeepProfiler.Start("RecipeDef resolver");
                try
                {
                    DeepProfiler.enabled = false;
                    DefDatabase <RecipeDef> .ResolveAllReferences(onlyExactlyMyType : true, parallel : true);

                    DeepProfiler.enabled = true;
                }
                finally
                {
                    DeepProfiler.End();
                }
                DeepProfiler.Start("Static resolver calls");
                try
                {
                    foreach (Type item2 in typeof(Def).AllSubclasses())
                    {
                        if (!(item2 == typeof(ThingDef)) && !(item2 == typeof(ThingCategoryDef)) && !(item2 == typeof(RecipeDef)))
                        {
                            GenGeneric.InvokeStaticMethodOnGenericType(typeof(DefDatabase <>), item2, "ResolveAllReferences", true, false);
                        }
                    }
                }
                finally
                {
                    DeepProfiler.End();
                }
                DeepProfiler.Start("ThingDef resolver");
                try
                {
                    DefDatabase <ThingDef> .ResolveAllReferences();
                }
                finally
                {
                    DeepProfiler.End();
                }
            }
            finally
            {
                DeepProfiler.End();
            }
            DeepProfiler.Start("Generate implied Defs (post-resolve).");
            try
            {
                DefGenerator.GenerateImpliedDefs_PostResolve();
            }
            finally
            {
                DeepProfiler.End();
            }
            DeepProfiler.Start("Other def binding, resetting and global operations (post-resolve).");
            try
            {
                PawnWeaponGenerator.Reset();
                BuildingProperties.FinalizeInit();
                ThingSetMakerUtility.Reset();
            }
            finally
            {
                DeepProfiler.End();
            }
            if (Prefs.DevMode)
            {
                DeepProfiler.Start("Error check all defs.");
                try
                {
                    foreach (Type item3 in typeof(Def).AllSubclasses())
                    {
                        GenGeneric.InvokeStaticMethodOnGenericType(typeof(DefDatabase <>), item3, "ErrorCheckAllDefs");
                    }
                }
                finally
                {
                    DeepProfiler.End();
                }
            }
            LongEventHandler.SetCurrentEventText("Initializing".Translate());
            DeepProfiler.Start("Load keyboard preferences.");
            try
            {
                KeyPrefs.Init();
            }
            finally
            {
                DeepProfiler.End();
            }
            DeepProfiler.Start("Short hash giving.");
            try
            {
                ShortHashGiver.GiveAllShortHashes();
            }
            finally
            {
                DeepProfiler.End();
            }
            LongEventHandler.ExecuteWhenFinished(delegate
            {
                DeepProfiler.Start("Load backstories.");
                try
                {
                    BackstoryDatabase.ReloadAllBackstories();
                }
                finally
                {
                    DeepProfiler.End();
                }
            });
            LongEventHandler.ExecuteWhenFinished(delegate
            {
                DeepProfiler.Start("Inject selected language data into game data.");
                try
                {
                    LanguageDatabase.activeLanguage.InjectIntoData_AfterImpliedDefs();
                    GenLabel.ClearCache();
                }
                finally
                {
                    DeepProfiler.End();
                }
            });
            LongEventHandler.ExecuteWhenFinished(delegate
            {
                DeepProfiler.Start("Static constructor calls");
                try
                {
                    StaticConstructorOnStartupUtility.CallAll();
                    if (Prefs.DevMode)
                    {
                        StaticConstructorOnStartupUtility.ReportProbablyMissingAttributes();
                    }
                }
                finally
                {
                    DeepProfiler.End();
                }
                DeepProfiler.Start("Garbage Collection");
                try
                {
                    AbstractFilesystem.ClearAllCache();
                    GC.Collect(int.MaxValue, GCCollectionMode.Forced);
                }
                finally
                {
                    DeepProfiler.End();
                }
            });
        }
        private static Dictionary <K, V> DictionaryFromXml <K, V>(XmlNode dictRootNode) where K : new() where V : new()
        {
            Dictionary <K, V> dictionary = new Dictionary <K, V>();

            try
            {
                bool flag  = typeof(Def).IsAssignableFrom(typeof(K));
                bool flag2 = typeof(Def).IsAssignableFrom(typeof(V));
                if (!flag && !flag2)
                {
                    IEnumerator enumerator = dictRootNode.ChildNodes.GetEnumerator();
                    try
                    {
                        while (enumerator.MoveNext())
                        {
                            object  obj     = enumerator.Current;
                            XmlNode xmlNode = (XmlNode)obj;
                            if (DirectXmlToObject.ValidateListNode(xmlNode, dictRootNode, typeof(KeyValuePair <K, V>)))
                            {
                                K key   = DirectXmlToObject.ObjectFromXml <K>(xmlNode["key"], true);
                                V value = DirectXmlToObject.ObjectFromXml <V>(xmlNode["value"], true);
                                dictionary.Add(key, value);
                            }
                        }
                    }
                    finally
                    {
                        IDisposable disposable;
                        if ((disposable = (enumerator as IDisposable)) != null)
                        {
                            disposable.Dispose();
                        }
                    }
                }
                else
                {
                    IEnumerator enumerator2 = dictRootNode.ChildNodes.GetEnumerator();
                    try
                    {
                        while (enumerator2.MoveNext())
                        {
                            object  obj2     = enumerator2.Current;
                            XmlNode xmlNode2 = (XmlNode)obj2;
                            if (DirectXmlToObject.ValidateListNode(xmlNode2, dictRootNode, typeof(KeyValuePair <K, V>)))
                            {
                                DirectXmlCrossRefLoader.RegisterDictionaryWantsCrossRef <K, V>(dictionary, xmlNode2, dictRootNode.Name);
                            }
                        }
                    }
                    finally
                    {
                        IDisposable disposable2;
                        if ((disposable2 = (enumerator2 as IDisposable)) != null)
                        {
                            disposable2.Dispose();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(string.Concat(new object[]
                {
                    "Malformed dictionary XML. Node: ",
                    dictRootNode.OuterXml,
                    ".\n\nException: ",
                    ex
                }), false);
            }
            return(dictionary);
        }
 public void LoadDataFromXmlCustom(XmlNode xmlRoot)
 {
     DirectXmlCrossRefLoader.RegisterObjectWantsCrossRef(this, "skill", xmlRoot.Name);
     this.minLevel = (int)ParseHelper.FromString(xmlRoot.FirstChild.Value, typeof(int));
 }
        public static T ObjectFromXml <T>(XmlNode xmlRoot, bool doPostLoad) where T : new()
        {
            MethodInfo methodInfo = DirectXmlToObject.CustomDataLoadMethodOf(typeof(T));
            T          result;

            if (methodInfo != null)
            {
                xmlRoot = XmlInheritance.GetResolvedNodeFor(xmlRoot);
                Type type = DirectXmlToObject.ClassTypeOf <T>(xmlRoot);
                DirectXmlToObject.currentlyInstantiatingObjectOfType.Push(type);
                T t;
                try
                {
                    t = (T)((object)Activator.CreateInstance(type));
                }
                finally
                {
                    DirectXmlToObject.currentlyInstantiatingObjectOfType.Pop();
                }
                try
                {
                    methodInfo.Invoke(t, new object[]
                    {
                        xmlRoot
                    });
                }
                catch (Exception ex)
                {
                    Log.Error(string.Concat(new object[]
                    {
                        "Exception in custom XML loader for ",
                        typeof(T),
                        ". Node is:\n ",
                        xmlRoot.OuterXml,
                        "\n\nException is:\n ",
                        ex.ToString()
                    }), false);
                    t = default(T);
                }
                if (doPostLoad)
                {
                    DirectXmlToObject.TryDoPostLoad(t);
                }
                result = t;
            }
            else if (xmlRoot.ChildNodes.Count == 1 && xmlRoot.FirstChild.NodeType == XmlNodeType.CDATA)
            {
                if (typeof(T) != typeof(string))
                {
                    Log.Error("CDATA can only be used for strings. Bad xml: " + xmlRoot.OuterXml, false);
                    result = default(T);
                }
                else
                {
                    result = (T)((object)xmlRoot.FirstChild.Value);
                }
            }
            else if (xmlRoot.ChildNodes.Count == 1 && xmlRoot.FirstChild.NodeType == XmlNodeType.Text)
            {
                try
                {
                    return((T)((object)ParseHelper.FromString(xmlRoot.InnerText, typeof(T))));
                }
                catch (Exception ex2)
                {
                    Log.Error(string.Concat(new object[]
                    {
                        "Exception parsing ",
                        xmlRoot.OuterXml,
                        " to type ",
                        typeof(T),
                        ": ",
                        ex2
                    }), false);
                }
                result = default(T);
            }
            else if (Attribute.IsDefined(typeof(T), typeof(FlagsAttribute)))
            {
                List <T> list = DirectXmlToObject.ListFromXml <T>(xmlRoot);
                int      num  = 0;
                foreach (T t2 in list)
                {
                    int num2 = (int)((object)t2);
                    num |= num2;
                }
                result = (T)((object)num);
            }
            else if (typeof(T).HasGenericDefinition(typeof(List <>)))
            {
                MethodInfo method           = typeof(DirectXmlToObject).GetMethod("ListFromXml", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
                Type[]     genericArguments = typeof(T).GetGenericArguments();
                MethodInfo methodInfo2      = method.MakeGenericMethod(genericArguments);
                object[]   parameters       = new object[]
                {
                    xmlRoot
                };
                object obj = methodInfo2.Invoke(null, parameters);
                result = (T)((object)obj);
            }
            else if (typeof(T).HasGenericDefinition(typeof(Dictionary <, >)))
            {
                MethodInfo method2           = typeof(DirectXmlToObject).GetMethod("DictionaryFromXml", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
                Type[]     genericArguments2 = typeof(T).GetGenericArguments();
                MethodInfo methodInfo3       = method2.MakeGenericMethod(genericArguments2);
                object[]   parameters2       = new object[]
                {
                    xmlRoot
                };
                object obj2 = methodInfo3.Invoke(null, parameters2);
                result = (T)((object)obj2);
            }
            else
            {
                if (!xmlRoot.HasChildNodes)
                {
                    if (typeof(T) == typeof(string))
                    {
                        return((T)((object)""));
                    }
                    XmlAttribute xmlAttribute = xmlRoot.Attributes["IsNull"];
                    if (xmlAttribute != null && xmlAttribute.Value.ToUpperInvariant() == "TRUE")
                    {
                        return(default(T));
                    }
                    if (typeof(T).IsGenericType)
                    {
                        Type genericTypeDefinition = typeof(T).GetGenericTypeDefinition();
                        if (genericTypeDefinition == typeof(List <>) || genericTypeDefinition == typeof(HashSet <>) || genericTypeDefinition == typeof(Dictionary <, >))
                        {
                            return(Activator.CreateInstance <T>());
                        }
                    }
                }
                xmlRoot = XmlInheritance.GetResolvedNodeFor(xmlRoot);
                Type type2 = DirectXmlToObject.ClassTypeOf <T>(xmlRoot);
                Type type3 = Nullable.GetUnderlyingType(type2) ?? type2;
                DirectXmlToObject.currentlyInstantiatingObjectOfType.Push(type3);
                T t3;
                try
                {
                    t3 = (T)((object)Activator.CreateInstance(type3));
                }
                finally
                {
                    DirectXmlToObject.currentlyInstantiatingObjectOfType.Pop();
                }
                List <string> list2 = null;
                if (xmlRoot.ChildNodes.Count > 1)
                {
                    list2 = new List <string>();
                }
                for (int i = 0; i < xmlRoot.ChildNodes.Count; i++)
                {
                    XmlNode xmlNode = xmlRoot.ChildNodes[i];
                    if (!(xmlNode is XmlComment))
                    {
                        if (xmlRoot.ChildNodes.Count > 1)
                        {
                            if (list2.Contains(xmlNode.Name))
                            {
                                Log.Error(string.Concat(new object[]
                                {
                                    "XML ",
                                    typeof(T),
                                    " defines the same field twice: ",
                                    xmlNode.Name,
                                    ".\n\nField contents: ",
                                    xmlNode.InnerText,
                                    ".\n\nWhole XML:\n\n",
                                    xmlRoot.OuterXml
                                }), false);
                            }
                            else
                            {
                                list2.Add(xmlNode.Name);
                            }
                        }
                        FieldInfo fieldInfo = DirectXmlToObject.GetFieldInfoForType(t3.GetType(), xmlNode.Name, xmlRoot);
                        if (fieldInfo == null)
                        {
                            foreach (FieldInfo fieldInfo2 in t3.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
                            {
                                foreach (object obj3 in fieldInfo2.GetCustomAttributes(typeof(LoadAliasAttribute), true))
                                {
                                    string alias = ((LoadAliasAttribute)obj3).alias;
                                    if (alias.EqualsIgnoreCase(xmlNode.Name))
                                    {
                                        fieldInfo = fieldInfo2;
                                        break;
                                    }
                                }
                                if (fieldInfo != null)
                                {
                                    break;
                                }
                            }
                        }
                        if (fieldInfo == null)
                        {
                            bool flag = false;
                            foreach (object obj4 in t3.GetType().GetCustomAttributes(typeof(IgnoreSavedElementAttribute), true))
                            {
                                string elementToIgnore = ((IgnoreSavedElementAttribute)obj4).elementToIgnore;
                                if (string.Equals(elementToIgnore, xmlNode.Name, StringComparison.OrdinalIgnoreCase))
                                {
                                    flag = true;
                                    break;
                                }
                            }
                            if (!flag)
                            {
                                Log.Error(string.Concat(new string[]
                                {
                                    "XML error: ",
                                    xmlNode.OuterXml,
                                    " doesn't correspond to any field in type ",
                                    t3.GetType().Name,
                                    ". Context: ",
                                    xmlRoot.OuterXml
                                }), false);
                            }
                        }
                        else if (typeof(Def).IsAssignableFrom(fieldInfo.FieldType))
                        {
                            if (xmlNode.InnerText.NullOrEmpty())
                            {
                                fieldInfo.SetValue(t3, null);
                            }
                            else
                            {
                                DirectXmlCrossRefLoader.RegisterObjectWantsCrossRef(t3, fieldInfo, xmlNode.InnerText);
                            }
                        }
                        else
                        {
                            object value = null;
                            try
                            {
                                MethodInfo method3     = typeof(DirectXmlToObject).GetMethod("ObjectFromXml", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
                                MethodInfo methodInfo4 = method3.MakeGenericMethod(new Type[]
                                {
                                    fieldInfo.FieldType
                                });
                                value = methodInfo4.Invoke(null, new object[]
                                {
                                    xmlNode,
                                    doPostLoad
                                });
                            }
                            catch (Exception ex3)
                            {
                                Log.Error("Exception loading from " + xmlNode.ToString() + ": " + ex3.ToString(), false);
                                goto IL_863;
                            }
                            if (!typeof(T).IsValueType)
                            {
                                fieldInfo.SetValue(t3, value);
                            }
                            else
                            {
                                object obj5 = t3;
                                fieldInfo.SetValue(obj5, value);
                                t3 = (T)((object)obj5);
                            }
                        }
                    }
                    IL_863 :;
                }
                if (doPostLoad)
                {
                    DirectXmlToObject.TryDoPostLoad(t3);
                }
                result = t3;
            }
            return(result);
        }
        public static T ObjectFromXml <T>(XmlNode xmlRoot, bool doPostLoad)
        {
            XmlAttribute xmlAttribute = xmlRoot.Attributes["IsNull"];

            if (xmlAttribute != null && xmlAttribute.Value.ToUpperInvariant() == "TRUE")
            {
                return(default(T));
            }
            MethodInfo methodInfo = CustomDataLoadMethodOf(typeof(T));

            if (methodInfo != null)
            {
                xmlRoot = XmlInheritance.GetResolvedNodeFor(xmlRoot);
                Type type = ClassTypeOf <T>(xmlRoot);
                currentlyInstantiatingObjectOfType.Push(type);
                T val;
                try
                {
                    val = (T)Activator.CreateInstance(type);
                }
                finally
                {
                    currentlyInstantiatingObjectOfType.Pop();
                }
                try
                {
                    methodInfo.Invoke(val, new object[1]
                    {
                        xmlRoot
                    });
                }
                catch (Exception ex)
                {
                    Log.Error(string.Concat("Exception in custom XML loader for ", typeof(T), ". Node is:\n ", xmlRoot.OuterXml, "\n\nException is:\n ", ex.ToString()));
                    val = default(T);
                }
                if (doPostLoad)
                {
                    TryDoPostLoad(val);
                }
                return(val);
            }
            if (typeof(ISlateRef).IsAssignableFrom(typeof(T)))
            {
                try
                {
                    return(ParseHelper.FromString <T>(InnerTextWithReplacedNewlinesOrXML(xmlRoot)));
                }
                catch (Exception ex2)
                {
                    Log.Error(string.Concat("Exception parsing ", xmlRoot.OuterXml, " to type ", typeof(T), ": ", ex2));
                }
                return(default(T));
            }
            if (xmlRoot.ChildNodes.Count == 1 && xmlRoot.FirstChild.NodeType == XmlNodeType.CDATA)
            {
                if (typeof(T) != typeof(string))
                {
                    Log.Error("CDATA can only be used for strings. Bad xml: " + xmlRoot.OuterXml);
                    return(default(T));
                }
                return((T)(object)xmlRoot.FirstChild.Value);
            }
            if (xmlRoot.ChildNodes.Count == 1 && xmlRoot.FirstChild.NodeType == XmlNodeType.Text)
            {
                try
                {
                    return(ParseHelper.FromString <T>(xmlRoot.InnerText));
                }
                catch (Exception ex3)
                {
                    Log.Error(string.Concat("Exception parsing ", xmlRoot.OuterXml, " to type ", typeof(T), ": ", ex3));
                }
                return(default(T));
            }
            if (Attribute.IsDefined(typeof(T), typeof(FlagsAttribute)))
            {
                List <T> list = ListFromXml <T>(xmlRoot);
                int      num  = 0;
                foreach (T item in list)
                {
                    int num2 = (int)(object)item;
                    num |= num2;
                }
                return((T)(object)num);
            }
            if (typeof(T).HasGenericDefinition(typeof(List <>)))
            {
                Func <XmlNode, object> value = null;
                if (!listFromXmlMethods.TryGetValue(typeof(T), out value))
                {
                    MethodInfo method           = typeof(DirectXmlToObject).GetMethod("ListFromXmlReflection", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
                    Type[]     genericArguments = typeof(T).GetGenericArguments();
                    value = (Func <XmlNode, object>)Delegate.CreateDelegate(typeof(Func <XmlNode, object>), method.MakeGenericMethod(genericArguments));
                    listFromXmlMethods.Add(typeof(T), value);
                }
                return((T)value(xmlRoot));
            }
            if (typeof(T).HasGenericDefinition(typeof(Dictionary <, >)))
            {
                Func <XmlNode, object> value2 = null;
                if (!dictionaryFromXmlMethods.TryGetValue(typeof(T), out value2))
                {
                    MethodInfo method2           = typeof(DirectXmlToObject).GetMethod("DictionaryFromXmlReflection", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
                    Type[]     genericArguments2 = typeof(T).GetGenericArguments();
                    value2 = (Func <XmlNode, object>)Delegate.CreateDelegate(typeof(Func <XmlNode, object>), method2.MakeGenericMethod(genericArguments2));
                    dictionaryFromXmlMethods.Add(typeof(T), value2);
                }
                return((T)value2(xmlRoot));
            }
            if (!xmlRoot.HasChildNodes)
            {
                if (typeof(T) == typeof(string))
                {
                    return((T)(object)"");
                }
                XmlAttribute xmlAttribute2 = xmlRoot.Attributes["IsNull"];
                if (xmlAttribute2 != null && xmlAttribute2.Value.ToUpperInvariant() == "TRUE")
                {
                    return(default(T));
                }
                if (typeof(T).IsGenericType)
                {
                    Type genericTypeDefinition = typeof(T).GetGenericTypeDefinition();
                    if (genericTypeDefinition == typeof(List <>) || genericTypeDefinition == typeof(HashSet <>) || genericTypeDefinition == typeof(Dictionary <, >))
                    {
                        return(Activator.CreateInstance <T>());
                    }
                }
            }
            xmlRoot = XmlInheritance.GetResolvedNodeFor(xmlRoot);
            Type type2 = ClassTypeOf <T>(xmlRoot);
            Type type3 = Nullable.GetUnderlyingType(type2) ?? type2;

            currentlyInstantiatingObjectOfType.Push(type3);
            T val2;

            try
            {
                val2 = (T)Activator.CreateInstance(type3);
            }
            finally
            {
                currentlyInstantiatingObjectOfType.Pop();
            }
            HashSet <string> hashSet = null;

            if (xmlRoot.ChildNodes.Count > 1)
            {
                hashSet = new HashSet <string>();
            }
            for (int i = 0; i < xmlRoot.ChildNodes.Count; i++)
            {
                XmlNode xmlNode = xmlRoot.ChildNodes[i];
                if (xmlNode is XmlComment)
                {
                    continue;
                }
                if (xmlRoot.ChildNodes.Count > 1)
                {
                    if (hashSet.Contains(xmlNode.Name))
                    {
                        Log.Error(string.Concat("XML ", typeof(T), " defines the same field twice: ", xmlNode.Name, ".\n\nField contents: ", xmlNode.InnerText, ".\n\nWhole XML:\n\n", xmlRoot.OuterXml));
                    }
                    else
                    {
                        hashSet.Add(xmlNode.Name);
                    }
                }
                FieldInfo value3 = null;
                DeepProfiler.Start("GetFieldInfoForType");
                try
                {
                    value3 = GetFieldInfoForType(val2.GetType(), xmlNode.Name, xmlRoot);
                }
                finally
                {
                    DeepProfiler.End();
                }
                if (value3 == null)
                {
                    DeepProfiler.Start("Field search");
                    try
                    {
                        FieldAliasCache key = new FieldAliasCache(val2.GetType(), xmlNode.Name);
                        if (!fieldAliases.TryGetValue(key, out value3))
                        {
                            FieldInfo[] fields = val2.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                            foreach (FieldInfo fieldInfo in fields)
                            {
                                object[] customAttributes = fieldInfo.GetCustomAttributes(typeof(LoadAliasAttribute), inherit: true);
                                for (int k = 0; k < customAttributes.Length; k++)
                                {
                                    if (((LoadAliasAttribute)customAttributes[k]).alias.EqualsIgnoreCase(xmlNode.Name))
                                    {
                                        value3 = fieldInfo;
                                        break;
                                    }
                                }
                                if (value3 != null)
                                {
                                    break;
                                }
                            }
                            fieldAliases.Add(key, value3);
                        }
                    }
                    finally
                    {
                        DeepProfiler.End();
                    }
                }
                if (value3 != null && value3.TryGetAttribute <UnsavedAttribute>() != null && !value3.TryGetAttribute <UnsavedAttribute>().allowLoading)
                {
                    Log.Error("XML error: " + xmlNode.OuterXml + " corresponds to a field in type " + val2.GetType().Name + " which has an Unsaved attribute. Context: " + xmlRoot.OuterXml);
                }
                else if (value3 == null)
                {
                    DeepProfiler.Start("Field search 2");
                    try
                    {
                        bool         flag          = false;
                        XmlAttribute xmlAttribute3 = xmlNode.Attributes?["IgnoreIfNoMatchingField"];
                        if (xmlAttribute3 != null && xmlAttribute3.Value.ToUpperInvariant() == "TRUE")
                        {
                            flag = true;
                        }
                        else
                        {
                            object[] customAttributes = val2.GetType().GetCustomAttributes(typeof(IgnoreSavedElementAttribute), inherit: true);
                            for (int j = 0; j < customAttributes.Length; j++)
                            {
                                if (string.Equals(((IgnoreSavedElementAttribute)customAttributes[j]).elementToIgnore, xmlNode.Name, StringComparison.OrdinalIgnoreCase))
                                {
                                    flag = true;
                                    break;
                                }
                            }
                        }
                        if (!flag)
                        {
                            Log.Error("XML error: " + xmlNode.OuterXml + " doesn't correspond to any field in type " + val2.GetType().Name + ". Context: " + xmlRoot.OuterXml);
                        }
                    }
                    finally
                    {
                        DeepProfiler.End();
                    }
                }
                else if (typeof(Def).IsAssignableFrom(value3.FieldType))
                {
                    if (xmlNode.InnerText.NullOrEmpty())
                    {
                        value3.SetValue(val2, null);
                        continue;
                    }
                    XmlAttribute xmlAttribute4 = xmlNode.Attributes["MayRequire"];
                    DirectXmlCrossRefLoader.RegisterObjectWantsCrossRef(val2, value3, xmlNode.InnerText, xmlAttribute4?.Value.ToLower());
                }
                else
                {
                    object obj = null;
                    try
                    {
                        obj = GetObjectFromXmlMethod(value3.FieldType)(xmlNode, doPostLoad);
                    }
                    catch (Exception ex4)
                    {
                        Log.Error("Exception loading from " + xmlNode.ToString() + ": " + ex4.ToString());
                        continue;
                    }
                    if (!typeof(T).IsValueType)
                    {
                        value3.SetValue(val2, obj);
                        continue;
                    }
                    object obj2 = val2;
                    value3.SetValue(obj2, obj);
                    val2 = (T)obj2;
                }
            }
            if (doPostLoad)
            {
                TryDoPostLoad(val2);
            }
            return(val2);
        }
Beispiel #23
0
        public static object Convert(object obj, Type to, object defaultValue)
        {
            if (obj == null)
            {
                return(defaultValue);
            }
            if (to.IsAssignableFrom(obj.GetType()))
            {
                return(obj);
            }
            if (to == typeof(string))
            {
                return(obj.ToString());
            }
            string text = obj as string;

            if (text != null && !to.IsPrimitive && ParseHelper.CanParse(to, (string)obj))
            {
                if (text == "")
                {
                    return(defaultValue);
                }
                return(ParseHelper.FromString(text, to));
            }
            if (text != null && typeof(Def).IsAssignableFrom(to))
            {
                if (text == "")
                {
                    return(defaultValue);
                }
                return(GenDefDatabase.GetDef(to, text));
            }
            if (text != null && to == typeof(Faction))
            {
                if (text == "")
                {
                    return(defaultValue);
                }
                List <Faction> allFactionsListForReading = Find.FactionManager.AllFactionsListForReading;
                for (int i = 0; i < allFactionsListForReading.Count; i++)
                {
                    if (allFactionsListForReading[i].GetUniqueLoadID() == text)
                    {
                        return(allFactionsListForReading[i]);
                    }
                }
                for (int j = 0; j < allFactionsListForReading.Count; j++)
                {
                    if (allFactionsListForReading[j].HasName && allFactionsListForReading[j].Name == text)
                    {
                        return(allFactionsListForReading[j]);
                    }
                }
                for (int k = 0; k < allFactionsListForReading.Count; k++)
                {
                    if (allFactionsListForReading[k].def.defName == text)
                    {
                        return(allFactionsListForReading[k]);
                    }
                }
                return(defaultValue);
            }
            if (CanConvertBetweenDataTypes(obj.GetType(), to))
            {
                return(ConvertBetweenDataTypes(obj, to));
            }
            if (IsXml(obj) && !to.IsPrimitive)
            {
                try
                {
                    Type type = to;
                    if (type == typeof(IEnumerable))
                    {
                        type = typeof(List <string>);
                    }
                    if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable <>) && type.GetGenericArguments().Length >= 1)
                    {
                        type = typeof(List <>).MakeGenericType(type.GetGenericArguments()[0]);
                    }
                    XmlDocument xmlDocument = new XmlDocument();
                    xmlDocument.LoadXml("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<root>\n" + text + "\n</root>");
                    object result = DirectXmlToObject.GetObjectFromXmlMethod(type)(xmlDocument.DocumentElement, arg2 : true);
                    DirectXmlCrossRefLoader.ResolveAllWantedCrossReferences(FailMode.LogErrors);
                    return(result);
                }
                finally
                {
                    DirectXmlCrossRefLoader.Clear();
                }
            }
            if (to.IsGenericType && (to.GetGenericTypeDefinition() == typeof(IEnumerable <>) || to.GetGenericTypeDefinition() == typeof(List <>)) && to.GetGenericArguments().Length >= 1 && (!(to.GetGenericArguments()[0] == typeof(string)) || !(obj is string)))
            {
                IEnumerable enumerable = obj as IEnumerable;
                if (enumerable != null)
                {
                    Type type2 = to.GetGenericArguments()[0];
                    bool flag  = true;
                    foreach (object item in enumerable)
                    {
                        if (!CanConvert(item, type2))
                        {
                            flag = false;
                            break;
                        }
                    }
                    if (flag)
                    {
                        IList list = (IList)Activator.CreateInstance(typeof(List <>).MakeGenericType(type2));
                        {
                            foreach (object item2 in enumerable)
                            {
                                list.Add(Convert(item2, type2));
                            }
                            return(list);
                        }
                    }
                }
            }
            if (obj is IEnumerable && !(obj is string))
            {
                IEnumerable e = (IEnumerable)obj;
                if (GenCollection.Count_EnumerableBase(e) == 1)
                {
                    object obj2 = GenCollection.FirstOrDefault_EnumerableBase(e);
                    if (CanConvert(obj2, to))
                    {
                        return(Convert(obj2, to));
                    }
                }
            }
            if (typeof(IList).IsAssignableFrom(to))
            {
                IList  list2            = (IList)Activator.CreateInstance(to);
                Type[] genericArguments = to.GetGenericArguments();
                if (genericArguments.Length >= 1)
                {
                    list2.Add(Convert(obj, genericArguments[0]));
                }
                else
                {
                    list2.Add(obj);
                }
                return(list2);
            }
            if (to == typeof(IEnumerable))
            {
                return(Gen.YieldSingleNonGeneric(obj));
            }
            if (to.IsGenericType && to.GetGenericTypeDefinition() == typeof(IEnumerable <>))
            {
                Type[] genericArguments2 = to.GetGenericArguments();
                if (genericArguments2.Length >= 1)
                {
                    IList obj3 = (IList)Activator.CreateInstance(typeof(List <>).MakeGenericType(genericArguments2[0]));
                    obj3.Add(Convert(obj, genericArguments2[0]));
                    return(obj3);
                }
                return(Gen.YieldSingleNonGeneric(obj));
            }
            IConvertible convertible = obj as IConvertible;

            if (convertible == null)
            {
                return(defaultValue);
            }
            try
            {
                return(ConvertToPrimitive(convertible, to, defaultValue));
            }
            catch (FormatException)
            {
                return(defaultValue);
            }
        }
            public override bool TryResolve(FailMode failReportMode)
            {
                failReportMode = FailMode.LogErrors;
                bool flag  = typeof(Def).IsAssignableFrom(typeof(K));
                bool flag2 = typeof(Def).IsAssignableFrom(typeof(V));
                List <Pair <K, V> > list = new List <Pair <K, V> >();

                foreach (XmlNode wantedDictRef in this.wantedDictRefs)
                {
                    XmlNode xmlNode  = wantedDictRef["key"];
                    XmlNode xmlNode2 = wantedDictRef["value"];
                    K       first    = (!flag) ? DirectXmlToObject.ObjectFromXml <K>(xmlNode, true) : DirectXmlCrossRefLoader.TryResolveDef <K>(xmlNode.InnerText, failReportMode);
                    V       second   = (!flag2) ? DirectXmlToObject.ObjectFromXml <V>(xmlNode2, true) : DirectXmlCrossRefLoader.TryResolveDef <V>(xmlNode2.InnerText, failReportMode);
                    list.Add(new Pair <K, V>(first, second));
                }
                Dictionary <K, V> dictionary = (Dictionary <K, V>)base.wanter;

                dictionary.Clear();
                foreach (Pair <K, V> item in list)
                {
                    try
                    {
                        dictionary.Add(item.First, item.Second);
                    }
                    catch
                    {
                        Log.Error("Failed to load key/value pair: " + item.First + ", " + item.Second);
                    }
                }
                return(true);
            }
        public static T ObjectFromXml <T>(XmlNode xmlRoot, bool doPostLoad) where T : new()
        {
            MethodInfo methodInfo = DirectXmlToObject.CustomDataLoadMethodOf(typeof(T));

            if (methodInfo != null)
            {
                xmlRoot = XmlInheritance.GetResolvedNodeFor(xmlRoot);
                Type type = DirectXmlToObject.ClassTypeOf <T>(xmlRoot);
                T    val  = (T)Activator.CreateInstance(type);
                try
                {
                    methodInfo.Invoke(val, new object[1]
                    {
                        xmlRoot
                    });
                }
                catch (Exception ex)
                {
                    Log.Error("Exception in custom XML loader for " + typeof(T) + ". Node is:\n " + xmlRoot.OuterXml + "\n\nException is:\n " + ex.ToString());
                    val = default(T);
                }
                if (doPostLoad)
                {
                    DirectXmlToObject.TryDoPostLoad(val);
                }
                return(val);
            }
            if (xmlRoot.ChildNodes.Count == 1 && xmlRoot.FirstChild.NodeType == XmlNodeType.CDATA)
            {
                if (typeof(T) != typeof(string))
                {
                    Log.Error("CDATA can only be used for strings. Bad xml: " + xmlRoot.OuterXml);
                    return(default(T));
                }
                return((T)(object)xmlRoot.FirstChild.Value);
            }
            if (xmlRoot.ChildNodes.Count == 1 && xmlRoot.FirstChild.NodeType == XmlNodeType.Text)
            {
                try
                {
                    return((T)ParseHelper.FromString(xmlRoot.InnerText, typeof(T)));
                }
                catch (Exception ex2)
                {
                    Log.Error("Exception parsing " + xmlRoot.OuterXml + " to type " + typeof(T) + ": " + ex2);
                }
                return(default(T));
            }
            if (Attribute.IsDefined(typeof(T), typeof(FlagsAttribute)))
            {
                List <T> list = DirectXmlToObject.ListFromXml <T>(xmlRoot);
                int      num  = 0;
                foreach (T item in list)
                {
                    int num2 = (int)(object)item;
                    num |= num2;
                }
                return((T)(object)num);
            }
            if (typeof(T).HasGenericDefinition(typeof(List <>)))
            {
                MethodInfo method           = typeof(DirectXmlToObject).GetMethod("ListFromXml", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
                Type[]     genericArguments = typeof(T).GetGenericArguments();
                MethodInfo methodInfo2      = method.MakeGenericMethod(genericArguments);
                object[]   parameters       = new object[1]
                {
                    xmlRoot
                };
                object obj = methodInfo2.Invoke(null, parameters);
                return((T)obj);
            }
            if (typeof(T).HasGenericDefinition(typeof(Dictionary <, >)))
            {
                MethodInfo method2           = typeof(DirectXmlToObject).GetMethod("DictionaryFromXml", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
                Type[]     genericArguments2 = typeof(T).GetGenericArguments();
                MethodInfo methodInfo3       = method2.MakeGenericMethod(genericArguments2);
                object[]   parameters2       = new object[1]
                {
                    xmlRoot
                };
                object obj2 = methodInfo3.Invoke(null, parameters2);
                return((T)obj2);
            }
            if (!xmlRoot.HasChildNodes)
            {
                if (typeof(T) == typeof(string))
                {
                    return((T)(object)string.Empty);
                }
                XmlAttribute xmlAttribute = xmlRoot.Attributes["IsNull"];
                if (xmlAttribute != null && xmlAttribute.Value.ToUpperInvariant() == "TRUE")
                {
                    return(default(T));
                }
                if (typeof(T).IsGenericType)
                {
                    Type genericTypeDefinition = typeof(T).GetGenericTypeDefinition();
                    if (genericTypeDefinition != typeof(List <>) && genericTypeDefinition != typeof(HashSet <>) && genericTypeDefinition != typeof(Dictionary <, >))
                    {
                        goto IL_03ed;
                    }
                    return(new T());
                }
            }
            goto IL_03ed;
IL_03ed:
            xmlRoot = XmlInheritance.GetResolvedNodeFor(xmlRoot);
            Type          type2 = DirectXmlToObject.ClassTypeOf <T>(xmlRoot);
            T             val2  = (T)Activator.CreateInstance(type2);
            List <string> list2 = null;

            if (xmlRoot.ChildNodes.Count > 1)
            {
                list2 = new List <string>();
            }
            for (int i = 0; i < xmlRoot.ChildNodes.Count; i++)
            {
                XmlNode xmlNode = xmlRoot.ChildNodes[i];
                if (!(xmlNode is XmlComment))
                {
                    if (xmlRoot.ChildNodes.Count > 1)
                    {
                        if (list2.Contains(xmlNode.Name))
                        {
                            Log.Error("XML " + typeof(T) + " defines the same field twice: " + xmlNode.Name + ".\n\nField contents: " + xmlNode.InnerText + ".\n\nWhole XML:\n\n" + xmlRoot.OuterXml);
                        }
                        else
                        {
                            list2.Add(xmlNode.Name);
                        }
                    }
                    FieldInfo fieldInfo = DirectXmlToObject.GetFieldInfoForType(val2.GetType(), xmlNode.Name, xmlRoot);
                    if (fieldInfo == null)
                    {
                        FieldInfo[] fields = val2.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                        int         num3   = 0;
                        while (num3 < fields.Length)
                        {
                            FieldInfo fieldInfo2       = fields[num3];
                            object[]  customAttributes = fieldInfo2.GetCustomAttributes(typeof(LoadAliasAttribute), true);
                            foreach (object obj3 in customAttributes)
                            {
                                string alias = ((LoadAliasAttribute)obj3).alias;
                                if (alias.EqualsIgnoreCase(xmlNode.Name))
                                {
                                    fieldInfo = fieldInfo2;
                                    break;
                                }
                            }
                            if (fieldInfo == null)
                            {
                                num3++;
                                continue;
                            }
                            break;
                        }
                    }
                    if (fieldInfo == null)
                    {
                        bool     flag = false;
                        object[] customAttributes2 = val2.GetType().GetCustomAttributes(typeof(IgnoreSavedElementAttribute), true);
                        foreach (object obj4 in customAttributes2)
                        {
                            string elementToIgnore = ((IgnoreSavedElementAttribute)obj4).elementToIgnore;
                            if (string.Equals(elementToIgnore, xmlNode.Name, StringComparison.OrdinalIgnoreCase))
                            {
                                flag = true;
                                break;
                            }
                        }
                        if (!flag)
                        {
                            Log.Error("XML error: " + xmlNode.OuterXml + " doesn't correspond to any field in type " + val2.GetType().Name + ".");
                        }
                    }
                    else if (typeof(Def).IsAssignableFrom(fieldInfo.FieldType))
                    {
                        if (xmlNode.InnerText.NullOrEmpty())
                        {
                            fieldInfo.SetValue(val2, null);
                        }
                        else
                        {
                            DirectXmlCrossRefLoader.RegisterObjectWantsCrossRef(val2, fieldInfo, xmlNode.InnerText);
                        }
                    }
                    else
                    {
                        object obj5 = null;
                        try
                        {
                            MethodInfo method3     = typeof(DirectXmlToObject).GetMethod("ObjectFromXml", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
                            MethodInfo methodInfo4 = method3.MakeGenericMethod(fieldInfo.FieldType);
                            obj5 = methodInfo4.Invoke(null, new object[2]
                            {
                                xmlNode,
                                doPostLoad
                            });
                        }
                        catch (Exception ex3)
                        {
                            Log.Error("Exception loading from " + xmlNode.ToString() + ": " + ex3.ToString());
                            continue;
                        }
                        if (!typeof(T).IsValueType)
                        {
                            fieldInfo.SetValue(val2, obj5);
                        }
                        else
                        {
                            object obj6 = val2;
                            fieldInfo.SetValue(obj6, obj5);
                            val2 = (T)obj6;
                        }
                    }
                }
            }
            if (doPostLoad)
            {
                DirectXmlToObject.TryDoPostLoad(val2);
            }
            return(val2);
        }
 private static void DoPlayLoad()
 {
     GraphicDatabase.Clear();
     DeepProfiler.Start("Load all active mods.");
     try
     {
         LoadedModManager.LoadAllActiveMods();
     }
     finally
     {
         DeepProfiler.End();
     }
     DeepProfiler.Start("Load language metadata.");
     try
     {
         LanguageDatabase.LoadAllMetadata();
     }
     finally
     {
         DeepProfiler.End();
     }
     LongEventHandler.SetCurrentEventText("LoadingDefs".Translate());
     DeepProfiler.Start("Copy all Defs from mods to global databases.");
     try
     {
         foreach (Type item in typeof(Def).AllSubclasses())
         {
             GenGeneric.InvokeStaticMethodOnGenericType(typeof(DefDatabase <>), item, "AddAllInMods");
         }
     }
     finally
     {
         DeepProfiler.End();
     }
     DeepProfiler.Start("Resolve cross-references between non-implied Defs.");
     try
     {
         DirectXmlCrossRefLoader.ResolveAllWantedCrossReferences(FailMode.Silent);
     }
     finally
     {
         DeepProfiler.End();
     }
     DeepProfiler.Start("Rebind defs (early).");
     try
     {
         DefOfHelper.RebindAllDefOfs(true);
     }
     finally
     {
         DeepProfiler.End();
     }
     DeepProfiler.Start("Generate implied Defs (pre-resolve).");
     try
     {
         DefGenerator.GenerateImpliedDefs_PreResolve();
     }
     finally
     {
         DeepProfiler.End();
     }
     DeepProfiler.Start("Resolve cross-references between Defs made by the implied defs.");
     try
     {
         DirectXmlCrossRefLoader.ResolveAllWantedCrossReferences(FailMode.LogErrors);
     }
     finally
     {
         DeepProfiler.End();
     }
     DeepProfiler.Start("Rebind DefOfs (final).");
     try
     {
         DefOfHelper.RebindAllDefOfs(false);
     }
     finally
     {
         DeepProfiler.End();
     }
     DeepProfiler.Start("Other def binding, resetting and global operations.");
     try
     {
         PlayerKnowledgeDatabase.ReloadAndRebind();
         LessonAutoActivator.Reset();
         CostListCalculator.Reset();
         PawnApparelGenerator.Reset();
         RestUtility.Reset();
         ThoughtUtility.Reset();
         PawnWeaponGenerator.Reset();
         ThinkTreeKeyAssigner.Reset();
         ThingCategoryNodeDatabase.FinalizeInit();
         TrainableUtility.Reset();
         HaulAIUtility.Reset();
         GenConstruct.Reset();
         WorkGiver_FillFermentingBarrel.Reset();
         WorkGiver_DoBill.Reset();
         Pawn.Reset();
         WorkGiver_InteractAnimal.Reset();
         WorkGiver_Warden_DoExecution.Reset();
         WorkGiver_GrowerSow.Reset();
         WorkGiver_Miner.Reset();
         MedicalCareUtility.Reset();
         InspectPaneUtility.Reset();
         GraphicDatabaseHeadRecords.Reset();
         DateReadout.Reset();
         ResearchProjectDef.GenerateNonOverlappingCoordinates();
         WorkGiver_FixBrokenDownBuilding.CacheTranslations();
         ItemCollectionGeneratorUtility.Reset();
         BaseGen.Reset();
         HealthUtility.Reset();
         ResourceCounter.ResetDefs();
         WildSpawner.Reset();
         ApparelProperties.Reset();
     }
     finally
     {
         DeepProfiler.End();
     }
     DeepProfiler.Start("Resolve references.");
     try
     {
         foreach (Type item2 in typeof(Def).AllSubclasses())
         {
             if (item2 != typeof(ThingDef))
             {
                 GenGeneric.InvokeStaticMethodOnGenericType(typeof(DefDatabase <>), item2, "ResolveAllReferences", true);
             }
         }
         DefDatabase <ThingDef> .ResolveAllReferences(true);
     }
     finally
     {
         DeepProfiler.End();
     }
     DeepProfiler.Start("Generate implied Defs (post-resolve).");
     try
     {
         DefGenerator.GenerateImpliedDefs_PostResolve();
     }
     finally
     {
         DeepProfiler.End();
     }
     if (Prefs.DevMode)
     {
         DeepProfiler.Start("Error check all defs.");
         try
         {
             foreach (Type item3 in typeof(Def).AllSubclasses())
             {
                 GenGeneric.InvokeStaticMethodOnGenericType(typeof(DefDatabase <>), item3, "ErrorCheckAllDefs");
             }
         }
         finally
         {
             DeepProfiler.End();
         }
     }
     LongEventHandler.SetCurrentEventText("Initializing".Translate());
     DeepProfiler.Start("Load keyboard preferences.");
     try
     {
         KeyPrefs.Init();
     }
     finally
     {
         DeepProfiler.End();
     }
     DeepProfiler.Start("Short hash giving.");
     try
     {
         ShortHashGiver.GiveAllShortHashes();
     }
     finally
     {
         DeepProfiler.End();
     }
     LongEventHandler.ExecuteWhenFinished(delegate
     {
         DeepProfiler.Start("Load backstories.");
         try
         {
             BackstoryDatabase.ReloadAllBackstories();
         }
         finally
         {
             DeepProfiler.End();
         }
     });
     LongEventHandler.ExecuteWhenFinished(delegate
     {
         DeepProfiler.Start("Inject selected language data into game data.");
         try
         {
             LanguageDatabase.activeLanguage.InjectIntoData();
             GenLabel.ClearCache();
         }
         finally
         {
             DeepProfiler.End();
         }
     });
     LongEventHandler.ExecuteWhenFinished(delegate
     {
         StaticConstructorOnStartupUtility.CallAll();
         if (Prefs.DevMode)
         {
             StaticConstructorOnStartupUtility.ReportProbablyMissingAttributes();
         }
     });
 }