Exemple #1
0
 public static object FromString(string str, Type itemType)
 {
     try
     {
         itemType = (Nullable.GetUnderlyingType(itemType) ?? itemType);
         if (itemType == typeof(string))
         {
             str = str.Replace("\\n", "\n");
             return(str);
         }
         if (itemType == typeof(int))
         {
             return(ParseIntPermissive(str));
         }
         if (itemType == typeof(float))
         {
             return(float.Parse(str, CultureInfo.InvariantCulture));
         }
         if (itemType == typeof(bool))
         {
             return(bool.Parse(str));
         }
         if (itemType == typeof(long))
         {
             return(long.Parse(str, CultureInfo.InvariantCulture));
         }
         if (itemType == typeof(double))
         {
             return(double.Parse(str, CultureInfo.InvariantCulture));
         }
         if (itemType == typeof(sbyte))
         {
             return(sbyte.Parse(str, CultureInfo.InvariantCulture));
         }
         if (itemType.IsEnum)
         {
             try
             {
                 object obj = BackCompatibility.BackCompatibleEnum(itemType, str);
                 if (obj != null)
                 {
                     return(obj);
                 }
                 return(Enum.Parse(itemType, str));
             }
             catch (ArgumentException innerException)
             {
                 string str2 = "'" + str + "' is not a valid value for " + itemType + ". Valid values are: \n";
                 str2 += GenText.StringFromEnumerable(Enum.GetValues(itemType));
                 ArgumentException ex = new ArgumentException(str2, innerException);
                 throw ex;
             }
         }
         if (itemType == typeof(Type))
         {
             if (str == "null" || str == "Null")
             {
                 return(null);
             }
             Type typeInAnyAssembly = GenTypes.GetTypeInAnyAssembly(str);
             if (typeInAnyAssembly == null)
             {
                 Log.Error("Could not find a type named " + str);
             }
             return(typeInAnyAssembly);
         }
         if (itemType == typeof(Action))
         {
             string[] array      = str.Split('.');
             string   methodName = array[array.Length - 1];
             string   empty      = string.Empty;
             empty = ((array.Length != 3) ? array[0] : (array[0] + "." + array[1]));
             Type       typeInAnyAssembly2 = GenTypes.GetTypeInAnyAssembly(empty);
             MethodInfo method             = typeInAnyAssembly2.GetMethods().First((MethodInfo m) => m.Name == methodName);
             return((Action)Delegate.CreateDelegate(typeof(Action), method));
         }
         if (itemType == typeof(Vector3))
         {
             return(FromStringVector3(str));
         }
         if (itemType == typeof(Vector2))
         {
             return(FromStringVector2(str));
         }
         if (itemType == typeof(Rect))
         {
             return(FromStringRect(str));
         }
         if (itemType == typeof(Color))
         {
             str = str.TrimStart('(', 'R', 'G', 'B', 'A');
             str = str.TrimEnd(')');
             string[] array2 = str.Split(',');
             float    num    = (float)FromString(array2[0], typeof(float));
             float    num2   = (float)FromString(array2[1], typeof(float));
             float    num3   = (float)FromString(array2[2], typeof(float));
             bool     flag   = num > 1f || num3 > 1f || num2 > 1f;
             float    num4   = (float)((!flag) ? 1 : 255);
             if (array2.Length == 4)
             {
                 num4 = (float)FromString(array2[3], typeof(float));
             }
             Color color = default(Color);
             if (!flag)
             {
                 color.r = num;
                 color.g = num2;
                 color.b = num3;
                 color.a = num4;
             }
             else
             {
                 color = GenColor.FromBytes(Mathf.RoundToInt(num), Mathf.RoundToInt(num2), Mathf.RoundToInt(num3), Mathf.RoundToInt(num4));
             }
             return(color);
         }
         if (itemType == typeof(PublishedFileId_t))
         {
             return(new PublishedFileId_t(ulong.Parse(str)));
         }
         if (itemType == typeof(IntVec2))
         {
             return(IntVec2.FromString(str));
         }
         if (itemType == typeof(IntVec3))
         {
             return(IntVec3.FromString(str));
         }
         if (itemType == typeof(Rot4))
         {
             return(Rot4.FromString(str));
         }
         if (itemType == typeof(CellRect))
         {
             return(CellRect.FromString(str));
         }
         if (itemType != typeof(CurvePoint))
         {
             if (itemType == typeof(NameTriple))
             {
                 NameTriple nameTriple = NameTriple.FromString(str);
                 nameTriple.ResolveMissingPieces();
             }
             else
             {
                 if (itemType == typeof(FloatRange))
                 {
                     return(FloatRange.FromString(str));
                 }
                 if (itemType == typeof(IntRange))
                 {
                     return(IntRange.FromString(str));
                 }
                 if (itemType == typeof(QualityRange))
                 {
                     return(QualityRange.FromString(str));
                 }
                 if (itemType == typeof(ColorInt))
                 {
                     str = str.TrimStart('(', 'R', 'G', 'B', 'A');
                     str = str.TrimEnd(')');
                     string[] array3   = str.Split(',');
                     ColorInt colorInt = new ColorInt(255, 255, 255, 255);
                     colorInt.r = (int)FromString(array3[0], typeof(int));
                     colorInt.g = (int)FromString(array3[1], typeof(int));
                     colorInt.b = (int)FromString(array3[2], typeof(int));
                     if (array3.Length == 4)
                     {
                         colorInt.a = (int)FromString(array3[3], typeof(int));
                     }
                     else
                     {
                         colorInt.a = 255;
                     }
                     return(colorInt);
                 }
             }
             throw new ArgumentException("Trying to parse to unknown data type " + itemType.Name + ". Content is '" + str + "'.");
         }
         return(CurvePoint.FromString(str));
     }
     catch (Exception innerException2)
     {
         ArgumentException ex2 = new ArgumentException("Exception parsing " + itemType + " from \"" + str + "\"", innerException2);
         throw ex2;
     }
 }
Exemple #2
0
 public static QualityRange ParseQualityRange(string str)
 {
     return(QualityRange.FromString(str));
 }
Exemple #3
0
        /// <summary>
        /// Reads the XML document and sets the name, description, and filter that will be used when creating this zone.
        /// </summary>
        /// <param name="xmlPath">The absolute path of the XML document to read.</param>
        private void InitFromXml(string xmlPath)
        {
            // Load the XML file into an XmlDocument
            XmlDocument xmlDocument = new XmlDocument();

            xmlDocument.LoadXml(File.ReadAllText(xmlPath));

            // Set the label and description
            this.defaultLabel = xmlDocument.SelectSingleNode("zoneData/defaultLabel").InnerText;
            this.defaultDesc  = xmlDocument.SelectSingleNode("zoneData/defaultDesc").InnerText;

            // If the description hasn't been set in this file yet, let the user know where the file is so they can edit it
            if (this.defaultDesc == "")
            {
                this.defaultDesc = "To customize this zone, edit the following file: " + xmlPath;
            }

            // Set the storage priority
            string storagePriorityString = xmlDocument.SelectSingleNode("zoneData/settings/priority").InnerText;

            switch (storagePriorityString.ToLower())
            {
            case "unstored":
                this.storageSettings.Priority = StoragePriority.Unstored;
                break;

            case "low":
                this.storageSettings.Priority = StoragePriority.Low;
                break;

            case "normal":
                this.storageSettings.Priority = StoragePriority.Normal;
                break;

            case "preferred":
                this.storageSettings.Priority = StoragePriority.Preferred;
                break;

            case "important":
                this.storageSettings.Priority = StoragePriority.Important;
                break;

            case "critical":
                this.storageSettings.Priority = StoragePriority.Critical;
                break;

            default:
                this.storageSettings.Priority = StoragePriority.Normal;
                break;
            }

            // Set the disallowed special filters
            XmlNodeList disallowedSpecialFilters = xmlDocument.SelectNodes("zoneData/settings/filter/disallowedSpecialFilters/li");

            foreach (XmlNode node in disallowedSpecialFilters)
            {
                this.storageSettings.filter.SetAllow(SpecialThingFilterDef.Named(node.InnerText), false);
            }

            // Set the allowed defs
            XmlNodeList allowedDefs = xmlDocument.SelectNodes("zoneData/settings/filter/allowedDefs/li");

            foreach (XmlNode node in allowedDefs)
            {
                this.storageSettings.filter.SetAllow(ThingDef.Named(node.InnerText), true);
            }

            // Set the allowed hit points range
            this.storageSettings.filter.AllowedHitPointsPercents = FloatRange.FromString(xmlDocument.SelectSingleNode("zoneData/settings/filter/allowedHitPointsPercents").InnerText);

            // Set the allowed quality range
            this.storageSettings.filter.AllowedQualityLevels = QualityRange.FromString(xmlDocument.SelectSingleNode("zoneData/settings/filter/allowedQualityLevels").InnerText);
        }
Exemple #4
0
        public static object FromString(string str, Type itemType)
        {
            object result;

            try
            {
                itemType = (Nullable.GetUnderlyingType(itemType) ?? itemType);
                if (itemType == typeof(string))
                {
                    str    = str.Replace("\\n", "\n");
                    result = str;
                }
                else if (itemType == typeof(int))
                {
                    result = int.Parse(str, CultureInfo.InvariantCulture);
                }
                else if (itemType == typeof(float))
                {
                    result = float.Parse(str, CultureInfo.InvariantCulture);
                }
                else if (itemType == typeof(bool))
                {
                    result = bool.Parse(str);
                }
                else if (itemType == typeof(long))
                {
                    result = long.Parse(str, CultureInfo.InvariantCulture);
                }
                else if (itemType == typeof(double))
                {
                    result = double.Parse(str, CultureInfo.InvariantCulture);
                }
                else if (itemType == typeof(sbyte))
                {
                    result = sbyte.Parse(str, CultureInfo.InvariantCulture);
                }
                else
                {
                    if (itemType.IsEnum)
                    {
                        try
                        {
                            result = Enum.Parse(itemType, str);
                            return(result);
                        }
                        catch (ArgumentException innerException)
                        {
                            string text = string.Concat(new object[]
                            {
                                "'",
                                str,
                                "' is not a valid value for ",
                                itemType,
                                ". Valid values are: \n"
                            });
                            text += GenText.StringFromEnumerable(Enum.GetValues(itemType));
                            ArgumentException ex = new ArgumentException(text, innerException);
                            throw ex;
                        }
                    }
                    if (itemType == typeof(Type))
                    {
                        if (str == "null" || str == "Null")
                        {
                            result = null;
                        }
                        else
                        {
                            Type typeInAnyAssembly = GenTypes.GetTypeInAnyAssembly(str);
                            if (typeInAnyAssembly == null)
                            {
                                Log.Error("Could not find a type named " + str);
                            }
                            result = typeInAnyAssembly;
                        }
                    }
                    else if (itemType == typeof(Action))
                    {
                        string[] array = str.Split(new char[]
                        {
                            '.'
                        });
                        string methodName = array[array.Length - 1];
                        string typeName   = string.Empty;
                        if (array.Length == 3)
                        {
                            typeName = array[0] + "." + array[1];
                        }
                        else
                        {
                            typeName = array[0];
                        }
                        Type       typeInAnyAssembly2 = GenTypes.GetTypeInAnyAssembly(typeName);
                        MethodInfo method             = typeInAnyAssembly2.GetMethods().First((MethodInfo m) => m.Name == methodName);
                        result = (Action)Delegate.CreateDelegate(typeof(Action), method);
                    }
                    else if (itemType == typeof(Vector3))
                    {
                        result = ParseHelper.FromStringVector3(str);
                    }
                    else if (itemType == typeof(Vector2))
                    {
                        result = ParseHelper.FromStringVector2(str);
                    }
                    else if (itemType == typeof(Rect))
                    {
                        result = ParseHelper.FromStringRect(str);
                    }
                    else if (itemType == typeof(Color))
                    {
                        str = str.TrimStart(new char[]
                        {
                            '(',
                            'R',
                            'G',
                            'B',
                            'A'
                        });
                        str = str.TrimEnd(new char[]
                        {
                            ')'
                        });
                        string[] array2 = str.Split(new char[]
                        {
                            ','
                        });
                        float num  = (float)ParseHelper.FromString(array2[0], typeof(float));
                        float num2 = (float)ParseHelper.FromString(array2[1], typeof(float));
                        float num3 = (float)ParseHelper.FromString(array2[2], typeof(float));
                        bool  flag = num > 1f || num3 > 1f || num2 > 1f;
                        float num4 = (float)((!flag) ? 1 : 255);
                        if (array2.Length == 4)
                        {
                            num4 = (float)ParseHelper.FromString(array2[3], typeof(float));
                        }
                        Color color;
                        if (!flag)
                        {
                            color.r = num;
                            color.g = num2;
                            color.b = num3;
                            color.a = num4;
                        }
                        else
                        {
                            color = GenColor.FromBytes(Mathf.RoundToInt(num), Mathf.RoundToInt(num2), Mathf.RoundToInt(num3), Mathf.RoundToInt(num4));
                        }
                        result = color;
                    }
                    else if (itemType == typeof(PublishedFileId_t))
                    {
                        result = new PublishedFileId_t(ulong.Parse(str));
                    }
                    else if (itemType == typeof(IntVec2))
                    {
                        result = IntVec2.FromString(str);
                    }
                    else if (itemType == typeof(IntVec3))
                    {
                        result = IntVec3.FromString(str);
                    }
                    else if (itemType == typeof(Rot4))
                    {
                        result = Rot4.FromString(str);
                    }
                    else if (itemType == typeof(CellRect))
                    {
                        result = CellRect.FromString(str);
                    }
                    else
                    {
                        if (itemType != typeof(CurvePoint))
                        {
                            if (itemType == typeof(NameTriple))
                            {
                                NameTriple nameTriple = NameTriple.FromString(str);
                                nameTriple.ResolveMissingPieces(null);
                            }
                            else
                            {
                                if (itemType == typeof(FloatRange))
                                {
                                    result = FloatRange.FromString(str);
                                    return(result);
                                }
                                if (itemType == typeof(IntRange))
                                {
                                    result = IntRange.FromString(str);
                                    return(result);
                                }
                                if (itemType == typeof(QualityRange))
                                {
                                    result = QualityRange.FromString(str);
                                    return(result);
                                }
                                if (itemType == typeof(ColorInt))
                                {
                                    str = str.TrimStart(new char[]
                                    {
                                        '(',
                                        'R',
                                        'G',
                                        'B',
                                        'A'
                                    });
                                    str = str.TrimEnd(new char[]
                                    {
                                        ')'
                                    });
                                    string[] array3 = str.Split(new char[]
                                    {
                                        ','
                                    });
                                    ColorInt colorInt = new ColorInt(255, 255, 255, 255);
                                    colorInt.r = (int)ParseHelper.FromString(array3[0], typeof(int));
                                    colorInt.g = (int)ParseHelper.FromString(array3[1], typeof(int));
                                    colorInt.b = (int)ParseHelper.FromString(array3[2], typeof(int));
                                    if (array3.Length == 4)
                                    {
                                        colorInt.a = (int)ParseHelper.FromString(array3[3], typeof(int));
                                    }
                                    else
                                    {
                                        colorInt.a = 255;
                                    }
                                    result = colorInt;
                                    return(result);
                                }
                            }
                            throw new ArgumentException(string.Concat(new string[]
                            {
                                "Trying to parse to unknown data type ",
                                itemType.Name,
                                ". Content is '",
                                str,
                                "'."
                            }));
                        }
                        result = CurvePoint.FromString(str);
                    }
                }
            }
            catch (Exception innerException2)
            {
                ArgumentException ex2 = new ArgumentException(string.Concat(new object[]
                {
                    "Exception parsing ",
                    itemType,
                    " from \"",
                    str,
                    "\""
                }), innerException2);
                throw ex2;
            }
            return(result);
        }
Exemple #5
0
        private static bool TryCreateBill(StreamReader sr, out Bill_Production bill)
        {
            bill = null;
            string[] kv = null;
            try
            {
                while (!sr.EndOfStream)
                {
                    if (ReadField(sr, out kv))
                    {
                        RecipeDef def;
                        switch (kv[0])
                        {
                        case BREAK:
                            return(true);

                        case "recipeDefName":
                            def = DefDatabase <RecipeDef> .GetNamed(kv[1]);

                            if (def == null)
                            {
                                string msg = "SaveStorageSettings.UnableToLoadRecipeDef".Translate().Replace("%s", kv[1]);
                                Messages.Message(msg, MessageTypeDefOf.SilentInput);
                                Log.Warning(msg);
                                return(false);
                            }
                            if (def.researchPrerequisite != null && !def.researchPrerequisite.IsFinished)
                            {
                                string msg = "SaveStorageSettings.ResearchNotDoneForRecipeDef".Translate().Replace("%s", def.label);
                                Messages.Message(msg, MessageTypeDefOf.SilentInput);
                                Log.Warning(msg);
                                return(false);
                            }
                            bill = new Bill_Production(def);
                            break;

                        case "recipeDefNameUft":
                            def = DefDatabase <RecipeDef> .GetNamed(kv[1]);

                            if (def == null)
                            {
                                string msg = "SaveStorageSettings.UnableToLoadRecipeDef".Translate().Replace("%s", kv[1]);
                                Messages.Message(msg, MessageTypeDefOf.SilentInput);
                                Log.Warning(msg);
                                return(false);
                            }
                            if (def.researchPrerequisite != null && !def.researchPrerequisite.IsFinished)
                            {
                                string msg = "SaveStorageSettings.ResearchNotDoneForRecipeDef".Translate().Replace("%s", def.label);
                                Messages.Message(msg, MessageTypeDefOf.SilentInput);
                                Log.Warning(msg);
                                return(false);
                            }
                            bill = new Bill_ProductionWithUft(def);
                            break;

                        case "skillRange":
                            kv = kv[1].Split('~');
                            bill.allowedSkillRange = new IntRange(int.Parse(kv[0]), int.Parse(kv[1]));
                            break;

                        case "suspended":
                            bill.suspended = bool.Parse(kv[1]);
                            break;

                        case "ingSearchRadius":
                            bill.ingredientSearchRadius = float.Parse(kv[1]);
                            break;

                        case "repeatMode":
                            bill.repeatMode = null;
                            if (BillRepeatModeDefOf.Forever.defName.Equals(kv[1]))
                            {
                                bill.repeatMode = BillRepeatModeDefOf.Forever;
                            }
                            else if (BillRepeatModeDefOf.RepeatCount.defName.Equals(kv[1]))
                            {
                                bill.repeatMode = BillRepeatModeDefOf.RepeatCount;
                            }
                            else if (BillRepeatModeDefOf.TargetCount.defName.Equals(kv[1]))
                            {
                                bill.repeatMode = BillRepeatModeDefOf.TargetCount;
                            }
                            else if ("TD_ColonistCount".Equals(kv[1]))
                            {
                                EverybodyGetsOneUtil.TryGetRepeatModeDef("TD_ColonistCount", out bill.repeatMode);
                            }
                            else if ("TD_XPerColonist".Equals(kv[1]))
                            {
                                EverybodyGetsOneUtil.TryGetRepeatModeDef("TD_XPerColonist", out bill.repeatMode);
                            }
                            else if ("TD_WithSurplusIng".Equals(kv[1]))
                            {
                                EverybodyGetsOneUtil.TryGetRepeatModeDef("TD_WithSurplusIng", out bill.repeatMode);
                            }

                            if (bill.repeatMode == null)
                            {
                                Log.Warning("Unknown repeatMode of [" + kv[1] + "] for bill " + bill.recipe.defName);
                                bill = null;
                                return(false);
                            }
                            break;

                        case "repeatCount":
                            bill.repeatCount = int.Parse(kv[1]);
                            break;

                        case "storeMode":
                            string[] storeSplit = kv[1].Split('/');

                            BillStoreModeDef storeMode = DefDatabase <BillStoreModeDef> .GetNamedSilentFail(storeSplit[0]);

                            if (storeMode == null)
                            {
                                Log.Message("Bill [" + bill.recipe.defName + "] storeMode [" + kv[1] + "] cannot be found. Defaulting to [" + BillStoreModeDefOf.BestStockpile.ToString() + "].");
                                storeMode = BillStoreModeDefOf.BestStockpile;
                            }

                            Zone_Stockpile storeZone = null;
                            if (storeMode == BillStoreModeDefOf.SpecificStockpile)
                            {
                                if (storeSplit.Length > 1)
                                {
                                    storeZone = (Zone_Stockpile)Find.CurrentMap?.zoneManager.AllZones.FirstOrFallback(z => z.GetUniqueLoadID() == storeSplit[1]);
                                }

                                if (storeZone == null)
                                {
                                    Log.Message("Bill [" + bill.recipe.defName + "] storeZone [" + kv[1] + "] cannot be found. Defaulting to storeMode [" + BillStoreModeDefOf.BestStockpile.ToString() + "].");
                                    storeMode = BillStoreModeDefOf.BestStockpile;
                                }
                            }

                            bill.SetStoreMode(storeMode, storeZone);
                            break;

                        case "targetCount":
                            bill.targetCount = int.Parse(kv[1]);
                            break;

                        case "includeEquipped":
                            bill.includeEquipped = bool.Parse(kv[1]);
                            break;

                        case "includeTainted":
                            bill.includeTainted = bool.Parse(kv[1]);
                            break;

                        case "includeFromZone":
                            Zone_Stockpile zone = (Zone_Stockpile)Find.CurrentMap?.zoneManager.AllZones.FirstOrFallback(z => z.GetUniqueLoadID() == kv[1]);

                            if (zone == null)
                            {
                                Log.Message("Bill [" + bill.recipe.defName + "] includeFromZone [" + kv[1] + "] cannot be found. Defaulting to Everywhere (null).");
                            }

                            bill.includeFromZone = zone;
                            break;

                        case "limitToAllowedStuff":
                            bill.limitToAllowedStuff = bool.Parse(kv[1]);
                            break;

                        case "pauseWhenSatisfied":
                            bill.pauseWhenSatisfied = bool.Parse(kv[1]);
                            break;

                        case "unpauseWhenYouHave":
                            bill.unpauseWhenYouHave = int.Parse(kv[1]);
                            break;

                        case "hpRange":
                            kv           = kv[1].Split('~');
                            bill.hpRange = new FloatRange(float.Parse(kv[0]), float.Parse(kv[1]));
                            break;

                        case "qualityRange":
                            bill.qualityRange = QualityRange.FromString(kv[1]);
                            break;

                        case "ingredientFilter":
                            ReadFiltersFromFile(bill.ingredientFilter, sr);
                            return(true);
                        }
                    }
                }
            }
            catch
            {
                string error = "";
                if (bill != null && bill.recipe != null)
                {
                    error = "Unable to load bill [" + bill.recipe.defName + "].";
                }
                else
                {
                    error = "Unable to load a bill.";
                }

                if (kv == null || kv.Length < 2)
                {
                    error += " Current line: [" + kv[0] + ":" + kv[1] + "]";
                }
                Log.Warning(error);
                bill = null;
                return(false);
            }
            return(true);
        }