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

59 lines
2.3 KiB
C#

using System;
using HarmonyLib;
using RimWorld;
using Verse;
namespace BlaxDefaults
{
/// <summary>
/// New stockpiles start from their type's default. Work package "hooks" (design.md: "New stockpiles start
/// from your default"). Designator_ZoneAdd.DesignateMultiCell calls MakeNewZone before RegisterZone and
/// before the zone has cells. Designators that override MakeNewZone without calling the base never get
/// here and keep their own filter. An Expand drag that grows a zone makes none, so it never gets here.
/// </summary>
public static class StockpileHooks
{
/// <summary>
/// When StockpilesOn and the zone is a Zone_Stockpile: the type from StorageKinds.StockpileTypeOf, and
/// its saved template applied with ApplyDefault. No template: vanilla stays.
/// </summary>
public static void OnNewZone(Designator_ZoneAddStockpile designator, Zone zone)
{
if (!BlaxDefaultsMod.StockpilesOn || !(zone is Zone_Stockpile pile))
return;
StockpileType type = StorageKinds.StockpileTypeOf(designator);
if (type == null)
return;
ApplyDefault(pile, type);
}
/// <summary>Applies the type's saved template onto zone.settings (on top of what the vanilla constructor set). False without a template.</summary>
public static bool ApplyDefault(Zone_Stockpile zone, StockpileType type)
{
if (zone?.settings == null || type == null)
return false;
StorageTemplate template = DefaultsLibrary.Get<StorageTemplate>(type.Key);
if (template == null)
return false;
template.ApplyTo(zone.settings, StorageKinds.StockpileParentFilter);
return true;
}
}
[HarmonyPatch(typeof(Designator_ZoneAddStockpile), "MakeNewZone")]
public static class Patch_Designator_ZoneAddStockpile_MakeNewZone
{
public static void Postfix(Designator_ZoneAddStockpile __instance, Zone __result)
{
try
{
StockpileHooks.OnNewZone(__instance, __result);
}
catch (Exception e)
{
HookGuard.Report("Designator_ZoneAddStockpile.MakeNewZone", e);
}
}
}
}