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

228 lines
10 KiB
C#
Raw Permalink Normal View History

using System;
using System.Collections.Generic;
using System.Globalization;
using RimWorld;
using Verse;
namespace BlaxDefaults
{
/// <summary>What a storage default does with items it lists in neither "allowed" nor "refused".</summary>
public enum UnlistedRule
{
/// <summary>Follow the game's default for the kind. What "Make default" saves.</summary>
Game,
/// <summary>Refuse them. What the quick setup saves, so an empty shelf stays empty when a mod adds items.</summary>
Refuse,
Allow,
}
public static class UnlistedRuleExtensions
{
public static string Label(this UnlistedRule rule) => ("BlaxDefaults_Unlisted" + rule).Translate();
}
/// <summary>
/// A storage default for a stockpile type or a storage building: the priority, every item it allows and
/// every item it refuses (ThingDef names), a rule for items it lists in neither, the special filters,
/// and the hit points and quality ranges. Never a deep-saved ThingFilter: ThingFilter.ExposeData
/// resolves defs, and a missing one would break the load.
/// </summary>
public class StorageTemplate : DefaultsEntry
{
/// <summary>StoragePriority enum name. An unknown name leaves the priority alone.</summary>
public string priority = nameof(StoragePriority.Normal);
public List<string> allowed = new List<string>();
public List<string> refused = new List<string>();
public UnlistedRule unlisted = UnlistedRule.Game;
public List<string> allowedSpecial = new List<string>();
public List<string> refusedSpecial = new List<string>();
public FloatRange hitPoints = FloatRange.ZeroToOne;
public QualityRange quality = QualityRange.All;
public StorageTemplate()
{
}
public StorageTemplate(string key)
{
this.key = key;
}
public StoragePriority Priority
{
get => Enum.TryParse(priority, out StoragePriority p) && p != StoragePriority.Unstored ? p : StoragePriority.Normal;
set => priority = value.ToString();
}
public override void ExposeData()
{
base.ExposeData();
Scribe_Values.Look(ref priority, "priority", nameof(StoragePriority.Normal));
Scribe_Collections.Look(ref allowed, "allowed", LookMode.Value);
Scribe_Collections.Look(ref refused, "refused", LookMode.Value);
// As a string, so a rule a later version adds loads as Game instead of logging a parse error.
string rule = unlisted.ToString();
Scribe_Values.Look(ref rule, "unlisted", nameof(UnlistedRule.Game));
Scribe_Collections.Look(ref allowedSpecial, "allowedSpecial", LookMode.Value);
Scribe_Collections.Look(ref refusedSpecial, "refusedSpecial", LookMode.Value);
Scribe_Values.Look(ref hitPoints, "hitPoints", FloatRange.ZeroToOne);
Scribe_Values.Look(ref quality, "quality", QualityRange.All);
if (Scribe.mode == LoadSaveMode.LoadingVars)
{
unlisted = Enum.TryParse(rule, out UnlistedRule r) ? r : UnlistedRule.Game;
allowed ??= new List<string>();
refused ??= new List<string>();
allowedSpecial ??= new List<string>();
refusedSpecial ??= new List<string>();
priority ??= nameof(StoragePriority.Normal);
}
}
public override DefaultsEntry Clone() => new StorageTemplate(key)
{
priority = priority,
allowed = CopyList(allowed),
refused = CopyList(refused),
unlisted = unlisted,
allowedSpecial = CopyList(allowedSpecial),
refusedSpecial = CopyList(refusedSpecial),
hitPoints = hitPoints,
quality = quality,
};
public StorageTemplate CloneTemplate() => (StorageTemplate)Clone();
public override string Fingerprint() => key + "|" + ContentFingerprint();
/// <summary>The fingerprint without the key: equal for two templates that set the same settings.</summary>
public string ContentFingerprint() =>
priority + "|a:" + SortedJoin(allowed) + "|r:" + SortedJoin(refused) + "|u:" + unlisted
+ "|as:" + SortedJoin(allowedSpecial) + "|rs:" + SortedJoin(refusedSpecial)
+ "|hp:" + hitPoints.min.ToString("R", CultureInfo.InvariantCulture) + "~" + hitPoints.max.ToString("R", CultureInfo.InvariantCulture)
+ "|q:" + quality.min + "~" + quality.max;
public bool SameSettingsAs(StorageTemplate other) => other != null && ContentFingerprint() == other.ContentFingerprint();
public override IEnumerable<string> UnresolvedNames()
{
foreach (string n in allowed)
if (DefDatabase<ThingDef>.GetNamedSilentFail(n) == null) yield return n;
foreach (string n in refused)
if (DefDatabase<ThingDef>.GetNamedSilentFail(n) == null) yield return n;
foreach (string n in allowedSpecial)
if (DefDatabase<SpecialThingFilterDef>.GetNamedSilentFail(n) == null) yield return n;
foreach (string n in refusedSpecial)
if (DefDatabase<SpecialThingFilterDef>.GetNamedSilentFail(n) == null) yield return n;
}
/// <summary>
/// Adds every name of the other template that doesn't resolve now (an inactive mod or DLC) to the list it
/// was in there, unless this template lists it already. Capture lists loaded defs only, so a default saved
/// over an older one calls this to keep that mod's items in the file (design.md: "Items from a mod you
/// removed stay in the file"). Used by "Make default" in the storage tab and by the edit window's Save.
/// </summary>
public void KeepUnresolvedFrom(StorageTemplate other)
{
if (other == null)
return;
KeepUnresolved(other.allowed, allowed, IsThingDef);
KeepUnresolved(other.refused, refused, IsThingDef);
KeepUnresolved(other.allowedSpecial, allowedSpecial, IsSpecialFilterDef);
KeepUnresolved(other.refusedSpecial, refusedSpecial, IsSpecialFilterDef);
}
private static bool IsThingDef(string name) => DefDatabase<ThingDef>.GetNamedSilentFail(name) != null;
private static bool IsSpecialFilterDef(string name) => DefDatabase<SpecialThingFilterDef>.GetNamedSilentFail(name) != null;
private static void KeepUnresolved(List<string> from, List<string> to, Func<string, bool> resolves)
{
if (from == null)
return;
foreach (string name in from)
{
if (!name.NullOrEmpty() && !resolves(name) && !to.Contains(name))
to.Add(name);
}
}
/// <summary>
/// A template of these settings: every storable def the parent filter allows goes into "allowed" or
/// "refused", every configurable special filter into "allowedSpecial" or "refusedSpecial", and the
/// rule for unlisted items is Game. A template never names a def the parent refuses.
/// </summary>
public static StorageTemplate Capture(string key, StorageSettings settings, ThingFilter parentFilter)
{
var t = new StorageTemplate(key) { Priority = settings.Priority, unlisted = UnlistedRule.Game };
ThingFilter f = settings.filter;
foreach (ThingDef def in StorageKinds.StorableDefs(parentFilter))
(f.Allows(def) ? t.allowed : t.refused).Add(def.defName);
foreach (SpecialThingFilterDef sf in DefDatabase<SpecialThingFilterDef>.AllDefsListForReading)
{
if (sf.configurable)
(f.Allows(sf) ? t.allowedSpecial : t.refusedSpecial).Add(sf.defName);
}
t.hitPoints = f.AllowedHitPointsPercents;
t.quality = f.AllowedQualityLevels;
return t;
}
/// <summary>
/// Writes the template onto settings that already hold the game's default for the kind (on a new
/// thing, what vanilla just set). The priority goes through the Priority setter; allowed names are
/// set only where the parent filter allows them; storable defs the parent allows that the template
/// lists in neither list follow the unlisted rule. The changes are made on a scratch copy and written
/// back with one CopyFrom, so a stockpile in play recalculates its haulables once, not per def.
/// </summary>
public void ApplyTo(StorageSettings target, ThingFilter parentFilter)
{
var scratch = new StorageSettings();
scratch.CopyFrom(target);
ApplyToScratch(scratch, parentFilter);
target.CopyFrom(scratch);
}
private void ApplyToScratch(StorageSettings s, ThingFilter parentFilter)
{
s.Priority = Priority;
ThingFilter f = s.filter;
var listed = new HashSet<string>(allowed, StringComparer.Ordinal);
listed.UnionWith(refused);
foreach (string name in allowed)
{
ThingDef def = DefDatabase<ThingDef>.GetNamedSilentFail(name);
if (def != null && (parentFilter == null || parentFilter.Allows(def)))
f.SetAllow(def, true);
}
foreach (string name in refused)
{
ThingDef def = DefDatabase<ThingDef>.GetNamedSilentFail(name);
if (def != null)
f.SetAllow(def, false);
}
if (unlisted != UnlistedRule.Game)
{
foreach (ThingDef def in StorageKinds.StorableDefs(parentFilter))
{
if (!listed.Contains(def.defName))
f.SetAllow(def, unlisted == UnlistedRule.Allow);
}
}
foreach (string name in allowedSpecial)
{
SpecialThingFilterDef sf = DefDatabase<SpecialThingFilterDef>.GetNamedSilentFail(name);
if (sf != null)
f.SetAllow(sf, true);
}
foreach (string name in refusedSpecial)
{
SpecialThingFilterDef sf = DefDatabase<SpecialThingFilterDef>.GetNamedSilentFail(name);
if (sf != null)
f.SetAllow(sf, false);
}
f.AllowedHitPointsPercents = hitPoints;
f.AllowedQualityLevels = quality;
}
}
}