using System;
using System.Collections.Generic;
using RimWorld;
using Verse;
using Verse.AI;
namespace BlaxZones
{
///
/// Package Router. Design: "DeliveryRouter, shared by every delivery path". One static class every
/// delivery path calls: orbital trade (DeliveryRouter.Orbital.cs, package Orbital), ZonesApi, and
/// from 1.1 rewards, caravans, cargo pods and direct delivery.
///
/// It holds no state: cell orders live in MapComponent_BlaxZones (MapComponent_BlaxZones.Router.cs),
/// cell validity in DeliveryRules. Nothing here catches: every entry point that calls it runs in
/// try/catch and falls back to vanilla.
///
public static partial class DeliveryRouter
{
/// At most this many cell checks per stack.
public const int MaxChecksPerStack = 400;
///
/// The overflow search radius: the setting (5 to 30), never below 5. DropCellFinder.TryFindDropSpotNear
/// grows its search by Min(maxRadius / 5, 1) (DropCellFinder.cs:272), which is 0 below 5, so a
/// failed search with a smaller radius never ends.
///
public static int OverflowRadius => Math.Max(BlaxZonesSettings.MinOverflowRadius, BlaxZonesMod.S.OverflowRadiusClamped);
///
/// A cell for one pod holding this thing, or false. Refusals (Refuses), then candidates in order,
/// then each candidate's cells (pass 1 empty valid cells, pass 2 cells with a mergeable stack, at
/// most MaxChecksPerStack checks), then overflow next to the top candidate when the setting allows.
/// Throws only when ZonesTestHooks.RouterThrows is set; callers wrap it in try/catch and fall back
/// to vanilla.
///
public static bool TryFindDropSpot(Map map, Thing thing, DeliverySource source, out IntVec3 cell)
{
if (ZonesTestHooks.RouterThrows)
throw new System.InvalidOperationException("ZonesTestHooks.RouterThrows");
cell = IntVec3.Invalid;
if (Refuses(map, thing))
return false;
List candidates = Candidates(map, thing, source);
if (candidates.Count == 0)
return false;
for (int i = 0; i < candidates.Count; i++)
{
if (TryPickCellInZone(candidates[i], thing, out cell))
return true;
}
// Every candidate is full: overflow next to the top one (false when the setting is off).
return TryOverflow(candidates[0], out cell);
}
///
/// Never routed: DeliveryFilters.NeverRouted (Pawn, Corpse, Wastepack), a map without
/// MapComponent_BlaxZones (after the removal button), a map with no delivery zones.
///
public static bool Refuses(Map map, Thing thing)
{
if (map == null || DeliveryFilters.NeverRouted(thing))
return true;
if (MapComponent_BlaxZones.Of(map) == null)
return true;
return !HasDeliveryZone(map);
}
///
/// Delivery zones on the map that accept the source and whose filter accepts the thing, ordered
/// by priority (highest first), then zone ID.
///
public static List Candidates(Map map, Thing thing, DeliverySource source)
{
var result = new List();
List zones = map?.zoneManager?.AllZones;
if (zones == null || thing == null)
return result;
for (int i = 0; i < zones.Count; i++)
{
if (zones[i] is Zone_Delivery zone && zone.cells.Count > 0 && zone.AcceptsSource(source) && zone.Accepts(thing))
result.Add(zone);
}
result.Sort(CompareCandidates);
return result;
}
///
/// A pod cell inside one zone: pass 1 empty cells passing DeliveryRules.PodCellOk, pass 2 cells
/// holding a stack the thing can merge into, both in the component's cell order (nearest the
/// centroid first), at most MaxChecksPerStack checks.
///
///
/// One walk over the first MaxChecksPerStack cells serves both passes: an empty cell is checked
/// with the pod rule at once (pass 1), a cell with a mergeable stack is remembered and checked
/// only if no empty cell passed (pass 2). A cell holding other items is taken. So each cell costs
/// one pod-rule check at most.
///
public static bool TryPickCellInZone(Zone_Delivery zone, Thing thing, out IntVec3 cell)
{
cell = IntVec3.Invalid;
Map map = zone?.MapOrNull;
if (map == null || thing == null || zone.cells.Count == 0)
return false;
MapComponent_BlaxZones comp = MapComponent_BlaxZones.Of(map);
List cells = comp != null ? comp.CellsByDistance(zone) : SortedByCentroid(zone.cells);
int checks = Math.Min(cells.Count, MaxChecksPerStack);
List mergeable = null;
for (int i = 0; i < checks; i++)
{
IntVec3 c = cells[i];
if (!c.InBounds(map))
continue;
switch (Occupancy(map, c, thing))
{
case CellOccupancy.Empty:
if (DeliveryRules.PodCellOk(map, c))
{
cell = c;
return true;
}
break;
case CellOccupancy.Mergeable:
(mergeable ??= new List()).Add(c);
break;
}
}
if (mergeable != null)
{
for (int i = 0; i < mergeable.Count; i++)
{
if (DeliveryRules.PodCellOk(map, mergeable[i]))
{
cell = mergeable[i];
return true;
}
}
}
return false;
}
/// The zone's cell nearest its centroid (not the raw centroid, which can be a wall in an L-shaped zone).
public static IntVec3 OverflowCenter(Zone_Delivery zone)
{
if (zone == null || zone.cells.Count == 0)
return IntVec3.Invalid;
MapComponent_BlaxZones comp = MapComponent_BlaxZones.Of(zone.MapOrNull);
if (comp != null)
return comp.CellsByDistance(zone)[0];
return NearestToCentroid(zone.cells);
}
///
/// The search of DropCellFinder.TryFindDropSpotNear(OverflowCenter(top), map, out cell, allowFogged:
/// false, canRoofPunch: false, maxRadius) (DropCellFinder.cs:229-317) plus the reach rule: random
/// cells within a square radius from Min(maxRadius / 2, 5) up to maxRadius, growing by
/// Min(maxRadius / 5, 1), each passing the pod rule (good drop spot and DeliveryRules.ColonyCanReach)
/// and reachable from the center with PassDoors, as vanilla requires. Without the reach rule a zone
/// in a walled-off pocket overflowed into that same pocket. maxRadius is OverflowRadius, never below
/// 5 (the step is 0 below 5: the search never ends). False when the overflow setting is off or no
/// cell fits, so the pod goes to the vanilla spot.
///
public static bool TryOverflow(Zone_Delivery top, out IntVec3 cell)
{
cell = IntVec3.Invalid;
if (top == null || !BlaxZonesMod.S.overflowNearZone)
return false;
Map map = top.MapOrNull;
if (map == null)
return false;
IntVec3 center = OverflowCenter(top);
if (!center.IsValid || !center.InBounds(map))
return false;
int maxRadius = OverflowRadius;
int step = Math.Min(maxRadius / 5, 1);
if (step <= 0)
return false;
bool Fits(IntVec3 c) =>
DeliveryRules.PodCellOk(map, c)
&& map.reachability.CanReach(center, c, PathEndMode.OnCell, TraverseMode.PassDoors, Danger.Deadly);
for (int radius = Math.Min(maxRadius / 2, 5); radius <= maxRadius; radius += step)
{
if (CellFinder.TryFindRandomCellNear(center, map, radius, Fits, out IntVec3 found))
{
cell = found;
return true;
}
}
return false;
}
// ---- helpers ---------------------------------------------------------------------
private enum CellOccupancy
{
/// No item on the cell.
Empty,
/// At least one stack the thing can merge into.
Mergeable,
/// Items, none the thing can merge into.
Taken,
}
///
/// What items lie on the cell, as the passes see it. A mergeable stack has the same def, accepts
/// the thing (CanStackWith: same stuff, not a relic, comps agree) and has room left.
///
private static CellOccupancy Occupancy(Map map, IntVec3 c, Thing thing)
{
List things = c.GetThingList(map);
bool anyItem = false;
for (int i = 0; i < things.Count; i++)
{
Thing t = things[i];
if (t.def.category != ThingCategory.Item)
continue;
if (t != thing && t.def == thing.def && t.stackCount < t.def.stackLimit && t.CanStackWith(thing))
return CellOccupancy.Mergeable;
anyItem = true;
}
return anyItem ? CellOccupancy.Taken : CellOccupancy.Empty;
}
/// Any delivery zone registered on the map. Cheap: one pass over ZoneManager's list.
private static bool HasDeliveryZone(Map map)
{
List zones = map.zoneManager?.AllZones;
if (zones == null)
return false;
for (int i = 0; i < zones.Count; i++)
{
if (zones[i] is Zone_Delivery)
return true;
}
return false;
}
/// Priority descending, then zone ID ascending. IDs are unique, so the order is total.
private static int CompareCandidates(Zone_Delivery a, Zone_Delivery b)
{
int byPriority = ((int)b.priority).CompareTo((int)a.priority);
return byPriority != 0 ? byPriority : a.ID.CompareTo(b.ID);
}
///
/// A copy of the cells sorted by distance to their centroid, ties by x then z. Exact: distances
/// are compared as (n*x - sumX)^2 + (n*z - sumZ)^2 in integers, so ties never depend on rounding,
/// and no Rand is used (Zone.Cells would shuffle).
///
internal static List SortedByCentroid(List cells)
{
var sorted = new List(cells);
if (sorted.Count < 2)
return sorted;
CentroidSums(cells, out long n, out long sumX, out long sumZ);
sorted.Sort((a, b) =>
{
int d = ScaledDistSq(a, n, sumX, sumZ).CompareTo(ScaledDistSq(b, n, sumX, sumZ));
if (d != 0)
return d;
d = a.x.CompareTo(b.x);
return d != 0 ? d : a.z.CompareTo(b.z);
});
return sorted;
}
/// The first cell SortedByCentroid would return, without sorting.
internal static IntVec3 NearestToCentroid(List cells)
{
if (cells == null || cells.Count == 0)
return IntVec3.Invalid;
CentroidSums(cells, out long n, out long sumX, out long sumZ);
IntVec3 best = cells[0];
long bestDist = ScaledDistSq(best, n, sumX, sumZ);
for (int i = 1; i < cells.Count; i++)
{
IntVec3 c = cells[i];
long d = ScaledDistSq(c, n, sumX, sumZ);
if (d < bestDist || (d == bestDist && (c.x < best.x || (c.x == best.x && c.z < best.z))))
{
best = c;
bestDist = d;
}
}
return best;
}
private static void CentroidSums(List cells, out long n, out long sumX, out long sumZ)
{
n = cells.Count;
sumX = 0;
sumZ = 0;
for (int i = 0; i < cells.Count; i++)
{
sumX += cells[i].x;
sumZ += cells[i].z;
}
}
/// Squared distance to the centroid, times n squared.
private static long ScaledDistSq(IntVec3 c, long n, long sumX, long sumZ)
{
long dx = n * c.x - sumX;
long dz = n * c.z - sumZ;
return dx * dx + dz * dz;
}
}
}