public virtual void CopyAllowancesFrom(ThingFilter other)
 {
     this.allowedDefs.Clear();
     foreach (ThingDef allStorableThingDef in ThingFilter.AllStorableThingDefs)
     {
         this.SetAllow(allStorableThingDef, other.Allows(allStorableThingDef));
     }
     this.disallowedSpecialFilters     = other.disallowedSpecialFilters.ListFullCopyOrNull();
     this.allowedHitPointsPercents     = other.allowedHitPointsPercents;
     this.allowedHitPointsConfigurable = other.allowedHitPointsConfigurable;
     this.allowedQualities             = other.allowedQualities;
     this.allowedQualitiesConfigurable = other.allowedQualitiesConfigurable;
     this.thingDefs                = other.thingDefs.ListFullCopyOrNull();
     this.categories               = other.categories.ListFullCopyOrNull();
     this.exceptedThingDefs        = other.exceptedThingDefs.ListFullCopyOrNull();
     this.exceptedCategories       = other.exceptedCategories.ListFullCopyOrNull();
     this.specialFiltersToAllow    = other.specialFiltersToAllow.ListFullCopyOrNull();
     this.specialFiltersToDisallow = other.specialFiltersToDisallow.ListFullCopyOrNull();
     this.stuffCategoriesToAllow   = other.stuffCategoriesToAllow.ListFullCopyOrNull();
     this.allowAllWhoCanMake       = other.allowAllWhoCanMake.ListFullCopyOrNull();
     if (this.settingsChangedCallback != null)
     {
         this.settingsChangedCallback();
     }
 }
        internal int GetWeaponCount(ThingDef expectedDef, QualityRange qualityRange, FloatRange hpRange, ThingFilter ingredientFilter)
        {
            int count = 0;

            foreach (IEnumerable <ThingWithComps> l in this.StoredWeapons.Values)
            {
                foreach (ThingWithComps t in l)
                {
                    if (this.Allows(t, expectedDef, qualityRange, hpRange, ingredientFilter))
                    {
                        ++count;
                    }
                }
            }
            foreach (IEnumerable <ThingWithComps> l in this.StoredBioEncodedWeapons.Values)
            {
                foreach (ThingWithComps t in l)
                {
                    if (this.Allows(t, expectedDef, qualityRange, hpRange, ingredientFilter))
                    {
                        ++count;
                    }
                }
            }
            return(count);
        }
        public static void Add(this ThingFilter filter, ThingFilter other)
        {
            foreach (ThingDef def in other.AllowedThingDefs)
            {
                filter.SetAllow(def, true);
            }

            List <SpecialThingFilterDef> disallowedSpecialFilters = (List <SpecialThingFilterDef>)specials.GetValue(other);

            foreach (SpecialThingFilterDef specDef in disallowedSpecialFilters)
            {
                if (other.Allows(specDef))
                {
                    filter.SetAllow(specDef, true);
                }
            }

            QualityRange q  = filter.AllowedQualityLevels;
            QualityRange qO = other.AllowedQualityLevels;

            q.max = q.max > qO.max ? q.max : qO.max;
            q.min = q.min < qO.min ? q.min : qO.min;
            filter.AllowedQualityLevels = q;

            FloatRange hp  = filter.AllowedHitPointsPercents;
            FloatRange hpO = other.AllowedHitPointsPercents;

            hp.max = Math.Max(hp.max, hpO.max);
            hp.min = Math.Min(hp.min, hpO.min);
            filter.AllowedHitPointsPercents = hp;
        }
        private bool Allows(Thing t, ThingDef expectedDef, QualityRange qualityRange, FloatRange hpRange, ThingFilter filter)
        {
#if DEBUG || DEBUG_DO_UNTIL_X
            Log.Warning("StoredApparel.Allows Begin [" + t.Label + "]");
#endif
            if (t.def != expectedDef)
            {
#if DEBUG || DEBUG_DO_UNTIL_X
                Log.Warning("StoredApparel.Allows End Def Does Not Match [False]");
#endif
                return(false);
            }
#if DEBUG || DEBUG_DO_UNTIL_X
            Log.Message("    def uses HP: " + expectedDef.useHitPoints + " filter: " + hpRange.min + " " + hpRange.max);
#endif
            if (expectedDef.useHitPoints &&
                hpRange != null &&
                hpRange.min != 0f && hpRange.max != 100f)
            {
                float num = (float)t.HitPoints / (float)t.MaxHitPoints;
                num = GenMath.RoundedHundredth(num);
                if (!hpRange.IncludesEpsilon(Mathf.Clamp01(num)))
                {
#if DEBUG || DEBUG_DO_UNTIL_X
                    Log.Warning("StoredApparel.Allows End Hit Points [False - HP]");
#endif
                    return(false);
                }
            }
#if DEBUG || DEBUG_DO_UNTIL_X
            Log.Message("    def follows quality: " + t.def.FollowQualityThingFilter() + " filter quality levels: " + qualityRange.min + " " + qualityRange.max);
#endif
            if (qualityRange != null && qualityRange != QualityRange.All && t.def.FollowQualityThingFilter())
            {
                QualityCategory p;
                if (!t.TryGetQuality(out p))
                {
                    p = QualityCategory.Normal;
                }
                if (!qualityRange.Includes(p))
                {
#if DEBUG || DEBUG_DO_UNTIL_X
                    Log.Warning("StoredApparel.Allows End Quality [False - Quality]");
#endif
                    return(false);
                }
            }

            if (filter != null && !filter.Allows(t.Stuff))
            {
#if DEBUG || DEBUG_DO_UNTIL_X
                Log.Warning("StoredApparel.Allows End Quality [False - filters.Allows]");
#endif
                return(false);
            }
#if DEBUG || DEBUG_DO_UNTIL_X
            Log.Warning("    StoredApparel.Allows End [True]");
#endif
            return(true);
        }
Example #5
0
 public virtual void CopyAllowancesFrom(ThingFilter other)
 {
     allowedDefs.Clear();
     foreach (ThingDef allDef in DefDatabase <ThingDef> .AllDefs)
     {
         SetAllow(allDef, other.Allows(allDef));
     }
     disallowedSpecialFilters     = other.disallowedSpecialFilters.ListFullCopyOrNull();
     allowedHitPointsPercents     = other.allowedHitPointsPercents;
     allowedHitPointsConfigurable = other.allowedHitPointsConfigurable;
     allowedQualities             = other.allowedQualities;
     allowedQualitiesConfigurable = other.allowedQualitiesConfigurable;
     thingDefs                   = other.thingDefs.ListFullCopyOrNull();
     categories                  = other.categories.ListFullCopyOrNull();
     tradeTagsToAllow            = other.tradeTagsToAllow.ListFullCopyOrNull();
     tradeTagsToDisallow         = other.tradeTagsToDisallow.ListFullCopyOrNull();
     thingSetMakerTagsToAllow    = other.thingSetMakerTagsToAllow.ListFullCopyOrNull();
     thingSetMakerTagsToDisallow = other.thingSetMakerTagsToDisallow.ListFullCopyOrNull();
     disallowedCategories        = other.disallowedCategories.ListFullCopyOrNull();
     specialFiltersToAllow       = other.specialFiltersToAllow.ListFullCopyOrNull();
     specialFiltersToDisallow    = other.specialFiltersToDisallow.ListFullCopyOrNull();
     stuffCategoriesToAllow      = other.stuffCategoriesToAllow.ListFullCopyOrNull();
     allowAllWhoCanMake          = other.allowAllWhoCanMake.ListFullCopyOrNull();
     disallowWorsePreferability  = other.disallowWorsePreferability;
     disallowInedibleByHuman     = other.disallowInedibleByHuman;
     allowWithComp               = other.allowWithComp;
     disallowWithComp            = other.disallowWithComp;
     disallowCheaperThan         = other.disallowCheaperThan;
     disallowedThingDefs         = other.disallowedThingDefs.ListFullCopyOrNull();
     if (settingsChangedCallback != null)
     {
         settingsChangedCallback();
     }
 }
 public virtual void CopyAllowancesFrom(ThingFilter other)
 {
     this.allowedDefs.Clear();
     foreach (ThingDef thingDef in ThingFilter.AllStorableThingDefs)
     {
         this.SetAllow(thingDef, other.Allows(thingDef));
     }
     this.disallowedSpecialFilters     = other.disallowedSpecialFilters.ListFullCopyOrNull <SpecialThingFilterDef>();
     this.allowedHitPointsPercents     = other.allowedHitPointsPercents;
     this.allowedHitPointsConfigurable = other.allowedHitPointsConfigurable;
     this.allowedQualities             = other.allowedQualities;
     this.allowedQualitiesConfigurable = other.allowedQualitiesConfigurable;
     this.thingDefs                   = other.thingDefs.ListFullCopyOrNull <ThingDef>();
     this.categories                  = other.categories.ListFullCopyOrNull <string>();
     this.tradeTagsToAllow            = other.tradeTagsToAllow.ListFullCopyOrNull <string>();
     this.tradeTagsToDisallow         = other.tradeTagsToDisallow.ListFullCopyOrNull <string>();
     this.thingSetMakerTagsToAllow    = other.thingSetMakerTagsToAllow.ListFullCopyOrNull <string>();
     this.thingSetMakerTagsToDisallow = other.thingSetMakerTagsToDisallow.ListFullCopyOrNull <string>();
     this.disallowedCategories        = other.disallowedCategories.ListFullCopyOrNull <string>();
     this.specialFiltersToAllow       = other.specialFiltersToAllow.ListFullCopyOrNull <string>();
     this.specialFiltersToDisallow    = other.specialFiltersToDisallow.ListFullCopyOrNull <string>();
     this.stuffCategoriesToAllow      = other.stuffCategoriesToAllow.ListFullCopyOrNull <StuffCategoryDef>();
     this.allowAllWhoCanMake          = other.allowAllWhoCanMake.ListFullCopyOrNull <ThingDef>();
     this.disallowWorsePreferability  = other.disallowWorsePreferability;
     this.disallowInedibleByHuman     = other.disallowInedibleByHuman;
     this.allowWithComp               = other.allowWithComp;
     this.disallowWithComp            = other.disallowWithComp;
     this.disallowCheaperThan         = other.disallowCheaperThan;
     this.disallowedThingDefs         = other.disallowedThingDefs.ListFullCopyOrNull <ThingDef>();
     if (this.settingsChangedCallback != null)
     {
         this.settingsChangedCallback();
     }
 }
Example #7
0
        public Filter(ThingDef thing)
        {
            this.forThing = thing;
            this.stuffs   = new HashSet <ThingDef>();

            this.allowedQualities = QualityRange.All;
            this.allowedHpRange   = FloatRange.ZeroToOne;
        }
Example #8
0
        public static void TrySpawnWeaponOnRack(Thing rack)
        {
            Building_Storage storage      = rack as Building_Storage;
            QualityRange     qualityRange = new QualityRange(QualityCategory.Good, QualityCategory.Legendary);

            storage.settings.filter.AllowedQualityLevels = qualityRange;
            FloatRange hitPointsRange = new FloatRange(0.8f, 1f);

            storage.settings.filter.AllowedHitPointsPercents = hitPointsRange;
            foreach (IntVec3 cell in rack.OccupiedRect())
            {
                if (Rand.Value < 0.33f)
                {
                    float       weaponSelector = Rand.Value;
                    ThingDef    thingDef       = ThingDefOf.Gun_Pistol;
                    const float weaponsRatio   = 1f / 7f;
                    if (weaponSelector < weaponsRatio * 1f)
                    {
                        thingDef = ThingDef.Named("Gun_PumpShotgun");
                    }
                    else if (weaponSelector < weaponsRatio * 2f)
                    {
                        thingDef = ThingDef.Named("Gun_AssaultRifle");
                    }
                    else if (weaponSelector < weaponsRatio * 3f)
                    {
                        thingDef = ThingDef.Named("Gun_SniperRifle");
                    }
                    else if (weaponSelector < weaponsRatio * 4f)
                    {
                        thingDef = ThingDef.Named("Gun_IncendiaryLauncher");
                    }
                    else if (weaponSelector < weaponsRatio * 5f)
                    {
                        thingDef = ThingDef.Named("Gun_LMG");
                    }
                    else if (weaponSelector < weaponsRatio * 6f)
                    {
                        thingDef = ThingDef.Named("Gun_ChargeRifle");
                    }
                    else
                    {
                        thingDef = ThingDefOf.Gun_Pistol;
                    }

                    Thing       weapon      = ThingMaker.MakeThing(thingDef);
                    CompQuality qualityComp = weapon.TryGetComp <CompQuality>();
                    if (qualityComp != null)
                    {
                        QualityCategory quality = (QualityCategory)Rand.RangeInclusive((int)QualityCategory.Normal, (int)QualityCategory.Excellent);
                        qualityComp.SetQuality(quality, ArtGenerationContext.Outsider);
                    }
                    GenSpawn.Spawn(weapon, cell);
                }
            }
        }
Example #9
0
		private static void DrawQualityFilterConfig(ref float y, float width, ThingFilter filter)
		{
			Rect rect = new Rect(20f, y, width - 20f, 28f);
			QualityRange range = filter.AllowedQualityLevels;
			Widgets.QualityRange(rect, 876813230, ref range);
			filter.AllowedQualityLevels = range;
			y += 28f;
			y += 5f;
			Text.Font = GameFont.Small;
		}
Example #10
0
 public static void Postfix(ThingFilter filter, QualityRange __state)
 {
     if (__state != filter.AllowedQualityLevels)
     {
         if (RankComp.settingsChangedCallbackInfo.GetValue(filter) is Action a)
         {
             a();
         }
     }
 }
        private static void DrawQualityFilterConfig(ref float y, float width, ThingFilter filter)
        {
            Rect         rect = new Rect(20f, y, (float)(width - 20.0), 28f);
            QualityRange allowedQualityLevels = filter.AllowedQualityLevels;

            Widgets.QualityRange(rect, 2, ref allowedQualityLevels);
            filter.AllowedQualityLevels = allowedQualityLevels;
            y        += 28f;
            y        += 5f;
            Text.Font = GameFont.Small;
        }
        private void DrawQualityFilterConfig(float x, ref float y, float width, SharedWeaponFilter filter)
        {
            Rect         rect = new Rect(x + 20f, y, width - 40f, 28f);
            QualityRange allowedQualityLevels = filter.QualityRange;

            Widgets.QualityRange(rect, "WeaponStorageQualityRange".GetHashCode(), ref allowedQualityLevels);
            filter.QualityRange = allowedQualityLevels;
            y        += 28f;
            y        += 5f;
            Text.Font = GameFont.Small;
        }
Example #13
0
        /// <summary>
        /// Draw quality slider.
        /// </summary>
        /// <param name="qualityRect"> Rect for drawing. </param>
        /// <param name="dragID"> A unique drag ID that can be used for identifying this slider. </param>
        protected virtual void DrawQualitySlider(Rect qualityRect, int dragID)
        {
            QualityRange qualityRange = _isSeparated ? _selectedSingleThingSelector.AllowedQualityLevel : _groupSelector.SingleThingSelectors.First().AllowedQualityLevel;

            Widgets.QualityRange(qualityRect, dragID, ref qualityRange);
            if (_isSeparated)
            {
                _selectedSingleThingSelector.SetQualityRange(qualityRange);
            }
            else
            {
                _groupSelector.SingleThingSelectors.ForEach(s => s.SetQualityRange(qualityRange));
            }
        }
Example #14
0
        private static void DrawQualityFilterConfig(ref float y, float width, ThingFilter filter)
        {
            if (!filter.allowedQualitiesConfigurable)
            {
                return;
            }
            Rect         arg_2B_0             = new Rect(20f, y, width - 20f, 26f);
            QualityRange allowedQualityLevels = filter.AllowedQualityLevels;

            Widgets.QualityRange(arg_2B_0, 2, ref allowedQualityLevels);
            filter.AllowedQualityLevels = allowedQualityLevels;
            y        += 26f;
            y        += 5f;
            Text.Font = GameFont.Small;
        }
        internal int GetApparelCount(ThingDef expectedDef, QualityRange qualityRange, FloatRange hpRange, ThingFilter filter)
        {
            LinkedList <Apparel> l;

            if (this.StoredApparelLookup.TryGetValue(expectedDef, out l))
            {
                int count = 0;
                foreach (Apparel a in l)
                {
                    if (this.Allows(a, expectedDef, qualityRange, hpRange, filter))
                    {
                        ++count;
                    }
                }
                return(count);
            }
            return(0);
        }
Example #16
0
        public override void DoWindowContents(Rect inRect)
        {
            if (thingFilter.AllowedThingDefs.Count() > 1)
            {
                thingFilter = new ThingFilter();
                thingFilter.AllowedQualityLevels     = SelectQualities;
                thingFilter.AllowedHitPointsPercents = SelectHitPointsPercents;
                thingFilter.SetDisallowAll(null, null);
            }
            SelectThingDef          = thingFilter.AllowedThingDefs.FirstOrDefault();
            SelectQualities         = thingFilter.AllowedQualityLevels;
            SelectHitPointsPercents = thingFilter.AllowedHitPointsPercents;

            const float mainListingSpacing = 6f;

            var btnSize      = new Vector2(140f, 40f);
            var buttonYStart = inRect.height - btnSize.y;

            /*
             * var ev = Event.current;
             * if (Widgets.ButtonText(new Rect(0, buttonYStart, btnSize.x, btnSize.y), "OCity_DialogInput_Ok".Translate())
             || ev.isKey && ev.type == EventType.KeyDown && ev.keyCode == KeyCode.Return)
             */
            if (SelectThingDef != null)
            {
                Close();
            }

            if (Widgets.ButtonText(new Rect(inRect.width - btnSize.x, buttonYStart, btnSize.x, btnSize.y), "OCity_DialogInput_Cancele".Translate()))
            {
                Close();
            }

            //выше кнопок
            Rect workRect = new Rect(inRect.x, inRect.y, inRect.width, buttonYStart - mainListingSpacing);

            ThingFilterUI.DoThingFilterConfigWindow(workRect, ref this.scrollPosition, thingFilter, null, 8);
        }
Example #17
0
        public static void TrySpawnWeaponOnRack(Thing rack)
        {
            Building_Storage storage = rack as Building_Storage;
            QualityRange qualityRange = new QualityRange(QualityCategory.Good, QualityCategory.Legendary);
            storage.settings.filter.AllowedQualityLevels = qualityRange;
            FloatRange hitPointsRange = new FloatRange(0.8f, 1f);
            storage.settings.filter.AllowedHitPointsPercents = hitPointsRange;
            foreach (IntVec3 cell in rack.OccupiedRect())
            {
                if (Rand.Value < 0.33f)
                {
                    float weaponSelector = Rand.Value;
                    ThingDef thingDef = ThingDefOf.Gun_Pistol;
                    const float weaponsRatio = 1f / 7f;
                    if (weaponSelector < weaponsRatio * 1f)
                    {
                        thingDef = ThingDef.Named("Gun_PumpShotgun");
                    }
                    else if (weaponSelector < weaponsRatio * 2f)
                    {
                        thingDef = ThingDef.Named("Gun_AssaultRifle");
                    }
                    else if (weaponSelector < weaponsRatio * 3f)
                    {
                        thingDef = ThingDef.Named("Gun_SniperRifle");
                    }
                    else if (weaponSelector < weaponsRatio * 4f)
                    {
                        thingDef = ThingDef.Named("Gun_IncendiaryLauncher");
                    }
                    else if (weaponSelector < weaponsRatio * 5f)
                    {
                        thingDef = ThingDef.Named("Gun_LMG");
                    }
                    else if (weaponSelector < weaponsRatio * 6f)
                    {
                        thingDef = ThingDef.Named("Gun_ChargeRifle");
                    }
                    else
                    {
                        thingDef = ThingDefOf.Gun_Pistol;
                    }

                    Thing weapon = ThingMaker.MakeThing(thingDef);
                    CompQuality qualityComp = weapon.TryGetComp<CompQuality>();
                    if (qualityComp != null)
                    {
                        QualityCategory quality = (QualityCategory)Rand.RangeInclusive((int)QualityCategory.Normal, (int)QualityCategory.Excellent);
                        qualityComp.SetQuality(quality, ArtGenerationContext.Outsider);
                    }
                    GenSpawn.Spawn(weapon, cell);
                }
            }
        }
Example #18
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;
     }
 }
Example #19
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);
        }
Example #20
0
 //private static void DrawQualityFilterConfig(ref float y, float width, ThingFilter filter)
 public static void Prefix(ThingFilter filter, ref QualityRange __state)
 {
     __state = filter.AllowedQualityLevels;
 }
Example #21
0
 internal int GetApparelCount(ThingDef def, QualityRange qualityRange, FloatRange hpRange, ThingFilter ingredientFilter)
 {
     return(this.StoredApparel.GetApparelCount(def, qualityRange, hpRange, ingredientFilter));
 }
        public QualityRangeWidget(QualityRange qr)
        {
            this.QualityRange = qr;

            this.ResetBuffers();
        }
            public static bool ProductMeetsQualityRequirement(Thing product, QualityRange qualityRange)
            {
                var qualityComp = product.GetInnerIfMinified().TryGetComp <CompQuality>();

                return(qualityComp == null || qualityRange.Includes(qualityComp.Quality));
            }
Example #24
0
 public void SetQualityRange(QualityRange range)
 {
     this.allowedQualities = range;
 }
Example #25
0
 public static void SetAllowedQualities(ThingFilter f, QualityRange qr)
 {
     typeof(ThingFilter).GetField("allowedQualities", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(f, qr);
 }
 public QualityRangeStats(QualityRange qr)
 {
     this.Min = qr.min;
     this.Max = qr.max;
 }
Example #27
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);
        }
Example #28
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);
        }
Example #29
0
 public static QualityRange ParseQualityRange(string str)
 {
     return(QualityRange.FromString(str));
 }