rimworld-blax-defaults/Source/BlaxDefaults/StorageKinds.cs

326 lines
15 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using HarmonyLib;
using RimWorld;
using Verse;
namespace BlaxDefaults
{
/// <summary>
/// A stockpile type: the vanilla stockpile, the vanilla dumping stockpile, or a modded subclass of
/// Designator_ZoneAddStockpile, which is a type of its own. A Zone_Stockpile doesn't remember which
/// designator made it, so on a stockpile every type is offered.
/// </summary>
public sealed class StockpileType
{
public readonly string Key;
public readonly StorageSettingsPreset Preset;
/// <summary>Null for the two vanilla types; the designator class for a modded type.</summary>
public readonly Type DesignatorType;
private readonly string moddedLabel;
public StockpileType(string key, StorageSettingsPreset preset, Type designatorType, string moddedLabel)
{
Key = key;
Preset = preset;
DesignatorType = designatorType;
this.moddedLabel = moddedLabel;
}
public bool IsVanilla => DesignatorType == null;
/// <summary>"stockpile", "dumping stockpile", or a modded designator's NewZoneLabel.</summary>
public string Label
{
get
{
if (Key == DefaultsKeys.Stockpile) return "BlaxDefaults_KindStockpile".Translate();
if (Key == DefaultsKeys.Dumping) return "BlaxDefaults_KindDumping".Translate();
return moddedLabel.NullOrEmpty() ? DesignatorType.Name : moddedLabel;
}
}
public string LabelPlural
{
get
{
if (Key == DefaultsKeys.Stockpile) return "BlaxDefaults_KindStockpilePlural".Translate();
if (Key == DefaultsKeys.Dumping) return "BlaxDefaults_KindDumpingPlural".Translate();
return StorageKinds.PluralOf(Label);
}
}
public override string ToString() => Key;
}
/// <summary>
/// One kind that has its own storage default: a stockpile type, a storage building def, or (1.1) a forbid
/// rule, whose filter is a template too. Knows its key, label, parent filter and the game's default, and
/// loads a default onto settings.
/// </summary>
public sealed class StorageKind
{
public readonly string Key;
/// <summary>The building def, or null for a stockpile type.</summary>
public readonly ThingDef Def;
/// <summary>The stockpile type, or null for a building.</summary>
public readonly StockpileType Stockpile;
/// <summary>The forbid rule whose filter this is, or null for storage.</summary>
public readonly ForbidRule Forbid;
public StorageKind(ThingDef def)
{
Def = def;
Key = DefaultsKeys.ForStorage(def);
}
public StorageKind(StockpileType stockpile)
{
Stockpile = stockpile;
Key = stockpile.Key;
}
public StorageKind(ForbidRule rule)
{
Forbid = rule;
Key = rule.Key;
}
public bool IsStockpile => Stockpile != null;
/// <summary>A forbid rule's filter: no priority, the unlisted rule is Refuse or Allow.</summary>
public bool IsForbid => Forbid != null;
/// <summary>"shelf", "stockpile", "gear enemies drop".</summary>
public string Label => Def != null ? Def.label : Forbid != null ? Forbid.Label : Stockpile.Label;
/// <summary>
/// "shelves", "stockpiles". A key BlaxDefaults_Plural_&lt;defName&gt; in the active language wins over
/// StorageKinds.PluralOf.
/// </summary>
public string LabelPlural
{
get
{
if (Forbid != null)
return Forbid.Label;
if (Def == null)
return Stockpile.LabelPlural;
string key = "BlaxDefaults_Plural_" + Def.defName;
return key.CanTranslate() ? key.Translate().Resolve() : StorageKinds.PluralOf(Def.label);
}
}
/// <summary>What settings of this kind may ever allow: the building's fixedStorageSettings, else every storable item.</summary>
public ThingFilter ParentFilter =>
Def != null ? StorageKinds.ParentFilterFor(Def) : Forbid != null ? ForbidRules.ParentFilter : StorageKinds.StockpileParentFilter;
/// <summary>The saved default, or null.</summary>
public StorageTemplate Saved => DefaultsLibrary.Get<StorageTemplate>(Key);
/// <summary>A fresh scratch StorageSettings holding the game's default for this kind.</summary>
public StorageSettings GameDefault() =>
Def != null ? StorageKinds.GameDefaultFor(Def) : Forbid != null ? ForbidRules.BaseSettings() : StorageKinds.GameDefaultFor(Stockpile);
/// <summary>Replaces the target's priority, filter, special filters and ranges with the game's default.</summary>
public void LoadGameDefault(StorageSettings target) => target.CopyFrom(GameDefault());
/// <summary>
/// The game's default with the template on top, written in one CopyFrom: the same settings a new
/// thing of this kind gets. Without a template, the game's default.
/// </summary>
public void LoadDefault(StorageSettings target, StorageTemplate template)
{
StorageSettings scratch = GameDefault();
template?.ApplyTo(scratch, ParentFilter);
target.CopyFrom(scratch);
}
/// <summary>A template of these settings under this kind's key (unlisted = Game), not yet saved.</summary>
public StorageTemplate Capture(StorageSettings settings) => StorageTemplate.Capture(Key, settings, ParentFilter);
public override string ToString() => Key;
}
/// <summary>The kinds Defaults covers and the game's defaults for them.</summary>
public static class StorageKinds
{
/// <summary>The protected preset field of the vanilla stockpile designators.</summary>
public static readonly AccessTools.FieldRef<Designator_ZoneAddStockpile, StorageSettingsPreset> PresetRef =
AccessTools.FieldRefAccess<Designator_ZoneAddStockpile, StorageSettingsPreset>("preset");
private static readonly Func<Designator_ZoneAdd, string> NewZoneLabelGetter =
AccessTools.MethodDelegate<Func<Designator_ZoneAdd, string>>(AccessTools.PropertyGetter(typeof(Designator_ZoneAdd), "NewZoneLabel"));
private static List<ThingDef> everStorable;
private static List<StockpileType> stockpileTypes;
public static readonly StockpileType VanillaStockpile =
new StockpileType(DefaultsKeys.Stockpile, StorageSettingsPreset.DefaultStockpile, null, null);
public static readonly StockpileType VanillaDumping =
new StockpileType(DefaultsKeys.Dumping, StorageSettingsPreset.DumpingStockpile, null, null);
/// <summary>Every def with EverStorable(willMinifyIfPossible: true), in def order. Built once.</summary>
public static List<ThingDef> EverStorableDefs =>
everStorable ??= DefDatabase<ThingDef>.AllDefsListForReading.Where(d => d.EverStorable(willMinifyIfPossible: true)).ToList();
/// <summary>Every storable def the parent filter allows (all storable defs when it is null).</summary>
public static IEnumerable<ThingDef> StorableDefs(ThingFilter parentFilter)
{
foreach (ThingDef def in EverStorableDefs)
{
if (parentFilter == null || parentFilter.Allows(def))
yield return def;
}
}
public static ThingFilter StockpileParentFilter => StorageSettings.EverStorableFixedSettings().filter;
/// <summary>The vanilla stockpile, the vanilla dumping stockpile, then one type per modded stockpile designator.</summary>
public static List<StockpileType> StockpileTypes => stockpileTypes ??= BuildStockpileTypes();
/// <summary>
/// The type a designator makes: _Resources and _Expand give the vanilla stockpile, _Dumping the dumping
/// stockpile, any other subclass its own type.
/// </summary>
public static StockpileType StockpileTypeOf(Designator_ZoneAddStockpile designator)
{
if (designator == null)
return null;
Type t = designator.GetType();
if (IsVanillaStockpileDesignator(t))
return PresetRef(designator) == StorageSettingsPreset.DumpingStockpile ? VanillaDumping : VanillaStockpile;
string key = DefaultsKeys.ForStockpileDesignator(t);
return StockpileTypes.FirstOrDefault(s => s.Key == key)
?? new StockpileType(key, PresetRef(designator), t, SafeNewZoneLabel(designator));
}
public static StockpileType StockpileTypeForKey(string key) => StockpileTypes.FirstOrDefault(s => s.Key == key);
public static bool IsVanillaStockpileDesignator(Type t) =>
t == typeof(Designator_ZoneAddStockpile_Resources) || t == typeof(Designator_ZoneAddStockpile_Expand) || t == typeof(Designator_ZoneAddStockpile_Dumping);
/// <summary>True when the def's blueprint is a Blueprint_Storage or a subclass: shelves, bookcases, the hopper, fridges, weapon racks.</summary>
public static bool HasStorageBlueprint(ThingDef def) =>
def?.building?.blueprintClass != null && typeof(Blueprint_Storage).IsAssignableFrom(def.building.blueprintClass);
/// <summary>
/// Building kinds that get a default when made and a Defaults button. 1.0: defs with a storage
/// blueprint. 1.1 widens this to every def with a storage tab.
/// </summary>
public static bool IsCovered(ThingDef def) => HasStorageBlueprint(def);
/// <summary>Every covered building def, in def order.</summary>
public static IEnumerable<ThingDef> CoveredDefs() => DefDatabase<ThingDef>.AllDefsListForReading.Where(IsCovered);
public static ThingFilter ParentFilterFor(ThingDef def) =>
def?.building?.fixedStorageSettings?.filter ?? StockpileParentFilter;
/// <summary>
/// The game's default for a building on a scratch StorageSettings: a copy of
/// def.building.defaultStorageSettings, or, when the def has none, an empty filter at the priority a
/// fresh StorageSettings(parent) takes (the fixed settings' priority, else Normal), as PostMake leaves it.
/// Defaults never edits defaultStorageSettings, so this always holds the loaded value.
/// </summary>
public static StorageSettings GameDefaultFor(ThingDef def)
{
var s = new StorageSettings();
StorageSettings d = def?.building?.defaultStorageSettings;
if (d != null)
s.CopyFrom(d);
else
s.Priority = def?.building?.fixedStorageSettings?.Priority ?? StoragePriority.Normal;
return s;
}
/// <summary>The game's default for a stockpile type: SetFromPreset with its preset at Normal, as the Zone_Stockpile constructor does.</summary>
public static StorageSettings GameDefaultFor(StockpileType type)
{
var s = new StorageSettings();
s.SetFromPreset(type?.Preset ?? StorageSettingsPreset.DefaultStockpile);
s.Priority = StoragePriority.Normal;
return s;
}
/// <summary>
/// The plural of a kind's label for the menu, tooltips and the settings page: the active language worker's,
/// with two fixes for English, whose rule appends "s" after any last character
/// (Verse/LanguageWorker_English.cs:140-152): a label ending in "shelf" ends in "shelves", and a note in
/// parentheses at the end stays there ("Weapon Rack (1 slot)" gives "Weapon Racks (1 slot)", not
/// "Weapon Rack (1 slot)s"). An English label that doesn't end in a letter is returned unchanged.
/// </summary>
public static string PluralOf(string label)
{
if (label.NullOrEmpty())
return label;
LanguageWorker worker = Find.ActiveLanguageWorker;
if (!(worker is LanguageWorker_English))
return worker != null ? worker.Pluralize(label) : label;
string head = label, note = "";
int open = label.LastIndexOf(" (", StringComparison.Ordinal);
if (open > 0 && label.EndsWith(")", StringComparison.Ordinal))
{
head = label.Substring(0, open);
note = label.Substring(open);
}
if (head.Length == 0 || !char.IsLetter(head[head.Length - 1]))
return label;
if (head.EndsWith("shelf", StringComparison.OrdinalIgnoreCase))
return head.Substring(0, head.Length - 1) + (char.IsUpper(head[head.Length - 1]) ? "VES" : "ves") + note;
return worker.Pluralize(head) + note;
}
public static StorageKind ForDef(ThingDef def) => def == null ? null : new StorageKind(def);
public static StorageKind ForStockpile(StockpileType type) => type == null ? null : new StorageKind(type);
public static StorageKind ForForbid(ForbidRule rule) => rule == null ? null : new StorageKind(rule);
/// <summary>The kind for a library key, or null when its def or designator is not loaded.</summary>
public static StorageKind ForKey(string key)
{
if (DefaultsKeys.IsStorage(key))
return ForDef(DefDatabase<ThingDef>.GetNamedSilentFail(DefaultsKeys.NameOf(key)));
if (DefaultsKeys.IsStockpile(key))
return ForStockpile(StockpileTypeForKey(key));
if (DefaultsKeys.IsForbid(key))
return ForForbid(ForbidRules.ForKey(key));
return null;
}
private static List<StockpileType> BuildStockpileTypes()
{
var list = new List<StockpileType> { VanillaStockpile, VanillaDumping };
// Modded designators: the instances the game made for its architect menu carry their preset.
var seen = new HashSet<Type>();
foreach (DesignationCategoryDef cat in DefDatabase<DesignationCategoryDef>.AllDefsListForReading)
{
if (cat.AllResolvedDesignators == null)
continue;
foreach (Designator d in cat.AllResolvedDesignators)
{
if (!(d is Designator_ZoneAddStockpile zd) || IsVanillaStockpileDesignator(d.GetType()) || !seen.Add(d.GetType()))
continue;
list.Add(new StockpileType(DefaultsKeys.ForStockpileDesignator(d.GetType()), PresetRef(zd), d.GetType(), SafeNewZoneLabel(zd)));
}
}
return list;
}
private static string SafeNewZoneLabel(Designator_ZoneAdd d)
{
try
{
return NewZoneLabelGetter(d);
}
catch
{
return null;
}
}
}
}