rimworld-blax-laws/Tests/BlaxLawsTests/Source/PerfTests.cs

661 lines
34 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using BlaxLaws;
using RimWorld;
using Verse;
namespace BlaxLawsTests
{
/// <summary>
/// The performance run (design: "Headless tests", First release, Performance): 60 colonists tick the game
/// with Laws and as if Laws were absent, and the time spent in Laws' own code must stay under 2% of the tick.
///
/// "Without" is Laws switched off as if it were absent: Watch.Clear(), every Harmony patch of Laws removed
/// and its game component's tick skipped (LawsTestHooks). "With" puts the patches back and runs
/// Watch.Rebuild() from the lawbook. The lawbook itself never changes between the two, so no case is
/// repealed or reopened by the switch. The empty book's own cost per hook call is DetectionTests.EmptyBookCost.
///
/// The measurement, built so a busy desktop doesn't make it flaky:
/// - The colonists have steady work in both arms: a stockpile, a resource dripped in before every block for
/// them to haul, and meals they get hungry for one after another.
/// - Warm-up first (JIT, caches, the first jobs), then 10 pairs of 250-tick blocks per round, the order
/// alternating (with, without; without, with; ...) so a slow drift in the game hits both arms alike.
/// 250 ticks hold exactly one rare tick, so every block carries the same periodic work.
/// - A full collection before each block, outside the timing, so garbage of one block isn't paid by the next.
/// - The decision is the time inside Laws' own code (LawsClock: every patch method of Laws and its component
/// tick, timed per call) over the rest of the tick, under 2% in one of up to 5 rounds. A round counts only if
/// hook C (meals) and the record hooks were timed in it, and every block with Laws timed hook calls, not only
/// the component tick.
/// - The time in patch bodies leaves out Harmony's dispatch into the patched game methods, so the median of all
/// paired ratios (with / without) so far, minus 1, must also stay under a coarse 10%. Single pairs scatter by 20
/// to 70% on a quiet desktop and by -66% to +334% on a busy one, where the plain median of 10 to 30 pairs moves
/// by 10 to 15%. So the median's one-sided 95% sign-test bounds decide: over 10% when even the lower bound is,
/// under when the upper bound is. While neither holds, rounds are added. Still undecided after the last round,
/// a quiet machine (interquartile range of the pairs under 30%) is judged on the plain median as before, and a
/// busy one ends as a SKIP that carries the numbers: load alone never fails the run, and a real dispatch cost
/// still does.
/// Every round's numbers go into the results as INFO lines and into the failure message.
/// </summary>
public static class PerfTests
{
private const int Colonists = 60;
private const int BlockTicks = 250;
private const int PairsPerRound = 10; // 2500 ticks per arm and round
private const int WarmupPairs = 2;
private const int MaxRounds = 5; // up to 50 pairs; a round takes about 10 to 20 s under load
private const double Budget = 0.02;
// A coarse bound on the pooled median of the paired ratios (with / without): it includes what LawsClock
// can't see, Harmony's dispatch into the patched game methods. Loose, so the desktop can't make it flaky.
private const double DispatchBound = 0.10;
// Interquartile range of the pooled paired ratios under which the machine counts as quiet: an undecided
// dispatch bound is then judged on the plain median, as before.
private const double QuietSpread = 0.30;
private enum Verdict { Under, Over, Open }
private const int HungryPerBlock = 3;
private const int HaulItemsPerBlock = 30;
private const int ZoneSize = 10;
[BlaxTest("perf: 60 colonists with the starter lawbook over 2500 ticks: the time in Laws' code stays under 2% of the tick (10 alternating 250-tick pairs with and without Laws, up to 5 rounds)")]
public static void StarterLawbook()
{
Work w = Build();
Lawbook.AddStarter();
foreach (Lawbook.StarterRow s in Lawbook.StarterRows)
T.NotNull(Lawbook.Find(s.actKey, s.option, s.stage), "starter row " + s.actKey + " " + s.stage);
Watch.Rebuild();
// The starter book watches breaks, the insult, the social fight and, through the binge's linked
// dose, every meal reaches hook C's set lookup.
T.Check(Watch.Break && Watch.Interaction && Watch.Special && Watch.Ate,
"the starter book doesn't watch breaks, interactions, special acts and eating: Break " + Watch.Break +
", Interaction " + Watch.Interaction + ", Special " + Watch.Special + ", Ate " + Watch.Ate);
Measure("starter lawbook", w, new List<(string, Law)>());
}
[BlaxTest("perf: 60 colonists with the starter lawbook plus 'Records: things hauled' and 'Ate: any meal' rows over 2500 ticks: the time in Laws' code stays under 2% of the tick, and both rows file while watching")]
public static void BusiestRows()
{
Work w = Build();
Lawbook.AddStarter();
string hauledKey = ActKey.Of(ActCategories.Record, RecordDefOf.ThingsHauled);
string mealKey = ActKey.OfGroup(ActCategories.Ate, ActGroups.AnyMeal);
T.NotNull(ActCatalogue.Get(hauledKey), "catalogue entry " + hauledKey);
T.NotNull(ActCatalogue.Get(mealKey), "catalogue entry " + mealKey);
Law hauled = Fixtures.LawRow(hauledKey, null, LawStage.DidIt, LawSeverity.Minor, "Warn", 1);
Law meal = Fixtures.LawRow(mealKey, null, LawStage.DidIt, LawSeverity.Minor, "Warn", 1);
Watch.Rebuild();
T.Check(Watch.IsWatched(ActCategories.Record, RecordDefOf.ThingsHauled), "the hauled row doesn't watch ThingsHauled");
T.Check(Watch.IsWatched(ActCategories.Ate, w.mealDef), "the meal row doesn't watch " + w.mealDef.defName);
Measure("starter lawbook + hauled + any meal", w, new List<(string, Law)> { ("things hauled", hauled), ("any meal", meal) });
}
// ---- the measurement ----------------------------------------------------------------------
private static void Measure(string label, Work w, List<(string name, Law law)> rows)
{
var growthWith = new long[rows.Count];
var growthWithout = new long[rows.Count];
long activityWithout = 0;
LawsClock.Install();
Fixtures.OnCleanup(LawsClock.Uninstall);
// Warm-up: both arms, results thrown away.
for (int i = 0; i < WarmupPairs; i++)
{
Block(w, true, rows, null, ref activityWithout);
Block(w, false, rows, null, ref activityWithout);
}
activityWithout = 0;
var report = new List<string>();
var pooledRatios = new List<double>();
bool shareOk = false;
Verdict dispatch = Verdict.Open;
for (int round = 1; round <= MaxRounds; round++)
{
var ratios = new List<double>();
var with = new List<double>();
var without = new List<double>();
long bytesWith = 0, bytesWithout = 0, tickTimeWith = 0, lawsTime = 0, lawsCalls = 0, lawsCallsWithout = 0;
long hookCalls = 0, ingestedCalls = 0, recordCalls = 0;
for (int pair = 0; pair < PairsPerRound; pair++)
{
bool withFirst = pair % 2 == 0;
BlockResult a = Block(w, withFirst, rows, withFirst ? growthWith : growthWithout, ref activityWithout);
BlockResult b = Block(w, !withFirst, rows, withFirst ? growthWithout : growthWith, ref activityWithout);
BlockResult on = withFirst ? a : b;
BlockResult off = withFirst ? b : a;
// The clock must time the hooks, not only the component tick, which runs every tick anyway.
T.Check(on.hookCalls > 0, "fixture: a block with Laws timed no call into a hook, only the component tick (" + on.lawsCalls + " calls)");
with.Add(on.ticks);
without.Add(off.ticks);
bytesWith += on.bytes;
bytesWithout += off.bytes;
tickTimeWith += on.ticks;
lawsTime += on.lawsTicks;
lawsCalls += on.lawsCalls;
lawsCallsWithout += off.lawsCalls;
hookCalls += on.hookCalls;
ingestedCalls += on.ingestedCalls;
recordCalls += on.recordCalls;
ratios.Add(off.ticks > 0 ? (double)on.ticks / off.ticks : 1.0);
}
pooledRatios.AddRange(ratios);
var (lo, hi) = MedianBounds(pooledRatios);
double spread = Quantile(pooledRatios, 0.75) - Quantile(pooledRatios, 0.25);
dispatch = lo - 1.0 > DispatchBound ? Verdict.Over : hi - 1.0 < DispatchBound ? Verdict.Under : Verdict.Open;
// The decision: the time spent inside Laws' own code (every Harmony patch method of Laws and its
// component tick, timed by LawsClock) over the rest of the tick. It doesn't move with the game's
// workload or the desktop the way the paired arms do, whose single pairs scatter by 20 to 70%.
double share = tickTimeWith - lawsTime > 0 ? (double)lawsTime / (tickTimeWith - lawsTime) : 0.0;
double overhead = Median(ratios) - 1.0;
double pooled = Median(pooledRatios) - 1.0;
double armOverhead = Median(without) > 0 ? Median(with) / Median(without) - 1.0 : 0.0;
int armTicks = PairsPerRound * BlockTicks;
string line = label + ", round " + round + ": " + w.colonists + " colonists, " + armTicks + " ticks per arm; " +
"time in Laws' code " + Pct(share) + " of the rest of the tick (" + (lawsTime * 1e6 / Stopwatch.Frequency / armTicks).ToString("0.00") +
" us/tick in " + (lawsCalls / (double)armTicks).ToString("0.0") + " calls/tick); " +
"hook calls " + hookCalls + " (hook C " + ingestedCalls + ", record hooks " + recordCalls + "); " +
"median ms/tick with " + MsPerTick(Median(with)) + ", without " + MsPerTick(Median(without)) + "; " +
"paired median " + Pct(overhead) + " (pairs " + Pct(ratios.Min() - 1.0) + " to " + Pct(ratios.Max() - 1.0) + "), " +
"pooled paired median of " + pooledRatios.Count + " pairs " + Pct(pooled) + " (bound " + Pct(DispatchBound) + "), " +
"arm medians " + Pct(armOverhead) + "; budget " + Pct(Budget) + " = " +
(Median(without) * Budget * 1e6 / Stopwatch.Frequency / BlockTicks).ToString("0.0") + " us/tick; " +
"allocated bytes/tick with " + (bytesWith / armTicks) + ", without " + (bytesWithout / armTicks) + "; " +
"95% bounds of the pooled median " + Pct(lo - 1.0) + " to " + Pct(hi - 1.0) + ", spread (IQR) " + Pct(spread) + ", dispatch " + dispatch;
T.Info(line);
report.Add(line);
// Without Laws only the component's suspended tick runs (one early return a tick, LawsTestHooks.TickSuspended).
T.Check(lawsCallsWithout <= armTicks, "calls into Laws' code without Laws: " + lawsCallsWithout + " in " + armTicks + " ticks");
// A round counts only if the two busiest hooks were timed in it: meals eaten (hook C) and records
// counted (the record hooks). A round without them would measure a lighter workload.
shareOk |= share < Budget && ingestedCalls > 0 && recordCalls > 0;
if (dispatch == Verdict.Over || (shareOk && dispatch == Verdict.Under))
break;
}
for (int i = 0; i < rows.Count; i++)
T.Info(label + ": row '" + rows[i].name + "' acts counted while watching " + growthWith[i] + ", without Laws " + growthWithout[i]);
// The switch is real: without Laws, nothing was filed or counted.
T.Equal(0L, activityWithout, "case activity (new cases plus counted acts) without Laws");
// The measured arm really did the work: each extra row took acts while watching.
for (int i = 0; i < rows.Count; i++)
T.Check(growthWith[i] > 0, "fixture: the '" + rows[i].name + "' row counted no act while watching, so the run measured no filing. " +
string.Join(" | ", report));
string all = string.Join(" | ", report);
T.Check(shareOk, "in none of " + report.Count + " rounds did Laws' code stay under " + Pct(Budget) + " of the tick with both hook C and the record hooks timed: " + all);
T.Check(dispatch != Verdict.Over, "with Laws the tick is slower by more than " + Pct(DispatchBound) + " even at the 95% lower bound of the pooled paired median (Harmony dispatch or hook cost): " + all);
if (dispatch == Verdict.Open)
{
double pooledSpread = Quantile(pooledRatios, 0.75) - Quantile(pooledRatios, 0.25);
if (pooledSpread < QuietSpread)
T.Check(Median(pooledRatios) - 1.0 < DispatchBound, "on a quiet machine (spread " + Pct(pooledSpread) + ") the pooled paired median stays over " + Pct(DispatchBound) + ": " + all);
else
T.Skip("Laws' own time passed, but the machine is too busy (spread " + Pct(pooledSpread) + ", over " + Pct(QuietSpread) + ") to bound Harmony's dispatch to " + Pct(DispatchBound) + ": " + all);
}
}
/// <summary>
/// Times Laws' own code: a prefix and a finalizer (test Harmony id) on every prefix, postfix and finalizer
/// Laws patched into the game and on GameComponent_BlaxLaws.GameComponentTick. Only the outermost call
/// counts for the time, so Laws code that calls Laws code isn't counted twice. The two timestamps per call
/// add about 50 ns, which counts against Laws. Not counted: Harmony's own call into a patch method (the
/// paired with/without median covers that, see Measure).
/// Calls are counted per kind: HookCalls are calls into patch methods (every call, nested or not), so a
/// clock that times only the component tick shows as no hook calls; IngestedCalls and RecordCalls are
/// hook C (Patch_Thing_Ingested) and the record hooks (Patch_Pawn_RecordsTracker_Increment and _AddTo).
/// </summary>
private static class LawsClock
{
private const string HarmonyId = "blax.laws.tests.perfclock";
private static int depth;
private static long enteredAt;
private static MethodBase tickTarget;
public static long Ticks;
public static long Calls;
public static long HookCalls;
public static long IngestedCalls;
public static long RecordCalls;
private static bool installed;
public static void Reset()
{
Ticks = 0;
Calls = 0;
HookCalls = 0;
IngestedCalls = 0;
RecordCalls = 0;
}
public static void Install()
{
if (installed)
return;
var targets = new HashSet<MethodInfo>();
foreach (MethodBase m in HarmonyLib.Harmony.GetAllPatchedMethods().ToList())
{
HarmonyLib.Patches info = HarmonyLib.Harmony.GetPatchInfo(m);
if (info == null)
continue;
foreach (HarmonyLib.Patch p in info.Prefixes.Concat(info.Postfixes).Concat(info.Finalizers))
{
if (p.owner == BlaxLawsStartup.HarmonyId && p.PatchMethod != null)
targets.Add(p.PatchMethod);
}
}
T.Check(targets.Count > 0, "fixture: Laws has no patch methods to time");
T.Check(targets.Any(m => m.DeclaringType == typeof(Patch_Thing_Ingested)), "fixture: hook C (Patch_Thing_Ingested) has no patch method to time");
T.Check(targets.Any(m => IsRecordHook(m.DeclaringType)), "fixture: the record hooks have no patch method to time");
MethodInfo tick = HarmonyLib.AccessTools.Method(typeof(GameComponent_BlaxLaws), nameof(GameComponent_BlaxLaws.GameComponentTick));
tickTarget = tick;
targets.Add(tick);
var harmony = new HarmonyLib.Harmony(HarmonyId);
var enter = new HarmonyLib.HarmonyMethod(HarmonyLib.AccessTools.Method(typeof(LawsClock), nameof(Enter)));
var exit = new HarmonyLib.HarmonyMethod(HarmonyLib.AccessTools.Method(typeof(LawsClock), nameof(Exit)));
installed = true;
foreach (MethodInfo m in targets)
harmony.Patch(m, prefix: enter, finalizer: exit);
depth = 0;
Reset();
}
private static bool IsRecordHook(Type t) =>
t == typeof(Patch_Pawn_RecordsTracker_Increment) || t == typeof(Patch_Pawn_RecordsTracker_AddTo);
public static void Uninstall()
{
if (!installed)
return;
new HarmonyLib.Harmony(HarmonyId).UnpatchAll(HarmonyId);
installed = false;
depth = 0;
}
public static void Enter()
{
if (depth++ == 0)
enteredAt = Stopwatch.GetTimestamp();
}
public static void Exit(MethodBase __originalMethod)
{
if (--depth == 0)
{
Ticks += Stopwatch.GetTimestamp() - enteredAt;
Calls++;
}
else if (depth < 0)
{
depth = 0;
}
if (__originalMethod != tickTarget)
{
HookCalls++;
Type t = __originalMethod?.DeclaringType;
if (t == typeof(Patch_Thing_Ingested))
IngestedCalls++;
else if (IsRecordHook(t))
RecordCalls++;
}
}
}
private struct BlockResult
{
public long ticks;
public long bytes;
public long lawsTicks;
public long lawsCalls;
public long hookCalls;
public long ingestedCalls;
public long recordCalls;
}
private static BlockResult Block(Work w, bool watching, List<(string name, Law law)> rows, long[] growth, ref long activityWithout)
{
if (watching)
{
List<string> failed = LawsTestHooks.RestorePatches();
T.Check(failed.Count == 0, "patch classes that failed to apply again: " + string.Join(", ", failed));
LawsTestHooks.TickSuspended = false;
Watch.Rebuild();
}
else
{
Watch.Clear();
LawsTestHooks.RemovePatches();
LawsTestHooks.TickSuspended = true;
}
T.Check(Watch.Any == watching, "Watch.Any is " + Watch.Any + " for a block " + (watching ? "with" : "without") + " Laws");
int patched = LawsPatchedMethods();
T.Check(watching ? patched > 0 : patched == 0, "methods Laws patches for a block " + (watching ? "with" : "without") + " Laws: " + patched);
Drip(w);
long[] before = new long[rows.Count];
for (int i = 0; i < rows.Count; i++)
before[i] = Acts(rows[i].law);
long activityBefore = Activity();
GC.Collect();
GC.WaitForPendingFinalizers();
long bytes = GC.GetAllocatedBytesForCurrentThread();
LawsClock.Reset();
TickManager tm = Find.TickManager;
var sw = Stopwatch.StartNew();
for (int t = 0; t < BlockTicks; t++)
tm.DoSingleTick();
sw.Stop();
bytes = GC.GetAllocatedBytesForCurrentThread() - bytes;
if (growth != null)
{
for (int i = 0; i < rows.Count; i++)
growth[i] += Acts(rows[i].law) - before[i];
}
if (!watching)
activityWithout += Activity() - activityBefore;
return new BlockResult { ticks = sw.ElapsedTicks, bytes = bytes, lawsTicks = LawsClock.Ticks, lawsCalls = LawsClock.Calls,
hookCalls = LawsClock.HookCalls, ingestedCalls = LawsClock.IngestedCalls, recordCalls = LawsClock.RecordCalls };
}
/// <summary>Methods that carry at least one Harmony patch of Laws.</summary>
private static int LawsPatchedMethods()
{
int n = 0;
foreach (System.Reflection.MethodBase m in HarmonyLib.Harmony.GetAllPatchedMethods())
{
HarmonyLib.Patches info = HarmonyLib.Harmony.GetPatchInfo(m);
if (info != null && info.Owners.Contains(BlaxLawsStartup.HarmonyId))
n++;
}
return n;
}
/// <summary>Acts the row took: every case filed under it as its did-it row, with each case's count.</summary>
private static long Acts(Law law)
{
long n = 0;
foreach (LawCase c in Fixtures.Comp.Cases)
{
if (c != null && c.didItLawId == law.id)
n += Math.Max(1, c.count);
}
return n;
}
/// <summary>Cases in the store plus every case's count: grows whenever CaseFiler files or counts an act.</summary>
private static long Activity()
{
long n = 0;
foreach (LawCase c in Fixtures.Comp.Cases)
n += 1 + (c?.count ?? 0);
return n;
}
private static double Median(List<double> values)
{
List<double> s = values.OrderBy(v => v).ToList();
if (s.Count == 0)
return 0.0;
int m = s.Count / 2;
return s.Count % 2 == 1 ? s[m] : (s[m - 1] + s[m]) / 2.0;
}
/// <summary>
/// One-sided 95% sign-test bounds of the median: the k-th smallest and the k-th largest value, with k the
/// largest count for which P(Binomial(n, 1/2) <= k - 1) <= 0.05 (n=10: k=2, n=20: k=6, n=30: k=11, n=50: k=19).
/// No bound (infinite) when n is too small for any k.
/// </summary>
private static (double lo, double hi) MedianBounds(List<double> values)
{
List<double> s = values.OrderBy(v => v).ToList();
int n = s.Count, k = 0;
double c = 1.0, p = Math.Pow(0.5, n), cum = 0.0;
for (int i = 0; i < n; i++)
{
cum += c * p;
if (cum > 0.05)
break;
k = i + 1;
c = c * (n - i) / (i + 1);
}
return k == 0 ? (double.NegativeInfinity, double.PositiveInfinity) : (s[k - 1], s[n - k]);
}
/// <summary>The q-quantile, linear between the two nearest values.</summary>
private static double Quantile(List<double> values, double q)
{
List<double> s = values.OrderBy(v => v).ToList();
if (s.Count == 0)
return 0.0;
double pos = q * (s.Count - 1);
int i = (int)Math.Floor(pos);
return i + 1 < s.Count ? s[i] + (s[i + 1] - s[i]) * (pos - i) : s[i];
}
private static string MsPerTick(double blockTicks) => (blockTicks * 1000.0 / Stopwatch.Frequency / BlockTicks).ToString("0.000");
private static string Pct(double fraction) => (fraction * 100.0).ToString("0.00") + "%";
// ---- the workload -------------------------------------------------------------------------
private sealed class Work
{
public Map map;
public ThingDef haulDef;
public ThingDef mealDef;
public CellRect zoneRect;
public District district;
public Zone_Stockpile zone;
public readonly List<Pawn> mine = new List<Pawn>();
public int colonists;
public int nextHungry;
}
/// <summary>
/// 60 free colonists on the map, a critical stockpile that takes only a resource and a meal the map holds
/// none of, one meal per colonist in it, and staggered hunger so the meals are eaten over the whole run.
/// The cleanup removes every thing of the two defs, carried ones included, and the stockpile, and rebuilds
/// Watch from the lawbook.
/// </summary>
private static Work Build()
{
Map map = Fixtures.Map;
T.NotNull(map, "the map");
DetectionKit.QuietSocialFights();
var w = new Work { map = map };
Fixtures.OnCleanup(() => Teardown(w));
w.haulDef = FirstAbsent(map, new[] { ThingDefOf.Jade, ThingDefOf.Gold, ThingDefOf.Uranium, ThingDefOf.Plasteel, ThingDefOf.Silver });
T.NotNull(w.haulDef, "fixture: a resource the map holds none of (Jade, Gold, Uranium, Plasteel, Silver)");
w.mealDef = FirstAbsent(map, new[] { ThingDefOf.MealFine, DefDatabase<ThingDef>.GetNamedSilentFail("MealLavish"), ThingDefOf.MealSimple, ThingDefOf.MealSurvivalPack }
.Where(d => d != null && FoodFacts.IsMeal(d)));
T.NotNull(w.mealDef, "fixture: a meal the map holds none of (MealFine, MealLavish, MealSimple, MealSurvivalPack)");
T.Check(FindZoneRect(map, out CellRect rect), "fixture: no " + ZoneSize + "x" + ZoneSize + " square near the map center that could be cleared");
w.zoneRect = rect;
w.district = rect.CenterCell.GetDistrict(map);
var zone = new Zone_Stockpile(StorageSettingsPreset.DefaultStockpile, map.zoneManager);
map.zoneManager.RegisterZone(zone);
w.zone = zone;
foreach (IntVec3 c in rect.Cells)
zone.AddCell(c);
zone.settings.filter.SetDisallowAll();
zone.settings.filter.SetAllow(w.haulDef, true);
zone.settings.filter.SetAllow(w.mealDef, true);
zone.settings.Priority = StoragePriority.Critical;
int meals = 0;
foreach (IntVec3 c in rect.Cells)
{
if (meals >= Colonists)
break;
Fixtures.Track(GenSpawn.Spawn(ThingMaker.MakeThing(w.mealDef), c, map));
meals++;
}
for (int guard = 0; map.mapPawns.FreeColonistsSpawnedCount < Colonists && guard < Colonists * 2; guard++)
{
Pawn p = Fixtures.Generate(PawnKindDefOf.Colonist, Faction.OfPlayer);
// An addiction sends the pawn after its drug, which the other arm's ticks don't share alike.
foreach (Hediff h in p.health.hediffSet.hediffs.OfType<Hediff_Addiction>().ToList())
p.health.RemoveHediff(h);
Fixtures.Spawn(p, CellNear(w));
w.mine.Add(p);
}
w.colonists = map.mapPawns.FreeColonistsSpawnedCount;
T.Check(w.colonists >= Colonists, "fixture: " + w.colonists + " free colonists spawned, not " + Colonists);
// Hungry one after another at the start: humans want to eat under 30% (RimWorld/JobGiver_GetFood.cs:44)
// and lose 2.6666667E-05 a tick of a 1.0 maximum (Need_Food.cs:11, :218), about 6.7% an hour of ticks,
// so 29% to 43% are all eaten by the end of round 1. Drip keeps eating going in every later block.
for (int i = 0; i < w.mine.Count; i++)
{
Pawn p = w.mine[i];
if (p.needs?.food != null)
p.needs.food.CurLevelPercentage = 0.29f + 0.14f * i / Math.Max(1, w.mine.Count - 1);
if (p.needs?.rest != null)
p.needs.rest.CurLevel = p.needs.rest.MaxLevel;
if (p.needs?.joy != null)
p.needs.joy.CurLevel = 1f;
}
return w;
}
private static ThingDef FirstAbsent(Map map, IEnumerable<ThingDef> candidates)
{
foreach (ThingDef d in candidates)
{
if (d == null || map.listerThings.ThingsOfDef(d).Count > 0)
continue;
bool held = false;
foreach (Pawn p in map.mapPawns.AllPawnsSpawned)
{
if (p.carryTracker?.CarriedThing?.def == d || (p.inventory != null && p.inventory.innerContainer.Any(t => t.def == d)))
{
held = true;
break;
}
}
if (!held)
return d;
}
return null;
}
/// <summary>
/// A square for the stockpile near the map center in a district that touches the map edge, on ground a
/// player could clear (Fixtures.Buildable: plants and starting items are cleared away, as for the prison
/// cell) and in no other zone. A wild map has few squares free of trees and starting items.
/// </summary>
private static bool FindZoneRect(Map map, out CellRect rect)
{
float radius = Math.Min(60f, GenRadial.MaxRadialPatternRadius - 1f);
foreach (IntVec3 corner in GenRadial.RadialCellsAround(map.Center, radius, true))
{
var r = new CellRect(corner.x, corner.z, ZoneSize, ZoneSize);
District district = corner.InBounds(map) ? corner.GetDistrict(map) : null;
if (district == null || !district.TouchesMapEdge)
continue;
bool ok = true;
foreach (IntVec3 c in r.Cells)
{
if (!Fixtures.Buildable(c, map, district) || map.zoneManager.ZoneAt(c) != null)
{
ok = false;
break;
}
}
if (ok)
{
Fixtures.ClearGround(r.Cells, map);
rect = r;
return true;
}
}
rect = default;
return false;
}
private static IntVec3 CellNear(Work w)
{
Map map = w.map;
if (CellFinder.TryFindRandomCellNear(w.zoneRect.CenterCell, map, 20,
c => c.Standable(map) && !c.Fogged(map) && c.GetDistrict(map) == w.district && !w.zoneRect.Contains(c) && c.GetFirstPawn(map) == null,
out IntVec3 cell))
return cell;
return Fixtures.PawnCell();
}
/// <summary>
/// Single resources on free ground near the stockpile, so every block has hauling to do, and a few
/// colonists in turn made hungry with a meal each in the stockpile, so every block has eating to do (the
/// staggered start alone is eaten up by the end of round 1).
/// </summary>
private static void Drip(Work w)
{
Map map = w.map;
for (int i = 0; i < HaulItemsPerBlock; i++)
{
if (!CellFinder.TryFindRandomCellNear(w.zoneRect.CenterCell, map, 25,
c => c.Standable(map) && !c.Fogged(map) && c.GetDistrict(map) == w.district && !w.zoneRect.Contains(c) && c.GetFirstItem(map) == null,
out IntVec3 cell))
continue;
Thing t = ThingMaker.MakeThing(w.haulDef);
t.stackCount = 1;
Fixtures.Track(GenSpawn.Spawn(t, cell, map));
}
for (int i = 0; i < HungryPerBlock && w.mine.Count > 0; i++)
{
Pawn p = w.mine[w.nextHungry++ % w.mine.Count];
if (p.Spawned && !p.Dead && p.needs?.food != null)
p.needs.food.CurLevelPercentage = 0.25f;
// May merge into a stack already there; Teardown removes every meal of the def.
GenPlace.TryPlaceThing(ThingMaker.MakeThing(w.mealDef), w.zoneRect.CenterCell, map, ThingPlaceMode.Near);
}
}
private static void Teardown(Work w)
{
Map map = w.map;
if (map != null)
{
bool Ours(ThingDef d) => d != null && (d == w.haulDef || d == w.mealDef);
foreach (Pawn p in map.mapPawns.AllPawnsSpawned.ToList())
{
Thing carried = p.carryTracker?.CarriedThing;
if (carried != null && Ours(carried.def))
carried.Destroy(DestroyMode.Vanish);
else if (carried != null && w.mine.Contains(p))
p.carryTracker.TryDropCarriedThing(p.Position, ThingPlaceMode.Near, out _);
if (p.inventory != null)
{
foreach (Thing t in p.inventory.innerContainer.ToList())
{
if (Ours(t.def))
t.Destroy(DestroyMode.Vanish);
}
}
}
foreach (ThingDef d in new[] { w.haulDef, w.mealDef })
{
if (d == null)
continue;
foreach (Thing t in map.listerThings.ThingsOfDef(d).ToList())
{
if (!t.Destroyed)
t.Destroy(DestroyMode.Vanish);
}
}
if (w.zone != null && map.zoneManager.AllZones.Contains(w.zone))
w.zone.Delete(false);
}
Watch.Rebuild();
}
}
}