using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using TabsBannerlord.Core.Battle; using TabsBannerlord.Core.Campaign; using TabsBannerlord.Core.Common; using TabsBannerlord.Core.Content; using TabsBannerlord.Core.Diagnostics; using TabsBannerlord.Core.Serialization; using TabsBannerlord.Core.State; using TabsBannerlord.Core.World; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("TabsBannerlord.Core")] [assembly: InternalsVisibleTo("TabsBannerlord.Core.Tests")] [assembly: AssemblyVersion("0.1.0.0")] namespace TabsBannerlord.Core.World { public sealed class PathResult { public bool Success; public List Points = new List(); public Vec2 Goal; public bool GoalAdjusted; public string Message = ""; public double Cost; } public sealed class NavGrid { private sealed class MinHeap { private int[] _items = new int[1024]; private double[] _keys = new double[1024]; private int _count; public int Count => _count; public void Clear() { _count = 0; } public void Push(int item, double key) { if (_count == _items.Length) { Array.Resize(ref _items, _count * 2); Array.Resize(ref _keys, _count * 2); } int num = _count++; _items[num] = item; _keys[num] = key; while (num > 0) { int num2 = (num - 1) / 2; if (!(_keys[num2] <= _keys[num])) { Swap(num2, num); num = num2; continue; } break; } } public int Pop() { int result = _items[0]; _count--; _items[0] = _items[_count]; _keys[0] = _keys[_count]; int num = 0; while (true) { int num2 = 2 * num + 1; int num3 = num2 + 1; int num4 = num; if (num2 < _count && _keys[num2] < _keys[num4]) { num4 = num2; } if (num3 < _count && _keys[num3] < _keys[num4]) { num4 = num3; } if (num4 == num) { break; } Swap(num4, num); num = num4; } return result; } private void Swap(int a, int b) { int num = _items[a]; _items[a] = _items[b]; _items[b] = num; double num2 = _keys[a]; _keys[a] = _keys[b]; _keys[b] = num2; } } public readonly int Width; public readonly int Height; public readonly double CellSize; private readonly TerrainDef[] _cells; private readonly int[] _component; private readonly bool[] _passable; private readonly double[] _inverseSpeed; private double[] _g; private int[] _came; private int[] _seen; private int[] _closed; private int _search; private readonly MinHeap _open = new MinHeap(); private static readonly int[] Dx = new int[8] { 1, -1, 0, 0, 1, 1, -1, -1 }; private static readonly int[] Dy = new int[8] { 0, 0, 1, -1, 1, -1, 1, -1 }; private double _maxSpeed = -1.0; public double WorldWidth => (double)Width * CellSize; public double WorldHeight => (double)Height * CellSize; private double MaxTerrainSpeed { get { if (_maxSpeed < 0.0) { _maxSpeed = 1.0; TerrainDef[] cells = _cells; foreach (TerrainDef terrainDef in cells) { if (terrainDef.Passable) { _maxSpeed = Math.Max(_maxSpeed, terrainDef.Speed); } } } return _maxSpeed; } } public NavGrid(WorldDef world) { Height = world.Rows.Count; Width = world.Rows[0].Length; CellSize = world.CellSize; Dictionary dictionary = new Dictionary(); foreach (TerrainDef item in world.Terrain) { dictionary[item.Symbol[0]] = item; } _cells = new TerrainDef[Width * Height]; for (int i = 0; i < Height; i++) { for (int j = 0; j < Width; j++) { _cells[i * Width + j] = dictionary[world.Rows[i][j]]; } } _component = new int[Width * Height]; _passable = new bool[_cells.Length]; _inverseSpeed = new double[_cells.Length]; for (int k = 0; k < _cells.Length; k++) { _passable[k] = _cells[k].Passable; _inverseSpeed[k] = 1.0 / _cells[k].Speed; } LabelComponents(); } public bool InBounds(int x, int y) { if (x >= 0 && y >= 0 && x < Width) { return y < Height; } return false; } public TerrainDef Cell(int x, int y) { return _cells[y * Width + x]; } public (int x, int y) ToCell(Vec2 p) { int val = (int)Math.Floor(p.X / CellSize); int val2 = (int)Math.Floor(p.Y / CellSize); return (x: Math.Max(0, Math.Min(Width - 1, val)), y: Math.Max(0, Math.Min(Height - 1, val2))); } public Vec2 CellCenter(int x, int y) { return new Vec2(((double)x + 0.5) * CellSize, ((double)y + 0.5) * CellSize); } public TerrainDef TerrainAt(Vec2 p) { var (x, y) = ToCell(p); return Cell(x, y); } public bool IsPassable(Vec2 p) { if (p.X < 0.0 || p.Y < 0.0 || p.X >= WorldWidth || p.Y >= WorldHeight) { return false; } return TerrainAt(p).Passable; } public int ComponentAt(Vec2 p) { var (num, num2) = ToCell(p); return _component[num2 * Width + num]; } public bool SameComponent(Vec2 a, Vec2 b) { int num = ComponentAt(a); int num2 = ComponentAt(b); if (num > 0) { return num == num2; } return false; } private void LabelComponents() { int num = 0; Queue queue = new Queue(); for (int i = 0; i < _cells.Length; i++) { if (!_cells[i].Passable || _component[i] != 0) { continue; } num++; _component[i] = num; queue.Enqueue(i); while (queue.Count > 0) { int num2 = queue.Dequeue(); int num3 = num2 % Width; int num4 = num2 / Width; for (int j = 0; j < 8; j++) { int num5 = num3 + Dx[j]; int num6 = num4 + Dy[j]; if (InBounds(num5, num6)) { int num7 = num6 * Width + num5; if (_cells[num7].Passable && _component[num7] == 0 && (j < 4 || DiagonalOpen(num3, num4, num5, num6))) { _component[num7] = num; queue.Enqueue(num7); } } } } } } private bool DiagonalOpen(int x, int y, int nx, int ny) { if (Cell(nx, y).Passable) { return Cell(x, ny).Passable; } return false; } public bool TryNearestReachable(Vec2 from, Vec2 target, out Vec2 result) { int num = ComponentAt(from); result = target; if (num == 0) { return false; } if (IsPassable(target) && ComponentAt(target) == num) { return true; } (int x, int y) tuple = ToCell(target); int item = tuple.x; int item2 = tuple.y; int num2 = Math.Max(Width, Height); for (int i = 1; i <= num2; i++) { double num3 = double.MaxValue; bool flag = false; for (int j = item2 - i; j <= item2 + i; j++) { for (int k = item - i; k <= item + i; k++) { if (Math.Max(Math.Abs(k - item), Math.Abs(j - item2)) == i && InBounds(k, j) && _component[j * Width + k] == num) { Vec2 vec = CellCenter(k, j); double lengthSquared = (vec - target).LengthSquared; if (lengthSquared < num3) { num3 = lengthSquared; result = vec; flag = true; } } } } if (flag) { return true; } } return false; } public bool LineWalkable(Vec2 a, Vec2 b, out double maxCost) { maxCost = 0.0; if (!IsPassable(a) || !IsPassable(b)) { return false; } (int x, int y) tuple = ToCell(a); int num = tuple.x; int num2 = tuple.y; (int x, int y) tuple2 = ToCell(b); int item = tuple2.x; int item2 = tuple2.y; double num3 = b.X - a.X; double num4 = b.Y - a.Y; int num5 = ((num3 > 0.0) ? 1 : ((num3 < 0.0) ? (-1) : 0)); int num6 = ((num4 > 0.0) ? 1 : ((num4 < 0.0) ? (-1) : 0)); double num7 = ((num5 == 0) ? double.PositiveInfinity : (((double)(num + ((num5 > 0) ? 1 : 0)) * CellSize - a.X) / num3)); double num8 = ((num6 == 0) ? double.PositiveInfinity : (((double)(num2 + ((num6 > 0) ? 1 : 0)) * CellSize - a.Y) / num4)); double num9 = ((num5 == 0) ? double.PositiveInfinity : (CellSize / Math.Abs(num3))); double num10 = ((num6 == 0) ? double.PositiveInfinity : (CellSize / Math.Abs(num4))); int num11 = Width + Height + 4; while (num11-- > 0) { if (!InBounds(num, num2)) { return false; } TerrainDef terrainDef = Cell(num, num2); if (!terrainDef.Passable) { return false; } maxCost = Math.Max(maxCost, 1.0 / terrainDef.Speed); if (num == item && num2 == item2) { return true; } if (Math.Abs(num7 - num8) < 1E-12) { if (!InBounds(num + num5, num2) || !InBounds(num, num2 + num6) || !Cell(num + num5, num2).Passable || !Cell(num, num2 + num6).Passable) { return false; } num += num5; num2 += num6; num7 += num9; num8 += num10; } else if (num7 < num8) { num += num5; num7 += num9; } else { num2 += num6; num8 += num10; } } return false; } public bool LineWalkable(Vec2 a, Vec2 b) { double maxCost; return LineWalkable(a, b, out maxCost); } public PathResult FindPath(Vec2 start, Vec2 goal) { PathResult pathResult = new PathResult { Goal = goal }; if (!IsPassable(start) && !TryNearestPassable(start, out start)) { pathResult.Message = "Start position is not on traversable terrain."; return pathResult; } if (!IsPassable(goal) || !SameComponent(start, goal)) { if (!TryNearestReachable(start, goal, out var result)) { pathResult.Message = "No reachable position near the destination."; return pathResult; } pathResult.GoalAdjusted = true; pathResult.Message = (IsPassable(goal) ? "Can't get there by land; heading as close as you can." : "Can't get there; heading as close as you can."); goal = result; pathResult.Goal = goal; } var (num, num2) = ToCell(start); var (num3, num4) = ToCell(goal); if (num == num3 && num2 == num4) { pathResult.Success = true; pathResult.Points.Add(goal); return pathResult; } if (LineWalkable(start, goal, out var maxCost) && maxCost <= 1.0 / MinSpeedOnLine(start, goal) + 1E-09) { pathResult.Success = true; pathResult.Points.Add(goal); pathResult.Cost = (goal - start).Length * maxCost; return pathResult; } int num5 = Width * Height; if (_g == null) { _g = new double[num5]; _came = new int[num5]; _seen = new int[num5]; _closed = new int[num5]; } if (++_search == int.MaxValue) { Array.Clear(_seen, 0, num5); Array.Clear(_closed, 0, num5); _search = 1; } int search = _search; double[] g = _g; int[] came = _came; int[] seen = _seen; int[] closed = _closed; int num6 = num2 * Width + num; int num7 = num4 * Width + num3; g[num6] = 0.0; came[num6] = -1; seen[num6] = search; MinHeap open = _open; open.Clear(); open.Push(num6, Heuristic(num, num2, num3, num4)); long num8 = 0L; while (open.Count > 0) { int num9 = open.Pop(); if (closed[num9] == search) { continue; } closed[num9] = search; if (num9 == num7) { break; } int num10 = num9 % Width; int num11 = num9 / Width; double num12 = _inverseSpeed[num9]; for (int i = 0; i < 8; i++) { int num13 = num10 + Dx[i]; int num14 = num11 + Dy[i]; if (num13 < 0 || num14 < 0 || num13 >= Width || num14 >= Height) { continue; } int num15 = num14 * Width + num13; if (_passable[num15] && closed[num15] != search && (i < 4 || (_passable[num11 * Width + num13] && _passable[num14 * Width + num10]))) { double num16 = ((i >= 4) ? 1.41421356237 : 1.0) * CellSize * 0.5 * (_inverseSpeed[num15] + num12); double num17 = g[num9] + num16; double num18 = ((seen[num15] == search) ? g[num15] : double.MaxValue); if (num17 < num18 - 1E-12) { g[num15] = num17; came[num15] = num9; seen[num15] = search; open.Push(num15, num17 + Heuristic(num13, num14, num3, num4) + (double)(++num8) * 1E-09); } } } } if (seen[num7] != search || came[num7] == -1) { pathResult.Message = "No route found."; return pathResult; } List list = new List(); for (int num19 = num7; num19 != num6; num19 = came[num19]) { list.Add(CellCenter(num19 % Width, num19 / Width)); } list.Reverse(); list[list.Count - 1] = goal; pathResult.Points = Smooth(start, list); pathResult.Cost = g[num7]; pathResult.Success = true; return pathResult; } public bool Reaches(Vec2 start, Vec2 goal, double tolerance) { if (!IsPassable(start) && !TryNearestPassable(start, out start)) { return false; } if (IsPassable(goal) && SameComponent(start, goal)) { return true; } if (TryNearestReachable(start, goal, out var result)) { return Vec2.Distance(result, goal) <= tolerance; } return false; } private double MinSpeedOnLine(Vec2 a, Vec2 b) { return Math.Max(TerrainAt(a).Speed, TerrainAt(b).Speed); } private bool TryNearestPassable(Vec2 p, out Vec2 result) { (int x, int y) tuple = ToCell(p); int item = tuple.x; int item2 = tuple.y; result = p; for (int i = 1; i < Math.Max(Width, Height); i++) { for (int j = item2 - i; j <= item2 + i; j++) { for (int k = item - i; k <= item + i; k++) { if (InBounds(k, j) && Cell(k, j).Passable) { result = CellCenter(k, j); return true; } } } } return false; } private double Heuristic(int x, int y, int gx, int gy) { int num = Math.Abs(x - gx); int num2 = Math.Abs(y - gy); return ((double)(num + num2) + -0.5857864376299999 * (double)Math.Min(num, num2)) * CellSize / MaxTerrainSpeed; } private List Smooth(Vec2 start, List cells) { List list = new List(); Vec2 a = start; int num = 0; while (num < cells.Count) { int num2 = num; double num3 = 0.0; for (int i = num; i < cells.Count; i++) { Vec2 a2 = ((i == 0) ? start : cells[i - 1]); num3 = Math.Max(num3, 1.0 / TerrainAt(Vec2.Lerp(a2, cells[i], 0.5)).Speed); if (!LineWalkable(a, cells[i], out var maxCost) || maxCost > num3 + 1E-09) { break; } num2 = i; } list.Add(cells[num2]); a = cells[num2]; num = num2 + 1; } return list; } } public static class ProceduralWorld { private sealed class IslandRoadHeap { private readonly List> _items = new List>(); public int Count => _items.Count; public void Push(int cell, double cost) { KeyValuePair keyValuePair = new KeyValuePair(cell, cost); int num = _items.Count; _items.Add(keyValuePair); while (num > 0) { int num2 = (num - 1) / 2; if (_items[num2].Value <= cost) { break; } _items[num] = _items[num2]; num = num2; } _items[num] = keyValuePair; } public int Pop() { int key = _items[0].Key; int num = _items.Count - 1; KeyValuePair value = _items[num]; _items.RemoveAt(num); if (num == 0) { return key; } int num2 = 0; while (num2 * 2 + 1 < num) { int num3 = num2 * 2 + 1; if (num3 + 1 < num && _items[num3 + 1].Value < _items[num3].Value) { num3++; } if (value.Value <= _items[num3].Value) { break; } _items[num2] = _items[num3]; num2 = num3; } _items[num2] = value; return key; } } public const string WorldId = "world.continent"; public const string ScenarioId = "scenario.continent"; public const int Version = 4; public const int FirstRealmsVersion = 5; public const int RealmsVersion = 6; public const int MinRealms = 2; public const int MaxRealms = 20; public const int Width = 300; public const int Height = 200; private const int LegacyWidth = 240; private const int LegacyHeight = 160; public static readonly string[] Cultures = new string[12] { "viking", "spooky", "fantasygood", "dynasty", "tribal", "medieval", "farmer", "fantasyevil", "pirate", "renaissance", "ancient", "wildwest" }; private static readonly string[] Names = new string[12] { "Frostheim", "Hollowmere", "Dawnspire", "Jade Reach", "Bonewood", "Wobblemark", "Harvest League", "Ember Dominion", "Tidebound Ports", "Gilded Republic", "Marble League", "Dustfall Frontier" }; private static readonly string[] Biomes = new string[12] { "snow", "swamp", "golden", "sakura", "autumn", "grassland", "grassland", "volcanic", "coast", "grassland", "grassland", "desert" }; private static readonly string[] Capitals = new string[12] { "Skaldhavn", "Lantern Hollow", "Dawnspire", "Jade Pavilion", "Bonewood Hearth", "Wobbleton", "Golden Acres", "Emberwatch", "Tumbledown Port", "Gilded Square", "Marblehaven", "Dustfall" }; private static readonly string[] CountWords = new string[21] { "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen", "Twenty" }; private static readonly Vec2[] IslandOutline = new Vec2[34] { new Vec2(15.0, 70.0), new Vec2(23.0, 54.0), new Vec2(18.0, 39.0), new Vec2(32.0, 21.0), new Vec2(48.0, 15.0), new Vec2(67.0, 25.0), new Vec2(82.0, 20.0), new Vec2(102.0, 29.0), new Vec2(122.0, 17.0), new Vec2(151.0, 12.0), new Vec2(173.0, 21.0), new Vec2(181.0, 34.0), new Vec2(199.0, 28.0), new Vec2(216.0, 36.0), new Vec2(229.0, 53.0), new Vec2(218.0, 68.0), new Vec2(223.0, 86.0), new Vec2(228.0, 105.0), new Vec2(215.0, 122.0), new Vec2(211.0, 137.0), new Vec2(195.0, 146.0), new Vec2(177.0, 141.0), new Vec2(163.0, 128.0), new Vec2(147.0, 140.0), new Vec2(129.0, 145.0), new Vec2(105.0, 135.0), new Vec2(87.0, 143.0), new Vec2(67.0, 140.0), new Vec2(53.0, 129.0), new Vec2(38.0, 136.0), new Vec2(24.0, 126.0), new Vec2(19.0, 109.0), new Vec2(27.0, 94.0), new Vec2(14.0, 85.0) }; private static readonly Vec2[] IslandRealms = new Vec2[12] { new Vec2(44.5, 38.5), new Vec2(89.5, 45.5), new Vec2(142.5, 35.5), new Vec2(196.5, 49.5), new Vec2(42.5, 80.5), new Vec2(95.5, 82.5), new Vec2(147.5, 78.5), new Vec2(197.5, 87.5), new Vec2(47.5, 115.5), new Vec2(94.5, 116.5), new Vec2(140.5, 116.5), new Vec2(191.5, 118.5) }; private static readonly string[] MarketTowns = new string[12] { "Ravenfjord", "Gloamwick", "Lumenhall", "Lotus Gate", "Drumrock", "Fumblebury", "Turnip Cross", "Ashfall", "Barnacle Bay", "Florin Bridge", "Columnae", "Tumbleweed Gulch" }; private static readonly string[] VillageSlots = new string[8] { "fields", "hollow", "brook", "crossing", "heath", "meadow", "orchard", "landing" }; private static readonly string[] FoodSlots = new string[3] { "fields", "hollow", "meadow" }; private static readonly Dictionary CultureProducts = new Dictionary(StringComparer.Ordinal) { { "viking", new string[6] { "good.fish", "good.fur", "good.hides", "good.timber", "good.ore", "good.meat" } }, { "spooky", new string[6] { "good.fish", "good.flax", "good.clay", "good.meat", "good.timber", "good.salt" } }, { "fantasygood", new string[5] { "good.grain", "good.grapes", "good.horses", "good.wool", "good.silver" } }, { "dynasty", new string[5] { "good.grain", "good.cotton", "good.fish", "good.silver", "good.clay" } }, { "tribal", new string[5] { "good.meat", "good.hides", "good.fur", "good.timber", "good.wool" } }, { "medieval", new string[6] { "good.grain", "good.wool", "good.horses", "good.ore", "good.hides", "good.timber" } }, { "farmer", new string[6] { "good.grain", "good.meat", "good.wool", "good.flax", "good.hides", "good.grapes" } }, { "fantasyevil", new string[5] { "good.meat", "good.ore", "good.silver", "good.salt", "good.clay" } }, { "pirate", new string[5] { "good.fish", "good.salt", "good.olives", "good.grapes", "good.timber" } }, { "renaissance", new string[6] { "good.grapes", "good.olives", "good.cotton", "good.silver", "good.clay", "good.grain" } }, { "ancient", new string[6] { "good.olives", "good.grapes", "good.fish", "good.clay", "good.salt", "good.grain" } }, { "wildwest", new string[6] { "good.dates", "good.meat", "good.horses", "good.hides", "good.silver", "good.salt" } } }; public static WorldDef Resolve(ContentDatabase content, CampaignState state) { string text = StateError(state); if (text.Length > 0) { throw new ArgumentException(text); } if (state.WorldId != "world.continent") { return content.World(state.WorldId); } if (state.WorldGeneration.Version < 5) { return Generate(state.WorldGeneration.Seed, state.WorldGeneration.Version); } return Generate(state.WorldGeneration.Seed, state.WorldGeneration.Realms, state.WorldGeneration.Version); } public static string StateError(CampaignState state) { if (state.WorldId == "world.continent") { if (state.WorldGeneration == null) { return "The procedural world is missing its saved generation identity."; } int version = state.WorldGeneration.Version; switch (version) { default: return "Unsupported procedural world version " + version + "."; case 5: case 6: { string text = RealmsError(state.WorldGeneration.Realms); if (text.Length > 0) { return text; } break; } case 1: case 2: case 3: case 4: if (state.WorldGeneration.Realms != null && state.WorldGeneration.Realms.Count > 0) { return "Only a version " + 5 + " or later world has a chosen list of realms."; } break; } } else if (state.WorldGeneration != null) { return "An authored world cannot use procedural generation metadata."; } return ""; } public static void Register(ContentDatabase content) { if (!Cultures.Any((string id) => !content.Cultures.Contains(id))) { if (!content.Worlds.ContainsKey("world.continent")) { content.Worlds.Add("world.continent", Generate(1uL)); } if (!content.Scenarios.Contains("scenario.continent")) { content.Scenarios.Add(CreateScenario(content, DefaultRealms())); } } } private static List Garrison(List line, int count, string basic) { List list = (from e in DefenderTroops.Split(line, count) select new RosterEntryDef { Unit = e.Key, Count = e.Value }).ToList(); if (list.Count == 0) { list.Add(new RosterEntryDef { Unit = basic, Count = count }); } return list; } public static WorldDef Generate(ulong seed) { return Generate(seed, 4); } public static WorldDef Generate(ulong seed, int version) { return version switch { 1 => GenerateVersion1(seed), 2 => GenerateVersion2(seed), 3 => GenerateVersion3(seed), 4 => GenerateVersion4(seed), _ => throw new ArgumentOutOfRangeException("version", version, "Unsupported procedural world version."), }; } public static List DefaultRealms() { List list = new List(); for (int i = 0; i < Cultures.Length; i++) { list.Add(new RealmSpec { Culture = Cultures[i], Name = Names[i], Capital = Capitals[i], MarketTown = MarketTowns[i], Biome = Biomes[i] }); } return list; } public static RealmSpec DefaultRealm(string culture) { int num = Array.IndexOf(Cultures, culture); if (num >= 0) { return DefaultRealms()[num]; } return null; } public static bool IsDefaultSet(IList realms) { if (realms != null && realms.Count == Cultures.Length) { return realms.Select((RealmSpec r) => r?.Culture).SequenceEqual(Cultures); } return false; } public static string RealmsError(IList realms) { if (realms == null || realms.Count < 2) { return "A campaign needs at least " + 2 + " realms."; } if (realms.Count > 20) { return "A campaign can have at most " + 20 + " realms."; } if (realms.Any((RealmSpec r) => r == null || string.IsNullOrWhiteSpace(r.Culture) || string.IsNullOrWhiteSpace(r.Name) || string.IsNullOrWhiteSpace(r.Capital) || string.IsNullOrWhiteSpace(r.MarketTown))) { return "Every realm needs a culture and names for its places."; } if (realms.Select((RealmSpec r) => r.Culture).Distinct(StringComparer.Ordinal).Count() != realms.Count) { return "Each faction can rule only one realm."; } if (realms.Any((RealmSpec r) => r.Culture.Any((char c) => char.IsWhiteSpace(c) || char.IsControl(c)))) { return "A realm's culture id is malformed."; } return ""; } public static WorldDef Generate(ulong seed, IList realms) { return Generate(seed, realms, 6); } public static WorldDef Generate(ulong seed, IList realms, int version) { string text = RealmsError(realms); if (text.Length > 0) { throw new ArgumentException(text); } if (version < 5 || version > 6) { throw new ArgumentOutOfRangeException("version", version, "Unsupported procedural world version."); } return GenerateIsland(seed, version, realms.ToList()); } private static WorldDef GenerateVersion1(ulong seed) { WorldDef worldDef = new WorldDef { Id = "world.continent", Name = "The Wobbling Continent", CellSize = 1.0, GenerationVersion = 1, GenerationSeed = seed }; worldDef.Terrain = Legend(); for (int i = 0; i < Cultures.Length; i++) { worldDef.Regions.Add(new WorldRegionDef { Id = "region." + Cultures[i], Culture = Cultures[i], Name = Names[i], Biome = Biomes[i], X = 33.5 + (double)(i % 4 * 57) + (double)(int)(Noise(seed, i, 7) * 7.0) - 3.0, Y = 30.5 + (double)(i / 4 * 49) + (double)(int)(Noise(seed, i, 13) * 7.0) - 3.0 }); } char[,] array = new char[240, 160]; for (int j = 0; j < 160; j++) { for (int k = 0; k < 240; k++) { WorldRegionDef worldRegionDef = RegionAt(worldDef, k, j); double num = ((double)k - 120.0) / 114.0; double num2 = ((double)j - 80.0) / 72.0; double num3 = Math.Atan2(num2, num); double num4 = Math.Sqrt(num * num + num2 * num2); double num5 = 0.91 + 0.075 * Math.Sin(num3 * 5.0 + Noise(seed, 6, 2) * 6.0) + 0.045 * Math.Sin(num3 * 9.0 + Noise(seed, 8, 2) * 6.0); double num6 = SmoothNoise(seed + 5, (double)k * 0.085, (double)j * 0.085); bool flag = Math.Sqrt(((double)k - worldRegionDef.X) * ((double)k - worldRegionDef.X) + ((double)j - worldRegionDef.Y) * ((double)j - worldRegionDef.Y)) < 23.0 + num6 * 3.0; bool flag2 = num4 < num5 + num6 * 0.035; if (k < 4 || j < 4 || k >= 236 || j >= 156 || (!flag && !flag2)) { array[k, j] = '~'; continue; } if (!flag && num4 > num5 - 0.025) { array[k, j] = ':'; continue; } double num7 = SmoothNoise(seed + 17, (double)k * 0.12, (double)j * 0.12); char c = ((worldRegionDef.Biome == "snow") ? 'S' : ((worldRegionDef.Biome == "desert") ? 'D' : ((worldRegionDef.Biome == "swamp") ? 'W' : '.'))); if (num7 > 0.6) { c = 'F'; } if (num7 < 0.23) { c = '^'; } double num8 = 61.0 + 7.0 * Math.Sin((double)j * 0.055 + Noise(seed, 31, 9) * 5.0); double num9 = 175.0 + 9.0 * Math.Sin((double)j * 0.043 + Noise(seed, 51, 9) * 5.0); if ((Math.Abs((double)k - num8) < 2.7 || Math.Abs((double)k - num9) < 3.0) && num7 > 0.3) { c = 'M'; } double num10 = 116.0 + 10.0 * Math.Sin((double)j * 0.061 + Noise(seed, 83, 19) * 5.0); if (Math.Abs((double)k - num10) < 1.4) { c = '='; } array[k, j] = c; } } for (int l = 0; l < worldDef.Regions.Count; l++) { WorldRegionDef worldRegionDef2 = worldDef.Regions[l]; string culture = worldRegionDef2.Culture; AddLocation(worldDef, array, "town." + culture, Capitals[l], SettlementType.Town, worldRegionDef2.X, worldRegionDef2.Y, culture, "", 8, 900.0); AddLocation(worldDef, array, "castle." + culture, Names[l] + " Keep", SettlementType.Castle, worldRegionDef2.X + 14.0, worldRegionDef2.Y - 9.0, culture, "", 5, 550.0); AddLocation(worldDef, array, "village." + culture + ".fields", Names[l] + " Fields", SettlementType.Village, worldRegionDef2.X - 11.0, worldRegionDef2.Y + 8.0, culture, "town." + culture, 6, 500.0); AddLocation(worldDef, array, "village." + culture + ".hollow", Names[l] + " Hollow", SettlementType.Village, worldRegionDef2.X + 13.0, worldRegionDef2.Y + 10.0, culture, "castle." + culture, 5, 400.0); foreach (LocationDef item in worldDef.Locations.Where((LocationDef locationDef) => locationDef.Culture == culture && locationDef.Type != SettlementType.Town)) { Road(array, worldRegionDef2.X, worldRegionDef2.Y, item.X, item.Y); } if (l % 4 > 0) { Road(array, worldDef.Regions[l - 1].X, worldDef.Regions[l - 1].Y, worldRegionDef2.X, worldRegionDef2.Y); } if (l >= 4) { Road(array, worldDef.Regions[l - 4].X, worldDef.Regions[l - 4].Y, worldRegionDef2.X, worldRegionDef2.Y); } } int[] array2 = new int[5] { 0, 4, 7, 8, 11 }; foreach (int num12 in array2) { WorldRegionDef worldRegionDef3 = worldDef.Regions[num12]; AddLocation(worldDef, array, "hideout.continent." + worldRegionDef3.Culture, Names[num12] + " Outlaw Camp", SettlementType.Hideout, worldRegionDef3.X - 17.0, worldRegionDef3.Y - 12.0, worldRegionDef3.Culture, "", 0, 100.0); worldDef.Locations.Last().BanditClan = "clan.continent.outlaws." + worldRegionDef3.Culture; Road(array, worldRegionDef3.X - 17.0, worldRegionDef3.Y - 12.0, worldRegionDef3.X, worldRegionDef3.Y); } for (int num13 = 0; num13 < 160; num13++) { char[] array3 = new char[240]; for (int num14 = 0; num14 < 240; num14++) { array3[num14] = array[num14, num13]; } worldDef.Rows.Add(new string(array3)); } return worldDef; } private static void AddLocation(WorldDef world, char[,] cells, string id, string name, SettlementType type, double x, double y, string culture, string bound, int recruits, double prosperity) { for (int i = -2; i <= 2; i++) { for (int j = -2; j <= 2; j++) { cells[(int)x + j, (int)y + i] = '.'; } } world.Locations.Add(new LocationDef { Id = id, Name = name, Type = type, X = x, Y = y, Culture = culture, BoundTo = bound, RecruitSlots = recruits, Prosperity = prosperity }); } private static void Road(char[,] cells, double ax, double ay, double bx, double by) { int num = Math.Max(1, (int)Math.Ceiling(Math.Max(Math.Abs(bx - ax), Math.Abs(by - ay)) * 2.0)); int num2 = (int)ax; int num3 = (int)ay; for (int i = 0; i <= num; i++) { int num4 = (int)(ax + (bx - ax) * (double)i / (double)num); int num5 = (int)(ay + (by - ay) * (double)i / (double)num); if (num4 != num2 && num5 != num3) { RoadCell(cells, num4, num3); } RoadCell(cells, num4, num5); num2 = num4; num3 = num5; } } private static void RoadCell(char[,] cells, int x, int y) { if (x <= 1 || y <= 1 || x >= cells.GetLength(0) - 2 || y >= cells.GetLength(1) - 2) { return; } for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { if (cells[x + j, y + i] == 'M') { cells[x + j, y + i] = '.'; } } } char c = cells[x, y]; cells[x, y] = ((c == '~' || c == '=' || c == '+') ? '+' : '#'); } public static WorldRegionDef RegionAt(WorldDef world, double x, double y) { WorldRegionDef result = null; double num = double.MaxValue; foreach (WorldRegionDef region in world.Regions) { double num2 = (x - region.X) * (x - region.X) + (y - region.Y) * (y - region.Y); if (num2 < num) { num = num2; result = region; } } return result; } public static double HeightAt(WorldDef world, double x, double y) { if (world.Rows.Count == 0) { return 1.5; } double cellSize = world.CellSize; int index = Math.Max(0, Math.Min(world.Rows[0].Length - 1, (int)Math.Floor(x / cellSize))); int index2 = Math.Max(0, Math.Min(world.Rows.Count - 1, (int)Math.Floor(y / cellSize))); char symbol = world.Rows[index2][index]; TerrainType terrainType = world.Terrain.FirstOrDefault((TerrainDef t) => t.Symbol.Length > 0 && t.Symbol[0] == symbol)?.Type ?? TerrainType.Plains; switch (terrainType) { case TerrainType.Water: return -0.25 * cellSize; case TerrainType.River: return -0.15 * cellSize; case TerrainType.Ford: case TerrainType.Bridge: return 1.5 * cellSize; default: { double num = SmoothNoise(world.GenerationSeed + 41, x / cellSize * 0.045, y / cellSize * 0.045); double num2 = 1.5 + num * 0.8; if (terrainType == TerrainType.Hills) { num2 += 1.0 + SmoothNoise(world.GenerationSeed + 59, x / cellSize * 0.17, y / cellSize * 0.17) * 2.6; } if (terrainType == TerrainType.Mountains) { num2 += 6.0 + SmoothNoise(world.GenerationSeed + 61, x / cellSize * 0.12, y / cellSize * 0.12) * 6.0; } if (terrainType == TerrainType.Beach) { num2 = 1.3 + num * 0.2; } return num2 * cellSize; } } } private static double Noise(ulong seed, int x, int y) { ulong b = (ulong)((x * -7046029254386353131L) ^ (y * -4658895280553007687L)); return (double)(StableHash.Combine(seed, b) >> 11) * 1.1102230246251565E-16; } private static double SmoothNoise(ulong seed, double x, double y) { int num = (int)Math.Floor(x); int num2 = (int)Math.Floor(y); double num3 = x - (double)num; double num4 = y - (double)num2; num3 = num3 * num3 * (3.0 - 2.0 * num3); num4 = num4 * num4 * (3.0 - 2.0 * num4); double num5 = Noise(seed, num, num2) * (1.0 - num3) + Noise(seed, num + 1, num2) * num3; double num6 = Noise(seed, num, num2 + 1) * (1.0 - num3) + Noise(seed, num + 1, num2 + 1) * num3; return num5 * (1.0 - num4) + num6 * num4; } private static List Legend() { return new List { Terrain(".", TerrainType.Plains, passable: true, 1.0, "grassland"), Terrain("F", TerrainType.Forest, passable: true, 0.72, "forest", 0.75), Terrain("^", TerrainType.Hills, passable: true, 0.8, "hills"), Terrain("M", TerrainType.Mountains, passable: false, 0.3, "mountains"), Terrain("~", TerrainType.Water, passable: false, 0.2, "water"), Terrain("=", TerrainType.River, passable: false, 0.2, "river"), Terrain("#", TerrainType.Road, passable: true, 1.35, "grassland"), Terrain("+", TerrainType.Bridge, passable: true, 1.15, "grassland"), Terrain("S", TerrainType.Snow, passable: true, 0.8, "snow"), Terrain("D", TerrainType.Desert, passable: true, 0.85, "desert"), Terrain("W", TerrainType.Swamp, passable: true, 0.6, "swamp", 0.8), Terrain(":", TerrainType.Beach, passable: true, 0.9, "coast") }; } private static TerrainDef Terrain(string symbol, TerrainType type, bool passable, double speed, string biome, double sight = 1.0) { return new TerrainDef { Symbol = symbol, Type = type, Passable = passable, Speed = speed, Biome = biome, Sight = sight }; } public static List SettlementIds(IList realms) { List list = new List(); foreach (RealmSpec realm in realms) { string culture = realm.Culture; list.Add("town." + culture); list.Add("castle." + culture); list.Add(MarketTownId(culture)); string[] villageSlots = VillageSlots; foreach (string text in villageSlots) { list.Add("village." + culture + "." + text); } } return list; } public static ScenarioDef CreateScenario(ContentDatabase content, IList realms) { int count = realms.Count; ScenarioDef scenarioDef = new ScenarioDef { Id = "scenario.continent", World = "world.continent", Name = "The Wobbling Continent", Description = ((count < CountWords.Length) ? CountWords[count] : count.ToString(CultureInfo.InvariantCulture)) + " kingdoms of two towns each across a seed-generated continent of mountain passes, forest roads and river crossings." }; bool flag = realms.Any((RealmSpec r) => r.Culture == "medieval"); for (int num = 0; num < count; num++) { string culture = realms[num].Culture; string name = realms[num].Name; string marketTown = realms[num].MarketTown; CultureDef cultureDef = content.Culture(culture); string text = "kingdom.continent." + culture; string text2 = "clan.continent." + culture; string id = text2 + ".wardens"; string id2 = text2 + ".stewards"; scenarioDef.Kingdoms.Add(new KingdomStartDef { Id = text, Name = name, Culture = culture, RulerClan = text2, Color = cultureDef.Color, Symbol = cultureDef.Symbol }); List list = (from t in cultureDef.TownRecruits where content.Unit(t.Unit).Tier <= 3 && content.Unit(t.Unit).Slots == 1 select t.Unit).Distinct().ToList(); if (list.Count == 0) { list.Add(cultureDef.BasicTroop); } scenarioDef.Clans.Add(Clan(text2, name + " Council", text, cultureDef, "", new string[2] { "town." + culture, "village." + culture + ".fields" }, list, 900 + Jitter(text2, 500), 30, 14)); scenarioDef.Clans.Add(Clan(id, name + " Wardens", text, cultureDef, "", new string[2] { "castle." + culture, "village." + culture + ".hollow" }, list, 180 + Jitter(id, 500), 18, 8)); scenarioDef.Clans.Add(Clan(id2, marketTown + " Stewards", text, cultureDef, "", new string[1] { MarketTownId(culture) }, list, 350 + Jitter(id2, 500), 22, 10)); List line = DefenderTroops.Line(content, culture); string[] array = new string[2] { "town." + culture, "castle." + culture }; foreach (string settlement in array) { scenarioDef.Garrisons.Add(new GarrisonStartDef { Settlement = settlement, Troops = Garrison(line, 26, cultureDef.BasicTroop) }); } scenarioDef.Garrisons.Add(new GarrisonStartDef { Settlement = MarketTownId(culture), Troops = Garrison(line, 22, cultureDef.BasicTroop) }); PlayerStartDef item = Start("start." + culture, cultureDef, "Independent " + cultureDef.Name + " warband"); scenarioDef.PlayerStarts.Add(item); if (culture == "medieval" || (!flag && num == 0)) { if (culture != "medieval") { scenarioDef.PlayerStarts.Insert(0, Start("start.warband", cultureDef, "Small warband")); continue; } scenarioDef.PlayerStarts.Insert(0, Start("start.warband", cultureDef, "Small warband")); PlayerStartDef playerStartDef = Start("start.commander", cultureDef, "Commander of Wobblemark"); playerStartDef.Kind = StartKind.Commander; playerStartDef.HeroUnit = cultureDef.HeroUnit; playerStartDef.Gold = 4000; playerStartDef.Renown = 250.0; playerStartDef.Kingdom = text; playerStartDef.StartLocation = "castle." + culture; playerStartDef.Food = 30.0; playerStartDef.OwnedSettlements.Add("castle." + culture); playerStartDef.OwnedSettlements.Add("village." + culture + ".hollow"); playerStartDef.Troops.Add(new RosterEntryDef { Unit = list.Last(), Count = 10 }); playerStartDef.Garrisons.Add(new GarrisonStartDef { Settlement = "castle." + culture, Troops = new List { new RosterEntryDef { Unit = cultureDef.BasicTroop, Count = 15 } } }); scenarioDef.PlayerStarts.Insert(1, playerStartDef); } } foreach (string item2 in from i in HideoutRealms(count) select realms[i].Culture) { CultureDef cultureDef2 = content.Culture(item2); scenarioDef.Clans.Add(new ClanStartDef { Id = "clan.continent.outlaws." + item2, Name = cultureDef2.Name + " Outlaws", Culture = item2, IsBandit = true, Gold = 0, Color = cultureDef2.Color, Symbol = "☠", BanditTroops = new List { new WeightedUnit { Unit = cultureDef2.BasicTroop, Weight = 1.0 } } }); } HashSet present = new HashSet(realms.Select((RealmSpec r) => r.Culture), StringComparer.Ordinal); List list2 = new string[3][] { new string[2] { "viking", "medieval" }, new string[2] { "fantasygood", "fantasyevil" }, new string[2] { "pirate", "renaissance" } }.Where((string[] pair) => present.Contains(pair[0]) && present.Contains(pair[1])).ToList(); if (list2.Count == 0) { for (int num3 = 0; num3 < Math.Max(1, count / 4); num3++) { list2.Add(new string[2] { realms[num3].Culture, realms[count - 1 - num3].Culture }); } } foreach (string[] item3 in list2) { scenarioDef.Stances.Add(new StanceDef { A = "kingdom.continent." + item3[0], B = "kingdom.continent." + item3[1], War = true }); } scenarioDef.Companions.Add(new CompanionDef { Id = "hero.companion.continent.trailguide", Name = "Pip Pebblefoot", Culture = "tribal", Unit = "tribal.spearthrower", Settlement = "town.medieval", Description = "A Bonewood guide who has walked the continent's mountain roads.", HireCost = 180L, DailyWage = 3, Skills = new SortedDictionary { { "scouting", 35 }, { "tactics", 10 } } }); scenarioDef.Companions.Add(new CompanionDef { Id = "hero.companion.continent.healer", Name = "Elsie Stitch", Culture = "medieval", Unit = "medieval.healer", Settlement = "town.farmer", Description = "A travelling healer tending the harvest communities.", HireCost = 300L, DailyWage = 4, Skills = new SortedDictionary { { "medicine", 40 }, { "stewardship", 10 } } }); scenarioDef.Companions.Add(new CompanionDef { Id = "hero.companion.continent.provisioner", Name = "Bryn Barrelback", Culture = "viking", Unit = "viking.brawler", Settlement = "town.pirate", Description = "A retired ship provisioner who knows the ports and their prices.", HireCost = 260L, DailyWage = 4, Skills = new SortedDictionary { { "stewardship", 40 }, { "trade", 15 } } }); return scenarioDef; } private static ClanStartDef Clan(string id, string name, string kingdom, CultureDef culture, string hero, string[] settlements, List troops, int renown, int basic, int veterans) { double num = 0.65 + 0.8 * (double)Jitter(id + "|party", 1000) / 1000.0; double num2 = 0.35 + 0.55 * (double)Jitter(id + "|second", 1000) / 1000.0; int gold = 4500 + 3000 * Jitter(id + "|gold", 1000) / 1000; ClanStartDef clanStartDef = new ClanStartDef { Id = id, Name = name, Kingdom = kingdom, Culture = culture.Id, Gold = gold, Renown = renown, Color = culture.Color, Symbol = culture.Symbol, Settlements = settlements.ToList(), Lords = new List() }; double[] array = new double[2] { 1.0, num2 }; foreach (double num3 in array) { clanStartDef.Lords.Add(new LordStartDef { Unit = hero, Troops = new List { new RosterEntryDef { Unit = culture.BasicTroop, Count = (int)Math.Round((double)basic * num * num3) }, new RosterEntryDef { Unit = troops.Last(), Count = (int)Math.Round((double)veterans * num * num3) } } }); } return clanStartDef; } private static int Jitter(string id, int range) { return (int)(StableHash.Fnv1a64(id) % (ulong)(range + 1)); } private static PlayerStartDef Start(string id, CultureDef culture, string name) { return new PlayerStartDef { Id = id, Name = name, Description = "Begin beside the local fields with a small company and an open road.", Culture = culture.Id, StartLocation = "village." + culture.Id + ".fields", HeroUnit = culture.BasicTroop, Gold = 600, Food = 10.0, Troops = new List { new RosterEntryDef { Unit = culture.BasicTroop, Count = 8 } } }; } private static WorldDef GenerateVersion2(ulong seed) { return GenerateIsland(seed, 2, DefaultRealms()); } private static WorldDef GenerateVersion3(ulong seed) { return GenerateIsland(seed, 3, DefaultRealms()); } private static WorldDef GenerateVersion4(ulong seed) { return GenerateIsland(seed, 4, DefaultRealms()); } internal static int RealmColumns(int count) { if (count != Cultures.Length) { return Math.Max(1, (int)Math.Ceiling(Math.Sqrt((double)(count * 4) / 3.0))); } return 4; } private static Vec2 RealmAnchor(int i, int count) { if (count == Cultures.Length) { return IslandRealms[i]; } int num = RealmColumns(count); int num2 = (count + num - 1) / num; int num3 = i / num; int num4 = i % num; int num5 = ((num3 == num2 - 1) ? (count - num3 * num) : num); double num6 = 42.0; double num7 = 198.0; double num8 = 38.0; double num9 = 117.0; double x = num6 + (num7 - num6) * ((double)num4 + 0.5 + (double)(num - num5) * 0.5) / (double)num; double y = ((num2 == 1) ? ((num8 + num9) / 2.0) : (num8 + (num9 - num8) * (double)num3 / ((double)num2 - 1.0))); return new Vec2(x, y); } private static Vec2[] SpreadRealms(char[,] cells, double[,] coastDistance, int count, double scale) { int length = cells.GetLength(0); int length2 = cells.GetLength(1); List list = new List(); for (int i = 6; i < length2 - 6; i += 2) { for (int j = 6; j < length - 6; j += 2) { if (cells[j, i] != '~' && coastDistance[j, i] >= 5.0) { list.Add(new Vec2((double)j + 0.5, (double)i + 0.5)); } } } Vec2[] array = (from i2 in Enumerable.Range(0, count) select RealmAnchor(i2, count) * scale).ToArray(); if (list.Count < count) { return array; } double[] array2 = new double[count]; double[] array3 = new double[count]; int[] array4 = new int[count]; for (int num = 0; num < 16; num++) { Array.Clear(array2, 0, count); Array.Clear(array3, 0, count); Array.Clear(array4, 0, count); foreach (Vec2 item in list) { int num2 = 0; double num3 = double.MaxValue; for (int num4 = 0; num4 < count; num4++) { double lengthSquared = (item - array[num4]).LengthSquared; if (lengthSquared < num3) { num3 = lengthSquared; num2 = num4; } } array2[num2] += item.X; array3[num2] += item.Y; array4[num2]++; } for (int num5 = 0; num5 < count; num5++) { if (array4[num5] > 0) { array[num5] = new Vec2(array2[num5] / (double)array4[num5], array3[num5] / (double)array4[num5]); } } } Vec2 vec = new Vec2(list.Average((Vec2 p) => p.X), list.Average((Vec2 p) => p.Y)); for (int num6 = 0; num6 < count; num6++) { array[num6] = vec + (array[num6] - vec) * 1.12; } return array; } internal static List HideoutRealms(int count) { if (count == Cultures.Length) { return new List { 0, 4, 7, 8, 11 }; } return (from i in Enumerable.Range(0, count) where (i + 1) * 5 / 12 > i * 5 / 12 || (count < 3 && i == 0) select i).ToList(); } private static WorldDef GenerateIsland(ulong seed, int version, List realms) { WorldDef worldDef = new WorldDef { Id = "world.continent", Name = "The Wobbling Continent", CellSize = 1.0, GenerationVersion = version, GenerationSeed = seed, Terrain = Legend() }; double num = ((version >= 5) ? (1.25 * Math.Sqrt((double)Math.Max(realms.Count, 4) / 12.0)) : ((version >= 4) ? 1.25 : 1.0)); int num2 = ((version >= 5) ? ((int)Math.Round(240.0 * num)) : ((version >= 4) ? 300 : 240)); int num3 = ((version >= 5) ? ((int)Math.Round(160.0 * num)) : ((version >= 4) ? 200 : 160)); List points = ShapeIslandOutline(seed, num); double[,] array = new double[num2, num3]; char[,] array2 = new char[num2, num3]; for (int i = 0; i < num3; i++) { for (int j = 0; j < num2; j++) { double x = (double)j + 0.5 + (SmoothNoise(seed + 101, (double)j * 0.045, (double)i * 0.045) - 0.5) * 5.0; double y = (double)i + 0.5 + (SmoothNoise(seed + 103, (double)j * 0.045, (double)i * 0.045) - 0.5) * 5.0; double num4 = (array[j, i] = DistanceInsideOutline(points, x, y) + (SmoothNoise(seed + 107, (double)j * 0.18, (double)i * 0.18) - 0.5) * 1.4); array2[j, i] = ((j < 6 || i < 6 || j >= num2 - 6 || i >= num3 - 6 || num4 <= 0.0) ? '~' : '.'); } } KeepMainIsland(array2); Vec2[] array3 = ((version >= 6) ? SpreadRealms(array2, array, realms.Count, num) : null); for (int k = 0; k < realms.Count; k++) { Vec2 desired = ((array3 != null) ? array3[k] : (RealmAnchor(k, realms.Count) * num)) + new Vec2((int)(Noise(seed, k, 7) * 7.0) - 3, (int)(Noise(seed, k, 13) * 7.0) - 3); Vec2 vec = InlandSite(worldDef, array2, array, desired, 8.0); RealmSpec realmSpec = realms[k]; worldDef.Regions.Add(new WorldRegionDef { Id = "region." + realmSpec.Culture, Culture = realmSpec.Culture, Name = realmSpec.Name, Biome = realmSpec.Biome, X = vec.X, Y = vec.Y }); } for (int l = 0; l < num3; l++) { for (int m = 0; m < num2; m++) { if (array2[m, l] != '~') { WorldRegionDef worldRegionDef = RegionAt(worldDef, m, l); double num5 = SmoothNoise(seed + 17, (double)m * 0.12, (double)l * 0.12); char c = ((worldRegionDef.Biome == "snow") ? 'S' : ((worldRegionDef.Biome == "desert") ? 'D' : ((worldRegionDef.Biome == "swamp") ? 'W' : '.'))); if (num5 > 0.6) { c = 'F'; } if (num5 < 0.23) { c = '^'; } double num6 = 61.0 * num + 7.0 * num * Math.Sin((double)l * 0.055 / num + Noise(seed, 31, 9) * 5.0); double num7 = 175.0 * num + 9.0 * num * Math.Sin((double)l * 0.043 / num + Noise(seed, 51, 9) * 5.0); if ((Math.Abs((double)m - num6) < 2.7 || Math.Abs((double)m - num7) < 3.0) && num5 > 0.3) { c = 'M'; } double num8 = SmoothNoise(seed + 109, (double)m * 0.055, (double)l * 0.055); if (array[m, l] < 1.2 + num8 * 1.8 && num8 > 0.35) { c = ':'; } double num9 = 116.0 * num + 10.0 * num * Math.Sin((double)l * 0.061 / num + Noise(seed, 83, 19) * 5.0); if (Math.Abs((double)m - num9) < 1.4) { c = '='; } array2[m, l] = c; } } } if (version >= 4) { PlaceRealmsVersion4(worldDef, array2, array, realms); } for (int n = 0; n < worldDef.Regions.Count; n++) { if (version >= 4) { break; } WorldRegionDef worldRegionDef2 = worldDef.Regions[n]; string culture = worldRegionDef2.Culture; AddIslandLocation(worldDef, array2, array, "town." + culture, Capitals[n], SettlementType.Town, worldRegionDef2.X, worldRegionDef2.Y, culture, "", 8, 900.0); AddIslandLocation(worldDef, array2, array, "castle." + culture, Names[n] + " Keep", SettlementType.Castle, worldRegionDef2.X + 14.0, worldRegionDef2.Y - 9.0, culture, "", 5, 550.0); AddIslandLocation(worldDef, array2, array, "village." + culture + ".fields", Names[n] + " Fields", SettlementType.Village, worldRegionDef2.X - 11.0, worldRegionDef2.Y + 8.0, culture, "town." + culture, 6, 500.0); AddIslandLocation(worldDef, array2, array, "village." + culture + ".hollow", Names[n] + " Hollow", SettlementType.Village, worldRegionDef2.X + 13.0, worldRegionDef2.Y + 10.0, culture, "castle." + culture, 5, 400.0); if (version >= 3) { AddIslandLocation(worldDef, array2, array, "village." + culture + ".brook", Names[n] + " Brook", SettlementType.Village, worldRegionDef2.X - 5.0, worldRegionDef2.Y - 12.0, culture, "town." + culture, 5, 450.0); AddIslandLocation(worldDef, array2, array, "village." + culture + ".crossing", Names[n] + " Crossing", SettlementType.Village, worldRegionDef2.X + 3.0, worldRegionDef2.Y + 13.0, culture, "town." + culture, 4, 380.0); AddIslandLocation(worldDef, array2, array, "village." + culture + ".heath", Names[n] + " Heath", SettlementType.Village, worldRegionDef2.X + 26.0, worldRegionDef2.Y - 3.0, culture, "castle." + culture, 4, 420.0); } foreach (LocationDef item in worldDef.Locations.Where((LocationDef locationDef2) => locationDef2.Culture == culture && locationDef2.Type != SettlementType.Town)) { IslandRoad(array2, worldRegionDef2.X, worldRegionDef2.Y, item.X, item.Y); } if (n % 4 > 0) { IslandRoad(array2, worldDef.Regions[n - 1].X, worldDef.Regions[n - 1].Y, worldRegionDef2.X, worldRegionDef2.Y); } if (n >= 4) { IslandRoad(array2, worldDef.Regions[n - 4].X, worldDef.Regions[n - 4].Y, worldRegionDef2.X, worldRegionDef2.Y); } } int[] array4 = new int[5] { 0, 4, 7, 8, 11 }; foreach (int num11 in array4) { if (version >= 4) { break; } WorldRegionDef worldRegionDef3 = worldDef.Regions[num11]; AddIslandLocation(worldDef, array2, array, "hideout.continent." + worldRegionDef3.Culture, Names[num11] + " Outlaw Camp", SettlementType.Hideout, worldRegionDef3.X - 17.0, worldRegionDef3.Y - 12.0, worldRegionDef3.Culture, "", 0, 100.0); LocationDef locationDef = worldDef.Locations.Last(); locationDef.BanditClan = "clan.continent.outlaws." + worldRegionDef3.Culture; IslandRoad(array2, locationDef.X, locationDef.Y, worldRegionDef3.X, worldRegionDef3.Y); } if (version >= 3) { SpecialiseRealms(worldDef, array2, array, seed, realms); } for (int num12 = 0; num12 < num3; num12++) { char[] array5 = new char[num2]; for (int num13 = 0; num13 < num2; num13++) { array5[num13] = array2[num13, num12]; } worldDef.Rows.Add(new string(array5)); } return worldDef; } private static List ShapeIslandOutline(ulong seed, double scale) { Vec2[] array = new Vec2[IslandOutline.Length]; for (int i = 0; i < array.Length; i++) { array[i] = IslandOutline[i] * scale + new Vec2((Noise(seed + 113, i, 0) - 0.5) * 7.0 * scale, (Noise(seed + 127, i, 0) - 0.5) * 7.0 * scale); } List list = new List(); for (int j = 0; j < array.Length; j++) { Vec2 vec = array[(j + array.Length - 1) % array.Length]; Vec2 vec2 = array[j]; Vec2 vec3 = array[(j + 1) % array.Length]; Vec2 vec4 = array[(j + 2) % array.Length]; for (int k = 0; k < 5; k++) { double num = (double)k / 5.0; double num2 = num * num; double num3 = num2 * num; list.Add(vec2 + (vec3 - vec) * (0.5 * num) + (vec * 2.0 - vec2 * 5.0 + vec3 * 4.0 - vec4) * (0.5 * num2) + (vec2 * 3.0 - vec3 * 3.0 + vec4 - vec) * (0.5 * num3)); } } return list; } private static double DistanceInsideOutline(List points, double x, double y) { bool flag = false; double num = double.MaxValue; int num2 = 0; int index = points.Count - 1; while (num2 < points.Count) { Vec2 vec = points[index]; Vec2 vec2 = points[num2]; if (vec.Y > y != vec2.Y > y && x < (vec2.X - vec.X) * (y - vec.Y) / (vec2.Y - vec.Y) + vec.X) { flag = !flag; } double num3 = vec2.X - vec.X; double num4 = vec2.Y - vec.Y; double num5 = Math.Max(0.0, Math.Min(1.0, ((x - vec.X) * num3 + (y - vec.Y) * num4) / (num3 * num3 + num4 * num4))); double num6 = x - vec.X - num3 * num5; double num7 = y - vec.Y - num4 * num5; num = Math.Min(num, num6 * num6 + num7 * num7); index = num2++; } return Math.Sqrt(num) * (double)(flag ? 1 : (-1)); } private static void KeepMainIsland(char[,] cells) { int length = cells.GetLength(0); int length2 = cells.GetLength(1); bool[,] array = new bool[length, length2]; Queue queue = new Queue(); queue.Enqueue(length2 / 2 * length + length / 2); array[length / 2, length2 / 2] = true; int[] array2 = new int[4] { 1, -1, 0, 0 }; int[] array3 = new int[4] { 0, 0, 1, -1 }; while (queue.Count > 0) { int num = queue.Dequeue(); int num2 = num % length; int num3 = num / length; for (int i = 0; i < 4; i++) { int num4 = num2 + array2[i]; int num5 = num3 + array3[i]; if (num4 >= 0 && num5 >= 0 && num4 < length && num5 < length2 && !array[num4, num5] && cells[num4, num5] != '~') { array[num4, num5] = true; queue.Enqueue(num5 * length + num4); } } } for (int j = 0; j < length2; j++) { for (int k = 0; k < length; k++) { if (!array[k, j]) { cells[k, j] = '~'; } } } } private static Vec2 InlandSite(WorldDef world, char[,] cells, double[,] coastDistance, Vec2 desired, double margin) { int length = cells.GetLength(0); int length2 = cells.GetLength(1); Vec2 result = desired; double num = double.MaxValue; for (int i = 6; i < length2 - 6; i++) { for (int j = 6; j < length - 6; j++) { if (cells[j, i] == '~' || coastDistance[j, i] < margin) { continue; } Vec2 vec = new Vec2((double)j + 0.5, (double)i + 0.5); double lengthSquared = (vec - desired).LengthSquared; if (lengthSquared >= num || TooClose(world, vec)) { continue; } bool flag = true; for (int k = -4; k <= 4 && flag; k++) { for (int l = -4; l <= 4; l++) { char c = cells[j + l, i + k]; if (c == '~' || (Math.Abs(l) <= 2 && Math.Abs(k) <= 2 && (c == '=' || c == '+'))) { flag = false; break; } } } if (flag) { result = vec; num = lengthSquared; } } } if (num == double.MaxValue) { throw new InvalidOperationException("The island has no inland location site."); } return result; } private static bool TooClose(WorldDef world, Vec2 point) { List locations = world.Locations; for (int i = 0; i < locations.Count; i++) { if ((point - new Vec2(locations[i].X, locations[i].Y)).LengthSquared < 49.0) { return true; } } return false; } private static void AddIslandLocation(WorldDef world, char[,] cells, double[,] coastDistance, string id, string name, SettlementType type, double x, double y, string culture, string bound, int recruits, double prosperity) { Vec2 vec = InlandSite(world, cells, coastDistance, new Vec2(x, y), 4.5); AddLocation(world, cells, id, name, type, vec.X, vec.Y, culture, bound, recruits, prosperity); } private static void IslandRoad(char[,] cells, double ax, double ay, double bx, double by) { int length = cells.GetLength(0); int length2 = cells.GetLength(1); int num = (int)ay * length + (int)ax; int num2 = (int)by * length + (int)bx; int[] array = new int[length * length2]; double[] array2 = new double[length * length2]; bool[] array3 = new bool[length * length2]; for (int i = 0; i < array2.Length; i++) { array2[i] = double.MaxValue; array[i] = -1; } IslandRoadHeap islandRoadHeap = new IslandRoadHeap(); array2[num] = 0.0; islandRoadHeap.Push(num, 0.0); int[] array4 = new int[8] { 1, -1, 0, 0, 1, 1, -1, -1 }; int[] array5 = new int[8] { 0, 0, 1, -1, 1, -1, 1, -1 }; while (islandRoadHeap.Count > 0) { int num3 = islandRoadHeap.Pop(); if (array3[num3]) { continue; } array3[num3] = true; if (num3 == num2) { break; } int num4 = num3 % length; int num5 = num3 / length; for (int j = 0; j < array4.Length; j++) { int num6 = num4 + array4[j]; int num7 = num5 + array5[j]; if (!IslandRoadCellAllowed(cells, num6, num7) || (j >= 4 && (!IslandRoadCellAllowed(cells, num6, num5) || !IslandRoadCellAllowed(cells, num4, num7)))) { continue; } int num8 = num7 * length + num6; if (!array3[num8]) { double num9; switch (cells[num6, num7]) { default: num9 = 1.0; break; case '^': num9 = 1.4; break; case '#': case '+': num9 = 0.8; break; case '=': num9 = 2.8; break; case 'M': num9 = 3.5; break; } double num10 = num9; double num11 = array2[num3] + num10 * ((j >= 4) ? 1.41421356237 : 1.0); if (!(num11 >= array2[num8])) { array2[num8] = num11; array[num8] = num3; double num12 = num6 - num2 % length; double num13 = num7 - num2 / length; islandRoadHeap.Push(num8, num11 + Math.Sqrt(num12 * num12 + num13 * num13) * 0.8); } } } } if (!array3[num2]) { throw new InvalidOperationException("An island road could not reach its destination by land."); } for (int num14 = num2; num14 != num; num14 = array[num14]) { int num15 = array[num14]; int num16 = num14 % length; int num17 = num14 / length; int num18 = num15 % length; int num19 = num15 / length; if (num16 != num18 && num17 != num19) { RoadCell(cells, num16, num19); } RoadCell(cells, num16, num17); } RoadCell(cells, num % length, num / length); } private static bool IslandRoadCellAllowed(char[,] cells, int x, int y) { if (x < 2 || y < 2 || x >= cells.GetLength(0) - 2 || y >= cells.GetLength(1) - 2 || cells[x, y] == '~') { return false; } if (cells[x, y] == '=' || cells[x, y] == '+') { for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { if (cells[x + j, y + i] == '~') { return false; } } } } return true; } public static string MarketTownId(string culture) { return "town." + culture + ".market"; } private static void PlaceRealmsVersion4(WorldDef world, char[,] cells, double[,] coastDistance, List realms) { for (int i = 0; i < world.Regions.Count; i++) { WorldRegionDef worldRegionDef = world.Regions[i]; string culture = worldRegionDef.Culture; string name = realms[i].Name; AddIslandLocation(world, cells, coastDistance, "town." + culture, realms[i].Capital, SettlementType.Town, worldRegionDef.X, worldRegionDef.Y, culture, "", 8, 900.0); AddIslandLocation(world, cells, coastDistance, "castle." + culture, name + " Keep", SettlementType.Castle, worldRegionDef.X + 14.0, worldRegionDef.Y - 9.0, culture, "", 5, 550.0); AddIslandLocation(world, cells, coastDistance, "village." + culture + ".fields", name + " Fields", SettlementType.Village, worldRegionDef.X - 11.0, worldRegionDef.Y + 8.0, culture, "town." + culture, 6, 500.0); AddIslandLocation(world, cells, coastDistance, "village." + culture + ".hollow", name + " Hollow", SettlementType.Village, worldRegionDef.X + 13.0, worldRegionDef.Y + 10.0, culture, "castle." + culture, 5, 400.0); AddIslandLocation(world, cells, coastDistance, "village." + culture + ".brook", name + " Brook", SettlementType.Village, worldRegionDef.X - 5.0, worldRegionDef.Y - 12.0, culture, "town." + culture, 5, 450.0); AddIslandLocation(world, cells, coastDistance, "village." + culture + ".crossing", name + " Crossing", SettlementType.Village, worldRegionDef.X + 3.0, worldRegionDef.Y + 13.0, culture, "town." + culture, 4, 380.0); AddIslandLocation(world, cells, coastDistance, "village." + culture + ".heath", name + " Heath", SettlementType.Village, worldRegionDef.X + 26.0, worldRegionDef.Y - 3.0, culture, "castle." + culture, 4, 420.0); } for (int j = 0; j < world.Regions.Count; j++) { WorldRegionDef worldRegionDef2 = world.Regions[j]; string culture2 = worldRegionDef2.Culture; string text = MarketTownId(culture2); Vec2 vec = new Vec2(worldRegionDef2.X, worldRegionDef2.Y); Vec2 vec2 = SecondTownSite(world, cells, coastDistance, worldRegionDef2); string marketTown = realms[j].MarketTown; AddLocation(world, cells, text, marketTown, SettlementType.Town, vec2.X, vec2.Y, culture2, "", 7, 700.0); Vec2 normalized = (vec2 - vec).Normalized; AddIslandLocation(world, cells, coastDistance, "village." + culture2 + ".meadow", marketTown + " Meadow", SettlementType.Village, (vec2 + Turn(normalized, 75.0) * 10.0).X, (vec2 + Turn(normalized, 75.0) * 10.0).Y, culture2, text, 5, 450.0); AddIslandLocation(world, cells, coastDistance, "village." + culture2 + ".orchard", marketTown + " Orchard", SettlementType.Village, (vec2 + Turn(normalized, -75.0) * 10.0).X, (vec2 + Turn(normalized, -75.0) * 10.0).Y, culture2, text, 5, 420.0); AddIslandLocation(world, cells, coastDistance, "village." + culture2 + ".landing", marketTown + " Landing", SettlementType.Village, (vec2 + normalized * 11.0).X, (vec2 + normalized * 11.0).Y, culture2, text, 4, 380.0); } foreach (int item in HideoutRealms(world.Regions.Count)) { WorldRegionDef worldRegionDef3 = world.Regions[item]; AddIslandLocation(world, cells, coastDistance, "hideout.continent." + worldRegionDef3.Culture, realms[item].Name + " Outlaw Camp", SettlementType.Hideout, worldRegionDef3.X - 17.0, worldRegionDef3.Y - 12.0, worldRegionDef3.Culture, "", 0, 100.0); world.Locations.Last().BanditClan = "clan.continent.outlaws." + worldRegionDef3.Culture; } for (int k = 0; k < world.Regions.Count; k++) { WorldRegionDef worldRegionDef4 = world.Regions[k]; string culture3 = worldRegionDef4.Culture; string market = MarketTownId(culture3); LocationDef locationDef = world.Locations.First((LocationDef l) => l.Id == market); foreach (LocationDef item2 in world.Locations.Where((LocationDef l) => l.Culture == culture3 && l.Id != "town." + culture3 && l.Type != SettlementType.Hideout)) { if (item2.BoundTo == market) { IslandRoad(cells, locationDef.X, locationDef.Y, item2.X, item2.Y); } else { IslandRoad(cells, worldRegionDef4.X, worldRegionDef4.Y, item2.X, item2.Y); } } int num = RealmColumns(world.Regions.Count); if (k % num > 0) { IslandRoad(cells, world.Regions[k - 1].X, world.Regions[k - 1].Y, worldRegionDef4.X, worldRegionDef4.Y); } if (k >= num) { IslandRoad(cells, world.Regions[k - num].X, world.Regions[k - num].Y, worldRegionDef4.X, worldRegionDef4.Y); } } foreach (LocationDef camp in world.Locations.Where((LocationDef l) => l.Type == SettlementType.Hideout).ToList()) { WorldRegionDef worldRegionDef5 = world.Regions.First((WorldRegionDef r) => r.Culture == camp.Culture); IslandRoad(cells, camp.X, camp.Y, worldRegionDef5.X, worldRegionDef5.Y); } } private static Vec2 Turn(Vec2 v, double degrees) { double num = degrees * Math.PI / 180.0; double num2 = Math.Cos(num); double num3 = Math.Sin(num); return new Vec2(v.X * num2 - v.Y * num3, v.X * num3 + v.Y * num2); } private static Vec2 SecondTownSite(WorldDef world, char[,] cells, double[,] coastDistance, WorldRegionDef region) { int length = cells.GetLength(0); int length2 = cells.GetLength(1); Vec2 vec = new Vec2(region.X, region.Y); double[][] array = new double[2][] { new double[4] { 20.0, 30.0, 12.0, 7.0 }, new double[4] { 14.0, 36.0, 9.0, 5.0 } }; foreach (double[] obj in array) { double num = obj[0]; double num2 = obj[1]; double num3 = obj[2]; double num4 = obj[3]; Vec2 result = vec; double num5 = double.MinValue; for (int j = Math.Max(6, (int)(region.Y - num2)); j <= Math.Min(length2 - 7, (int)(region.Y + num2)); j++) { for (int k = Math.Max(6, (int)(region.X - num2)); k <= Math.Min(length - 7, (int)(region.X + num2)); k++) { if (cells[k, j] == '~' || coastDistance[k, j] < num4) { continue; } Vec2 vec2 = new Vec2((double)k + 0.5, (double)j + 0.5); double length3 = (vec2 - vec).Length; if (length3 < num || length3 > num2 || RegionAt(world, vec2.X, vec2.Y) != region) { continue; } double num6 = double.MaxValue; foreach (LocationDef location in world.Locations) { num6 = Math.Min(num6, (vec2 - new Vec2(location.X, location.Y)).Length); } if (!(num6 < num3)) { double num7 = Math.Min(num6, 20.0) - Math.Abs(length3 - 24.0) * 0.5; if (!(num7 <= num5) && DrySite(cells, k, j)) { result = vec2; num5 = num7; } } } } if (num5 > double.MinValue) { return result; } } return InlandSite(world, cells, coastDistance, vec + new Vec2(-22.0, 4.0), 4.5); } private static bool DrySite(char[,] cells, int x, int y) { for (int i = -4; i <= 4; i++) { for (int j = -4; j <= 4; j++) { char c = cells[x + j, y + i]; if (c == '~' || (Math.Abs(j) <= 2 && Math.Abs(i) <= 2 && (c == '=' || c == '+'))) { return false; } } } return true; } private static void SpecialiseRealms(WorldDef world, char[,] cells, double[,] coastDistance, ulong seed, List realms) { for (int i = 0; i < realms.Count; i++) { string culture = realms[i].Culture; HashSet used = new HashSet(StringComparer.Ordinal); string[] villageSlots = VillageSlots; foreach (string slot in villageSlots) { LocationDef village = world.Locations.FirstOrDefault((LocationDef l) => l.Id == "village." + culture + "." + slot); if (village != null) { bool food = FoodSlots.Contains(slot); VillageProductDef kind = (from k in VillageProducts.All where !used.Contains(k.GoodId) && (!food || k.FoodVillage) select new { Kind = k, Score = ProductScore(k.GoodId, culture, village, cells, coastDistance, seed) } into x orderby x.Score descending select x).ThenBy(x => x.Kind.GoodId, StringComparer.Ordinal).First().Kind; used.Add(kind.GoodId); village.Product = kind.GoodId; village.Name = ((village.BoundTo == MarketTownId(culture)) ? realms[i].MarketTown : realms[i].Name) + " " + kind.NameSuffix; } } foreach (LocationDef item in world.Locations.Where((LocationDef l) => l.Culture == culture)) { if (item.Type == SettlementType.Town) { item.WallLevel = 2; } else if (item.Type == SettlementType.Castle) { item.WallLevel = 1; } } } } private static double ProductScore(string good, string culture, LocationDef village, char[,] cells, double[,] coastDistance, ulong seed) { double num = 0.0; if (CultureProducts.TryGetValue(culture, out var value)) { int num2 = Array.IndexOf(value, good); if (num2 >= 0) { num += 1.5 - 0.15 * (double)num2; } } int num3 = (int)village.X; int num4 = (int)village.Y; Dictionary count = new Dictionary(); for (int i = num4 - 5; i <= num4 + 5; i++) { for (int j = num3 - 5; j <= num3 + 5; j++) { if (j >= 0 && i >= 0 && j < cells.GetLength(0) && i < cells.GetLength(1)) { char key = cells[j, i]; count[key] = (count.TryGetValue(key, out var value2) ? value2 : 0) + 1; } } } int num5 = Of('F'); int num6 = Of('^'); int num7 = Of('M'); int num8 = Of('D'); int num9 = Of('S'); int num10 = Of('W'); int num11 = Of('=') + Of('+'); int num12 = Of(':'); int num13 = Of('.') + Of('#'); bool flag = coastDistance[Math.Max(0, Math.Min(cells.GetLength(0) - 1, num3)), Math.Max(0, Math.Min(cells.GetLength(1) - 1, num4))] < 9.0 || num12 >= 3; double val; switch (good) { case "good.fish": val = ((flag || num11 >= 3) ? 1 : 0); break; case "good.salt": val = Math.Max((num12 >= 3) ? 0.7 : 0.0, Cap((double)num8 / 30.0) * 0.7); break; case "good.timber": val = Cap((double)num5 / 30.0); break; case "good.fur": val = Cap((double)(num5 + num9) / 40.0) * ((num9 > 0) ? 1.0 : 0.5); break; case "good.ore": val = Cap((double)(num6 + num7) / 25.0); break; case "good.silver": val = Cap((double)(num6 + num7) / 25.0) * 0.8; break; case "good.clay": val = ((num11 >= 2) ? 0.5 : 0.0) + Cap((double)num10 / 60.0); break; case "good.dates": val = Cap((double)num8 / 40.0); break; case "good.grain": val = Cap((double)num13 / 70.0); break; case "good.horses": val = Cap((double)num13 / 70.0) * 0.8; break; case "good.flax": val = Cap((double)num13 / 70.0) * 0.6 + Cap((double)num10 / 60.0) * 0.4; break; case "good.cotton": val = Cap((double)num13 / 70.0) * 0.5; break; case "good.wool": val = Cap((double)num6 / 30.0) + Cap((double)num13 / 120.0); break; case "good.olives": case "good.grapes": val = Cap((double)num6 / 40.0) + Cap((double)num13 / 120.0); break; case "good.meat": case "good.hides": val = Cap((double)num13 / 100.0) + Cap((double)num5 / 100.0); break; default: val = 0.0; break; } num += 0.8 * Math.Min(1.2, val); return num + 0.5 * Noise(seed + 211, (int)(StableHash.Fnv1a64(village.Id + "|" + good) % 1000003), 17); static double Cap(double v) { return Math.Max(0.0, Math.Min(1.0, v)); } int Of(char c) { if (!count.TryGetValue(c, out var value3)) { return 0; } return value3; } } } } namespace TabsBannerlord.Core.State { public sealed class KingdomArmiesState { public bool Initialized; public long LastDay = -1L; public List Armies = new List(); public SortedDictionary AttachedTo = new SortedDictionary(StringComparer.Ordinal); } public sealed class AiArmy { public string Id = ""; public string KingdomId = ""; public string LeaderPartyId = ""; public string LeaderHeroId = ""; public List MemberPartyIds = new List(); public long FormedDay; public double Cohesion = 100.0; public string TargetSettlementId = ""; public bool PlayerJoined; public long PlayerJoinedDay = -1L; } public enum TimeSpeed { Paused, Normal, Fast, Rapid } public sealed class ClockState { public long Minute; public double PendingMinutes; public TimeSpeed Speed; public TimeSpeed LastRunningSpeed = TimeSpeed.Normal; public long NextHourMinute = 60L; public long NextDayMinute = 1440L; public string PauseReason = ""; public long Day => Minute / 1440; public int HourOfDay => (int)(Minute % 1440 / 60); } public sealed class CampaignSettings { public string Difficulty = "Hard"; public double PlayerDamageTaken = 1.0; public double TroopDamageTaken = 1.0; public double PersuasionEase; public double PlayerMapSpeedBonus; public double DisguiseDetection = 1.0; public double AiLordStrength = 1.0; public int ActiveUnitBudget = 120; public bool FullInformation; public bool HeroesCanDie; public bool Ironman; public bool PeopleAge = true; public bool OldAgeDeaths = true; public bool Births = true; public bool LordsMarry = true; public bool Rebellions = true; public bool RandomEvents = true; public bool AiGarrisonsImprove; public int AutosaveSlots = 3; public double AutosaveIntervalDays = 1.0; } public enum PlayerActivity { Idle, Travelling, InSettlement, Waiting, InEncounter, InBattle, Captive, Raiding, Besieging } public sealed class PlayerState { public PlayerActivity Activity; public string MenuSettlementId = ""; public string KeepAccessSettlementId = ""; public string PendingEncounterId = ""; public long WaitUntilMinute; public string CaptorPartyId = ""; public string CaptorSettlementId = ""; public long CaptiveSinceMinute; public int CaptivityMaxDays; public long LastAutosaveDay; public BattleReport LastReport; public bool LastReportSeen = true; } public sealed class PendingConsequence { public string Id = ""; public string Kind = ""; public string SubjectId = ""; public string Data = ""; } public sealed class CampaignState { public const int CurrentSchemaVersion = 1; public int SchemaVersion = 1; public string CampaignId = ""; public string ScenarioId = ""; public string WorldId = ""; public WorldGenerationState WorldGeneration; public CustomContentState CustomContent; public string PlayerStartId = ""; public ContentManifest Content = new ContentManifest(); public CampaignSettings Settings = new CampaignSettings(); public RandomStreams Random = new RandomStreams(); public IdAllocator Ids = new IdAllocator(); public ClockState Clock = new ClockState(); public long Revision; public string PlayerHeroId = ""; public string PlayerClanId = ""; public string PlayerPartyId = ""; public PlayerState Player = new PlayerState(); public EntityTable Heroes = new EntityTable(); public EntityTable Clans = new EntityTable(); public EntityTable Kingdoms = new EntityTable(); public EntityTable Settlements = new EntityTable(); public EntityTable Parties = new EntityTable(); public EntityTable Encounters = new EntityTable(); public List Stances = new List(); public SortedDictionary PlayerSightings = new SortedDictionary(StringComparer.Ordinal); public SortedSet CommittedEncounters = new SortedSet(StringComparer.Ordinal); public SortedSet AppliedEventIds = new SortedSet(StringComparer.Ordinal); public List PendingConsequences = new List(); public List Ledger = new List(); public List Log = new List(); public List Workshops = new List(); public List Contracts = new List(); public List Caravans = new List(); public List MilitaryParties = new List(); public List GarrisonParties = new List(); public ClanArmyState ClanArmy = new ClanArmyState(); public List Notables = new List(); public ClanServiceState ClanService = new ClanServiceState(); public DiplomacyState Diplomacy = new DiplomacyState(); public KingdomArmiesState KingdomArmies = new KingdomArmiesState(); public List Sieges = new List(); public PoliticsState Politics = new PoliticsState(); public ClanAllegianceState ClanAllegiance = new ClanAllegianceState(); public WardrobeState Wardrobe = new WardrobeState(); public SmithingState Smithing = new SmithingState(); public HorsesState Horses = new HorsesState(); public bool OutlawPartiesDoubled; public bool LordUnitsVaried; public bool MerchantCaravansStarted; public bool EquipmentPiecesStocked; public SortedSet EquipmentIntroduced = new SortedSet(StringComparer.Ordinal); public bool DeveloperTools; public bool DeveloperToolsDecided; public HeroBondsState HeroBonds = new HeroBondsState(); public SortedDictionary MerchantCaravanDue = new SortedDictionary(StringComparer.Ordinal); public SortedDictionary ClanCaravanDue = new SortedDictionary(StringComparer.Ordinal); public SortedDictionary PlayerCargoCosts = new SortedDictionary(StringComparer.Ordinal); public TournamentsState Tournaments = new TournamentsState(); public AbilitiesState Abilities = new AbilitiesState(); public List EncyclopediaBookmarks = new List(); public SortedSet MetHeroes = new SortedSet(StringComparer.Ordinal); public ConversationsState Conversations = new ConversationsState(); public WanderersState Wanderers = new WanderersState(); public FamiliesState Families = new FamiliesState(); public CrimeState Crime = new CrimeState(); public RebellionState Rebellions = new RebellionState(); public QuestsState Quests = new QuestsState(); public TutorialState Tutorial = new TutorialState(); public StoryEventsState StoryEvents = new StoryEventsState(); public HideoutsState Hideouts = new HideoutsState(); public LegendsState Legends = new LegendsState(); public ScoutingState Scouting = new ScoutingState(); public const int MaxLogEntries = 400; public const int MaxLedgerEntries = 600; public const double HuntedCrime = 90.0; public Party PlayerParty => Parties.Get(PlayerPartyId); public Hero PlayerHero => Heroes.Get(PlayerHeroId); public Clan PlayerClan => Clans.Get(PlayerClanId); public IEnumerable ActiveParties => Parties.Where((Party p) => p.State == PartyState.Active || p.State == PartyState.InSettlement || p.State == PartyState.Engaged); public string FactionOf(Clan clan) { if (clan != null) { if (!string.IsNullOrEmpty(clan.KingdomId)) { return clan.KingdomId; } return clan.Id; } return ""; } public string FactionOfParty(Party p) { return FactionOf(Clans.Get(p.ClanId)); } public StanceRecord FindStance(string a, string b) { foreach (StanceRecord stance in Stances) { if ((stance.A == a && stance.B == b) || (stance.A == b && stance.B == a)) { return stance; } } return null; } public bool AtWar(string factionA, string factionB) { if (factionA == factionB) { return false; } StanceRecord stanceRecord = FindStance(factionA, factionB); if (stanceRecord != null) { return stanceRecord.Stance == Stance.War; } return false; } public bool AreHostile(Clan a, Clan b) { if (a == null || b == null || a.Id == b.Id) { return false; } if (a.IsBandit || b.IsBandit) { return a.IsBandit != b.IsBandit; } return AtWar(FactionOf(a), FactionOf(b)); } public bool AreHostile(Party a, Party b) { if (!AreHostile(Clans.Get(a.ClanId), Clans.Get(b.ClanId)) && !HuntsPlayer(a, b)) { return HuntsPlayer(b, a); } return true; } public bool HuntsPlayer(Party hunter, Party player) { if (hunter == null || player == null || player.Id != PlayerPartyId || hunter.Id == player.Id || Crime?.Rating == null) { return false; } if (hunter.Kind == PartyKind.Villager || hunter.Kind == PartyKind.Caravan) { return false; } Clan clan = Clans.Get(hunter.ClanId); if (clan == null || clan.IsBandit || clan.Id == PlayerClanId) { return false; } string text = FactionOf(clan); if (text == FactionOf(PlayerClan)) { return false; } if (Crime.Rating.TryGetValue(text, out var value)) { return value >= 90.0; } return false; } public bool AreAllied(Party a, Party b) { Clan clan = Clans.Get(a.ClanId); Clan clan2 = Clans.Get(b.ClanId); if (clan == null || clan2 == null) { return false; } if (clan.IsBandit || clan2.IsBandit) { if (clan.IsBandit && clan2.IsBandit) { return clan.Id == clan2.Id; } return false; } string text = FactionOf(clan); string text2 = FactionOf(clan2); if (!(text == text2)) { return FactionsAllied(text, text2); } return true; } public bool FactionsAllied(string a, string b) { if (a != b && Diplomacy?.Agreements != null) { return Diplomacy.Agreements.Any((DiplomaticAgreement x) => x != null && x.Kind == AgreementKind.Alliance && x.EndsDay > Clock.Day && ((x.A == a && x.B == b) || (x.A == b && x.B == a))); } return false; } public void SetStance(string a, string b, Stance stance) { StanceRecord stanceRecord = FindStance(a, b); if (stanceRecord == null) { stanceRecord = new StanceRecord { A = ((string.CompareOrdinal(a, b) < 0) ? a : b), B = ((string.CompareOrdinal(a, b) < 0) ? b : a) }; Stances.Add(stanceRecord); } if (stanceRecord.Stance != stance) { stanceRecord.Stance = stance; stanceRecord.SinceMinute = Clock.Minute; } } public LogEntry AddLog(LogCategory category, string text, params string[] links) { LogEntry logEntry = new LogEntry { Id = Ids.AllocateNumber("log"), Minute = Clock.Minute, Category = category, Text = text }; logEntry.Links.AddRange(links.Where((string l) => !string.IsNullOrEmpty(l))); Log.Add(logEntry); if (Log.Count > 400) { Log.RemoveRange(0, Log.Count - 400); } return logEntry; } public long Transact(Clan clan, long amount, LedgerAccount account, string reason, bool allowPartial = false) { if (clan == null || amount == 0L) { return 0L; } if (amount < 0 && clan.Gold + amount < 0) { if (!allowPartial) { throw new InvalidOperationException($"{clan.Name} cannot afford {-amount} gold for {reason}"); } amount = -clan.Gold; if (amount == 0L) { return 0L; } } clan.Gold += amount; Ledger.Add(new LedgerEntry { Minute = Clock.Minute, ClanId = clan.Id, Account = account, Amount = amount, Reason = reason }); if (Ledger.Count > 600) { Ledger.RemoveRange(0, Ledger.Count - 600); } return amount; } public void Touch() { Revision++; } } public sealed class CaravanState { public string Id = ""; public string PartyId = ""; public string OwnerClanId = ""; public string HomeSettlementId = ""; public string Status = "Trading"; public bool RecallRequested; public long LastArrivalMinute = -1L; public string LastArrivalSettlementId = ""; public long LastTradeProfit; public long TotalTradeProfit; public long StartedMinute; public bool Merchant; public bool ClanCaravan; public SortedDictionary CargoCosts = new SortedDictionary(StringComparer.Ordinal); public bool IsActive { get { if (Status != "Lost") { return Status != "Disbanded"; } return false; } } } public sealed class CharacterCreationState { public string BackgroundId = ""; public string TrainingId = ""; public string TraitId = ""; public string CultureId = ""; public string ArchetypeId = ""; public string BannerColor = ""; public string BannerSymbol = ""; public string BannerEmblemColor = ""; public SortedDictionary LifeStages = new SortedDictionary(StringComparer.Ordinal); public int Age; public SortedDictionary Focus = new SortedDictionary(StringComparer.Ordinal); public string StartSettlementId = ""; public bool HasLifeStages { get { if (LifeStages != null) { return LifeStages.Count > 0; } return false; } } } public enum ClanAllegianceChange { Recruited, Expelled, Seceded, Swore } public sealed class ClanAllegianceState { public bool Initialized; public long LastAiDay = -1L; public List Records = new List(); } public sealed class ClanAllegianceRecord { public string ClanId = ""; public string PreviousKingdomId = ""; public string KingdomId = ""; public string SponsorClanId = ""; public ClanAllegianceChange Kind; public long ChangedDay; public long CooldownUntilDay; public long SigningPayment; } public sealed class ClanArmyMember { public string PartyId = ""; public MilitaryPartyDirective PreviousDirective; public bool KingdomCall; public string OwnerClanId = ""; public string LeaderHeroId = ""; public string KingdomId = ""; public long CalledDay = -1L; public long EndsDay = -1L; public long LastSupportDay = -1L; } public sealed class ClanArmyState { public bool Active; public string Id = ""; public string OwnerClanId = ""; public string LeaderPartyId = ""; public long StartedMinute; public long LastDailyDay = -1L; public long LastRallyDay = -1L; public double Cohesion = 100.0; public List Members = new List(); } public enum ClanServiceKind { Independent, Mercenary, Vassal, Ruler } public sealed class ClanServiceState { public bool Initialized; public ClanServiceKind Kind; public string KingdomId = ""; public long StartedDay; public long EndsDay = -1L; public long LastPaidDay = -1L; public long LastPayment; } public enum ContractKind { Delivery, BanditBounty, SettlementSupply } public enum ContractStatus { Offered, Active, Completed, Failed, Cancelled } public sealed class ContractState { public string Id = ""; public ContractKind Kind; public ContractStatus Status; public bool WasAccepted; public string IssuerSettlementId = ""; public string IssuerClanId = ""; public string IssuerNotableId = ""; public string TargetSettlementId = ""; public string TargetPartyId = ""; public string GoodId = ""; public int Quantity; public long Reward; public long Escrow; public long OfferedDay; public long DeadlineMinute; public int Progress; public string Description = ""; } public sealed class ConversationsState { public SortedDictionary SmallTalkDay = new SortedDictionary(StringComparer.Ordinal); public SortedDictionary PersuasionBarredUntilDay = new SortedDictionary(StringComparer.Ordinal); public SortedDictionary RecruitPersuadedUntilDay = new SortedDictionary(StringComparer.Ordinal); } public sealed class CrimeState { public SortedDictionary Rating = new SortedDictionary(StringComparer.Ordinal); public string GateSettlementId = ""; public string DisguisedSettlementId = ""; public SortedDictionary SneakBarredUntil = new SortedDictionary(StringComparer.Ordinal); public List Alleys = new List(); public bool AlleysStarted; public List Executed = new List(); } public sealed class AlleyState { public string Id = ""; public string SettlementId = ""; public int Index; public string Name = ""; public string OwnerClanId = ""; public string GangName = ""; public string GangLeaderName = ""; public int GangSize = 4; public string OverseerHeroId = ""; public long TakenDay = -1L; public long IncomeTotal; public long ChallengeDay; } public sealed class DiplomacyState { public bool Initialized; public long LastAiDay = -1L; public List Truces = new List(); public List Agreements = new List(); public List Calls = new List(); public List Captures = new List(); public List PendingElections = new List(); public long LastPactAiDay = -1L; } public enum AgreementKind { Alliance, TradeAgreement, Tribute } public sealed class DiplomaticAgreement { public string Id = ""; public AgreementKind Kind; public string A = ""; public string B = ""; public long SignedDay; public long EndsDay; public string PayerFactionId = ""; public string RecipientFactionId = ""; public long DailyAmount; public long PaidTotal; public int MissedDays; } public enum CallToWarStatus { Pending, Accepted, Declined, Expired } public sealed class CallToWarRequest { public string Id = ""; public string CallerFactionId = ""; public string AllyFactionId = ""; public string EnemyFactionId = ""; public long Payment; public long CreatedDay; public long ExpiresDay; public CallToWarStatus Status; public long AnsweredDay = -1L; } public sealed class WarCapture { public string CaptorFactionId = ""; public string LoserFactionId = ""; public string SettlementId = ""; public long Day; } public sealed class DiplomaticTruce { public string A = ""; public string B = ""; public long SignedDay; public long EndsDay; public string PayerClanId = ""; public string RecipientClanId = ""; public long Payment; } public sealed class WorkshopState { public string Id = ""; public string OwnerClanId = ""; public string SettlementId = ""; public string SettlementOwnerClanId = ""; public string TypeId = ""; public long PurchasePrice; public long Capital; public long LastProfit; public long TotalProfit; public bool Enabled = true; public string Status = "Ready"; public long LastDay = -1L; } public enum HeroState { Active, Captive, Dead, Inactive } public enum HeroOccupation { Player, Lord, Companion, Notable, BanditBoss } public sealed class Hero : IEntity { public string Name = ""; public string Description = ""; public CharacterCreationState Creation; public HeroEquipmentState Loadout; public long HireCost; public int DailyWage; public string ClanId = ""; public string CultureId = ""; public string UnitId = ""; public HeroOccupation Occupation = HeroOccupation.Lord; public bool IsPlayer; public HeroState State; public double Health = 1.0; public string PartyId = ""; public string SettlementId = ""; public string CaptorPartyId = ""; public string CaptorSettlementId = ""; public long CaptiveSinceMinute; public int Level = 1; public long Xp; public SortedDictionary Skills = new SortedDictionary(StringComparer.Ordinal); public SortedDictionary SkillXp = new SortedDictionary(StringComparer.Ordinal); public SortedDictionary SkillFocus = new SortedDictionary(StringComparer.Ordinal); public SortedDictionary Attributes = new SortedDictionary(StringComparer.Ordinal); public int OriginAttributes; public int BonusFocus; public int OriginFocus; public List Perks = new List(); public SortedDictionary SkillXpRemainders = new SortedDictionary(StringComparer.Ordinal); public long RoleTrainingDay = -1L; public SortedDictionary RoleTrainingEarned = new SortedDictionary(StringComparer.Ordinal); public long BornDay; public string MountId = ""; public bool Dismounted; public List Abilities = new List(); public HeroSex Sex; public string FatherId = ""; public string MotherId = ""; public string SpouseId = ""; public List FormerSpouseIds = new List(); public List DivorcedIds = new List(); public string BirthClanId = ""; public bool IsFamily; public long DeathDay = -1L; public string DeathCause = ""; public long ChildDueDay = -1L; public string ChildFatherId = ""; public SortedDictionary Education = new SortedDictionary(StringComparer.Ordinal); public const double FitToFight = 0.5; public string Id { get; set; } = ""; public bool CanFight { get { if (State == HeroState.Active) { return Health >= 0.5; } return false; } } public int Skill(string id) { if (!Skills.TryGetValue(id, out var value)) { return 0; } return value; } } public static class SkillIds { public const string OneHanded = "one_handed"; public const string TwoHanded = "two_handed"; public const string Polearm = "polearm"; public const string Bow = "bow"; public const string Crossbow = "crossbow"; public const string Throwing = "throwing"; public const string Riding = "riding"; public const string Athletics = "athletics"; public const string Smithing = "smithing"; public const string Scouting = "scouting"; public const string Tactics = "tactics"; public const string Roguery = "roguery"; public const string Charm = "charm"; public const string Leadership = "leadership"; public const string Trade = "trade"; public const string Diplomacy = "diplomacy"; public const string Stewardship = "stewardship"; public const string Medicine = "medicine"; public const string Engineering = "engineering"; public static readonly string[] All = new string[19] { "one_handed", "two_handed", "polearm", "bow", "crossbow", "throwing", "riding", "athletics", "smithing", "scouting", "tactics", "roguery", "charm", "leadership", "trade", "diplomacy", "stewardship", "medicine", "engineering" }; public static readonly string[] Original = new string[10] { "leadership", "tactics", "scouting", "stewardship", "medicine", "trade", "engineering", "diplomacy", "smithing", "riding" }; public static readonly string[] Weapons = new string[6] { "one_handed", "two_handed", "polearm", "bow", "crossbow", "throwing" }; } public static class AttributeIds { public const string Vigor = "vigor"; public const string Control = "control"; public const string Endurance = "endurance"; public const string Cunning = "cunning"; public const string Social = "social"; public const string Intelligence = "intelligence"; public static readonly string[] All = new string[6] { "vigor", "control", "endurance", "cunning", "social", "intelligence" }; } public sealed class Clan : IEntity { public string Name = ""; public string KingdomId = ""; public string LeaderHeroId = ""; public string CultureId = ""; public long Gold; public double Renown; public double Influence; public string Color = "#888888"; public string Symbol = "?"; public string EmblemColor = ""; public bool IsBandit; public bool IsPlayerClan; public bool IsEliminated; public List BanditTroops = new List(); public int UnpaidDays; public string Id { get; set; } = ""; } public sealed class Kingdom : IEntity { public string Name = ""; public string CultureId = ""; public string RulerClanId = ""; public string Color = "#888888"; public string Symbol = "?"; public bool IsEliminated; public string Id { get; set; } = ""; } public sealed class RecruitSlot { public string UnitId = ""; public bool Available; public string ProviderId = ""; public int RequiredRelation; } public sealed class Settlement : IEntity { public string Name = ""; public SettlementType Type; public Vec2 Position; public string CultureId = ""; public string OwnerClanId = ""; public string BoundTo = ""; public string Product = ""; public int WallLevel; public double Prosperity = 500.0; public double Security = 60.0; public double Loyalty = 60.0; public double FoodStock; public bool FoodInMarket; public double FoodPart; public MarketState Market = new MarketState(); public SettlementManagementState Management = new SettlementManagementState(); public VillageRecoveryState VillageRecovery = new VillageRecoveryState(); public int Militia; public int WoundedMilitia; public TroopRoster Garrison = new TroopRoster(); public TroopRoster Prisoners = new TroopRoster(); public List Recruits = new List(); public bool HideoutActive = true; public string BanditClanId = ""; public long LastSpawnDay = -1L; public long StatsDay = -1L; public int StarvingDays; public double Unrest; public string Id { get; set; } = ""; } public enum PartyKind { Player, Lord, Bandit, Caravan, Villager, SiegeDefender, Garrison } public enum PartyState { Active, InSettlement, Engaged, Destroyed, Disbanded } public enum PartyRole { Scout, Surgeon, Quartermaster, Engineer } public enum OrderKind { None, MoveToPoint, GoToSettlement, Engage, Follow, Flee, Patrol, Hold, Raid, Besiege } public sealed class MovementOrder { public OrderKind Kind; public Vec2 Point; public string TargetId = ""; public Vec2 LastKnownTargetPosition; public bool TargetLost; public List Path = new List(); public int PathIndex; public Vec2 PathGoal; public long IssuedAtMinute; public string Reason = ""; public string ThreatId = ""; public bool HasPath { get { if (Path != null) { return PathIndex < Path.Count; } return false; } } } public sealed class AiAlternative { public string Task = ""; public double Score; public string Detail = ""; } public sealed class AiDecision { public string Task = "Idle"; public string Reason = ""; public long AtMinute; public List Alternatives = new List(); public int OscillationCount; public string PreviousTask = ""; } public sealed class Party : IEntity { public string Name = ""; public PartyKind Kind = PartyKind.Lord; public PartyState State; public string ClanId = ""; public string LeaderHeroId = ""; public string HomeSettlementId = ""; public Dictionary RoleAssignments = new Dictionary(); public Vec2 Position; public MovementOrder Order = new MovementOrder(); public RaidState ActiveRaid; public string CurrentSettlementId = ""; public TroopRoster Troops = new TroopRoster(); public TroopRoster Prisoners = new TroopRoster(); public double Food; public SortedDictionary Cargo = new SortedDictionary(StringComparer.Ordinal); public SortedDictionary Equipment = new SortedDictionary(StringComparer.Ordinal); public long Gold; public double Morale = 50.0; public int StarvingDays; public int UnpaidDays; public long DisengagedUntilMinute; public string EncounterId = ""; public long NextThinkMinute; public AiDecision Ai = new AiDecision(); public long CreatedAtMinute; public string DestinationSettlementId = ""; public long WaitUntilMinute; public bool AiFrozen; public string MerchantTownId = ""; public string HideoutGuardOf = ""; public string Id { get; set; } = ""; } public enum Stance { Peace, War } public sealed class StanceRecord { public string A = ""; public string B = ""; public Stance Stance; public long SinceMinute; } public sealed class Sighting { public string PartyId = ""; public Vec2 Position; public long SeenAtMinute; public int EstimatedStrength; public bool CurrentlyVisible; } public enum LedgerAccount { Wages, Recruitment, Food, Loot, Ransom, Taxes, GarrisonWages, Quest, Trade, Upgrade, Other, CompanionHire, HeroTraining, EquipmentTrade, Smithing, Horses, Developer, Tournament, Marriage, Discovery, Events, Scouting } public sealed class LedgerEntry { public long Minute; public string ClanId = ""; public LedgerAccount Account; public long Amount; public string Reason = ""; } public enum LogCategory { Info, Travel, Battle, Recruitment, Economy, Captivity, Warning, Politics } public sealed class LogEntry { public long Id; public long Minute; public LogCategory Category; public string Text = ""; public List Links = new List(); } public sealed class EquipmentCombatStats { public double Attack; public double Defense; public double Health; public double Ranged; public TroopRole Role; } public sealed class HeroEquipmentState { public string WeaponId = ""; public string OutfitId = ""; public string ShieldId = ""; public string AmmoId = ""; public SortedDictionary Clothing = new SortedDictionary(StringComparer.Ordinal); public double Size = 1.0; public List Abilities = new List(); public bool HasOverrides { get { if (string.IsNullOrEmpty(WeaponId) && string.IsNullOrEmpty(OutfitId) && string.IsNullOrEmpty(ShieldId) && string.IsNullOrEmpty(AmmoId) && (Clothing?.Count ?? 0) <= 0 && !(Math.Abs(Size - 1.0) > 1E-09)) { return (Abilities?.Count ?? 0) > 0; } return true; } } public string ItemId(EquipmentSlot slot) { string text; switch (slot) { default: return ""; case EquipmentSlot.Ammo: text = AmmoId; if (text == null) { return ""; } break; case EquipmentSlot.Shield: text = ShieldId; if (text == null) { return ""; } break; case EquipmentSlot.Outfit: return OutfitId; case EquipmentSlot.Weapon: text = WeaponId; break; } return text; } public void SetItem(EquipmentSlot slot, string id) { id = id ?? ""; switch (slot) { case EquipmentSlot.Weapon: WeaponId = id; break; case EquipmentSlot.Outfit: OutfitId = id; break; case EquipmentSlot.Shield: ShieldId = id; break; case EquipmentSlot.Ammo: AmmoId = id; break; } } public IEnumerable SlotItems() { string[] array = new string[4] { WeaponId, OutfitId, ShieldId, AmmoId }; foreach (string text in array) { if (!string.IsNullOrEmpty(text)) { yield return text; } } } public HeroEquipmentState Copy() { return new HeroEquipmentState { WeaponId = WeaponId, OutfitId = OutfitId, ShieldId = (ShieldId ?? ""), AmmoId = (AmmoId ?? ""), Size = Size, Abilities = new List(Abilities ?? new List()), Clothing = new SortedDictionary((Clothing ?? new SortedDictionary(StringComparer.Ordinal)).Where((KeyValuePair x) => x.Value != null).ToDictionary, string, WornClothingState>((KeyValuePair x) => x.Key, (KeyValuePair x) => x.Value.Copy(), StringComparer.Ordinal), StringComparer.Ordinal) }; } } public enum HeroSex { Unspecified, Male, Female } public sealed class CourtshipState { public string HeroId = ""; public string SuitorId = ""; public int Progress; public int Failures; public long LastTalkDay = -1L; public long StartedDay; public long RefusedUntilDay = -1L; public bool Won => Progress >= 3; public bool Refused => RefusedUntilDay >= 0; } public sealed class FamiliesState { public bool Started; public bool PlayerSexChosen = true; public SortedDictionary ClanSurnames = new SortedDictionary(StringComparer.Ordinal); public List Courtships = new List(); public SortedDictionary RelativeDueDay = new SortedDictionary(StringComparer.Ordinal); public bool AwaitingHeir; public string DeceasedPlayerId = ""; public bool LineEnded; public SortedDictionary LordParties = new SortedDictionary(StringComparer.Ordinal); public long LastDay = -1L; } public sealed class GarrisonOrdersState { public bool Training = true; public bool AutoUpgrade; public int TierCap; public SortedDictionary UpgradePaths = new SortedDictionary(StringComparer.Ordinal); public int Target; public bool RecruitPrisoners; } public enum GarrisonPartyRole { Guards, Recruits, Transfer } public enum GarrisonPartyOrder { Patrol, Guard, Escort, Follow, Return } public sealed class GarrisonPartyState { public string Id = ""; public string PartyId = ""; public string OwnerClanId = ""; public string HomeSettlementId = ""; public GarrisonPartyRole Role; public GarrisonPartyOrder Order; public string TargetId = ""; public string DestinationId = ""; public long StartedMinute; } public sealed class HeroMemoryState { public string Kind = ""; public long Day; public string Detail = ""; } public sealed class CompanionRequestState { public string Kind = ""; public string TargetId = ""; public long AskedDay; } public sealed class HeroBondsState { public SortedDictionary> Memories = new SortedDictionary>(StringComparer.Ordinal); public SortedDictionary GiftDay = new SortedDictionary(StringComparer.Ordinal); public SortedDictionary FavourDay = new SortedDictionary(StringComparer.Ordinal); public SortedDictionary SparDay = new SortedDictionary(StringComparer.Ordinal); public SortedDictionary LessonDay = new SortedDictionary(StringComparer.Ordinal); public SortedDictionary Approval = new SortedDictionary(StringComparer.Ordinal); public SortedDictionary LastRemark = new SortedDictionary(StringComparer.Ordinal); public SortedDictionary Requests = new SortedDictionary(StringComparer.Ordinal); public SortedDictionary LeaveWarned = new SortedDictionary(StringComparer.Ordinal); public long HardshipDay = -1L; } public sealed class HideoutRecord { public string SettlementId = ""; public bool Found; public long FoundMinute = -1L; public string GuardPartyId = ""; public string ChiefUnitId = ""; public string ChiefName = ""; public string Stage = ""; public SortedDictionary SquadTroops = new SortedDictionary(StringComparer.Ordinal); public List SquadHeroes = new List(); public long ClearedMinute = -1L; public long ResettleDay = -1L; public int TimesCleared; public int Generation; } public sealed class HideoutsState { public bool Started; public List Records = new List(); } public sealed class LegendsState { public bool SitesPlaced; public SortedSet Joined = new SortedSet(StringComparer.Ordinal); } public sealed class HorseState { public string Id = ""; public string Name = ""; public string BreedId = ""; public string CrossBreedId = ""; public HorseSex Sex = HorseSex.Gelding; public int Coat; public long BornDay; public double Speed; public double Manoeuvre; public double Charge; public double HitPoints; public double Stamina; public int Temperament = 50; public double Condition = 1.0; public double Fatigue; public HorseInjury Injury; public int InjuryDays; public double Experience; public SortedDictionary Bond = new SortedDictionary(StringComparer.Ordinal); public HorsePlace Place; public string PlaceId = ""; public int Battles; public string SireId = ""; public string DamId = ""; public string SireName = ""; public string DamName = ""; public long PregnantSinceDay = -1L; public string FoalSireId = ""; public string FoalSireName = ""; public string FoalSireBreedId = ""; public List FoalSireTraits = new List(); public long LastFoalDay = -1L; public long StockPeriod = -1L; public long AcquiredDay; public string Origin = ""; } public sealed class StudFarmState { public string SettlementId = ""; public long PurchasePrice; public long BoughtDay; public long LastUpkeepDay = -1L; } public sealed class HorsesState { public SortedDictionary Horses = new SortedDictionary(StringComparer.Ordinal); public List StudFarms = new List(); public SortedDictionary MarketPeriods = new SortedDictionary(StringComparer.Ordinal); public long NextHorseNumber = 1L; public SortedDictionary TravelRidingToday = new SortedDictionary(StringComparer.Ordinal); public long TravelRidingDay = -1L; public long LastDailyDay = -1L; public bool RidingInitialized; public SortedDictionary LordHorses = new SortedDictionary(StringComparer.Ordinal); public SortedDictionary LordRemountDay = new SortedDictionary(StringComparer.Ordinal); public long LordHorsesDay = -1L; } public sealed class MarketState { public bool Initialized; public SortedDictionary Stock = new SortedDictionary(StringComparer.Ordinal); public bool EquipmentInitialized; public SortedDictionary EquipmentStock = new SortedDictionary(StringComparer.Ordinal); public bool ClothingInitialized; public bool ExpandedGoods; public long Gold; public long LastDay = -1L; } public enum MilitaryPartyDirective { Patrol, Follow, Recall } public sealed class MilitaryPartyState { public string Id = ""; public string PartyId = ""; public string OwnerClanId = ""; public string LeaderHeroId = ""; public string HomeSettlementId = ""; public long StartedMinute; public MilitaryPartyDirective Directive; public string Status = "Active"; public bool AutoRecruit; public int RecruitmentTarget = 20; public long DailyRecruitBudget = 100L; public long DailyFoodBudget = -1L; public long RecruitmentWageLimit = -1L; public long TreasuryReserve; public long SpendingDay = -1L; public long RecruitmentSpentToday; public long FoodSpentToday; public int RecruitsToday; public bool IsActive => Status == "Active"; } public sealed class NotableState { public string Id = ""; public string SettlementId = ""; public string Name = ""; public string Occupation = ""; public string CultureId = ""; public string OwnerClanId = ""; public bool IsAlive = true; public int PlayerRelation; public int Generation; public string PredecessorId = ""; public long LastRecruitRefillDay = -1L; } public enum OwnedItemKind { WeaponKit, Outfit, Clothing, CraftedWeapon, Material, Shield } public sealed class OwnedItemInfo { public string Id = ""; public string Name = ""; public OwnedItemKind Kind; public double Weight; public long Price; public int Limit; public EquipmentDef Kit; public ClothingPieceDef Piece; public CraftedWeaponState Crafted; public SmithingMaterial Material; public bool Shoppable { get { if (Kind != OwnedItemKind.WeaponKit && Kind != OwnedItemKind.Outfit && Kind != OwnedItemKind.Clothing) { return Kind == OwnedItemKind.Shield; } return true; } } public bool IsWeapon { get { if (Kind != OwnedItemKind.CraftedWeapon) { return Kind == OwnedItemKind.WeaponKit; } return true; } } } public static class OwnedItems { public static OwnedItemInfo Resolve(CampaignState state, string id) { if (string.IsNullOrEmpty(id)) { return null; } EquipmentDef equipmentDef = EquipmentCatalog.Find(id); if (equipmentDef != null) { return new OwnedItemInfo { Id = id, Name = equipmentDef.Name, Kind = ((equipmentDef.Slot != EquipmentSlot.Weapon) ? ((equipmentDef.Slot != EquipmentSlot.Shield) ? OwnedItemKind.Outfit : OwnedItemKind.Shield) : OwnedItemKind.WeaponKit), Weight = equipmentDef.Weight, Price = equipmentDef.Price, Limit = 100, Kit = equipmentDef }; } if (Wardrobe.IsPieceId(id)) { ClothingPieceDef value = null; if (state?.Wardrobe?.Pieces == null || !state.Wardrobe.Pieces.TryGetValue(id, out value) || value == null) { return null; } return new OwnedItemInfo { Id = id, Name = value.Name, Kind = OwnedItemKind.Clothing, Weight = value.Weight, Price = value.Price, Limit = 100, Piece = value }; } if (Smithing.IsCraftedId(id)) { CraftedWeaponState value2 = null; if (state?.Smithing?.Weapons == null || !state.Smithing.Weapons.TryGetValue(id, out value2) || value2 == null) { return null; } return new OwnedItemInfo { Id = id, Name = CraftedName(value2), Kind = OwnedItemKind.CraftedWeapon, Weight = (value2.Stats?.Weight ?? 0.0), Price = value2.Value, Limit = 1, Crafted = value2 }; } if (Smithing.TryMaterialForItem(id, out var material)) { return new OwnedItemInfo { Id = id, Name = Smithing.MaterialName(material), Kind = OwnedItemKind.Material, Weight = 0.5, Price = Smithing.MaterialValue(material), Limit = 999, Material = material }; } return null; } public static string CraftedName(CraftedWeaponState weapon) { if (weapon == null) { return ""; } string text = Smithing.QualityName(weapon.Quality); if (text.Length != 0) { return text + " " + weapon.Name; } return weapon.Name; } public static double Weight(CampaignState state, SortedDictionary bag) { double num = 0.0; if (bag == null) { return 0.0; } foreach (KeyValuePair item in bag) { OwnedItemInfo ownedItemInfo = Resolve(state, item.Key); if (ownedItemInfo != null && item.Value > 0) { num += ownedItemInfo.Weight * (double)item.Value; } } return num; } } public enum RealmPolicy { Balanced, LocalCharters, WarLevy } public enum KingdomDecisionKind { FiefGrant, Policy, ClanExpulsion, DeclareWar, MakePeace, Law, RulerElection } public enum KingdomLaw { None, RoadTolls, Serfdom, DebasementOfTheCurrency, GrazingRights, HuntingRights, Magistrates, Bailiffs, TrialByJury, Citizenship, Cantons, CouncilOfTheCommons, TribunesOfThePeople, NobleRetinues, RoyalGuard, MilitaryCoronae, Marches, CastleCharters, LandGrantsForVeterans, RoyalPrivilege, SacredMajesty, Senate } public enum KingdomDecisionStatus { Queued, Voting, Resolved, Cancelled } public sealed class PoliticsState { public bool Initialized; public long LastInfluenceDay = -1L; public List Decisions = new List(); public List KingdomPolicies = new List(); public List Relations = new List(); public List Laws = new List(); public SortedDictionary NextLawProposalDay = new SortedDictionary(StringComparer.Ordinal); } public sealed class KingdomLawState { public string KingdomId = ""; public KingdomLaw Law; public long EnactedMinute; } public sealed class KingdomPolicyState { public string KingdomId = ""; public RealmPolicy Policy; public long ChangedMinute; } public sealed class ClanRelationState { public string A = ""; public string B = ""; public int Value; public long LastGiftDay = -1L; } public sealed class CouncilBallot { public string ClanId = ""; public bool Support; public int InfluenceSpent; } public sealed class KingdomDecision { public string Id = ""; public string KingdomId = ""; public string ProposerClanId = ""; public string RulerClanId = ""; public KingdomDecisionKind Kind; public string SettlementId = ""; public string OwnerClanId = ""; public string RecipientClanId = ""; public string SourceSiegeId = ""; public string TargetClanId = ""; public string TargetKingdomId = ""; public string TargetRulerClanId = ""; public long TreatyPayment; public long TargetStanceSinceMinute = -1L; public RealmPolicy Policy; public KingdomLaw Law; public bool Repeal; public string CandidateClanId = ""; public string RivalClanId = ""; public bool Abdication; public long CreatedMinute; public long OpenedMinute = -1L; public long ClosesMinute = -1L; public long ResolvedMinute = -1L; public KingdomDecisionStatus Status; public bool Passed; public int FinalSupportWeight; public int FinalOppositionWeight; public string Result = ""; public List EligibleClanIds = new List(); public List Ballots = new List(); } public enum QuestStatus { Offered, Active, Succeeded, Failed, Cancelled } public enum QuestSource { Notable, Lord, Chain, Discovery } public sealed class QuestLogLine { public long Minute; public string Text = ""; } public sealed class QuestState { public string Id = ""; public string TemplateId = ""; public QuestSource Source; public QuestStatus Status; public string Title = ""; public string GiverHeroId = ""; public string GiverNotableId = ""; public string GiverSettlementId = ""; public string GiverClanId = ""; public string GiverName = ""; public string TargetSettlementId = ""; public string TargetPartyId = ""; public string TargetHeroId = ""; public string TargetClanId = ""; public string TargetSiteId = ""; public string TargetName = ""; public string OtherSettlementId = ""; public string OtherSiteId = ""; public string GoodId = ""; public string UnitId = ""; public int Quantity; public int Progress; public int Needed; public string Approach = ""; public string Stage = ""; public long Reward; public long Escrow; public string EscrowFrom = ""; public long OfferedMinute; public long AcceptedMinute = -1L; public long DeadlineMinute; public long EndedMinute = -1L; public long StageMinute; public int Hours; public string Result = ""; public string Note = ""; public List Log = new List(); public string DelegateHeroId = ""; public SortedDictionary DelegateUnits = new SortedDictionary(StringComparer.Ordinal); public long DelegateDueMinute = -1L; public double DelegateChance; } public enum SiteKind { Ruins, Battlefield, Shrine, Wreck, Cave, Camp, Barrow, Tower } public sealed class DiscoverySite { public string Id = ""; public string Name = ""; public SiteKind Kind; public Vec2 Position; public string RegionSettlementId = ""; public string QuestId = ""; public bool Found; public bool Explored; public long FoundMinute = -1L; public long ExploredMinute = -1L; public string Outcome = ""; public string LegendPlace = ""; public SortedDictionary Stock = new SortedDictionary(StringComparer.Ordinal); public long NextStockDay = -1L; } public sealed class QuestsState { public bool Started; public long LastDay = -1L; public List Quests = new List(); public string TrackedQuestId = ""; public SortedDictionary GiverNextDay = new SortedDictionary(StringComparer.Ordinal); public SortedDictionary StoriesTold = new SortedDictionary(StringComparer.Ordinal); public List Sites = new List(); public int NextQuestNumber = 1; } public sealed class PendingEventState { public string InstanceId = ""; public string EventId = ""; public long Minute; public string Context = ""; public string SettlementId = ""; public string HeroId = ""; public string UnitId = ""; public string GoodId = ""; public string SiteId = ""; public int Number; } public sealed class EventRecord { public string InstanceId = ""; public string EventId = ""; public string Title = ""; public string Context = ""; public long Minute; public string Choice = ""; public string Result = ""; } public sealed class StoryEventsState { public bool Started; public long NextDay = -1L; public PendingEventState Pending; public SortedDictionary CooldownUntilDay = new SortedDictionary(StringComparer.Ordinal); public List History = new List(); public long LastVictoryMinute = -1L; public int Count; } public sealed class RaidState { public string SettlementId = ""; public string OwnerClanId = ""; public long StartedAtMinute; public long LastProgressMinute; public int ProgressMinutes; public int RequiredMinutes; } public enum RebellionOutcome { Holding, JoinedKingdom, Recognised, Crushed } public sealed class RebellionState { public bool Initialized; public long LastDay = -1L; public List Records = new List(); } public sealed class RebellionRecord { public string Id = ""; public string ClanId = ""; public string SettlementId = ""; public string FormerOwnerClanId = ""; public string FormerFactionId = ""; public long RoseDay; public long EndedDay = -1L; public RebellionOutcome Outcome; public string KingdomId = ""; } public sealed class TroopStack { public string UnitId = ""; public int Healthy; public int Wounded; public int Xp; public double PrisonerRecruitment; public int Total => Healthy + Wounded; } public sealed class TroopRoster { public List Stacks = new List(); public List Heroes = new List(); public int TotalHealthy => Stacks.Sum((TroopStack s) => s.Healthy); public int TotalWounded => Stacks.Sum((TroopStack s) => s.Wounded); public int TotalTroops => Stacks.Sum((TroopStack s) => s.Total); public bool IsEmpty { get { if (TotalTroops == 0) { return Heroes.Count == 0; } return false; } } public TroopStack Find(string unitId) { return Stacks.FirstOrDefault((TroopStack s) => s.UnitId == unitId); } private TroopStack GetOrAdd(string unitId) { TroopStack troopStack = Find(unitId); if (troopStack == null) { troopStack = new TroopStack { UnitId = unitId }; Stacks.Add(troopStack); } return troopStack; } public int Healthy(string unitId) { return Find(unitId)?.Healthy ?? 0; } public int Wounded(string unitId) { return Find(unitId)?.Wounded ?? 0; } public void Add(string unitId, int healthy, int wounded = 0, int xp = 0) { if (healthy < 0 || wounded < 0) { throw new ArgumentOutOfRangeException("healthy", "Cannot add negative troops"); } if (healthy != 0 || wounded != 0 || xp != 0) { TroopStack orAdd = GetOrAdd(unitId); orAdd.Healthy += healthy; orAdd.Wounded += wounded; orAdd.Xp += xp; } } public int Remove(string unitId, int count, bool woundedFirst = false) { TroopStack troopStack = Find(unitId); if (troopStack == null || count <= 0) { return 0; } int num = 0; if (woundedFirst) { int num2 = Math.Min(count, troopStack.Wounded); troopStack.Wounded -= num2; num += num2; int num3 = Math.Min(count - num, troopStack.Healthy); troopStack.Healthy -= num3; num += num3; } else { int num4 = Math.Min(count, troopStack.Healthy); troopStack.Healthy -= num4; num += num4; int num5 = Math.Min(count - num, troopStack.Wounded); troopStack.Wounded -= num5; num += num5; } int num6 = troopStack.Total + num; if (num6 > 0 && troopStack.Xp > 0) { troopStack.Xp = (int)Math.Round((double)troopStack.Xp * (double)troopStack.Total / (double)num6); } ReducePrisonerRecruitment(troopStack, num6); Prune(); return num; } public int RemoveHealthy(string unitId, int count) { TroopStack troopStack = Find(unitId); if (troopStack == null || count <= 0) { return 0; } int num = Math.Min(count, troopStack.Healthy); int total = troopStack.Total; troopStack.Healthy -= num; if (total > 0 && troopStack.Xp > 0) { troopStack.Xp = (int)Math.Round((double)troopStack.Xp * (double)troopStack.Total / (double)total); } ReducePrisonerRecruitment(troopStack, total); Prune(); return num; } public int RemoveWounded(string unitId, int count) { TroopStack troopStack = Find(unitId); if (troopStack == null || count <= 0) { return 0; } int num = Math.Min(count, troopStack.Wounded); int total = troopStack.Total; troopStack.Wounded -= num; if (total > 0 && troopStack.Xp > 0) { troopStack.Xp = (int)Math.Round((double)troopStack.Xp * (double)troopStack.Total / (double)total); } ReducePrisonerRecruitment(troopStack, total); Prune(); return num; } public int Wound(string unitId, int count) { TroopStack troopStack = Find(unitId); if (troopStack == null || count <= 0) { return 0; } int num = Math.Min(count, troopStack.Healthy); troopStack.Healthy -= num; troopStack.Wounded += num; return num; } public int Heal(string unitId, int count) { TroopStack troopStack = Find(unitId); if (troopStack == null || count <= 0) { return 0; } int num = Math.Min(count, troopStack.Wounded); troopStack.Wounded -= num; troopStack.Healthy += num; return num; } public void AddXp(string unitId, int xp) { TroopStack troopStack = Find(unitId); if (troopStack != null && xp > 0) { troopStack.Xp += xp; } } private static void ReducePrisonerRecruitment(TroopStack stack, int before) { double prisonerRecruitment = stack.PrisonerRecruitment; stack.PrisonerRecruitment = Math.Max(0.0, Math.Min(val2: (before > 0 && !double.IsNaN(prisonerRecruitment) && !double.IsInfinity(prisonerRecruitment)) ? (prisonerRecruitment * ((double)stack.Total / (double)before)) : 0.0, val1: stack.Total)); } public void Prune() { Stacks.RemoveAll((TroopStack s) => s.Total == 0); } public TroopRoster Clone() { TroopRoster troopRoster = new TroopRoster(); foreach (TroopStack stack in Stacks) { troopRoster.Stacks.Add(new TroopStack { UnitId = stack.UnitId, Healthy = stack.Healthy, Wounded = stack.Wounded, Xp = stack.Xp, PrisonerRecruitment = stack.PrisonerRecruitment }); } troopRoster.Heroes.AddRange(Heroes); return troopRoster; } public void Validate(string owner, List errors) { HashSet hashSet = new HashSet(StringComparer.Ordinal); foreach (TroopStack stack in Stacks) { if (stack.Healthy < 0 || stack.Wounded < 0 || stack.Xp < 0) { errors.Add(owner + ": negative counts for " + stack.UnitId); } if (double.IsNaN(stack.PrisonerRecruitment) || double.IsInfinity(stack.PrisonerRecruitment) || stack.PrisonerRecruitment < 0.0 || stack.PrisonerRecruitment > (double)stack.Total + 1E-07) { errors.Add(owner + ": invalid prisoner recruitment progress for " + stack.UnitId); } if (!hashSet.Add(stack.UnitId)) { errors.Add(owner + ": duplicate stack " + stack.UnitId); } } HashSet hashSet2 = new HashSet(StringComparer.Ordinal); foreach (string hero in Heroes) { if (!hashSet2.Add(hero)) { errors.Add(owner + ": hero " + hero + " listed twice"); } } } } public sealed class ScoutedUnitState { public string UnitId = ""; public int Low; public int High; } public sealed class ScoutReportState { public string SettlementId = ""; public string ScoutName = ""; public int Rating; public long ObservedMinute; public long DeliveredMinute; public int FoodLow; public int FoodHigh; public int DefendersLow; public int DefendersHigh; public List Units = new List(); public int OthersLow; public int OthersHigh; public int WallLevel; } public sealed class ScoutMissionState { public string Id = ""; public string ScoutName = ""; public int Rating; public long Price; public string TownId = ""; public string TargetId = ""; public long HiredMinute; public long ObserveMinute; public long ReturnMinute; public ScoutReportState Report; } public sealed class ScoutingState { public List Missions = new List(); public SortedDictionary Reports = new SortedDictionary(StringComparer.Ordinal); public SortedSet Hired = new SortedSet(StringComparer.Ordinal); } public enum TaxPolicy { Balanced, Relief, Levy } public sealed class SettlementManagementState { public bool Initialized; public string OwnerClanId = ""; public TaxPolicy Policy; public int GranaryLevel; public int WatchtowerLevel; public string ProjectId = ""; public int ProjectRemainingDays; public string ProjectOwnerClanId = ""; public long LastDay = -1L; public string GovernorHeroId = ""; public long LastGovernorDay = -1L; public long GovernorPaidDay = -1L; public List ProjectQueue = new List(); public long QueueWaitingDay = -1L; public long GarrisonWageLimit; public bool GarrisonAutoRecruit; public long LastGarrisonBudgetDay = -1L; public long GovernorBudget; public long GovernorSpentToday; public long GovernorSpendDay = -1L; public double Hardship; public long LastRiotDay = -1L; public long HardshipDay = -1L; public GarrisonOrdersState GarrisonOrders = new GarrisonOrdersState(); } public enum SiegeStage { Marching, Preparing, Ready, Assault, Ended } public enum SiegeCapturePolicy { Occupy, Pillage } public sealed class SiegeState { public string Id = ""; public string SettlementId = ""; public string BesiegerPartyId = ""; public string OwnerClanId = ""; public SiegeStage Stage; public long StartedMinute; public long LastProcessedMinute; public double PreparationMinutes; public long EndedMinute = -1L; public long LastSupplyDay = -1L; public int StarvationDays; public string Result = ""; public string EncounterId = ""; public string GarrisonPartyId = ""; public string MilitiaPartyId = ""; public SiegeCapturePolicy CapturePolicy; public SiegeWorksState Works; public TroopRoster KeepTroops = new TroopRoster(); public string KeepPartyId = ""; public bool KeepStage; public bool KeepPending; public List KeepAttackerIds = new List(); public bool NoKeepBattle; public string Sortie = ""; public string SortieEncounterId = ""; public string SortiePartyId = ""; } public enum SiegeEngineKind { None, Ballista, Catapult, Trebuchet, SiegeTower, BatteringRam } public sealed class SiegeEngineState { public SiegeEngineKind Kind; public int Slot; public double Health; public double BuildProgress; public double MaxHealth => SiegeWorksRules.MaxHealth(Kind); public bool IsBuilt { get { if (Kind != SiegeEngineKind.None) { return BuildProgress >= SiegeWorksRules.BuildMinutes(Kind); } return false; } } public bool IsOperational { get { if (IsBuilt) { return Health > 0.0; } return false; } } } public sealed class SiegeWorksState { public List Attackers = new List(); public List Defenders = new List(); public double LeftWallHealth = 1200.0; public double RightWallHealth = 1200.0; public double BombardmentMinutes; public bool BatteryEngaged; } public static class SiegeWorksRules { public const double WallMaxHealth = 1200.0; public const double VolleyMinutes = 30.0; public const int ArtillerySlots = 4; public const int AttackerSlots = 7; public const int DefenderSlots = 4; public const double ConstructionSlowdown = 4.0; public const double DefenderVolleyDamage = 25.0; public const double AttackerCatapultTimeFactor = 0.953; public static double WallMaxHealthFor(int wallLevel) { return 1200.0 * (1.0 + 0.5 * (double)(Math.Max(1, Math.Min(3, wallLevel)) - 1)); } public static double EngineeringSpeed(int engineering) { return 1.0 + (double)Math.Max(0, Math.Min(300, engineering)) / 100.0; } public static double AttackerConstructionRate(int engineering) { return EngineeringSpeed(engineering) / 4.0; } public static double AttackerBuildSpeed(SiegeEngineKind kind) { if (kind != SiegeEngineKind.Catapult) { return 1.0; } return 1.0493179433368311; } public static double AttackerBuildMinutes(SiegeEngineKind kind, double attackerRate, double progress = 0.0) { return Math.Max(0.0, BuildMinutes(kind) - progress) / (Math.Max(0.01, Math.Min(4.0, attackerRate)) * AttackerBuildSpeed(kind)); } public static double DefenderConstructionRate(int engineering) { return EngineeringSpeed(engineering) / 4.0; } public static string Name(SiegeEngineKind kind) { return kind switch { SiegeEngineKind.Ballista => "Ballista", SiegeEngineKind.Catapult => "Catapult", SiegeEngineKind.Trebuchet => "Trebuchet", SiegeEngineKind.SiegeTower => "Siege tower", SiegeEngineKind.BatteringRam => "Battering ram", _ => "Empty", }; } public static double MaxHealth(SiegeEngineKind kind) { return kind switch { SiegeEngineKind.Ballista => 240.0, SiegeEngineKind.Catapult => 300.0, SiegeEngineKind.Trebuchet => 600.0, SiegeEngineKind.SiegeTower => 540.0, SiegeEngineKind.BatteringRam => 720.0, _ => 0.0, }; } public static double BuildMinutes(SiegeEngineKind kind) { return kind switch { SiegeEngineKind.Ballista => 120.0, SiegeEngineKind.Catapult => 180.0, SiegeEngineKind.Trebuchet => 240.0, SiegeEngineKind.SiegeTower => 180.0, SiegeEngineKind.BatteringRam => 180.0, _ => 0.0, }; } public static bool IsArtillery(SiegeEngineKind kind) { if (kind != SiegeEngineKind.Ballista && kind != SiegeEngineKind.Catapult) { return kind == SiegeEngineKind.Trebuchet; } return true; } public static bool FitsSlot(int slot, SiegeEngineKind kind) { switch (slot) { case 6: return kind == SiegeEngineKind.BatteringRam; case 4: case 5: return kind == SiegeEngineKind.SiegeTower; case 0: case 1: case 2: case 3: return IsArtillery(kind); default: return false; } } public static SiegeWorksState Create(int wallLevel = 1) { SiegeWorksState siegeWorksState = new SiegeWorksState(); siegeWorksState.LeftWallHealth = (siegeWorksState.RightWallHealth = WallMaxHealthFor(wallLevel)); for (int i = 0; i < 7; i++) { siegeWorksState.Attackers.Add(new SiegeEngineState { Slot = i }); } for (int j = 0; j < 4; j++) { siegeWorksState.Defenders.Add(new SiegeEngineState { Slot = j, Kind = SiegeEngineKind.Catapult, Health = MaxHealth(SiegeEngineKind.Catapult), BuildProgress = BuildMinutes(SiegeEngineKind.Catapult) }); } return siegeWorksState; } public static double EngineDamage(SiegeEngineKind kind) { return kind switch { SiegeEngineKind.Ballista => 50.0, SiegeEngineKind.Catapult => 45.0, SiegeEngineKind.Trebuchet => 35.0, _ => 0.0, }; } public static double WallDamage(SiegeEngineKind kind) { return kind switch { SiegeEngineKind.Ballista => 4.0, SiegeEngineKind.Catapult => 15.0, SiegeEngineKind.Trebuchet => 30.0, _ => 0.0, }; } public static double IncomingDamageMultiplier(SiegeEngineKind kind) { if (kind != SiegeEngineKind.Trebuchet) { return 1.0; } return 1.5; } public static void Advance(SiegeWorksState works, double minutes, double attackerRate, double defenderRate) { if (works == null || minutes <= 0.0 || double.IsNaN(minutes) || double.IsInfinity(minutes)) { return; } attackerRate = Math.Max(0.01, Math.Min(4.0, attackerRate)); defenderRate = Math.Max(0.01, Math.Min(4.0, defenderRate)); while (minutes > 1E-09) { foreach (SiegeEngineState item in works.Defenders.Where((SiegeEngineState e) => e.IsBuilt && e.Health <= 0.0)) { item.BuildProgress = 0.0; } SiegeEngineState siegeEngineState = (from e in works.Attackers where e.Kind != SiegeEngineKind.None && !e.IsBuilt orderby e.Slot select e).FirstOrDefault(); SiegeEngineState siegeEngineState2 = (from e in works.Defenders where !e.IsBuilt orderby e.Slot select e).FirstOrDefault(); double num = Math.Min(minutes, 30.0 - works.BombardmentMinutes); double num2 = ((siegeEngineState == null) ? 0.0 : (attackerRate * AttackerBuildSpeed(siegeEngineState.Kind))); if (siegeEngineState != null) { num = Math.Min(num, (BuildMinutes(siegeEngineState.Kind) - siegeEngineState.BuildProgress) / num2); } if (siegeEngineState2 != null) { num = Math.Min(num, (BuildMinutes(siegeEngineState2.Kind) - siegeEngineState2.BuildProgress) / defenderRate); } Work(siegeEngineState, num * num2); Work(siegeEngineState2, num * defenderRate); works.BombardmentMinutes += num; minutes -= num; if (works.BombardmentMinutes >= 29.999999999) { works.BombardmentMinutes = 0.0; Volley(works); } } } private static void Work(SiegeEngineState engine, double work) { if (engine != null) { double num = BuildMinutes(engine.Kind); engine.BuildProgress = Math.Min(num, engine.BuildProgress + work); if (engine.BuildProgress >= num - 1E-09) { engine.BuildProgress = num; engine.Health = MaxHealth(engine.Kind); } } } private static void Volley(SiegeWorksState works) { List source = (from e in works.Attackers where e.IsOperational && IsArtillery(e.Kind) orderby e.Slot select e).ToList(); List list = (from e in works.Defenders where e.IsOperational orderby e.Slot select e).ToList(); SiegeEngineState siegeEngineState = list.FirstOrDefault(); SiegeEngineState siegeEngineState2 = source.FirstOrDefault() ?? (from e in works.Attackers where e.IsOperational && (e.Kind == SiegeEngineKind.SiegeTower || e.Kind == SiegeEngineKind.BatteringRam) orderby e.Slot select e).FirstOrDefault(); double num = source.Sum((SiegeEngineState e) => EngineDamage(e.Kind)); double num2 = (double)list.Count * 25.0; if (siegeEngineState != null) { siegeEngineState.Health = Math.Max(0.0, siegeEngineState.Health - num); } else if (works.LeftWallHealth > 0.0) { works.LeftWallHealth = Math.Max(0.0, works.LeftWallHealth - source.Sum((SiegeEngineState e) => WallDamage(e.Kind))); } else if (works.RightWallHealth > 0.0) { works.RightWallHealth = Math.Max(0.0, works.RightWallHealth - source.Sum((SiegeEngineState e) => WallDamage(e.Kind))); } if (siegeEngineState2 != null) { siegeEngineState2.Health = Math.Max(0.0, siegeEngineState2.Health - num2 * IncomingDamageMultiplier(siegeEngineState2.Kind)); } } } public sealed class WardrobeState { public SortedDictionary Pieces = new SortedDictionary(StringComparer.Ordinal); public SortedDictionary> UnitPieces = new SortedDictionary>(StringComparer.Ordinal); } public sealed class WornClothingState { public string PieceId = ""; public bool Bare; public List Colors = new List(); public WornClothingState Copy() { return new WornClothingState { PieceId = (PieceId ?? ""), Bare = Bare, Colors = new List(Colors ?? new List()) }; } } public sealed class CraftedWeaponState { public string Id = ""; public string Name = ""; public WeaponClass Class; public List Parts = new List(); public WeaponQuality Quality = WeaponQuality.Common; public WeaponStats Stats = new WeaponStats(); public long Value; public int Tier = 1; public double TierScore = 1.0; public int Difficulty; public string CrafterHeroId = ""; public long CraftedMinute; } public sealed class CraftingOrderState { public string Id = ""; public string SettlementId = ""; public int Slot; public string IssuerKind = ""; public string IssuerId = ""; public string IssuerName = ""; public WeaponClass Class; public List DesignParts = new List(); public long BaseReward; public long PostedDay; public bool Valid => Smithing.DesignReason(Class, DesignParts).Length == 0; public WeaponStats Required { get { if (!Valid) { return new WeaponStats(); } return Smithing.Stats(Class, DesignParts); } } public int Difficulty { get { if (!Valid) { return 0; } return Smithing.Difficulty(DesignParts); } } public long OrderValue { get { if (!Valid) { return 0L; } return Smithing.Value(Class, Smithing.TierScore(Class, Required, DesignParts), WeaponQuality.Common); } } } public sealed class SmithingState { public SortedDictionary Stamina = new SortedDictionary(StringComparer.Ordinal); public SortedSet UnlockedParts = new SortedSet(StringComparer.Ordinal); public SortedDictionary Research = new SortedDictionary(StringComparer.Ordinal); public bool PartsInitialized; public SortedDictionary Weapons = new SortedDictionary(StringComparer.Ordinal); public List Orders = new List(); public bool OrdersInitialized; public long LastOrderDay = -1L; public long NextWeaponNumber = 1L; public long NextOrderNumber = 1L; } public enum TournamentPrizeKind { Weapon, Horse, Ability } public enum TournamentFighterKind { Player, Companion, Lord, Local } public sealed class TournamentPrizeState { public TournamentPrizeKind Kind; public string Name = ""; public CraftedWeaponState Weapon; public HorseState Horse; public string AbilityId = ""; public long Value; } public sealed class TournamentFighterState { public int Id; public string Name = ""; public TournamentFighterKind Kind; public string HeroId = ""; public string UnitId = ""; public string ClanId = ""; public double Strength = 1.0; public bool Eliminated; public int EliminatedInRound = -1; } public sealed class TournamentMatchState { public int Round; public List TeamA = new List(); public List TeamB = new List(); public int Winner = -1; public bool Fought; } public sealed class TournamentRunState { public int Round; public List Fighters = new List(); public List Matches = new List(); public long BetThisRound; public long BetTotal; public long BetPayout; public double Odds = 1.0; public int Attempts; public string AttemptId = ""; public bool Spectating; } public sealed class TournamentState { public string Id = ""; public string TownId = ""; public long AnnouncedMinute; public long EndMinute; public TournamentPrizeState Prize = new TournamentPrizeState(); public TournamentRunState Run; } public sealed class TournamentResultState { public string TownId = ""; public string TownName = ""; public string PrizeName = ""; public string WinnerName = ""; public bool PlayerWon; public bool ClanWon; public double Renown; public long BetTotal; public long BetPaid; public List Lines = new List(); public bool Seen; } public sealed class TournamentsState { public bool Started; public List Active = new List(); public long NextNumber = 1L; public TournamentResultState LastResult; public List Heard = new List(); public SortedDictionary Wins = new SortedDictionary(StringComparer.Ordinal); public bool WinsSeeded; } public sealed class AbilityDef { public string Id = ""; public string Name = ""; } public sealed class AbilitiesState { public SortedDictionary Known = new SortedDictionary(StringComparer.Ordinal); } public sealed class TutorialState { public bool Active; public List Chapters = new List(); public List Done = new List(); public string Chapter = ""; public int Step; public long StepStartMinute; public SortedDictionary Marks = new SortedDictionary(StringComparer.Ordinal); public SortedSet Signals = new SortedSet(StringComparer.Ordinal); public bool Minimised; public long StepDoneMinute = -1L; } public sealed class VillageRecoveryState { public bool Initialized; public int Damage; public long LastRecoveryDay = -1L; public long LastAidDay = -1L; public long LastPlayerRaidDay = -1L; public long LastRaidMinute = -1L; public SortedDictionary ProductionRemainders = new SortedDictionary(StringComparer.Ordinal); } public sealed class WanderersState { public bool Started; public long NextArrivalDay; public SortedDictionary Plans = new SortedDictionary(StringComparer.Ordinal); } public sealed class WandererPlan { public long LeaveDay; public string DestinationId = ""; public string FromId = ""; public long ArriveMinute; public bool Travelling => !string.IsNullOrEmpty(DestinationId); } public sealed class WorldGenerationState { public int Version = 1; public ulong Seed; public List Realms; } public sealed class RealmSpec { public string Culture = ""; public string Name = ""; public string Capital = ""; public string MarketTown = ""; public string Biome = "grassland"; } public sealed class CustomContentState { public List Cultures = new List(); public List Units = new List(); } } namespace TabsBannerlord.Core.Serialization { public abstract class JsonNode { public virtual JsonObject AsObject { get { throw new JsonException("Expected object but found " + GetType().Name); } } public virtual JsonArray AsArray { get { throw new JsonException("Expected array but found " + GetType().Name); } } public virtual string AsString { get { throw new JsonException("Expected string but found " + GetType().Name); } } public virtual double AsDouble { get { throw new JsonException("Expected number but found " + GetType().Name); } } public virtual long AsLong { get { throw new JsonException("Expected number but found " + GetType().Name); } } public virtual bool AsBool { get { throw new JsonException("Expected bool but found " + GetType().Name); } } public int AsInt => checked((int)AsLong); public virtual bool IsNull => false; public override string ToString() { return JsonWriter.Write(this, indented: false); } public string ToJson(bool indented = true) { return JsonWriter.Write(this, indented); } public static implicit operator JsonNode(string s) { if (s != null) { return new JsonString(s); } return JsonNull.Instance; } public static implicit operator JsonNode(long v) { return new JsonNumber(v); } public static implicit operator JsonNode(int v) { return new JsonNumber(v); } public static implicit operator JsonNode(double v) { return new JsonNumber(v); } public static implicit operator JsonNode(bool v) { if (!v) { return JsonBool.False; } return JsonBool.True; } } public sealed class JsonException : Exception { public JsonException(string message) : base(message) { } } public sealed class JsonObject : JsonNode { private readonly List _order = new List(); private readonly Dictionary _values = new Dictionary(StringComparer.Ordinal); public override JsonObject AsObject => this; public int Count => _order.Count; public IEnumerable Keys => _order; public JsonNode this[string key] { get { if (!_values.TryGetValue(key, out var value)) { return null; } return value; } set { if (!_values.ContainsKey(key)) { _order.Add(key); } _values[key] = value ?? JsonNull.Instance; } } public bool Has(string key) { return _values.ContainsKey(key); } public bool TryGet(string key, out JsonNode node) { return _values.TryGetValue(key, out node); } public bool Remove(string key) { if (!_values.Remove(key)) { return false; } _order.Remove(key); return true; } public void Rename(string oldKey, string newKey) { if (_values.TryGetValue(oldKey, out var value)) { int index = _order.IndexOf(oldKey); _values.Remove(oldKey); _values[newKey] = value; _order[index] = newKey; } } public string GetString(string key, string fallback = null) { JsonNode jsonNode = this[key]; if (jsonNode != null && !jsonNode.IsNull) { return jsonNode.AsString; } return fallback; } public long GetLong(string key, long fallback = 0L) { JsonNode jsonNode = this[key]; if (jsonNode != null && !jsonNode.IsNull) { return jsonNode.AsLong; } return fallback; } public int GetInt(string key, int fallback = 0) { JsonNode jsonNode = this[key]; if (jsonNode != null && !jsonNode.IsNull) { return jsonNode.AsInt; } return fallback; } public double GetDouble(string key, double fallback = 0.0) { JsonNode jsonNode = this[key]; if (jsonNode != null && !jsonNode.IsNull) { return jsonNode.AsDouble; } return fallback; } public bool GetBool(string key, bool fallback = false) { JsonNode jsonNode = this[key]; if (jsonNode != null && !jsonNode.IsNull) { return jsonNode.AsBool; } return fallback; } public JsonObject GetObject(string key) { JsonNode jsonNode = this[key]; if (jsonNode != null && !jsonNode.IsNull) { return jsonNode.AsObject; } return null; } public JsonArray GetArray(string key) { JsonNode jsonNode = this[key]; if (jsonNode != null && !jsonNode.IsNull) { return jsonNode.AsArray; } return null; } } public sealed class JsonArray : JsonNode { public readonly List Items = new List(); public override JsonArray AsArray => this; public int Count => Items.Count; public JsonNode this[int i] => Items[i]; public void Add(JsonNode n) { Items.Add(n ?? JsonNull.Instance); } } public sealed class JsonString : JsonNode { public readonly string Value; public override string AsString => Value; public JsonString(string v) { Value = v; } } public sealed class JsonNumber : JsonNode { public readonly string Raw; public override double AsDouble => double.Parse(Raw, NumberStyles.Float, CultureInfo.InvariantCulture); public override long AsLong { get { if (long.TryParse(Raw, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) { return result; } double asDouble = AsDouble; if (Math.Abs(asDouble - Math.Round(asDouble)) > 1E-09) { throw new JsonException("Expected integer but found " + Raw); } return (long)Math.Round(asDouble); } } public JsonNumber(long v) { Raw = v.ToString(CultureInfo.InvariantCulture); } public JsonNumber(double v) { if (double.IsNaN(v) || double.IsInfinity(v)) { throw new JsonException("NaN/Infinity cannot be stored in JSON"); } Raw = v.ToString("R", CultureInfo.InvariantCulture); } internal JsonNumber(string raw, bool _) { Raw = raw; } } public sealed class JsonBool : JsonNode { public static readonly JsonBool True = new JsonBool(v: true); public static readonly JsonBool False = new JsonBool(v: false); public readonly bool Value; public override bool AsBool => Value; private JsonBool(bool v) { Value = v; } } public sealed class JsonNull : JsonNode { public static readonly JsonNull Instance = new JsonNull(); public override bool IsNull => true; private JsonNull() { } } public static class JsonWriter { public static string Write(JsonNode node, bool indented) { StringBuilder stringBuilder = new StringBuilder(); WriteNode(stringBuilder, node, indented, 0); return stringBuilder.ToString(); } private static void Indent(StringBuilder sb, int depth) { sb.Append('\n'); sb.Append(' ', depth * 2); } private static void WriteNode(StringBuilder sb, JsonNode node, bool indented, int depth) { if (node != null && !(node is JsonNull)) { if (!(node is JsonBool jsonBool)) { if (!(node is JsonNumber jsonNumber)) { if (!(node is JsonString jsonString)) { if (!(node is JsonArray jsonArray)) { if (node is JsonObject jsonObject) { if (jsonObject.Count == 0) { sb.Append("{}"); return; } sb.Append('{'); bool flag = true; foreach (string key in jsonObject.Keys) { if (!flag) { sb.Append(','); } flag = false; if (indented) { Indent(sb, depth + 1); } WriteString(sb, key); sb.Append(indented ? ": " : ":"); WriteNode(sb, jsonObject[key], indented, depth + 1); } if (indented) { Indent(sb, depth); } sb.Append('}'); return; } throw new JsonException("Unknown node type " + node.GetType()); } if (jsonArray.Count == 0) { sb.Append("[]"); return; } bool flag2 = indented && AllScalars(jsonArray); sb.Append('['); for (int i = 0; i < jsonArray.Count; i++) { if (i > 0) { sb.Append(flag2 ? ", " : ","); } if (indented && !flag2) { Indent(sb, depth + 1); } WriteNode(sb, jsonArray[i], indented, depth + 1); } if (indented && !flag2) { Indent(sb, depth); } sb.Append(']'); } else { WriteString(sb, jsonString.Value); } } else { sb.Append(jsonNumber.Raw); } } else { sb.Append(jsonBool.Value ? "true" : "false"); } } else { sb.Append("null"); } } private static bool AllScalars(JsonArray a) { if (a.Count > 16) { return false; } foreach (JsonNode item in a.Items) { if (item is JsonObject || item is JsonArray) { return false; } } return true; } public static void WriteString(StringBuilder sb, string s) { sb.Append('"'); foreach (char c in s) { switch (c) { case '"': sb.Append("\\\""); continue; case '\\': sb.Append("\\\\"); continue; case '\n': sb.Append("\\n"); continue; case '\r': sb.Append("\\r"); continue; case '\t': sb.Append("\\t"); continue; case '\b': sb.Append("\\b"); continue; case '\f': sb.Append("\\f"); continue; } if (c < ' ') { StringBuilder stringBuilder = sb.Append("\\u"); int num = c; stringBuilder.Append(num.ToString("x4", CultureInfo.InvariantCulture)); } else { sb.Append(c); } } sb.Append('"'); } } public static class JsonParser { public static JsonNode Parse(string text) { if (text == null) { throw new JsonException("No JSON text"); } int i = 0; SkipWs(text, ref i); JsonNode result = ParseValue(text, ref i); SkipWs(text, ref i); if (i != text.Length) { throw Error(text, i, "Unexpected trailing characters"); } return result; } private static JsonException Error(string t, int i, string msg) { int num = 1; int num2 = 1; for (int j = 0; j < i && j < t.Length; j++) { if (t[j] == '\n') { num++; num2 = 1; } else { num2++; } } return new JsonException($"{msg} at line {num}, column {num2}"); } private static void SkipWs(string t, ref int i) { while (i < t.Length) { switch (t[i]) { case '\t': case '\n': case '\r': case ' ': i++; break; case '/': if (i + 1 < t.Length && t[i + 1] == '/') { while (i < t.Length && t[i] != '\n') { i++; } break; } return; default: return; } } } private static JsonNode ParseValue(string t, ref int i) { if (i >= t.Length) { throw Error(t, i, "Unexpected end of JSON"); } char c = t[i]; switch (c) { case '{': return ParseObject(t, ref i); case '[': return ParseArray(t, ref i); case '"': return new JsonString(ParseString(t, ref i)); case 't': Expect(t, ref i, "true"); return JsonBool.True; case 'f': Expect(t, ref i, "false"); return JsonBool.False; case 'n': Expect(t, ref i, "null"); return JsonNull.Instance; default: switch (c) { case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return ParseNumber(t, ref i); default: throw Error(t, i, $"Unexpected character '{c}'"); } } } private static void Expect(string t, ref int i, string word) { if (string.CompareOrdinal(t, i, word, 0, word.Length) != 0) { throw Error(t, i, "Expected " + word); } i += word.Length; } private static JsonObject ParseObject(string t, ref int i) { JsonObject jsonObject = new JsonObject(); i++; SkipWs(t, ref i); if (i < t.Length && t[i] == '}') { i++; return jsonObject; } while (true) { SkipWs(t, ref i); if (i >= t.Length || t[i] != '"') { throw Error(t, i, "Expected property name"); } string text = ParseString(t, ref i); SkipWs(t, ref i); if (i >= t.Length || t[i] != ':') { throw Error(t, i, "Expected ':'"); } i++; SkipWs(t, ref i); if (jsonObject.Has(text)) { throw Error(t, i, "Duplicate key '" + text + "'"); } jsonObject[text] = ParseValue(t, ref i); SkipWs(t, ref i); if (i >= t.Length) { throw Error(t, i, "Unterminated object"); } if (t[i] != ',') { break; } i++; SkipWs(t, ref i); if (i < t.Length && t[i] == '}') { i++; return jsonObject; } } if (t[i] == '}') { i++; return jsonObject; } throw Error(t, i, "Expected ',' or '}'"); } private static JsonArray ParseArray(string t, ref int i) { JsonArray jsonArray = new JsonArray(); i++; SkipWs(t, ref i); if (i < t.Length && t[i] == ']') { i++; return jsonArray; } while (true) { SkipWs(t, ref i); jsonArray.Add(ParseValue(t, ref i)); SkipWs(t, ref i); if (i >= t.Length) { throw Error(t, i, "Unterminated array"); } if (t[i] != ',') { break; } i++; SkipWs(t, ref i); if (i < t.Length && t[i] == ']') { i++; return jsonArray; } } if (t[i] == ']') { i++; return jsonArray; } throw Error(t, i, "Expected ',' or ']'"); } private static string ParseString(string t, ref int i) { i++; StringBuilder stringBuilder = new StringBuilder(); while (i < t.Length) { char c = t[i++]; switch (c) { case '"': return stringBuilder.ToString(); default: stringBuilder.Append(c); break; case '\\': { if (i >= t.Length) { throw Error(t, i, "Bad escape"); } char c2 = t[i++]; switch (c2) { case '"': stringBuilder.Append('"'); break; case '\\': stringBuilder.Append('\\'); break; case '/': stringBuilder.Append('/'); break; case 'b': stringBuilder.Append('\b'); break; case 'f': stringBuilder.Append('\f'); break; case 'n': stringBuilder.Append('\n'); break; case 'r': stringBuilder.Append('\r'); break; case 't': stringBuilder.Append('\t'); break; case 'u': if (i + 4 > t.Length) { throw Error(t, i, "Bad unicode escape"); } stringBuilder.Append((char)int.Parse(t.Substring(i, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture)); i += 4; break; default: throw Error(t, i, "Bad escape \\" + c2); } break; } } } throw Error(t, i, "Unterminated string"); } private static JsonNumber ParseNumber(string t, ref int i) { int num = i; if (t[i] == '-') { i++; } while (i < t.Length && (char.IsDigit(t[i]) || t[i] == '.' || t[i] == 'e' || t[i] == 'E' || t[i] == '+' || t[i] == '-')) { i++; } string text = t.Substring(num, i - num); if (!double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out var _)) { throw Error(t, num, "Bad number " + text); } return new JsonNumber(text, _: true); } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] public sealed class NotSavedAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class)] public sealed class SaveTypeAttribute : Attribute { public readonly string Alias; public SaveTypeAttribute(string alias) { Alias = alias; } } public interface IJsonCustom { JsonNode ToJson(JsonSerializer serializer); void FromJson(JsonNode node, JsonSerializer serializer); } public sealed class JsonSerializer { private sealed class Member { public string Name; public Type Type; public Func Get; public Action Set; } private static readonly Dictionary> MemberCache = new Dictionary>(); private static readonly Dictionary AliasToType = new Dictionary(StringComparer.Ordinal); private static readonly Dictionary TypeToAlias = new Dictionary(); private static readonly object Lock = new object(); private static bool _aliasesScanned; public readonly List Warnings = new List(); public bool CollectUnknownMemberWarnings = true; public static JsonSerializer Default => new JsonSerializer(); public static string Serialize(object value, bool indented = true) { return new JsonSerializer().ToNode(value, value?.GetType() ?? typeof(object)).ToJson(indented); } public static T Deserialize(string json) { return (T)new JsonSerializer().FromNode(JsonParser.Parse(json), typeof(T)); } public T FromJson(JsonNode node) { return (T)FromNode(node, typeof(T)); } private static void EnsureAliases() { if (_aliasesScanned) { return; } lock (Lock) { if (_aliasesScanned) { return; } Type[] types = typeof(JsonSerializer).Assembly.GetTypes(); foreach (Type type in types) { SaveTypeAttribute customAttribute = type.GetCustomAttribute(); if (customAttribute != null) { if (AliasToType.ContainsKey(customAttribute.Alias)) { throw new InvalidOperationException("Duplicate save type alias " + customAttribute.Alias); } AliasToType[customAttribute.Alias] = type; TypeToAlias[type] = customAttribute.Alias; } } _aliasesScanned = true; } } public static void RegisterAlias(string alias, Type type) { EnsureAliases(); lock (Lock) { AliasToType[alias] = type; TypeToAlias[type] = alias; } } private static List GetMembers(Type t) { lock (Lock) { if (MemberCache.TryGetValue(t, out var value)) { return value; } List<(int, Member)> list = new List<(int, Member)>(); FieldInfo[] fields = t.GetFields(BindingFlags.Instance | BindingFlags.Public); foreach (FieldInfo fieldInfo in fields) { if (!fieldInfo.IsInitOnly && !fieldInfo.IsDefined(typeof(NotSavedAttribute)) && !fieldInfo.IsDefined(typeof(NonSerializedAttribute))) { FieldInfo fieldInfo2 = fieldInfo; list.Add((fieldInfo2.MetadataToken, new Member { Name = fieldInfo2.Name, Type = fieldInfo2.FieldType, Get = fieldInfo2.GetValue, Set = fieldInfo2.SetValue })); } } PropertyInfo[] properties = t.GetProperties(BindingFlags.Instance | BindingFlags.Public); foreach (PropertyInfo propertyInfo in properties) { if (propertyInfo.GetIndexParameters().Length != 0 || propertyInfo.IsDefined(typeof(NotSavedAttribute))) { continue; } MethodInfo? getMethod = propertyInfo.GetGetMethod(); MethodInfo setMethod = propertyInfo.GetSetMethod(); if (!(getMethod == null) && !(setMethod == null)) { PropertyInfo pi = propertyInfo; list.Add((pi.MetadataToken, new Member { Name = pi.Name, Type = pi.PropertyType, Get = (object o) => pi.GetValue(o, null), Set = delegate(object o, object v) { pi.SetValue(o, v, null); } })); } } List list2 = (from x in list orderby Depth(t, x.m.Name), x.token select x.m).ToList(); MemberCache[t] = list2; return list2; } } private static int Depth(Type t, string memberName) { int num = 0; List list = new List(); Type type = t; while (type != null && type != typeof(object)) { list.Add(type); type = type.BaseType; } list.Reverse(); foreach (Type item in list) { if (item.GetMember(memberName, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public).Length != 0) { return num; } num++; } return num; } public JsonNode ToNode(object value, Type declared) { if (value == null) { return JsonNull.Instance; } Type type = value.GetType(); if (value is IJsonCustom jsonCustom) { return jsonCustom.ToJson(this); } if (type == typeof(string)) { return new JsonString((string)value); } if (type == typeof(bool)) { if (!(bool)value) { return JsonBool.False; } return JsonBool.True; } if (type == typeof(int)) { return new JsonNumber((int)value); } if (type == typeof(long)) { return new JsonNumber((long)value); } if (type == typeof(short)) { return new JsonNumber((short)value); } if (type == typeof(byte)) { return new JsonNumber((byte)value); } if (type == typeof(uint)) { return new JsonNumber((uint)value); } if (type == typeof(ulong)) { return new JsonString(((ulong)value).ToString(CultureInfo.InvariantCulture)); } if (type == typeof(double)) { return new JsonNumber((double)value); } if (type == typeof(float)) { return new JsonNumber((float)value); } if (type.IsEnum) { return new JsonString(value.ToString()); } if (value is IDictionary dictionary) { Type declared2 = DictionaryValueType(type); JsonObject jsonObject = new JsonObject(); List list = new List(); foreach (object key in dictionary.Keys) { list.Add(key); } list.Sort((object a, object b) => string.CompareOrdinal(KeyToString(a), KeyToString(b))); { foreach (object item in list) { jsonObject[KeyToString(item)] = ToNode(dictionary[item], declared2); } return jsonObject; } } if (value is IEnumerable enumerable && !(value is string)) { Type declared3 = EnumerableElementType(type); JsonArray jsonArray = new JsonArray(); { foreach (object item2 in enumerable) { jsonArray.Add(ToNode(item2, declared3)); } return jsonArray; } } JsonObject jsonObject2 = new JsonObject(); if (declared != null && type != declared && !declared.IsValueType) { EnsureAliases(); if (!TypeToAlias.TryGetValue(type, out var value2)) { throw new JsonException("Type " + type.FullName + " is stored polymorphically as " + declared.Name + " but has no [SaveType] alias"); } jsonObject2["$type"] = value2; } foreach (Member member in GetMembers(type)) { jsonObject2[member.Name] = ToNode(member.Get(value), member.Type); } return jsonObject2; } private static string KeyToString(object k) { if (k is string result) { return result; } if (k is IFormattable formattable) { return formattable.ToString(null, CultureInfo.InvariantCulture); } return k.ToString(); } public object FromNode(JsonNode node, Type t, string path = "$") { if (node == null || node.IsNull) { if (t.IsValueType && Nullable.GetUnderlyingType(t) == null) { throw new JsonException(path + ": null for value type " + t.Name); } return null; } Type underlyingType = Nullable.GetUnderlyingType(t); if (underlyingType != null) { t = underlyingType; } if (typeof(IJsonCustom).IsAssignableFrom(t)) { IJsonCustom obj = (IJsonCustom)Activator.CreateInstance(t, nonPublic: true); obj.FromJson(node, this); return obj; } if (t == typeof(string)) { return node.AsString; } if (t == typeof(bool)) { return node.AsBool; } if (t == typeof(int)) { return node.AsInt; } if (t == typeof(long)) { return node.AsLong; } checked { if (t == typeof(short)) { return (short)node.AsLong; } if (t == typeof(byte)) { return (byte)node.AsLong; } if (t == typeof(uint)) { return (uint)node.AsLong; } if (t == typeof(ulong)) { return ulong.Parse(node.AsString, CultureInfo.InvariantCulture); } if (t == typeof(double)) { return node.AsDouble; } if (t == typeof(float)) { return (float)node.AsDouble; } if (t.IsEnum) { string asString = node.AsString; try { return Enum.Parse(t, asString); } catch (ArgumentException) { throw new JsonException(path + ": unknown " + t.Name + " value '" + asString + "'"); } } if (t == typeof(object)) { throw new JsonException(path + ": cannot deserialize untyped object"); } } if (t.IsArray) { Type elementType = t.GetElementType(); JsonArray asArray = node.AsArray; Array array = Array.CreateInstance(elementType, asArray.Count); for (int i = 0; i < asArray.Count; i++) { array.SetValue(FromNode(asArray[i], elementType, $"{path}[{i}]"), i); } return array; } if (typeof(IDictionary).IsAssignableFrom(t)) { IDictionary dictionary = (IDictionary)Activator.CreateInstance(t); Type type = (t.IsGenericType ? t.GetGenericArguments()[0] : typeof(string)); Type t2 = DictionaryValueType(t); JsonObject asObject = node.AsObject; { foreach (string key2 in asObject.Keys) { object key = ((type == typeof(string)) ? key2 : (type.IsEnum ? Enum.Parse(type, key2) : Convert.ChangeType(key2, type, CultureInfo.InvariantCulture))); dictionary[key] = FromNode(asObject[key2], t2, path + "." + key2); } return dictionary; } } if (t.IsGenericType && IsCollection(t)) { Type type2 = EnumerableElementType(t); object obj2 = Activator.CreateInstance(t); MethodInfo method = t.GetMethod("Add", new Type[1] { type2 }); JsonArray asArray2 = node.AsArray; for (int j = 0; j < asArray2.Count; j++) { method.Invoke(obj2, new object[1] { FromNode(asArray2[j], type2, $"{path}[{j}]") }); } return obj2; } JsonObject asObject2 = node.AsObject; Type value = t; string text = asObject2.GetString("$type"); if (text != null) { EnsureAliases(); if (!AliasToType.TryGetValue(text, out value)) { throw new JsonException(path + ": unknown $type '" + text + "'"); } if (!t.IsAssignableFrom(value)) { throw new JsonException(path + ": $type '" + text + "' is not a " + t.Name); } } if (value.IsAbstract || value.IsInterface) { throw new JsonException(path + ": abstract type " + value.Name + " needs $type"); } object obj3 = Activator.CreateInstance(value, nonPublic: true); List members = GetMembers(value); foreach (Member item in members) { if (asObject2.TryGet(item.Name, out var node2)) { object obj4 = ((node2 == null || node2.IsNull) ? null : item.Get(obj3)); if (obj4 == null || obj4 is IJsonCustom || obj4.GetType().IsArray || !TryPopulate(obj4, node2, path + "." + item.Name)) { item.Set(obj3, FromNode(node2, item.Type, path + "." + item.Name)); } } } if (CollectUnknownMemberWarnings) { foreach (string key3 in asObject2.Keys) { if (key3 == "$type") { continue; } bool flag = false; foreach (Member item2 in members) { if (item2.Name == key3) { flag = true; break; } } if (!flag) { Warnings.Add(path + ": ignored unknown member '" + key3 + "' on " + value.Name); } } } return obj3; } private bool TryPopulate(object existing, JsonNode node, string path) { Type type = existing.GetType(); if (existing is IDictionary dictionary) { if ((type.IsGenericType ? type.GetGenericArguments()[0] : typeof(string)) != typeof(string)) { return false; } Type t = DictionaryValueType(type); dictionary.Clear(); JsonObject asObject = node.AsObject; foreach (string key in asObject.Keys) { dictionary[key] = FromNode(asObject[key], t, path + "." + key); } return true; } if (type.IsGenericType && IsCollection(type)) { Type type2 = EnumerableElementType(type); MethodInfo method = type.GetMethod("Clear", Type.EmptyTypes); MethodInfo method2 = type.GetMethod("Add", new Type[1] { type2 }); if (method == null || method2 == null) { return false; } method.Invoke(existing, null); JsonArray asArray = node.AsArray; for (int i = 0; i < asArray.Count; i++) { method2.Invoke(existing, new object[1] { FromNode(asArray[i], type2, $"{path}[{i}]") }); } return true; } return false; } private static bool IsCollection(Type t) { Type[] interfaces = t.GetInterfaces(); foreach (Type type in interfaces) { if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(ICollection<>)) { return true; } } return false; } private static Type DictionaryValueType(Type t) { Type type = t; while (type != null) { if (type.IsGenericType && type.GetGenericArguments().Length == 2) { return type.GetGenericArguments()[1]; } type = type.BaseType; } return typeof(object); } private static Type EnumerableElementType(Type t) { if (t.IsArray) { return t.GetElementType(); } Type[] interfaces = t.GetInterfaces(); foreach (Type type in interfaces) { if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>)) { return type.GetGenericArguments()[0]; } } return typeof(object); } public static T Clone(T value) where T : class { JsonSerializer jsonSerializer = new JsonSerializer(); return (T)jsonSerializer.FromNode(jsonSerializer.ToNode(value, typeof(T)), typeof(T)); } } } namespace TabsBannerlord.Core.Persistence { public static class SaveContentRepair { public static bool Repairable(IEnumerable missing) { return missing.All((string m) => m.StartsWith("unit ", StringComparison.Ordinal) || m.StartsWith("culture ", StringComparison.Ordinal)); } public static string Repair(CampaignState s, ContentDatabase content) { string fallback = ((content.Cultures.Count > 0) ? content.Cultures[0].Id : ""); int cultures = 0; int troops = 0; int num = 0; foreach (Kingdom kingdom in s.Kingdoms) { kingdom.CultureId = Culture(kingdom.CultureId, new string[1] { ClanCulture(kingdom.RulerClanId) }); } foreach (Clan clan2 in s.Clans) { clan2.CultureId = Culture(clan2.CultureId, new string[1] { s.Kingdoms.Get(clan2.KingdomId ?? "")?.CultureId }); } foreach (Settlement settlement in s.Settlements) { settlement.CultureId = Culture(settlement.CultureId, new string[1] { ClanCulture(settlement.OwnerClanId) }); settlement.Garrison = Roster(settlement.Garrison, settlement.CultureId); settlement.Prisoners = Roster(settlement.Prisoners, settlement.CultureId); foreach (RecruitSlot item in settlement.Recruits ?? new List()) { if (item != null) { item.UnitId = Unit(item.UnitId, settlement.CultureId); } } } foreach (NotableState item2 in s.Notables ?? new List()) { if (item2 != null) { item2.CultureId = Culture(item2.CultureId, new string[1] { s.Settlements.Get(item2.SettlementId ?? "")?.CultureId }); } } foreach (Hero hero in s.Heroes) { hero.CultureId = Culture(hero.CultureId, new string[1] { ClanCulture(hero.ClanId) }); string text = Unit(hero.UnitId, hero.CultureId, hero.Occupation == HeroOccupation.Lord || hero.IsPlayer); if (text != hero.UnitId) { num++; hero.UnitId = text; } if (hero.Creation != null) { hero.Creation.CultureId = Culture(hero.Creation.CultureId, new string[1] { hero.CultureId }); hero.Creation.ArchetypeId = Unit(hero.Creation.ArchetypeId, hero.CultureId, hero: true); } } foreach (Party party in s.Parties) { string cultureId = ClanCulture(party.ClanId); party.Troops = Roster(party.Troops, cultureId); party.Prisoners = Roster(party.Prisoners, cultureId); } if (s.Player?.LastReport?.RescuedTroops != null) { s.Player.LastReport.RescuedTroops = Roster(s.Player.LastReport.RescuedTroops, ClanCulture(s.PlayerClanId)); } foreach (Encounter encounter in s.Encounters) { foreach (Combatant item3 in encounter?.Manifest?.Combatants ?? new List()) { if (item3 != null) { item3.UnitId = Unit(item3.UnitId, fallback); } } } foreach (TournamentState item4 in s.Tournaments?.Active ?? new List()) { foreach (TournamentFighterState item5 in item4?.Run?.Fighters ?? new List()) { if (item5 != null && !string.IsNullOrEmpty(item5.UnitId)) { item5.UnitId = Unit(item5.UnitId, s.Settlements.Get(item4.TownId ?? "")?.CultureId); } } } List list = new List(); if (troops > 0) { list.Add(troops + " troops"); } if (num > 0) { list.Add(num + ((num == 1) ? " hero" : " heroes")); } string text2 = ((list.Count == 0) ? "" : (string.Join(" and ", list.ToArray()) + " of their units now serve as their culture's own")); string text3 = ((cultures == 0) ? "" : (cultures + " cultures were swapped for ones that are loaded")); return string.Join("; ", new string[2] { text2, text3 }.Where((string x) => x.Length > 0).ToArray()); string ClanCulture(string clanId) { Clan clan = s.Clans.Get(clanId ?? ""); if (clan == null || !content.Cultures.Contains(clan.CultureId)) { return fallback; } return clan.CultureId; } string Culture(string id, params string[] nearer) { if (string.IsNullOrEmpty(id) || content.Cultures.Contains(id)) { return id; } cultures++; return nearer.FirstOrDefault((string c) => !string.IsNullOrEmpty(c) && content.Cultures.Contains(c)) ?? fallback; } TroopRoster Roster(TroopRoster roster, string cultureId2) { if (roster == null || roster.Stacks.All((TroopStack st) => content.Units.Contains(st.UnitId))) { return roster; } TroopRoster troopRoster = new TroopRoster(); troopRoster.Heroes.AddRange(roster.Heroes); foreach (TroopStack stack in roster.Stacks) { string text4 = Unit(stack.UnitId, cultureId2); if (text4 != stack.UnitId) { troops += stack.Total; } troopRoster.Add(text4, stack.Healthy, stack.Wounded, stack.Xp); TroopStack troopStack = troopRoster.Find(text4); if (troopStack != null) { troopStack.PrisonerRecruitment = Math.Max(troopStack.PrisonerRecruitment, stack.PrisonerRecruitment); } } return troopRoster; } string Unit(string id, string text4, bool hero = false) { if (string.IsNullOrEmpty(id) || content.Units.Contains(id)) { return id; } CultureDef cultureDef = content.Cultures.Get(text4 ?? "") ?? content.Cultures.Get(fallback); string text5 = ((hero && content.Units.Contains(cultureDef?.HeroUnit ?? "")) ? cultureDef.HeroUnit : (cultureDef?.BasicTroop ?? "")); if (!content.Units.Contains(text5)) { if (content.Units.Count <= 0) { return id; } return content.Units[0].Id; } return text5; } } } public enum SaveKind { Manual, Autosave, PreBattle, PostBattle } public sealed class SaveHeader { public int SchemaVersion; public string CampaignId = ""; public string Slot = ""; public long Generation; public long Revision; public SaveKind Kind; public string SavedAtUtc = ""; public string Description = ""; public long CampaignMinute; public string PlayerName = ""; public bool Ironman; public ContentManifest Content = new ContentManifest(); public string Checksum = ""; } public sealed class SaveSnapshot { public SaveHeader Header; public string Body = ""; } public sealed class SaveInfo { public string Slot = ""; public string Path = ""; public SaveHeader Header; public bool Readable; public string Problem = ""; } public sealed class LoadResult { public bool Success; public CampaignState State; public SaveHeader Header; public string Error = ""; public List Notices = new List(); public bool RecoveredFromBackup; public bool Migrated; public List MissingContent = new List(); } public sealed class WriteResult { public bool Success; public bool Stale; public string Error = ""; public string Path = ""; public long Generation; } public interface ISaveMigration { int FromVersion { get; } void Migrate(JsonObject body, List notices); } public sealed class SaveSystem { public sealed class SnapshotBuilder { private readonly SaveSystem _sys; private readonly CampaignState _state; internal SnapshotBuilder(SaveSystem sys, CampaignState state) { _sys = sys; _state = state; } public SaveSnapshot For(string slot, SaveKind kind, string description = "") { string text = new JsonSerializer().ToNode(_state, typeof(CampaignState)).ToJson(indented: false); SaveHeader header = new SaveHeader { SchemaVersion = _state.SchemaVersion, CampaignId = _state.CampaignId, Slot = SanitizeSlot(slot), Revision = _state.Revision, Kind = kind, SavedAtUtc = DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture), Description = (description ?? ""), CampaignMinute = _state.Clock.Minute, PlayerName = (_state.PlayerHero?.Name ?? ""), Ironman = (_state.Settings?.Ironman ?? false), Content = _state.Content, Checksum = StableHash.Fnv1a64(text).ToString("x16"), Generation = _sys.NextGeneration(slot) }; return new SaveSnapshot { Header = header, Body = text }; } } public readonly string Directory; private readonly object _lock = new object(); private readonly List _migrations = new List(); public const string Extension = ".tbsave"; private readonly Dictionary _issued = new Dictionary(StringComparer.Ordinal); private readonly Dictionary _headerCache = new Dictionary(StringComparer.OrdinalIgnoreCase); public SaveSystem(string directory) { Directory = directory; System.IO.Directory.CreateDirectory(directory); } public void AddMigration(ISaveMigration m) { _migrations.Add(m); } public static string SanitizeSlot(string slot) { StringBuilder stringBuilder = new StringBuilder(); string text = slot ?? ""; foreach (char c in text) { stringBuilder.Append((char.IsLetterOrDigit(c) || c == '-' || c == '_') ? c : '_'); } string text2 = stringBuilder.ToString().Trim(new char[1] { '_' }); if (!string.IsNullOrEmpty(text2)) { return text2; } return "save"; } public string PathFor(string slot) { return Path.Combine(Directory, SanitizeSlot(slot) + ".tbsave"); } private string BackupPathFor(string slot) { return PathFor(slot) + ".bak"; } private string GenerationPathFor(string slot) { return PathFor(slot) + ".gen"; } public SnapshotBuilder Snapshot(CampaignState state) { return new SnapshotBuilder(this, state); } private long NextGeneration(string slot) { lock (_lock) { slot = SanitizeSlot(slot); if (!_issued.TryGetValue(slot, out var value)) { value = ReadGeneration(slot); } value++; _issued[slot] = value; return value; } } private long ReadGeneration(string slot) { try { long val = 0L; string path = GenerationPathFor(slot); if (File.Exists(path) && long.TryParse(File.ReadAllText(path).Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) { val = result; } return Math.Max(val, ReadHeader(PathFor(slot))?.Generation ?? 0); } catch (IOException) { return 0L; } } public static string Compose(SaveSnapshot s) { JsonSerializer jsonSerializer = new JsonSerializer(); return new JsonObject { ["header"] = jsonSerializer.ToNode(s.Header, typeof(SaveHeader)), ["body"] = JsonParser.Parse(s.Body) }.ToJson(indented: false); } public WriteResult Write(SaveSnapshot snap) { lock (_lock) { string slot = snap.Header.Slot; string text = PathFor(slot); WriteResult writeResult = new WriteResult { Path = text, Generation = snap.Header.Generation }; long num = ReadGeneration(slot); if (snap.Header.Generation <= num) { writeResult.Stale = true; writeResult.Error = $"Stale save generation {snap.Header.Generation} (slot already at {num}); newer save kept."; return writeResult; } SaveHeader saveHeader = ReadHeader(text); if (saveHeader != null && saveHeader.CampaignId != snap.Header.CampaignId && snap.Header.Kind != SaveKind.Manual) { writeResult.Error = "Slot belongs to a different campaign; automatic save refused."; return writeResult; } string text2 = text + ".tmp"; try { string s = Compose(snap); using (FileStream fileStream = new FileStream(text2, FileMode.Create, FileAccess.Write, FileShare.None)) { byte[] bytes = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false).GetBytes(s); fileStream.Write(bytes, 0, bytes.Length); fileStream.Flush(flushToDisk: true); } LoadResult loadResult = ReadFile(text2, verifyOnly: true); if (!loadResult.Success) { throw new IOException("Verification failed: " + loadResult.Error); } if (File.Exists(text)) { string text3 = BackupPathFor(slot); if (File.Exists(text3)) { File.Delete(text3); } File.Move(text, text3); } File.Move(text2, text); File.WriteAllText(GenerationPathFor(slot), snap.Header.Generation.ToString(CultureInfo.InvariantCulture)); writeResult.Success = true; return writeResult; } catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException) { try { if (File.Exists(text2)) { File.Delete(text2); } } catch (IOException) { } if (!File.Exists(text) && File.Exists(BackupPathFor(slot))) { try { File.Move(BackupPathFor(slot), text); } catch (IOException) { } } writeResult.Error = "Save failed: " + ex.Message + " The previous save is intact; your newest progress is only in memory."; return writeResult; } } } public WriteResult Save(CampaignState state, string slot, SaveKind kind, string description = "") { return Write(Snapshot(state).For(slot, kind, description)); } public static SaveHeader ReadHeader(string path) { try { if (!File.Exists(path)) { return null; } SaveHeader saveHeader = ReadHeaderFast(path); if (saveHeader != null) { return saveHeader; } JsonObject asObject = JsonParser.Parse(File.ReadAllText(path, Encoding.UTF8)).AsObject; return new JsonSerializer { CollectUnknownMemberWarnings = false }.FromJson(asObject.GetObject("header")); } catch (Exception ex) when (ex is JsonException || ex is IOException || ex is InvalidCastException) { return null; } } private SaveHeader CachedHeader(string path) { FileInfo fileInfo; try { fileInfo = new FileInfo(path); if (!fileInfo.Exists) { return null; } } catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException) { return ReadHeader(path); } long length = fileInfo.Length; DateTime lastWriteTimeUtc = fileInfo.LastWriteTimeUtc; lock (_headerCache) { if (_headerCache.TryGetValue(path, out (long, DateTime, SaveHeader) value) && value.Item1 == length && value.Item2 == lastWriteTimeUtc) { return value.Item3; } } SaveHeader saveHeader = ReadHeader(path); lock (_headerCache) { _headerCache[path] = (length, lastWriteTimeUtc, saveHeader); return saveHeader; } } internal static SaveHeader ReadHeaderFast(string path) { try { StringBuilder stringBuilder = new StringBuilder(); using StreamReader streamReader = new StreamReader(path, Encoding.UTF8, detectEncodingFromByteOrderMarks: true, 16384); char[] array = new char[16384]; int num = -1; int num2 = 0; int num3 = 0; bool flag = false; bool flag2 = false; while (stringBuilder.Length < 1048576) { int num4 = streamReader.Read(array, 0, array.Length); if (num4 <= 0) { return null; } stringBuilder.Append(array, 0, num4); if (num < 0) { int num5 = stringBuilder.ToString().IndexOf("\"header\"", StringComparison.Ordinal); if (num5 < 0) { continue; } int num6 = stringBuilder.ToString().IndexOf('{', num5); if (num6 < 0) { continue; } for (int i = 0; i < num5; i++) { if (stringBuilder[i] != '{' && !char.IsWhiteSpace(stringBuilder[i]) && stringBuilder[i] != '\ufeff') { return null; } } num = num6; num3 = num6; } for (int j = num3; j < stringBuilder.Length; j++) { char c = stringBuilder[j]; if (flag) { if (flag2) { flag2 = false; continue; } switch (c) { case '\\': flag2 = true; break; case '"': flag = false; break; } continue; } switch (c) { case '"': flag = true; break; case '{': num2++; break; case '}': if (--num2 == 0) { JsonNode jsonNode = JsonParser.Parse(stringBuilder.ToString(num, j - num + 1)); return new JsonSerializer { CollectUnknownMemberWarnings = false }.FromJson(jsonNode.AsObject); } break; } } num3 = stringBuilder.Length; } return null; } catch (Exception) { return null; } } public List List() { List list = new List(); HashSet seen = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (string item in System.IO.Directory.GetFiles(Directory, "*.tbsave").OrderBy((string f) => f, StringComparer.Ordinal)) { seen.Add(item); SaveInfo saveInfo = new SaveInfo { Path = item, Slot = Path.GetFileNameWithoutExtension(item) }; saveInfo.Header = CachedHeader(item); saveInfo.Readable = saveInfo.Header != null; if (!saveInfo.Readable) { saveInfo.Problem = "Unreadable save; a backup may be available."; } list.Add(saveInfo); } lock (_headerCache) { foreach (string item2 in _headerCache.Keys.Where((string k) => !seen.Contains(k)).ToList()) { _headerCache.Remove(item2); } } return list.OrderByDescending((SaveInfo i) => i.Header?.SavedAtUtc ?? "").ToList(); } public LoadResult Load(string slot, ContentDatabase content = null) { string text = PathFor(slot); LoadResult loadResult = ReadFile(text, verifyOnly: false); if (!loadResult.Success && File.Exists(BackupPathFor(slot))) { LoadResult loadResult2 = ReadFile(BackupPathFor(slot), verifyOnly: false); if (loadResult2.Success) { try { if (File.Exists(text)) { File.Copy(text, text + ".damaged-" + DateTime.UtcNow.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture), overwrite: true); } } catch (IOException) { } loadResult2.RecoveredFromBackup = true; loadResult2.Notices.Add("The latest save was unreadable (" + loadResult.Error + "); the previous generation was loaded."); loadResult = loadResult2; } } if (loadResult.Success && content != null) { CheckContent(loadResult, content); } if (loadResult.Success && loadResult.Migrated) { try { string text2 = text + ".v" + loadResult.Header.SchemaVersion + ".orig"; if (!File.Exists(text2) && File.Exists(text)) { File.Copy(text, text2); } loadResult.Notices.Add("This save was upgraded from schema " + loadResult.Header.SchemaVersion + "; the original was preserved."); } catch (IOException) { } } return loadResult; } private LoadResult ReadFile(string path, bool verifyOnly) { LoadResult loadResult = new LoadResult(); try { if (!File.Exists(path)) { loadResult.Error = "Save not found."; return loadResult; } JsonObject asObject = JsonParser.Parse(File.ReadAllText(path, Encoding.UTF8)).AsObject; JsonSerializer jsonSerializer = new JsonSerializer { CollectUnknownMemberWarnings = false }; loadResult.Header = jsonSerializer.FromJson(asObject.GetObject("header")); JsonObject jsonObject = asObject.GetObject("body"); if (jsonObject == null) { loadResult.Error = "Save has no body."; return loadResult; } if (StableHash.Fnv1a64(jsonObject.ToJson(indented: false)).ToString("x16") != loadResult.Header.Checksum) { loadResult.Error = "Checksum mismatch (file damaged or edited)."; return loadResult; } if (verifyOnly) { loadResult.Success = true; return loadResult; } if (loadResult.Header.SchemaVersion > 1) { loadResult.Error = $"This save uses schema {loadResult.Header.SchemaVersion}, newer than this version of the mod supports ({1}). It was not modified."; return loadResult; } int version = loadResult.Header.SchemaVersion; while (version < 1) { ISaveMigration saveMigration = _migrations.FirstOrDefault((ISaveMigration m) => m.FromVersion == version); if (saveMigration == null) { loadResult.Error = $"No migration from schema {version}."; return loadResult; } saveMigration.Migrate(jsonObject, loadResult.Notices); version++; loadResult.Migrated = true; } jsonObject["SchemaVersion"] = 1; if (jsonObject.GetString("WorldId") == "world.continent") { JsonObject jsonObject2 = jsonObject.GetObject("WorldGeneration"); if (jsonObject2 == null || !jsonObject2.Has("Version") || jsonObject2["Version"].IsNull || !jsonObject2.Has("Seed") || jsonObject2["Seed"].IsNull) { loadResult.Error = "This procedural world is missing its saved generation version or seed. The save was not modified."; return loadResult; } } JsonSerializer jsonSerializer2 = new JsonSerializer(); loadResult.State = jsonSerializer2.FromJson(jsonObject); List list = InvariantChecker.CheckEconomyState(loadResult.State, checkContent: false); if (list.Count > 0) { loadResult.Error = "This save has invalid economy data: " + string.Join("; ", list.Take(5)) + ". The save was not modified."; return loadResult; } List list2 = InvariantChecker.CheckSettlementState(loadResult.State, checkContent: false); list2.AddRange(CharacterCreationValidation.Check(loadResult.State)); string text = ProceduralWorld.StateError(loadResult.State); if (text.Length > 0) { list2.Add(text); } list2.AddRange(HeroDevelopmentValidation.Check(loadResult.State)); list2.AddRange(EquipmentValidation.Check(loadResult.State)); list2.AddRange(SmithingValidation.Check(loadResult.State)); list2.AddRange(HorseValidation.Check(loadResult.State)); list2.AddRange(RealmValidation.Check(loadResult.State)); list2.AddRange(DiplomacyValidation.Check(loadResult.State)); list2.AddRange(SiegeValidation.Check(loadResult.State)); list2.AddRange(PoliticsValidation.Check(loadResult.State)); list2.AddRange(ClanAllegianceValidation.Check(loadResult.State)); list2.AddRange(RaidValidation.Check(loadResult.State)); list2.AddRange(MilitaryPartyValidation.Check(loadResult.State)); list2.AddRange(ClanArmyValidation.Check(loadResult.State)); list2.AddRange(NamedCustodyValidation.Check(loadResult.State)); list2.AddRange(RescueValidation.Check(loadResult.State)); list2.AddRange(TournamentValidation.Check(loadResult.State)); list2.AddRange(ScoutingValidation.Check(loadResult.State)); if (list2.Count > 0) { loadResult.Error = "This save has invalid settlement data: " + string.Join("; ", list2.Take(5)) + ". The save was not modified."; return loadResult; } foreach (string item in jsonSerializer2.Warnings.Take(10)) { loadResult.Notices.Add("Ignored saved data: " + item); } loadResult.Success = true; return loadResult; } catch (Exception ex) when (ex is JsonException || ex is IOException || ex is InvalidCastException || ex is FormatException || ex is OverflowException || ex is ArgumentException || ex is InvalidOperationException) { loadResult.Error = ex.Message; return loadResult; } } public static void CheckContent(LoadResult r, ContentDatabase content) { CampaignState s = r.State; CustomFactions.Register(content, s.CustomContent, replace: true); SortedSet missing = new SortedSet(StringComparer.Ordinal); if (s.Player?.LastReport?.RescuedTroops != null) { Roster(s.Player.LastReport.RescuedTroops); } if (s.Encounters != null) { foreach (Encounter encounter in s.Encounters) { if (encounter?.Manifest?.Combatants == null) { continue; } foreach (Combatant combatant in encounter.Manifest.Combatants) { if (combatant?.Loadout == null) { continue; } Unit(combatant.UnitId); foreach (string item in combatant.Loadout.SlotItems()) { Equipment(item); } } } } foreach (Party party in s.Parties) { Roster(party.Troops); Roster(party.Prisoners); if (party.Cargo != null) { foreach (string key in party.Cargo.Keys) { Good(key); } } if (party.Equipment == null) { continue; } foreach (string key2 in party.Equipment.Keys) { Equipment(key2); } } foreach (Settlement settlement in s.Settlements) { Roster(settlement.Garrison); Roster(settlement.Prisoners); foreach (RecruitSlot item2 in settlement.Recruits ?? new List()) { if (item2 != null) { Unit(item2.UnitId); } } if (settlement.Market?.Stock != null) { foreach (string key3 in settlement.Market.Stock.Keys) { Good(key3); } } if (settlement.Market?.EquipmentStock != null) { foreach (string key4 in settlement.Market.EquipmentStock.Keys) { Equipment(key4); } } string text = settlement.Management?.ProjectId; if (!string.IsNullOrEmpty(settlement.Product)) { Good(settlement.Product); } if (!string.IsNullOrEmpty(text) && !TabsBannerlord.Core.Campaign.Campaign.IsSettlementProject(text)) { missing.Add("settlement project " + text); } } if (s.Workshops != null) { foreach (WorkshopState item3 in s.Workshops.Where((WorkshopState x) => x != null)) { if (WorkshopTypes.Get(item3.TypeId) == null) { missing.Add("workshop type " + (item3.TypeId ?? "")); } } } if (s.Contracts != null) { foreach (ContractState item4 in s.Contracts.Where((ContractState x) => x != null && (x.Kind == ContractKind.Delivery || x.Kind == ContractKind.SettlementSupply))) { Good(item4.GoodId); } } if (s.Caravans != null) { foreach (CaravanState item5 in s.Caravans.Where((CaravanState x) => x?.CargoCosts != null)) { foreach (string key5 in item5.CargoCosts.Keys) { Good(key5); } } } foreach (Hero hero in s.Heroes) { Unit(hero.UnitId); if (hero.Loadout != null) { foreach (string item6 in hero.Loadout.SlotItems()) { Equipment(item6); } } if (hero.Creation != null) { Unit(hero.Creation.ArchetypeId); if (!string.IsNullOrEmpty(hero.Creation.CultureId) && !content.Cultures.Contains(hero.Creation.CultureId)) { missing.Add("culture " + hero.Creation.CultureId); } } } foreach (Clan clan in s.Clans) { if (!string.IsNullOrEmpty(clan.CultureId) && !content.Cultures.Contains(clan.CultureId)) { missing.Add("culture " + clan.CultureId); } } foreach (Kingdom kingdom in s.Kingdoms) { if (!string.IsNullOrEmpty(kingdom.CultureId) && !content.Cultures.Contains(kingdom.CultureId)) { missing.Add("culture " + kingdom.CultureId); } } foreach (NotableState item7 in s.Notables ?? new List()) { if (item7 != null && !string.IsNullOrEmpty(item7.CultureId) && !content.Cultures.Contains(item7.CultureId)) { missing.Add("culture " + item7.CultureId); } } if (!content.Worlds.ContainsKey(s.WorldId)) { missing.Add("world " + s.WorldId); } List list = (s.Content?.Packs ?? new List()).Where((ContentPackInfo p) => p != null && !string.IsNullOrEmpty(p.Id) && content.Manifest.Packs.All((ContentPackInfo q) => q.Id != p.Id)).ToList(); if (missing.Count > 0 && list.Count > 0 && SaveContentRepair.Repairable(missing)) { string text2 = SaveContentRepair.Repair(s, content); r.Notices.Add("This campaign was made with mods that aren't loaded: " + string.Join(", ", list.Select((ContentPackInfo p) => (string.IsNullOrEmpty(p.Name) ? p.Id : p.Name) + " v" + p.Version).ToArray()) + "." + ((text2.Length > 0) ? (" " + char.ToUpperInvariant(text2[0]) + text2.Substring(1) + ".") : "")); s.Content.Packs = content.Manifest.Packs.ToList(); missing.Clear(); } else if (list.Count > 0) { r.Notices.Add("This campaign was made with mods that aren't loaded: " + string.Join(", ", list.Select((ContentPackInfo p) => (string.IsNullOrEmpty(p.Name) ? p.Id : p.Name) + " v" + p.Version).ToArray()) + "."); if (missing.Count == 0) { s.Content.Packs = content.Manifest.Packs.ToList(); } } r.MissingContent = missing.ToList(); if (missing.Count > 0) { r.Success = false; r.Error = "This campaign needs content that is not installed: " + string.Join(", ", missing.Take(8)) + ((missing.Count > 8) ? "…" : "") + ". The save was not modified."; } else if (EquipmentValidation.Check(s, content).Count > 0) { r.Success = false; r.Error = "This campaign has incompatible equipment: " + string.Join("; ", EquipmentValidation.Check(s, content).Take(5)) + ". The save was not modified."; } else if (s.Content.Hash != content.Manifest.Hash) { r.Notices.Add("Campaign content or balance has changed since this save was created; existing troops keep their identities."); } void Equipment(string id) { if (!string.IsNullOrEmpty(id)) { OwnedItemInfo ownedItemInfo = OwnedItems.Resolve(s, id); if (ownedItemInfo == null) { missing.Add("equipment " + id); } else if (ownedItemInfo.Kit != null) { Unit(ownedItemInfo.Kit.SourceUnitId); } } } void Good(string id) { if (!TradeGoods.All.Any((TradeGoodDef x) => x.Id == id)) { missing.Add("trade good " + (id ?? "")); } } void Roster(TroopRoster ro) { foreach (TroopStack stack in ro.Stacks) { Unit(stack.UnitId); } } void Unit(string id) { if (!string.IsNullOrEmpty(id) && !content.Units.Contains(id)) { missing.Add("unit " + id); } } } public string NextAutosaveSlot(int count, string prefix = "") { count = Math.Max(1, count); string text = (string.IsNullOrEmpty(prefix) ? "autosave-" : (SanitizeSlot(prefix) + "-auto-")); string text2 = null; string text3 = null; for (int i = 1; i <= count; i++) { string text4 = text + i; SaveHeader saveHeader = ReadHeader(PathFor(text4)); if (saveHeader == null) { return text4; } if (text3 == null || string.CompareOrdinal(saveHeader.SavedAtUtc, text3) < 0) { text2 = text4; text3 = saveHeader.SavedAtUtc; } } return text2 ?? (text + "1"); } } } namespace TabsBannerlord.Core.Diagnostics { public static class CharacterCreationValidation { public static List Check(CampaignState state) { List list = new List(); if (state?.Heroes == null) { return list; } foreach (Hero hero in state.Heroes) { CharacterCreationState origin = hero?.Creation; if (origin == null) { if (hero != null && hero.OriginFocus != 0) { list.Add("hero development " + hero.Id + " has creation focus without a character origin"); } continue; } string text = "character origin " + hero.Id; if ((hero.State != HeroState.Dead || hero.IsPlayer || hero.Occupation != HeroOccupation.Player || !(hero.Id != state.PlayerHeroId)) && (hero.Id != state.PlayerHeroId || !hero.IsPlayer || hero.Occupation != HeroOccupation.Player)) { list.Add(text + " belongs to a non-player hero"); } if (origin.HasLifeStages) { CheckLifeStages(state, hero, origin, text, list); } else { if (!CharacterCreation.Backgrounds.Any((CharacterChoiceDef x) => x.Id == origin.BackgroundId)) { list.Add(text + " has an unknown background"); } if (!CharacterCreation.Trainings.Any((CharacterChoiceDef x) => x.Id == origin.TrainingId)) { list.Add(text + " has an unknown training"); } if (!CharacterCreation.Traits.Any((CharacterChoiceDef x) => x.Id == origin.TraitId)) { list.Add(text + " has an unknown trait"); } if (hero.OriginFocus != 0) { list.Add(text + " has creation focus without life stages"); } } if (string.IsNullOrWhiteSpace(origin.CultureId)) { list.Add(text + " has no culture"); } if (string.IsNullOrWhiteSpace(origin.ArchetypeId)) { list.Add(text + " has no archetype"); } if (!CharacterCreation.IsBannerColor(origin.BannerColor)) { list.Add(text + " has an unknown banner color"); } if (!CharacterCreation.IsEmblemColor(origin.BannerEmblemColor)) { list.Add(text + " has an unknown emblem color"); } if (!CharacterCreation.BannerSymbols.Contains(origin.BannerSymbol)) { list.Add(text + " has an unknown banner symbol"); } } return list; } private static void CheckLifeStages(CampaignState state, Hero hero, CharacterCreationState origin, string label, List errors) { if (!string.IsNullOrEmpty(origin.BackgroundId) || !string.IsNullOrEmpty(origin.TrainingId) || !string.IsNullOrEmpty(origin.TraitId)) { errors.Add(label + " records both life stages and a background"); } if (CharacterCreation.LifeStagesReason(origin.LifeStages).Length > 0) { errors.Add(label + " has an invalid life story"); return; } if (CharacterCreation.StartingAge(origin.Age) == null) { errors.Add(label + " has an unknown starting age"); return; } if (CharacterCreation.FocusReason(origin.LifeStages, origin.Age, origin.Focus).Length > 0) { errors.Add(label + " has invalid creation focus"); } if (hero.OriginFocus != CharacterCreation.OriginFocus(origin.Age)) { errors.Add(label + " has a different amount of creation focus than its life story gives"); } if (origin.StartSettlementId == null) { errors.Add(label + " has no starting place"); } else if (origin.StartSettlementId.Length > 0) { Settlement settlement = state.Settlements?.Get(origin.StartSettlementId); if (settlement == null || settlement.Type == SettlementType.Hideout) { errors.Add(label + " began in an unknown place"); } } } } public static class ClanAllegianceValidation { public static List Check(CampaignState state) { List list = new List(); ClanAllegianceState clanAllegiance = state.ClanAllegiance; if (clanAllegiance == null) { return list; } if (!clanAllegiance.Initialized) { if (clanAllegiance.LastAiDay == -1) { List records = clanAllegiance.Records; if (records == null || records.Count == 0) { goto IL_0043; } } list.Add("clan allegiance was never set up but has data in it"); goto IL_0043; } if (clanAllegiance.LastAiDay < 0 || clanAllegiance.LastAiDay > state.Clock.Day) { list.Add("clan allegiance has an invalid evaluation day"); } if (clanAllegiance.Records == null) { list.Add("clan allegiance has no history list"); return list; } HashSet hashSet = new HashSet(StringComparer.Ordinal); foreach (ClanAllegianceRecord record in clanAllegiance.Records) { if (record == null) { list.Add("clan allegiance contains an empty record"); continue; } string text = "clan allegiance " + record.ClanId; Clan clan = state.Clans.Get(record.ClanId); Clan clan2 = state.Clans.Get(record.SponsorClanId); if (clan == null || clan.IsBandit || clan.IsPlayerClan || clan.Id == state.PlayerClanId || !hashSet.Add(record.ClanId ?? "")) { list.Add(text + " has an unknown, duplicate or unrecruitable clan"); } if (clan2 == null || clan2.IsBandit || clan2.Id == record.ClanId) { list.Add(text + " has a bad sponsor"); } if (record.PreviousKingdomId == null || record.KingdomId == null || (record.PreviousKingdomId.Length > 0 && !state.Kingdoms.Contains(record.PreviousKingdomId)) || (record.KingdomId.Length > 0 && !state.Kingdoms.Contains(record.KingdomId))) { list.Add(text + " has an unknown realm"); } if (!Enum.IsDefined(typeof(ClanAllegianceChange), record.Kind)) { list.Add(text + " has an unknown change kind"); } else if (record.Kind == ClanAllegianceChange.Recruited) { if (string.IsNullOrEmpty(record.KingdomId) || record.KingdomId == record.PreviousKingdomId || record.SigningPayment < 1000) { list.Add(text + " has invalid recruitment terms"); } } else if (record.Kind == ClanAllegianceChange.Swore) { if (string.IsNullOrEmpty(record.KingdomId) || record.KingdomId == record.PreviousKingdomId || record.SigningPayment != 0L) { list.Add(text + " has invalid fealty terms"); } } else if (string.IsNullOrEmpty(record.PreviousKingdomId) || !string.IsNullOrEmpty(record.KingdomId) || record.SigningPayment != 0L) { list.Add(text + " has invalid departure terms"); } if (record.ChangedDay < 0 || record.ChangedDay > state.Clock.Day || record.ChangedDay > 9223372036854775800L || record.CooldownUntilDay != record.ChangedDay + 7) { list.Add(text + " has an invalid change day or cooldown"); } } return list; IL_0043: return list; } } public static class ClanArmyValidation { public static List Check(CampaignState state) { List list = new List(); ClanArmyState clanArmy = state.ClanArmy; if (clanArmy == null) { return list; } if (double.IsNaN(clanArmy.Cohesion) || double.IsInfinity(clanArmy.Cohesion) || clanArmy.Cohesion < 0.0 || clanArmy.Cohesion > 100.0) { list.Add("clan army has invalid cohesion"); } if (clanArmy.StartedMinute < 0 || clanArmy.StartedMinute > state.Clock.Minute || clanArmy.LastDailyDay < -1 || clanArmy.LastDailyDay > state.Clock.Day || clanArmy.LastRallyDay < -1 || clanArmy.LastRallyDay > state.Clock.Day) { list.Add("clan army has invalid clocks"); } if (clanArmy.Members == null) { list.Add("clan army has no member collection"); return list; } if (!string.IsNullOrEmpty(clanArmy.OwnerClanId) && clanArmy.OwnerClanId != state.PlayerClanId) { list.Add("clan army is commanded by someone outside the clan"); } if (!string.IsNullOrEmpty(clanArmy.LeaderPartyId) && clanArmy.LeaderPartyId != state.PlayerPartyId) { list.Add("clan army leader can't lead it"); } if (!clanArmy.Active) { if (clanArmy.Members.Count > 0) { list.Add("clan army still has members after breaking up"); } return list; } if (clanArmy.Cohesion <= 0.0) { list.Add("clan army still active at zero cohesion"); } Clan clan = state.Clans.Get(clanArmy.OwnerClanId); Party party = state.Parties.Get(clanArmy.LeaderPartyId); if (string.IsNullOrEmpty(clanArmy.Id) || clanArmy.OwnerClanId != state.PlayerClanId || clan == null || clan.IsBandit || clanArmy.LeaderPartyId != state.PlayerPartyId || party == null || party.Kind != PartyKind.Player || party.ClanId != clanArmy.OwnerClanId) { list.Add("clan army has a bad commander id"); } if (clanArmy.Members.Count < 1 || clanArmy.Members.Count > 5 || clanArmy.Members.Count((ClanArmyMember clanArmyMember) => clanArmyMember != null && !clanArmyMember.KingdomCall) > 2 || clanArmy.Members.Count((ClanArmyMember clanArmyMember) => clanArmyMember?.KingdomCall ?? false) > 3) { list.Add("clan army has an invalid member count"); } HashSet hashSet = new HashSet(StringComparer.Ordinal); foreach (ClanArmyMember member in clanArmy.Members) { if (member == null) { list.Add("clan army has a null member"); continue; } if (string.IsNullOrEmpty(member.PartyId) || member.PartyId == clanArmy.LeaderPartyId || !hashSet.Add(member.PartyId)) { list.Add("clan army has duplicate or missing membership"); } if (!Enum.IsDefined(typeof(MilitaryPartyDirective), member.PreviousDirective)) { list.Add("clan army has an invalid previous directive"); } Party party2 = state.Parties.Get(member.PartyId); MilitaryPartyState militaryPartyState = state.MilitaryParties?.FirstOrDefault((MilitaryPartyState candidate) => candidate != null && candidate.PartyId == member.PartyId); if (member.KingdomCall) { Clan clan2 = state.Clans.Get(member.OwnerClanId); Hero hero = state.Heroes.Get(member.LeaderHeroId); if (party2 == null || party2.Kind != PartyKind.Lord || party2.ClanId != member.OwnerClanId || clan2 == null || clan2.IsBandit || clan2.IsPlayerClan || clan2.Id == state.PlayerClanId || hero == null || hero.ClanId != member.OwnerClanId || state.Kingdoms.Get(member.KingdomId) == null || militaryPartyState != null) { list.Add("clan army has a bad kingdom party id"); } if (member.CalledDay < 0 || member.CalledDay > state.Clock.Day || member.CalledDay > 9223372036854775800L || member.EndsDay != member.CalledDay + 7 || member.LastSupportDay < member.CalledDay || member.LastSupportDay > state.Clock.Day) { list.Add("clan army has bad kingdom service dates"); } continue; } if (!string.IsNullOrEmpty(member.OwnerClanId) || !string.IsNullOrEmpty(member.LeaderHeroId) || !string.IsNullOrEmpty(member.KingdomId) || member.CalledDay != -1 || member.EndsDay != -1 || member.LastSupportDay != -1) { list.Add("clan army's own party has kingdom service terms on it"); } if (party2 == null || party2.Kind != PartyKind.Lord || party2.ClanId != clanArmy.OwnerClanId || militaryPartyState == null || militaryPartyState.OwnerClanId != clanArmy.OwnerClanId) { list.Add("clan army member has no military party"); } if (militaryPartyState != null && militaryPartyState.IsActive && militaryPartyState.Directive != MilitaryPartyDirective.Follow) { list.Add("clan army member is still on its own orders"); } } return list; } } public sealed class DeveloperFieldSetup { public bool Defend; public FieldSite Site = new FieldSite { Seed = 1, Relief = 0.3, Trees = 0.35, Rocks = 0.2, Road = true, Hill = true, HillSide = 1 }; public DeveloperSiegeSide Player = new DeveloperSiegeSide(); public DeveloperSiegeSide Enemy = new DeveloperSiegeSide(); public DeveloperFieldSetup Copy() { return new DeveloperFieldSetup { Defend = Defend, Site = Site.Copy(), Player = Player.Copy(), Enemy = Enemy.Copy() }; } } public static class DeveloperFieldScenario { public static readonly string[] Grounds = new string[5] { "grass", "snow", "sand", "swamp", "ash" }; public static readonly string[] Flavors = new string[5] { "", "golden", "autumn", "sakura", "volcanic" }; public static readonly TerrainType[] MapGrounds = new TerrainType[10] { TerrainType.Plains, TerrainType.Forest, TerrainType.Hills, TerrainType.River, TerrainType.Bridge, TerrainType.Road, TerrainType.Snow, TerrainType.Desert, TerrainType.Swamp, TerrainType.Beach }; private static TabsBannerlord.Core.Campaign.Campaign _mapCampaign; private static int _mapSeed = -1; public static DeveloperFieldSetup DefaultSetup(ContentDatabase content, int troopsPerSide) { return new DeveloperFieldSetup { Player = new DeveloperSiegeSide { ClanId = "clan.continent.medieval.wardens", Troops = DeveloperSiegeScenario.FactionMix(content, "medieval", troopsPerSide, 1) }, Enemy = new DeveloperSiegeSide { ClanId = "clan.continent.viking.wardens", Troops = DeveloperSiegeScenario.FactionMix(content, "viking", troopsPerSide, 1) } }; } public static string SetupReason(ContentDatabase content, DeveloperFieldSetup setup) { if (content == null) { return "Campaign content is unavailable."; } if (setup?.Site == null || setup.Player == null || setup.Enemy == null) { return "Choose the battlefield and both sides."; } BattleMapDef battleMapDef = content.BattleMaps.Get("map.bannerlord_field_v1"); if (battleMapDef == null || battleMapDef.ContentVersion != 1) { return "The open-field battlefield is missing from the battle-map content."; } if (content.Scenarios.Get("scenario.continent") == null) { return "The continent scenario is unavailable."; } if (!Grounds.Contains(setup.Site.Ground ?? "")) { return "Unknown ground " + setup.Site.Ground + "."; } if (!Flavors.Contains(setup.Site.Flavor ?? "")) { return "Unknown region colours " + setup.Site.Flavor + "."; } List source = DeveloperSiegeScenario.Clans(content); if (setup.Player.ClanId == setup.Enemy.ClanId) { return "Choose two different clans."; } DeveloperSiegeSide[] array = new DeveloperSiegeSide[2] { setup.Player, setup.Enemy }; foreach (DeveloperSiegeSide side in array) { string text = ((side == setup.Player) ? "your side" : "the enemy side"); if (source.All((ClanStartDef c) => c.Id != side.ClanId)) { return "Choose a clan for " + text + "."; } if (side.Troops == null || side.Troops.Count == 0 || side.Total <= 0) { return "Give " + text + " at least one troop."; } if (side.Total > 200) { return "A side can have at most " + 200 + " troops."; } foreach (KeyValuePair troop in side.Troops) { if (troop.Value < 0) { return "Troop counts cannot be negative."; } UnitDef unitDef = content.Units.Get(troop.Key ?? ""); if (unitDef == null) { return "Unknown unit " + troop.Key + "."; } if (string.IsNullOrEmpty(unitDef.TabsUnitId)) { return unitDef.Name + " has no TABS unit to fight with."; } } } return ""; } public static FieldSite RandomSite(int seed) { RandomStream randomStream = new RandomStream("dev.field", (ulong)(Math.Abs((long)seed) + 1)); FieldSite fieldSite = new FieldSite { Seed = randomStream.Range(0, 100000), Ground = Grounds[randomStream.Range(0, Grounds.Length)], Flavor = (randomStream.Chance(0.4) ? Flavors[randomStream.Range(1, Flavors.Length)] : ""), Relief = Math.Round(randomStream.NextDouble(), 1), Trees = Math.Round(randomStream.NextDouble(), 1), Rocks = Math.Round(randomStream.NextDouble() * 0.8, 1), River = randomStream.Chance(0.35), Road = randomStream.Chance(0.5), Coast = randomStream.Chance(0.2), Hill = randomStream.Chance(0.45), Ruins = randomStream.Chance(0.25), HillSide = randomStream.Range(-1, 2), CoastSide = ((!randomStream.Chance(0.5)) ? 1 : (-1)) }; if (fieldSite.River) { fieldSite.Bridge = randomStream.Chance(0.6); fieldSite.Ford = !fieldSite.Bridge || randomStream.Chance(0.5); } if (randomStream.Chance(0.2)) { fieldSite.Village = true; } else if (randomStream.Chance(0.15)) { fieldSite.Camp = true; } if (fieldSite.Flavor == "volcanic") { fieldSite.Ground = "ash"; } if (fieldSite.Ground == "sand") { fieldSite.River = false; } return fieldSite.Normalized(); } public static FieldSite SiteFromMap(ContentDatabase content, TerrainType ground, int seed, EncounterKind kind = EncounterKind.FieldBattle) { if (content == null) { throw new ArgumentNullException("content"); } int num = Math.Abs(seed % 50) + 1; if (_mapCampaign == null || _mapSeed != num || _mapCampaign.Content != content) { _mapCampaign = CampaignFactory.Create(content, new NewCampaignOptions { ScenarioId = "scenario.continent", StartId = "start.warband", Seed = (ulong)num, PlayerName = "Surveyor", CampaignId = "dev-field-survey" }); _mapSeed = num; } NavGrid nav = _mapCampaign.Nav; List list = new List(); for (int i = 2; i < nav.Height - 2; i++) { for (int j = 2; j < nav.Width - 2; j++) { TerrainDef terrainDef = nav.Cell(j, i); if (terrainDef.Type == ground && (terrainDef.Passable || ground == TerrainType.River)) { list.Add(nav.CellCenter(j, i)); } } } if (list.Count == 0) { for (int k = 2; k < nav.Height - 2; k++) { for (int l = 2; l < nav.Width - 2; l++) { if (nav.Cell(l, k).Passable) { list.Add(nav.CellCenter(l, k)); } } } } RandomStream randomStream = new RandomStream("dev.field.map", (ulong)(Math.Abs((long)seed) + 7)); Vec2 vec = list[randomStream.Range(0, list.Count)]; return FieldBattlefield.Plan(_mapCampaign, new Encounter { Id = "dev.field." + seed, Kind = kind, Position = vec, Biome = nav.TerrainAt(vec).Biome }).Normalized(); } public static TabsBannerlord.Core.Campaign.Campaign Create(ContentDatabase content, DeveloperFieldSetup setup) { if (content == null) { throw new ArgumentNullException("content"); } string text = SetupReason(content, setup); if (text.Length > 0) { throw new ArgumentException(text, "setup"); } ScenarioDef scenarioDef = content.Scenarios.Require("scenario.continent"); ClanStartDef ours = scenarioDef.Clans.First((ClanStartDef clanStartDef) => clanStartDef.Id == setup.Player.ClanId); ClanStartDef theirs = scenarioDef.Clans.First((ClanStartDef clanStartDef) => clanStartDef.Id == setup.Enemy.ClanId); string startId = (scenarioDef.PlayerStarts.Any((PlayerStartDef s) => s.Id == "start." + ours.Culture && s.Kind == StartKind.SmallWarband && string.IsNullOrEmpty(s.Kingdom)) ? ("start." + ours.Culture) : "start.warband"); TabsBannerlord.Core.Campaign.Campaign campaign = CampaignFactory.Create(content, new NewCampaignOptions { DeveloperTools = true, ScenarioId = scenarioDef.Id, StartId = startId, Seed = (ulong)Math.Max(1, setup.Site.Seed % 1000 + 1), PlayerName = "Field Tester", ClanName = ours.Name + " (test)", PlayerCulture = ours.Culture, CampaignId = "dev-field-" + Guid.NewGuid().ToString("N"), Settings = new CampaignSettings { ActiveUnitBudget = 150, FullInformation = true, HeroesCanDie = false } }); CampaignState state = campaign.State; Clan playerClan = state.PlayerClan; playerClan.Color = ours.Color; playerClan.Symbol = ours.Symbol; playerClan.CultureId = ours.Culture; playerClan.KingdomId = ""; playerClan.Gold = 100000L; Clan clan = state.Clans.Require(theirs.Id); state.SetStance(playerClan.Id, state.FactionOf(clan), Stance.War); Party playerParty = state.PlayerParty; Party party = state.Parties.FirstOrDefault((Party p) => p.Kind == PartyKind.Lord && p.ClanId == theirs.Id && !string.IsNullOrEmpty(p.LeaderHeroId)) ?? throw new InvalidOperationException("The enemy clan has no lord in the field."); List source = (from s in state.Settlements where s.Type != SettlementType.Hideout select s.Position).ToList(); Vec2 position = state.Settlements.First().Position; Vec2 meet = playerParty.Position; double num = -1.0; for (int num2 = 2; num2 < campaign.Nav.Height - 2; num2 += 2) { for (int num3 = 2; num3 < campaign.Nav.Width - 2; num3 += 2) { Vec2 c = campaign.Nav.CellCenter(num3, num2); if (campaign.Nav.IsPassable(c)) { double num4 = source.Min((Vec2 s) => Vec2.Distance(s, c)); if (num4 > num) { num = num4; meet = c; } } } } position = state.Settlements.OrderByDescending((Settlement s) => Vec2.Distance(s.Position, meet)).First().Position; foreach (Party item in state.Parties.Where((Party p) => string.IsNullOrEmpty(p.HideoutGuardOf))) { item.AiFrozen = true; item.State = PartyState.Active; item.CurrentSettlementId = ""; item.Position = position; item.Order = new MovementOrder(); item.Food = Math.Max(500.0, item.Food); } playerParty.Position = meet; playerParty.Morale = 100.0; party.Position = meet; party.Morale = 100.0; SetRoster(playerParty.Troops, setup.Player.Troops); SetRoster(party.Troops, setup.Enemy.Troops); state.Player.Activity = PlayerActivity.Idle; state.Player.MenuSettlementId = ""; campaign.FieldSiteOverride = setup.Site.Normalized(); if ((setup.Defend ? campaign.StartEncounter(party, playerParty) : campaign.StartEncounter(playerParty, party)).AllParties.Count() != 2) { throw new InvalidOperationException("Other parties joined the battlefield test."); } campaign.UpdatePlayerTimeStates(); List list = InvariantChecker.Check(campaign); if (list.Count > 0) { throw new InvalidOperationException("Invalid battlefield test: " + string.Join("; ", list.Take(3))); } return campaign; } private static void SetRoster(TroopRoster roster, IDictionary troops) { roster.Stacks.Clear(); foreach (KeyValuePair troop in troops) { if (troop.Value > 0) { roster.Add(troop.Key, troop.Value); } } } } public sealed class DeveloperSiegeSide { public string ClanId = ""; public SortedDictionary Troops = new SortedDictionary(StringComparer.Ordinal); public int Total => Troops?.Values.Where((int n) => n > 0).Sum() ?? 0; public DeveloperSiegeSide Copy() { return new DeveloperSiegeSide { ClanId = ClanId, Troops = new SortedDictionary(Troops ?? new SortedDictionary(StringComparer.Ordinal), StringComparer.Ordinal) }; } } public sealed class DeveloperSiegeSetup { public bool Defend; public bool CampOnly; public int Seed = 771; public DeveloperSiegeSide Player = new DeveloperSiegeSide(); public DeveloperSiegeSide Enemy = new DeveloperSiegeSide(); public DeveloperSiegeSetup Copy() { return new DeveloperSiegeSetup { Defend = Defend, CampOnly = CampOnly, Seed = Seed, Player = Player.Copy(), Enemy = Enemy.Copy() }; } } public static class DeveloperSiegeScenario { public const int MaximumTroopsPerSide = 200; public static List Clans(ContentDatabase content) { ScenarioDef scenarioDef = content?.Scenarios.Get("scenario.continent"); if (scenarioDef != null) { return scenarioDef.Clans.Where((ClanStartDef c) => !c.IsBandit).ToList(); } return new List(); } public static string FortressOf(ContentDatabase content, string clanId) { ClanStartDef clan = Clans(content).FirstOrDefault((ClanStartDef c) => c.Id == clanId); if (clan == null) { return ""; } List source = content.World("world.continent").Locations.Where((LocationDef l) => clan.Settlements.Contains(l.Id)).ToList(); return (source.FirstOrDefault((LocationDef l) => l.Type == SettlementType.Castle) ?? source.FirstOrDefault((LocationDef l) => l.Type == SettlementType.Town))?.Id ?? ""; } public static SortedDictionary FactionMix(ContentDatabase content, string cultureId, int combatants, int commanders = 0) { SortedDictionary sortedDictionary = new SortedDictionary(StringComparer.Ordinal); if (content == null || combatants - commanders <= 0) { return sortedDictionary; } List foot = content.Units.Where((UnitDef u) => u.Culture == cultureId && !u.Mounted && u.Slots == 1 && !string.IsNullOrEmpty(u.TabsUnitId)).ToList(); Func obj = (TroopRole role) => (from u in foot where u.Role == role orderby Math.Abs(u.Tier - 2), u.Tier select u).ThenBy((UnitDef u) => u.Id, StringComparer.Ordinal).FirstOrDefault(); UnitDef unitDef = obj(TroopRole.Infantry); UnitDef unitDef2 = obj(TroopRole.Ranged); if (unitDef == null || unitDef.Tier >= 4) { unitDef = content.Units.Get(content.Cultures.Get(cultureId)?.BasicTroop ?? "") ?? unitDef; } if (unitDef == null) { return sortedDictionary; } int num = combatants - commanders; int num2 = ((unitDef2 != null && !(unitDef2.Id == unitDef.Id)) ? Math.Min(num, combatants / 4) : 0); if (num - num2 > 0) { sortedDictionary[unitDef.Id] = num - num2; } if (num2 > 0) { sortedDictionary[unitDef2.Id] = num2; } return sortedDictionary; } public static string SetupReason(ContentDatabase content, DeveloperSiegeSetup setup) { if (content == null) { return "Campaign content is unavailable."; } if (setup?.Player == null || setup.Enemy == null) { return "Choose both sides of the siege test."; } if (content.Scenarios.Get("scenario.continent") == null) { return "The continent scenario is unavailable."; } if (setup.Seed < 0) { return "The test seed cannot be negative."; } if (setup.CampOnly && setup.Defend) { return "Construction tests use the attacking camp."; } List source = Clans(content); DeveloperSiegeSide[] array = new DeveloperSiegeSide[2] { setup.Player, setup.Enemy }; foreach (DeveloperSiegeSide side in array) { string text = ((side == setup.Player) ? "your side" : "the enemy side"); if (source.All((ClanStartDef c) => c.Id != side.ClanId)) { return "Choose a clan for " + text + "."; } if (side.Troops == null || side.Troops.Count == 0 || side.Total <= 0) { return "Give " + text + " at least one troop."; } if (side.Total > 200) { return "A side can have at most " + 200 + " troops."; } foreach (KeyValuePair troop in side.Troops) { if (troop.Value < 0) { return "Troop counts cannot be negative."; } UnitDef unitDef = content.Units.Get(troop.Key ?? ""); if (unitDef == null) { return "Unknown unit " + troop.Key + "."; } if (string.IsNullOrEmpty(unitDef.TabsUnitId)) { return unitDef.Name + " has no TABS unit to fight with."; } } } if (FortressOf(content, setup.Defend ? setup.Player.ClanId : setup.Enemy.ClanId).Length == 0) { return "That clan holds no fortress."; } return ""; } public static TabsBannerlord.Core.Campaign.Campaign Create(ContentDatabase content, bool defend, int troopsPerSide, int seed = 771, bool campOnly = false) { if (content == null) { throw new ArgumentNullException("content"); } if (troopsPerSide != 20 && troopsPerSide != 50 && troopsPerSide != 100) { throw new ArgumentOutOfRangeException("troopsPerSide", "Choose 20, 50 or 100 combatants per side."); } if (seed < 0) { throw new ArgumentOutOfRangeException("seed"); } if (campOnly && defend) { throw new ArgumentException("Construction tests use the attacking camp.", "defend"); } return Create(content, DefaultSetup(content, defend, troopsPerSide, seed, campOnly)); } public static DeveloperSiegeSetup DefaultSetup(ContentDatabase content, bool defend, int troopsPerSide, int seed = 771, bool campOnly = false) { return new DeveloperSiegeSetup { Defend = defend, CampOnly = campOnly, Seed = seed, Player = new DeveloperSiegeSide { ClanId = "clan.continent.medieval.wardens", Troops = FactionMix(content, "medieval", troopsPerSide, 1) }, Enemy = new DeveloperSiegeSide { ClanId = "clan.continent.viking.wardens", Troops = FactionMix(content, "viking", troopsPerSide, defend ? 1 : 0) } }; } public static TabsBannerlord.Core.Campaign.Campaign Create(ContentDatabase content, DeveloperSiegeSetup setup) { if (content == null) { throw new ArgumentNullException("content"); } string text = SetupReason(content, setup); if (text.Length > 0) { throw new ArgumentException(text, "setup"); } ScenarioDef scenarioDef = content.Scenarios.Require("scenario.continent"); ClanStartDef ours = scenarioDef.Clans.First((ClanStartDef c) => c.Id == setup.Player.ClanId); ClanStartDef theirs = scenarioDef.Clans.First((ClanStartDef c) => c.Id == setup.Enemy.ClanId); string startId = (scenarioDef.PlayerStarts.Any((PlayerStartDef s) => s.Id == "start." + ours.Culture && s.Kind == StartKind.SmallWarband && string.IsNullOrEmpty(s.Kingdom)) ? ("start." + ours.Culture) : "start.warband"); TabsBannerlord.Core.Campaign.Campaign campaign = CampaignFactory.Create(content, new NewCampaignOptions { DeveloperTools = true, ScenarioId = scenarioDef.Id, StartId = startId, Seed = (ulong)setup.Seed, PlayerName = "Siege Tester", ClanName = ours.Name + " (test)", PlayerCulture = ours.Culture, CampaignId = "dev-siege-" + Guid.NewGuid().ToString("N"), Settings = new CampaignSettings { ActiveUnitBudget = 150, FullInformation = true, HeroesCanDie = false } }); CampaignState state = campaign.State; Clan playerClan = state.PlayerClan; playerClan.Color = ours.Color; playerClan.Symbol = ours.Symbol; playerClan.CultureId = ours.Culture; playerClan.KingdomId = ""; Clan clan = state.Clans.Require(theirs.Id); state.SetStance(playerClan.Id, state.FactionOf(clan), Stance.War); Settlement fort = state.Settlements.Require(FortressOf(content, setup.Defend ? ours.Id : theirs.Id)); Party playerParty = state.PlayerParty; Party party = (setup.Defend ? state.Parties.First((Party p) => p.Kind == PartyKind.Lord && p.ClanId == theirs.Id) : null); Settlement settlement = state.Settlements.OrderByDescending((Settlement s) => Vec2.Distance(s.Position, fort.Position)).First(); if (Vec2.Distance(settlement.Position, fort.Position) <= campaign.Rules.JoinBattleRadius) { throw new InvalidOperationException("The siege test needs a location outside the reinforcement radius."); } foreach (Party item in state.Parties.Where((Party p) => string.IsNullOrEmpty(p.HideoutGuardOf))) { item.AiFrozen = true; item.State = PartyState.Active; item.CurrentSettlementId = ""; item.Position = settlement.Position; item.Order = new MovementOrder(); item.Food = Math.Max(500.0, item.Food); } playerParty.Position = fort.Position; playerParty.Morale = 100.0; playerClan.Gold = 100000L; if (setup.Defend) { foreach (Settlement item2 in state.Settlements.Where((Settlement s) => s.Id == fort.Id || (s.Type == SettlementType.Village && s.BoundTo == fort.Id))) { item2.OwnerClanId = playerClan.Id; } } fort.Garrison = new TroopRoster(); fort.Militia = 0; fort.WoundedMilitia = 0; campaign.SetSettlementFood(fort, 500.0); if (setup.Defend) { int total = setup.Player.Total; KeyValuePair, SortedDictionary> keyValuePair = Split(setup.Player.Troops, (total + 1) / 2); SetRoster(fort.Garrison, keyValuePair.Key); SetRoster(playerParty.Troops, keyValuePair.Value); SetRoster(party.Troops, setup.Enemy.Troops); party.Position = fort.Position; playerParty.State = PartyState.InSettlement; playerParty.CurrentSettlementId = fort.Id; } else { SetRoster(playerParty.Troops, setup.Player.Troops); SetRoster(fort.Garrison, setup.Enemy.Troops); } CommandResult commandResult = campaign.OrderSiege(setup.Defend ? party : playerParty, fort); if (!commandResult.Ok) { throw new InvalidOperationException(commandResult.Message); } campaign.UpdateSieges(); state.Clock.Minute += 360L; state.Clock.NextHourMinute = (state.Clock.Minute / 60 + 1) * 60; state.Clock.NextDayMinute = (state.Clock.Minute / 1440 + 1) * 1440; campaign.UpdateSieges(); SiegeState siegeState = campaign.SiegeForSettlement(fort.Id); siegeState.NoKeepBattle = true; if (setup.CampOnly) { campaign.UpdatePlayerTimeStates(); List list = InvariantChecker.Check(campaign); if (list.Count > 0) { throw new InvalidOperationException("Invalid siege camp test: " + string.Join("; ", list)); } return campaign; } siegeState.Works.LeftWallHealth = 0.0; int[] array = new int[2] { 5, 6 }; foreach (int num2 in array) { SiegeEngineState siegeEngineState = siegeState.Works.Attackers[num2]; siegeEngineState.Kind = ((num2 == 6) ? SiegeEngineKind.BatteringRam : SiegeEngineKind.SiegeTower); siegeEngineState.BuildProgress = SiegeWorksRules.BuildMinutes(siegeEngineState.Kind); siegeEngineState.Health = siegeEngineState.MaxHealth; } CommandResult commandResult2 = campaign.BeginSiegeAssault(siegeState); if (!commandResult2.Ok) { throw new InvalidOperationException(commandResult2.Message); } campaign.UpdatePlayerTimeStates(); List list2 = InvariantChecker.Check(campaign); if (list2.Count > 0) { throw new InvalidOperationException("Invalid siege test: " + string.Join("; ", list2)); } return campaign; } private static void SetRoster(TroopRoster roster, IDictionary troops) { roster.Stacks.Clear(); foreach (KeyValuePair troop in troops) { if (troop.Value > 0) { roster.Add(troop.Key, troop.Value); } } } private static KeyValuePair, SortedDictionary> Split(IDictionary troops, int first) { SortedDictionary sortedDictionary = new SortedDictionary(StringComparer.Ordinal); SortedDictionary sortedDictionary2 = new SortedDictionary(StringComparer.Ordinal); int num = troops.Values.Where((int n) => n > 0).Sum(); int num2 = 0; int num3 = 0; foreach (KeyValuePair item in troops.Where((KeyValuePair e) => e.Value > 0)) { num3 += item.Value; int val = ((num != 0) ? ((int)Math.Round((double)first * (double)num3 / (double)num) - num2) : 0); val = Math.Max(0, Math.Min(item.Value, val)); num2 += val; if (val > 0) { sortedDictionary[item.Key] = val; } if (item.Value - val > 0) { sortedDictionary2[item.Key] = item.Value - val; } } return new KeyValuePair, SortedDictionary>(sortedDictionary, sortedDictionary2); } } public static class DiplomacyValidation { public static List Check(CampaignState state) { List list = new List(); HashSet hashSet = new HashSet(StringComparer.Ordinal); if (state.Stances == null) { list.Add("diplomacy has no relation list"); } else { foreach (StanceRecord stance in state.Stances) { if (stance == null) { list.Add("diplomacy contains an empty relation"); continue; } if (!Known(stance.A) || !Known(stance.B) || string.CompareOrdinal(stance.A, stance.B) >= 0) { list.Add("diplomacy relation has invalid faction identities"); } if (!hashSet.Add(stance.A + "\n" + stance.B)) { list.Add("diplomacy contains duplicate relations"); } if (!Enum.IsDefined(typeof(Stance), stance.Stance) || stance.SinceMinute < 0 || stance.SinceMinute > state.Clock.Minute) { list.Add("diplomacy relation has an invalid stance or clock"); } } } DiplomacyState diplomacy = state.Diplomacy; if (diplomacy == null) { return list; } if (!diplomacy.Initialized) { if (diplomacy.LastAiDay == -1) { List truces = diplomacy.Truces; if (truces == null || truces.Count == 0) { goto IL_0180; } } list.Add("diplomacy was never set up but has data in it"); goto IL_0180; } if (diplomacy.LastAiDay < 0 || diplomacy.LastAiDay > state.Clock.Day) { list.Add("diplomacy has an invalid evaluation day"); } if (diplomacy.Truces == null) { list.Add("diplomacy has no truce list"); return list; } hashSet.Clear(); foreach (DiplomaticTruce truce in diplomacy.Truces) { if (truce == null) { list.Add("diplomacy contains an empty truce"); continue; } if (Known(truce.A) && Known(truce.B) && string.CompareOrdinal(truce.A, truce.B) < 0) { Clan clan = state.Clans.Get(truce.A); if (clan == null || !clan.IsBandit) { Clan clan2 = state.Clans.Get(truce.B); if (clan2 == null || !clan2.IsBandit) { goto IL_02b6; } } } list.Add("truce has invalid faction identities"); goto IL_02b6; IL_02b6: if (!hashSet.Add(truce.A + "\n" + truce.B)) { list.Add("diplomacy contains duplicate truces"); } if (truce.SignedDay < 0 || truce.SignedDay > state.Clock.Day || truce.SignedDay > 9223372036854775800L || truce.EndsDay != truce.SignedDay + 7) { list.Add("truce has invalid dates"); } if (truce.Payment == 0L) { if (!string.IsNullOrEmpty(truce.PayerClanId) || !string.IsNullOrEmpty(truce.RecipientClanId)) { list.Add("truce paid nobody but names a recipient"); } } else if (truce.Payment != 1000 || truce.PayerClanId == truce.RecipientClanId || !state.Clans.Contains(truce.PayerClanId) || !state.Clans.Contains(truce.RecipientClanId)) { list.Add("truce has an invalid payment record"); } if (state.Stances != null && truce.EndsDay > state.Clock.Day && state.Stances.Exists((StanceRecord s) => s != null && s.Stance == Stance.War && ((s.A == truce.A && s.B == truce.B) || (s.A == truce.B && s.B == truce.A)))) { list.Add("truce and war at the same time"); } } HashSet hashSet2 = new HashSet(StringComparer.Ordinal); foreach (DiplomaticAgreement item in diplomacy.Agreements ?? new List()) { if (item == null) { list.Add("diplomacy contains an empty agreement"); continue; } if (string.IsNullOrEmpty(item.Id) || !hashSet2.Add(item.Id)) { list.Add("diplomatic agreement has a missing or duplicate id"); } if (!Enum.IsDefined(typeof(AgreementKind), item.Kind) || (!state.Kingdoms.Contains(item.A) && !state.Clans.Contains(item.A)) || (!state.Kingdoms.Contains(item.B) && !state.Clans.Contains(item.B)) || string.CompareOrdinal(item.A, item.B) >= 0) { list.Add("diplomatic agreement " + item.Id + " has invalid parties"); } if (item.SignedDay < 0 || item.SignedDay > state.Clock.Day || item.EndsDay <= item.SignedDay) { list.Add("diplomatic agreement " + item.Id + " has invalid dates"); } bool flag = item.Kind == AgreementKind.Tribute; if (flag != item.DailyAmount > 0 || (flag && (item.PayerFactionId == item.RecipientFactionId || ((!(item.PayerFactionId == item.A) || !(item.RecipientFactionId == item.B)) && (!(item.PayerFactionId == item.B) || !(item.RecipientFactionId == item.A))))) || (!flag && (item.PayerFactionId.Length > 0 || item.RecipientFactionId.Length > 0)) || item.PaidTotal < 0 || item.MissedDays < 0) { list.Add("diplomatic agreement " + item.Id + " has invalid terms"); } if (item.Kind == AgreementKind.Alliance && item.EndsDay > state.Clock.Day && state.AtWar(item.A, item.B)) { list.Add("allies " + item.A + " and " + item.B + " are at war"); } } hashSet2.Clear(); foreach (CallToWarRequest item2 in diplomacy.Calls ?? new List()) { if (item2 == null) { list.Add("diplomacy contains an empty call to war"); } else if (string.IsNullOrEmpty(item2.Id) || !hashSet2.Add(item2.Id) || !Enum.IsDefined(typeof(CallToWarStatus), item2.Status) || item2.Payment < 0 || item2.CreatedDay > state.Clock.Day || item2.ExpiresDay < item2.CreatedDay || item2.Status == CallToWarStatus.Pending != item2.AnsweredDay < 0 || item2.CallerFactionId == item2.AllyFactionId || item2.AllyFactionId == item2.EnemyFactionId) { list.Add("call to war " + item2.Id + " is invalid"); } } foreach (string item3 in diplomacy.PendingElections ?? new List()) { if (!state.Kingdoms.Contains(item3)) { list.Add("an election is pending in an unknown kingdom"); } } return list; IL_0180: return list; bool Known(string id) { if (!string.IsNullOrEmpty(id)) { if (!state.Kingdoms.Contains(id)) { return state.Clans.Contains(id); } return true; } return false; } } } public static class EquipmentValidation { public static List Check(CampaignState state, ContentDatabase content = null) { List list = new List(); if (state == null) { return list; } CheckWardrobe(state, list); Dictionary craftedOwners = new Dictionary(StringComparer.Ordinal); if (state.Heroes != null) { foreach (Hero hero in state.Heroes) { if (hero?.Loadout == null) { continue; } CheckLoadout(state, hero.Loadout, "hero " + hero.Id, list); if (hero.State != HeroState.Dead) { foreach (string item in hero.Loadout.SlotItems()) { Own(item, 1); } } if (content != null) { string shieldId = hero.Loadout.ShieldId; if (shieldId != null && shieldId.Length > 0 && !TabsBannerlord.Core.Campaign.Campaign.SupportsWardrobe(content.Units.Get(hero.UnitId))) { list.Add("hero " + hero.Id + " carries a forged shield on an unsupported archetype"); } } bool flag = !string.IsNullOrEmpty(hero.Loadout.WeaponId) || !string.IsNullOrEmpty(hero.Loadout.OutfitId); if (content != null && flag && !EquipmentCatalog.SupportsArchetype(content.Units.Get(hero.UnitId))) { list.Add("hero " + hero.Id + " has equipment on an unsupported archetype"); } if (content != null && WearsClothing(hero.Loadout) && !TabsBannerlord.Core.Campaign.Campaign.SupportsWardrobe(content.Units.Get(hero.UnitId))) { list.Add("hero " + hero.Id + " has clothing on an unsupported archetype"); } TroopRole? troopRole = ((content == null) ? ((TroopRole?)null) : WeaponRole(state, content, hero.Loadout.WeaponId)); if (troopRole.HasValue && troopRole != content.Units.Get(hero.UnitId)?.Role) { list.Add("hero " + hero.Id + " has a weapon incompatible with its combat role"); } } } if (state.Parties != null) { foreach (Party party in state.Parties) { if (party == null) { continue; } CheckInventory(state, party.Equipment, "party " + party.Id, list); foreach (KeyValuePair item2 in party.Equipment ?? new SortedDictionary(StringComparer.Ordinal)) { Own(item2.Key, item2.Value); } } } foreach (KeyValuePair item3 in craftedOwners) { if (item3.Value > 1) { list.Add("forged weapon " + item3.Key + " is held in more than one place"); } } if (state.Settlements != null) { foreach (Settlement settlement in state.Settlements) { if (settlement?.Market == null) { continue; } MarketState market = settlement.Market; CheckInventory(state, market.EquipmentStock, "equipment market " + settlement.Id, list); if (market.EquipmentStock != null && market.EquipmentStock.Keys.Any((string id) => !IsShoppable(state, id))) { list.Add("equipment market " + settlement.Id + " stocks an item outfitters do not sell"); } if (market.EquipmentInitialized && market.EquipmentStock == null) { list.Add("equipment market " + settlement.Id + " has bad setup flags"); } if (!market.EquipmentInitialized) { SortedDictionary equipmentStock = market.EquipmentStock; if (equipmentStock != null && equipmentStock.Count > 0) { list.Add("equipment market " + settlement.Id + " has stock but was never set up"); } } if (market.ClothingInitialized && !market.EquipmentInitialized) { list.Add("equipment market " + settlement.Id + " has clothing without an outfitter"); } } } if (state.Encounters != null) { foreach (Encounter encounter in state.Encounters) { if (encounter?.Manifest?.Combatants == null) { continue; } foreach (Combatant combatant in encounter.Manifest.Combatants) { if (combatant == null || (combatant.Loadout == null && combatant.EquipmentStats == null)) { continue; } string text = "encounter " + encounter.Id + " combatant " + combatant.Id; if (!combatant.IsHero) { list.Add(text + " assigns hero equipment to an ordinary troop"); } if (combatant.Loadout == null || combatant.EquipmentStats == null) { list.Add(text + " has an incomplete equipment record"); } CheckLoadout(state, combatant.Loadout, text, list); EquipmentCombatStats equipmentStats = combatant.EquipmentStats; if (equipmentStats != null && (!Positive(equipmentStats.Attack) || !Positive(equipmentStats.Defense) || !Positive(equipmentStats.Health) || !Finite(equipmentStats.Ranged) || equipmentStats.Ranged < 0.0 || !Enum.IsDefined(typeof(TroopRole), equipmentStats.Role))) { list.Add(text + " has invalid equipment battle ratings"); } if (content == null || combatant.Loadout == null || equipmentStats == null) { continue; } UnitDef unitDef = content.Units.Get(combatant.UnitId); EquipmentDef equipmentDef = EquipmentCatalog.Find(combatant.Loadout.WeaponId); CraftedWeaponState craftedWeaponState = Crafted(state, combatant.Loadout.WeaponId); if ((!string.IsNullOrEmpty(combatant.Loadout.WeaponId) || !string.IsNullOrEmpty(combatant.Loadout.OutfitId)) && !EquipmentCatalog.SupportsArchetype(unitDef)) { list.Add(text + " has equipment on an unsupported archetype"); } if (WearsClothing(combatant.Loadout) && !TabsBannerlord.Core.Campaign.Campaign.SupportsWardrobe(unitDef)) { list.Add(text + " has clothing on an unsupported archetype"); } TroopRole? troopRole2 = WeaponRole(state, content, combatant.Loadout.WeaponId); if (unitDef != null && (equipmentStats.Role != unitDef.Role || combatant.Role != equipmentStats.Role || (troopRole2.HasValue && troopRole2 != unitDef.Role))) { list.Add(text + " has incompatible equipment combat roles"); } if (unitDef != null && !(state.Content?.Hash != content.Manifest.Hash)) { EquipmentCombatStats equipmentCombatStats = TabsBannerlord.Core.Campaign.Campaign.LoadoutCombatStats(state, (string id) => content.Units.Get(id), unitDef, combatant.Loadout); if ((craftedWeaponState != null || equipmentDef == null || content.Units.Get(equipmentDef.SourceUnitId) != null) && (!Same(equipmentStats.Attack, equipmentCombatStats.Attack) || !Same(equipmentStats.Defense, equipmentCombatStats.Defense) || !Same(equipmentStats.Health, equipmentCombatStats.Health) || !Same(equipmentStats.Ranged, equipmentCombatStats.Ranged))) { list.Add(text + " has equipment ratings that don't match its loadout"); } } } } } return list; void Own(string id, int count) { if (Smithing.IsCraftedId(id)) { craftedOwners[id] = (craftedOwners.TryGetValue(id, out var value) ? value : 0) + count; } } } private static bool WearsClothing(HeroEquipmentState loadout) { if ((loadout?.Clothing?.Count).GetValueOrDefault() <= 0) { return Math.Abs((loadout?.Size ?? 1.0) - 1.0) > 1E-09; } return true; } private static CraftedWeaponState Crafted(CampaignState state, string id) { if (!Smithing.IsCraftedId(id) || state?.Smithing?.Weapons == null || !state.Smithing.Weapons.TryGetValue(id, out var value)) { return null; } return value; } private static TroopRole? WeaponRole(CampaignState state, ContentDatabase content, string id) { CraftedWeaponState craftedWeaponState = Crafted(state, id); if (craftedWeaponState != null && Enum.IsDefined(typeof(WeaponClass), craftedWeaponState.Class)) { return Smithing.ClassDef(craftedWeaponState.Class).Role; } EquipmentDef equipmentDef = EquipmentCatalog.Find(id); if (equipmentDef == null || equipmentDef.Slot != EquipmentSlot.Weapon) { return null; } return content.Units.Get(equipmentDef.SourceUnitId)?.Role; } private static bool IsShoppable(CampaignState state, string id) { return OwnedItems.Resolve(state, id)?.Shoppable ?? true; } private static bool Finite(double value) { if (!double.IsNaN(value)) { return !double.IsInfinity(value); } return false; } private static bool Positive(double value) { if (Finite(value)) { return value > 0.0; } return false; } private static bool Same(double left, double right) { if (Finite(left) && Finite(right)) { return Math.Abs(left - right) <= 1E-09; } return false; } private static void CheckWardrobe(CampaignState state, List errors) { if (state.Wardrobe == null) { return; } foreach (KeyValuePair item in state.Wardrobe.Pieces ?? new SortedDictionary(StringComparer.Ordinal)) { ClothingPieceDef value = item.Value; if (value == null || value.Id != item.Key || !Wardrobe.IsPieceId(value.Id) || !Enum.IsDefined(typeof(ClothingSlot), value.Slot) || value.Tier < 1 || value.Tier > 5 || string.IsNullOrWhiteSpace(value.Name) || value.ColorChannels < 0 || value.ColorChannels > 12) { errors.Add("wardrobe piece " + item.Key + " is malformed"); } } foreach (KeyValuePair> item2 in state.Wardrobe.UnitPieces ?? new SortedDictionary>(StringComparer.Ordinal)) { if (item2.Value == null || item2.Value.Any((string id) => state.Wardrobe.Pieces == null || !state.Wardrobe.Pieces.ContainsKey(id ?? ""))) { errors.Add("wardrobe troop " + item2.Key + " wears an unknown piece"); } } } public static void CheckLoadout(HeroEquipmentState loadout, string label, List errors) { CheckLoadout(null, loadout, label, errors); } public static void CheckLoadout(CampaignState state, HeroEquipmentState loadout, string label, List errors) { if (loadout == null) { return; } CheckSlot(state, loadout.WeaponId, EquipmentSlot.Weapon, label, errors); CheckSlot(state, loadout.OutfitId, EquipmentSlot.Outfit, label, errors); CheckSlot(state, loadout.ShieldId, EquipmentSlot.Shield, label, errors); CheckSlot(state, loadout.AmmoId, EquipmentSlot.Ammo, label, errors); if (state != null) { CraftedWeaponState craftedWeaponState = Crafted(state, loadout.WeaponId); WeaponClassDef weaponClassDef = ((craftedWeaponState == null) ? null : Smithing.ClassDef(craftedWeaponState.Class)); if (!string.IsNullOrEmpty(loadout.ShieldId) && weaponClassDef != null && weaponClassDef.BothHands) { errors.Add(label + " carries a shield with a weapon that needs both hands"); } CraftedWeaponState craftedWeaponState2 = Crafted(state, loadout.AmmoId); if (craftedWeaponState2 != null && ((craftedWeaponState2.Class == WeaponClass.Arrows && (weaponClassDef == null || weaponClassDef.Family != WeaponFamily.Bow)) || (craftedWeaponState2.Class == WeaponClass.Bolts && (weaponClassDef == null || weaponClassDef.Family != WeaponFamily.Crossbow)))) { errors.Add(label + " carries ammunition its weapon cannot shoot"); } } if (!Wardrobe.ValidSize(loadout.Size)) { errors.Add(label + " has an invalid size"); } List list = loadout.Abilities ?? new List(); if (list.Count > 5 || list.Distinct(StringComparer.Ordinal).Count() != list.Count || list.Any((string id) => !Tournaments.IsAbilityId(id))) { errors.Add(label + " has invalid special abilities"); } foreach (KeyValuePair item in loadout.Clothing ?? new SortedDictionary(StringComparer.Ordinal)) { WornClothingState value = item.Value; if (!Wardrobe.TryParseLayerKey(item.Key, out var slot, out var layer) || value == null) { errors.Add(label + " has an invalid clothing slot " + item.Key); continue; } bool flag = !string.IsNullOrEmpty(value.PieceId); if (flag == value.Bare) { errors.Add(label + " has a clothing slot that is neither worn nor bare"); continue; } if (layer > 1 && value.Bare) { errors.Add(label + " has a bare extra clothing layer"); continue; } List list2 = value.Colors ?? new List(); if (list2.Any((int c) => c < -1 || c > 255) || list2.Count > 12 || (!flag && list2.Count > 0) || (list2.Count > 0 && list2[list2.Count - 1] == -1)) { errors.Add(label + " has invalid clothing colours"); } if (flag) { ClothingPieceDef value2 = null; if (state != null && (state.Wardrobe?.Pieces == null || !state.Wardrobe.Pieces.TryGetValue(value.PieceId, out value2) || value2 == null)) { errors.Add(label + " wears an unknown clothing piece " + value.PieceId); } else if (value2 != null && value2.Slot != slot) { errors.Add(label + " wears clothing in the wrong slot: " + value.PieceId); } else if (value2 != null && list2.Count > value2.ColorChannels) { errors.Add(label + " has invalid clothing colours"); } else if (state == null && !Wardrobe.IsPieceId(value.PieceId)) { errors.Add(label + " wears an unknown clothing piece " + value.PieceId); } } } } private static void CheckSlot(CampaignState state, string id, EquipmentSlot slot, string label, List errors) { if (string.IsNullOrEmpty(id)) { return; } if (Smithing.IsCraftedId(id)) { CraftedWeaponState craftedWeaponState = ((state == null) ? null : Crafted(state, id)); if (state != null && craftedWeaponState == null) { errors.Add(label + " has an unknown equipment item " + id); } else if (craftedWeaponState != null && Enum.IsDefined(typeof(WeaponClass), craftedWeaponState.Class) && Smithing.ClassDef(craftedWeaponState.Class).Slot != slot && (slot != EquipmentSlot.Shield || !Smithing.ClassDef(craftedWeaponState.Class).OffHand)) { errors.Add(label + " has equipment in the wrong slot: " + id); } else if (craftedWeaponState == null && slot != EquipmentSlot.Weapon && slot != EquipmentSlot.Shield && slot != EquipmentSlot.Ammo) { errors.Add(label + " has equipment in the wrong slot: " + id); } } else if (slot == EquipmentSlot.Ammo) { errors.Add(label + " has equipment in the wrong slot: " + id); } else { EquipmentDef equipmentDef = EquipmentCatalog.Find(id); if (equipmentDef == null) { errors.Add(label + " has an unknown equipment item " + id); } else if (equipmentDef.Slot != slot && (slot != EquipmentSlot.Shield || !EquipmentCatalog.OffHandKit(equipmentDef))) { errors.Add(label + " has equipment in the wrong slot: " + id); } } } public static void CheckInventory(SortedDictionary inventory, string label, List errors) { CheckInventory(null, inventory, label, errors); } public static void CheckInventory(CampaignState state, SortedDictionary inventory, string label, List errors) { if (inventory == null) { return; } foreach (KeyValuePair item in inventory) { OwnedItemInfo ownedItemInfo = ((state != null) ? OwnedItems.Resolve(state, item.Key) : ((EquipmentCatalog.Find(item.Key) == null) ? null : OwnedItems.Resolve(null, item.Key))); if (ownedItemInfo == null) { errors.Add(label + " has an unknown equipment item " + item.Key); } else if (item.Value < 0 || item.Value > ownedItemInfo.Limit) { errors.Add(label + " has an invalid equipment count for " + item.Key); } } } } public static class FamilyValidation { public static List Check(CampaignState state) { List list = new List(); FamiliesState familiesState = state?.Families; if (familiesState == null || state.Heroes == null) { return list; } long day = state.Clock.Day; foreach (Hero hero4 in state.Heroes) { string text = "family of " + hero4.Id; bool flag = hero4.State != HeroState.Dead; if (flag && !string.IsNullOrEmpty(hero4.SpouseId)) { Hero hero = state.Heroes.Get(hero4.SpouseId); if (hero == null || hero.State == HeroState.Dead) { list.Add(text + " is married to someone who is not alive"); } else if (hero.SpouseId != hero4.Id) { list.Add(text + " is married to " + hero.Id + ", who is not married to them"); } else if (hero.Sex == hero4.Sex) { list.Add(text + " is married to someone of the same sex"); } } string[] array = new string[2] { hero4.FatherId, hero4.MotherId }; foreach (string text2 in array) { if (!string.IsNullOrEmpty(text2) && (!state.Heroes.Contains(text2) || text2 == hero4.Id)) { list.Add(text + " has an unknown parent " + text2); } } if (!string.IsNullOrEmpty(hero4.FatherId)) { Hero hero2 = state.Heroes.Get(hero4.FatherId); if (hero2 != null && hero2.Sex == HeroSex.Female) { list.Add(text + " has a woman as father"); } } if (!string.IsNullOrEmpty(hero4.MotherId)) { Hero hero3 = state.Heroes.Get(hero4.MotherId); if (hero3 != null && hero3.Sex == HeroSex.Male) { list.Add(text + " has a man as mother"); } } if (hero4.ChildDueDay >= 0) { if (!flag || hero4.Sex != HeroSex.Female) { list.Add(text + " is expecting while dead or not a woman"); } if (!state.Heroes.Contains(hero4.ChildFatherId)) { list.Add(text + " is expecting with an unknown father"); } if (hero4.ChildDueDay > day + 36) { list.Add(text + " is due too far ahead"); } } if (hero4.State == HeroState.Inactive) { if (!hero4.IsFamily) { list.Add(text + " is inactive but not a family member's child"); } if (!string.IsNullOrEmpty(hero4.PartyId)) { list.Add(text + " is a child in a party"); } if (!string.IsNullOrEmpty(hero4.SettlementId) && !state.Settlements.Contains(hero4.SettlementId)) { list.Add(text + " is a child at an unknown place"); } } if (hero4.Education == null) { continue; } foreach (KeyValuePair item in hero4.Education) { if (CharacterCreation.LifeStageChoice(item.Key, item.Value) == null) { list.Add(text + " has an unknown upbringing " + item.Key + "=" + item.Value); } } } foreach (CourtshipState item2 in familiesState.Courtships ?? new List()) { if (!state.Heroes.Contains(item2.HeroId) || item2.SuitorId != state.PlayerHeroId) { list.Add("courtship of " + item2.HeroId + " has no living suitor or person"); } if (item2.Progress < 0 || item2.Progress > 3 || item2.Failures < 0 || item2.Failures >= 3) { list.Add("courtship of " + item2.HeroId + " has impossible progress"); } } Hero playerHero = state.PlayerHero; if ((playerHero != null && playerHero.State == HeroState.Dead) != (familiesState.AwaitingHeir || familiesState.LineEnded)) { list.Add("succession doesn't match the player character being alive or dead"); } if (familiesState.AwaitingHeir && familiesState.LineEnded) { list.Add("succession is both waiting and finished"); } return list; } } public static class HeroDevelopmentValidation { public static List Check(CampaignState state) { List list = new List(); if (state?.Heroes == null) { return list; } foreach (Hero hero in state.Heroes) { if (hero == null) { continue; } string text = "hero development " + hero.Id; if (hero.BonusFocus < 0 || hero.BonusFocus > 100) { list.Add(text + " has an invalid number of bonus focus points"); } if (hero.OriginFocus < 0 || hero.OriginFocus > CharacterCreation.MaximumOriginFocus) { list.Add(text + " has an invalid number of creation focus points"); } if (hero.SkillFocus == null) { continue; } long num = 0L; foreach (KeyValuePair item in hero.SkillFocus) { if (!SkillIds.All.Contains(item.Key)) { list.Add(text + " has an unknown focus skill " + item.Key); } if (item.Value < 0 || item.Value > 5) { list.Add(text + " has an invalid focus rank for " + item.Key); } num += Math.Max(0, item.Value); } int level = Math.Max(TabsBannerlord.Core.Campaign.Campaign.HeroLevelForXp(hero.Xp), Math.Max(1, Math.Min(50, hero.Level))); if (num > TabsBannerlord.Core.Campaign.Campaign.HeroFocusPointsForLevel(level) + TabsBannerlord.Core.Campaign.Campaign.ExtraFocus(hero)) { list.Add(text + " has spent more focus than its level allows"); } } return list; } } public static class HideoutValidation { public static List Check(CampaignState state) { List list = new List(); HideoutsState hideoutsState = state?.Hideouts; if (hideoutsState == null || !hideoutsState.Started) { return list; } if (hideoutsState.Records == null) { list.Add("hideouts are missing their records"); return list; } HashSet hashSet = new HashSet(StringComparer.Ordinal); HashSet hashSet2 = new HashSet(StringComparer.Ordinal); foreach (HideoutRecord record in hideoutsState.Records) { if (record == null) { list.Add("a hideout record is missing"); continue; } string text = "hideout " + record.SettlementId; Settlement settlement = state.Settlements.Get(record.SettlementId); if (settlement == null || settlement.Type != SettlementType.Hideout) { list.Add(text + " is not a bandit camp"); continue; } if (!hashSet.Add(record.SettlementId)) { list.Add(text + " has two records"); } if (record.SquadTroops == null || record.SquadHeroes == null) { list.Add(text + " is missing its squad lists"); } if (record.Stage != "" && record.Stage != "chief") { list.Add(text + " is at an unknown stage " + record.Stage); } if (!string.IsNullOrEmpty(record.GuardPartyId)) { hashSet2.Add(record.GuardPartyId); Party party = state.Parties.Get(record.GuardPartyId); if (party == null) { list.Add(text + " has a gang that does not exist"); } else if (party.State != PartyState.Destroyed && party.State != PartyState.Disbanded) { if (party.Kind != PartyKind.Bandit || party.HideoutGuardOf != settlement.Id) { list.Add(text + "'s gang " + party.Id + " is not its own bandit party"); } if (party.State == PartyState.InSettlement && party.CurrentSettlementId != settlement.Id) { list.Add(text + "'s gang is somewhere else"); } if (party.State == PartyState.Active) { list.Add(text + "'s gang has left the camp"); } if (party.State == PartyState.Engaged && state.Encounters.Get(party.EncounterId) == null) { list.Add(text + "'s gang fights in an encounter that does not exist"); } } if (record.Stage == "chief") { list.Add(text + " waits on its chief but still has a gang"); } } if (!settlement.HideoutActive && record.ResettleDay < 0 && record.Stage != "chief") { list.Add(text + " is abandoned with no day to be settled again"); } if (record.Stage == "chief" && string.IsNullOrEmpty(record.ChiefUnitId)) { list.Add(text + " waits on a chief it does not have"); } } foreach (Party item in state.Parties.Where((Party x) => !string.IsNullOrEmpty(x.HideoutGuardOf) && x.State != PartyState.Destroyed && x.State != PartyState.Disbanded)) { if (!hashSet2.Contains(item.Id)) { Encounter encounter = state.Encounters.Get(item.EncounterId); if (encounter == null || encounter.Kind != EncounterKind.HideoutRaid || encounter.HideoutId != item.HideoutGuardOf) { list.Add("party " + item.Id + " guards " + item.HideoutGuardOf + " but no camp knows it"); } } } LegendsState legends = state.Legends; if (legends != null) { if (legends.Joined == null) { list.Add("legends are missing their list"); } else { foreach (string item2 in legends.Joined) { LegendDef legendDef = Legends.For(item2); if (legendDef == null || !legendDef.Unique) { list.Add("legend " + item2 + " joined but is no unique legend"); } } } } foreach (DiscoverySite item3 in state.Quests?.Sites ?? new List()) { if (item3 == null || string.IsNullOrEmpty(item3.LegendPlace)) { continue; } if (!Legends.Places.Contains(item3.LegendPlace)) { list.Add("site " + item3.Id + " is the place of no known legend"); } if (item3.Stock == null) { list.Add("site " + item3.Id + " is missing its stock"); continue; } foreach (KeyValuePair item4 in item3.Stock) { if (item4.Value < 0 || item4.Value > 3) { list.Add("site " + item3.Id + " holds " + item4.Value + " " + item4.Key); } } } return list; } } public static class HorseValidation { private static bool Finite(double v) { if (!double.IsNaN(v)) { return !double.IsInfinity(v); } return false; } public static List Check(CampaignState state) { List list = new List(); HorsesState horsesState = state?.Horses; if (horsesState == null) { return list; } long num = 0L; foreach (KeyValuePair item in horsesState.Horses ?? new SortedDictionary(StringComparer.Ordinal)) { HorseState horse = item.Value; string text = "horse " + item.Key; if (horse == null || horse.Id != item.Key || !horse.Id.StartsWith("horse.", StringComparison.Ordinal)) { list.Add(text + " is malformed"); continue; } if (long.TryParse(horse.Id.Substring("horse.".Length), NumberStyles.None, CultureInfo.InvariantCulture, out var result)) { num = Math.Max(num, result); } else { list.Add(text + " has an invalid id"); } if (Horses.Breed(horse.BreedId) == null) { list.Add(text + " has an unknown breed"); } if (!string.IsNullOrEmpty(horse.CrossBreedId) && Horses.Breed(horse.CrossBreedId) == null) { list.Add(text + " has an unknown cross breed"); } if (string.IsNullOrWhiteSpace(horse.Name) || horse.Name.Length > 24) { list.Add(text + " has an invalid name"); } if (!Enum.IsDefined(typeof(HorseSex), horse.Sex) || !Enum.IsDefined(typeof(HorseInjury), horse.Injury) || !Enum.IsDefined(typeof(HorsePlace), horse.Place)) { list.Add(text + " has an invalid sex, injury or place"); } if (horse.Coat < 0 || horse.Coat >= Horses.Coats.Length) { list.Add(text + " has an invalid coat"); } if (new double[4] { horse.Speed, horse.Manoeuvre, horse.HitPoints, horse.Stamina }.Any((double v) => !Finite(v) || v <= 0.0) || !Finite(horse.Charge) || horse.Charge < 0.0 || horse.Stamina > 100.0 || horse.Speed > 120.0 || horse.Manoeuvre > 120.0 || horse.Charge > 100.0 || horse.HitPoints > 800.0) { list.Add(text + " has invalid qualities"); } if (horse.Temperament < 0 || horse.Temperament > 100) { list.Add(text + " has an invalid temperament"); } if (!Finite(horse.Condition) || horse.Condition < 0.0 || horse.Condition > 1.0 || !Finite(horse.Fatigue) || horse.Fatigue < 0.0 || horse.Fatigue > 1.0) { list.Add(text + " has an invalid condition or fatigue"); } if (horse.InjuryDays < 0 || horse.Injury == HorseInjury.None != (horse.InjuryDays == 0)) { list.Add(text + " has an invalid injury"); } if (!Finite(horse.Experience) || horse.Experience < 0.0 || horse.Battles < 0) { list.Add(text + " has invalid experience"); } if (horse.Bond == null || horse.Bond.Any((KeyValuePair b) => state.Heroes?.Get(b.Key) == null || !Finite(b.Value) || b.Value < 0.0 || b.Value > 100.0)) { list.Add(text + " has invalid bonds"); } if (horse.PregnantSinceDay >= 0 && (horse.Sex != HorseSex.Mare || horse.PregnantSinceDay > state.Clock.Day)) { list.Add(text + " has an invalid pregnancy"); } switch (horse.Place) { case HorsePlace.Party: if (state.Parties?.Get(horse.PlaceId ?? "") == null) { list.Add(text + " is with an unknown party"); } break; case HorsePlace.Stud: if (horsesState.StudFarms == null || !horsesState.StudFarms.Any((StudFarmState f) => f != null && f.SettlementId == horse.PlaceId)) { list.Add(text + " is at a stud farm you do not own"); } break; case HorsePlace.Market: if (state.Settlements?.Get(horse.PlaceId ?? "") == null || horsesState.MarketPeriods == null || !horsesState.MarketPeriods.ContainsKey(horse.PlaceId)) { list.Add(text + " is for sale at an unknown market"); } break; } } if (horsesState.NextHorseNumber <= num) { list.Add("the next horse id would repeat an existing horse"); } HashSet hashSet = new HashSet(StringComparer.Ordinal); foreach (Hero item2 in state.Heroes ?? new EntityTable()) { if (!string.IsNullOrEmpty(item2?.MountId)) { HorseState value = null; if (horsesState.Horses == null || !horsesState.Horses.TryGetValue(item2.MountId, out value) || value == null || value.Place == HorsePlace.Market) { list.Add("hero " + item2.Id + " rides an unknown horse"); } else if (!hashSet.Add(item2.MountId)) { list.Add("horse " + item2.MountId + " has more than one rider"); } } } HashSet hashSet2 = new HashSet(StringComparer.Ordinal); foreach (StudFarmState item3 in horsesState.StudFarms ?? new List()) { Settlement settlement = state.Settlements?.Get(item3?.SettlementId ?? ""); if (item3 == null || settlement == null || settlement.Type != SettlementType.Village || !hashSet2.Add(item3.SettlementId) || item3.PurchasePrice < 0) { list.Add("stud farm " + (item3?.SettlementId ?? "?") + " is invalid"); } } foreach (KeyValuePair item4 in horsesState.MarketPeriods ?? new SortedDictionary(StringComparer.Ordinal)) { if (state.Settlements?.Get(item4.Key) == null || item4.Value < 0) { list.Add("horse market " + item4.Key + " is invalid"); } } return list; } } public static class InvariantChecker { public static List Check(TabsBannerlord.Core.Campaign.Campaign campaign) { CampaignState state = campaign.State; List list = new List(); string text = ProceduralWorld.StateError(state); if (text.Length > 0) { list.Add(text); } list.AddRange(CharacterCreationValidation.Check(state)); list.AddRange(HeroDevelopmentValidation.Check(state)); list.AddRange(EquipmentValidation.Check(state, campaign.Content)); list.AddRange(SmithingValidation.Check(state)); list.AddRange(HorseValidation.Check(state)); list.AddRange(CheckEconomyState(state)); list.AddRange(CheckSettlementState(state)); list.AddRange(RealmValidation.Check(state)); list.AddRange(DiplomacyValidation.Check(state)); list.AddRange(SiegeValidation.Check(state)); list.AddRange(PoliticsValidation.Check(state)); list.AddRange(ClanAllegianceValidation.Check(state)); list.AddRange(RaidValidation.Check(state)); list.AddRange(MilitaryPartyValidation.Check(state)); list.AddRange(ClanArmyValidation.Check(state)); list.AddRange(NamedCustodyValidation.Check(state)); list.AddRange(RescueValidation.Check(state)); list.AddRange(TournamentValidation.Check(state)); list.AddRange(ScoutingValidation.Check(state)); list.AddRange(FamilyValidation.Check(state)); list.AddRange(RebellionValidation.Check(state)); list.AddRange(QuestValidation.Check(state)); list.AddRange(HideoutValidation.Check(state)); foreach (Clan clan in state.Clans) { if (clan.Gold < 0) { list.Add($"clan {clan.Id} has negative gold {clan.Gold}"); } } Dictionary> heroLocations = new Dictionary>(StringComparer.Ordinal); foreach (Party party3 in state.Parties) { party3.Troops.Validate("party " + party3.Id, list); party3.Prisoners.Validate("party " + party3.Id + " prisoners", list); if (party3.Food < -1E-06) { list.Add("party " + party3.Id + " has negative food"); } if (party3.Gold < 0) { list.Add("party " + party3.Id + " has negative gold"); } if (party3.RoleAssignments != null) { HashSet hashSet = new HashSet(StringComparer.Ordinal); foreach (KeyValuePair roleAssignment in party3.RoleAssignments) { string text2 = $"party {party3.Id} role {roleAssignment.Key}"; if (!Enum.IsDefined(typeof(PartyRole), roleAssignment.Key)) { list.Add(text2 + " is unknown"); } if (!hashSet.Add(roleAssignment.Value)) { list.Add("party " + party3.Id + " assigns hero " + roleAssignment.Value + " to several roles"); } Hero hero = state.Heroes.Get(roleAssignment.Value); if (hero == null) { list.Add(text2 + " has no valid hero"); continue; } if (hero.State != HeroState.Active || hero.PartyId != party3.Id || !party3.Troops.Heroes.Contains(hero.Id) || !string.IsNullOrEmpty(hero.CaptorPartyId) || !string.IsNullOrEmpty(hero.CaptorSettlementId)) { list.Add(text2 + " is assigned to an absent or captive hero " + hero.Id); } if (hero.ClanId != party3.ClanId || (party3.Id == state.PlayerPartyId && hero.Id != state.PlayerHeroId && hero.Occupation != HeroOccupation.Companion)) { list.Add(text2 + " is assigned to a hero outside the party's ownership " + hero.Id); } if (party3.State == PartyState.Destroyed || party3.State == PartyState.Disbanded) { list.Add(text2 + " remains assigned after the party ended"); } } } if (party3.State == PartyState.Destroyed) { if (party3.Troops.Heroes.Count > 0) { list.Add("destroyed party " + party3.Id + " still lists heroes"); } continue; } if (!state.Clans.Contains(party3.ClanId) && party3.Kind != PartyKind.Villager) { list.Add("party " + party3.Id + " has unknown clan " + party3.ClanId); } if (!campaign.Nav.IsPassable(party3.Position) && party3.State != PartyState.InSettlement) { list.Add($"party {party3.Id} is on impassable terrain at {party3.Position}"); } if (party3.State == PartyState.InSettlement && !state.Settlements.Contains(party3.CurrentSettlementId)) { list.Add("party " + party3.Id + " is in unknown settlement"); } if (party3.State == PartyState.Engaged && !state.Encounters.Contains(party3.EncounterId)) { list.Add("party " + party3.Id + " engaged in missing encounter " + party3.EncounterId); } foreach (string hero3 in party3.Troops.Heroes) { Place(hero3, "party " + party3.Id); Hero hero2 = state.Heroes.Get(hero3); if (hero2 == null) { list.Add("party " + party3.Id + " lists unknown hero " + hero3); } else if (hero2.PartyId != party3.Id || hero2.State != HeroState.Active) { list.Add("party " + party3.Id + " lists hero " + hero3 + " without an active party backreference"); } } foreach (string hero4 in party3.Prisoners.Heroes) { Place(hero4, "prisoner of " + party3.Id); } } foreach (Settlement settlement in state.Settlements) { settlement.Garrison.Validate("garrison " + settlement.Id, list); settlement.Prisoners.Validate("prisoners " + settlement.Id, list); if (settlement.Type != SettlementType.Hideout && !state.Clans.Contains(settlement.OwnerClanId)) { list.Add("settlement " + settlement.Id + " has invalid owner " + settlement.OwnerClanId); } foreach (string hero5 in settlement.Prisoners.Heroes) { Place(hero5, "prisoner at " + settlement.Id); } } foreach (KeyValuePair> item in heroLocations.Where((KeyValuePair> k) => k.Value.Count > 1)) { list.Add("hero " + item.Key + " is in several places: " + string.Join(", ", item.Value)); } foreach (Hero hero6 in state.Heroes) { heroLocations.TryGetValue(hero6.Id, out var value); if (hero6.State == HeroState.Captive) { if (value == null || !value.Any((string x) => x.StartsWith("prisoner", StringComparison.Ordinal))) { list.Add("captive hero " + hero6.Id + " has no captor record"); } } else if (hero6.State == HeroState.Active && !string.IsNullOrEmpty(hero6.PartyId)) { Party party = state.Parties.Get(hero6.PartyId); if (party == null || !party.Troops.Heroes.Contains(hero6.Id)) { list.Add("hero " + hero6.Id + " points at party " + hero6.PartyId + " which does not list them"); } } if (hero6.State == HeroState.Dead && value != null) { list.Add("dead hero " + hero6.Id + " is still listed in " + string.Join(", ", value)); } if (hero6.Health < 0.0 || hero6.Health > 1.0001) { list.Add($"hero {hero6.Id} has invalid health {hero6.Health}"); } if (hero6.Occupation != HeroOccupation.Companion) { continue; } if (!string.IsNullOrEmpty(hero6.ClanId) && !state.Clans.Contains(hero6.ClanId)) { list.Add("companion " + hero6.Id + " has unknown clan " + hero6.ClanId); } if (hero6.State != HeroState.Active) { continue; } if (string.IsNullOrEmpty(hero6.PartyId)) { WandererPlan value2 = null; bool flag = string.IsNullOrEmpty(hero6.ClanId) && string.IsNullOrEmpty(hero6.SettlementId) && state.Wanderers?.Plans != null && state.Wanderers.Plans.TryGetValue(hero6.Id, out value2) && value2.Travelling; if (flag && !state.Settlements.Contains(value2.DestinationId)) { list.Add("wanderer " + hero6.Id + " is walking to unknown town " + value2.DestinationId); } else if (!flag && !state.Settlements.Contains(hero6.SettlementId)) { list.Add("waiting companion " + hero6.Id + " has no valid settlement"); } } else { Party party2 = state.Parties.Get(hero6.PartyId); if (party2 != null && (string.IsNullOrEmpty(hero6.ClanId) || hero6.ClanId != party2.ClanId)) { list.Add("companion " + hero6.Id + " does not belong to party " + party2.Id + "'s clan"); } if (party2 != null && (party2.State == PartyState.Destroyed || party2.State == PartyState.Disbanded)) { list.Add("companion " + hero6.Id + " remains in an ended party " + party2.Id); } if (!string.IsNullOrEmpty(hero6.SettlementId)) { list.Add("companion " + hero6.Id + " is both travelling and waiting in a settlement"); } } if (!string.IsNullOrEmpty(hero6.CaptorPartyId) || !string.IsNullOrEmpty(hero6.CaptorSettlementId)) { list.Add("active companion " + hero6.Id + " still has a captor"); } } foreach (Encounter encounter in state.Encounters) { if (state.CommittedEncounters.Contains(encounter.Id) && encounter.Phase != EncounterPhase.Committed) { list.Add($"encounter {encounter.Id} committed in phase {encounter.Phase}"); } } if (state.PlayerParty == null) { list.Add("player party missing"); } if (state.Player.Activity == PlayerActivity.Captive) { Hero playerHero = state.PlayerHero; if (playerHero == null || playerHero.State != HeroState.Captive) { list.Add("player marked captive but hero is not"); } } Hero playerHero2 = state.PlayerHero; if (playerHero2 != null && playerHero2.State == HeroState.Captive && state.Player.Activity != PlayerActivity.Captive) { list.Add("player hero captive but activity is " + state.Player.Activity); } return list; void Place(string key, string where) { if (!heroLocations.TryGetValue(key, out var value3)) { value3 = (heroLocations[key] = new List()); } value3.Add(where); } } public static List CheckEconomyState(CampaignState state, bool checkContent = true) { List list = new List(); HashSet hashSet = new HashSet(TradeGoods.All.Select((TradeGoodDef x) => x.Id), StringComparer.Ordinal); foreach (Party party3 in state.Parties) { if (party3.State == PartyState.Destroyed || party3.State == PartyState.Disbanded) { SortedDictionary equipment = party3.Equipment; if (equipment != null && equipment.Any((KeyValuePair item) => item.Value > 0)) { list.Add("ended party " + party3.Id + " still carries equipment"); } } if (party3.Cargo == null) { continue; } foreach (KeyValuePair item in party3.Cargo) { if (item.Value < 0) { list.Add("party " + party3.Id + " has negative cargo " + item.Key); } if (checkContent && !hashSet.Contains(item.Key)) { list.Add("party " + party3.Id + " has unknown trade good " + item.Key); } if (item.Value > 0 && (party3.State == PartyState.Destroyed || party3.State == PartyState.Disbanded)) { list.Add("ended party " + party3.Id + " still carries cargo " + item.Key); } } } foreach (Settlement settlement2 in state.Settlements) { MarketState market = settlement2.Market; if (market == null) { continue; } if (market.Gold < 0) { list.Add("market " + settlement2.Id + " has negative gold"); } if (market.LastDay < -1) { list.Add("market " + settlement2.Id + " has invalid last production day"); } if (market.Stock == null) { continue; } foreach (KeyValuePair item2 in market.Stock) { if (item2.Value < 0 || item2.Value > 500) { list.Add("market " + settlement2.Id + " has invalid stock for " + item2.Key); } if (checkContent && !hashSet.Contains(item2.Key)) { list.Add("market " + settlement2.Id + " has unknown trade good " + item2.Key); } } } HashSet hashSet2 = new HashSet(StringComparer.Ordinal); foreach (WorkshopState item3 in state.Workshops ?? new List()) { if (item3 == null) { list.Add("workshop list has a null entry"); continue; } if (string.IsNullOrEmpty(item3.Id) || !hashSet2.Add(item3.Id)) { list.Add("workshop has missing or duplicate id " + item3.Id); } if (item3.Capital < 0 || item3.PurchasePrice < 0) { list.Add("workshop " + item3.Id + " has negative capital or purchase price"); } if (item3.LastDay < -1) { list.Add("workshop " + item3.Id + " has invalid last production day"); } if (checkContent && WorkshopTypes.Get(item3.TypeId) == null) { list.Add("workshop " + item3.Id + " has unknown type " + item3.TypeId); } } HashSet hashSet3 = new HashSet(StringComparer.Ordinal); foreach (ContractState item4 in state.Contracts ?? new List()) { if (item4 == null) { list.Add("contract list has a null entry"); continue; } if (string.IsNullOrEmpty(item4.Id) || !hashSet3.Add(item4.Id)) { list.Add("contract has missing or duplicate id " + item4.Id); } if (!Enum.IsDefined(typeof(ContractKind), item4.Kind) || !Enum.IsDefined(typeof(ContractStatus), item4.Status)) { list.Add("contract " + item4.Id + " has an unknown kind or status"); } if (item4.Reward < 0 || item4.Escrow < 0) { list.Add("contract " + item4.Id + " has negative reward or escrow"); } if (item4.Quantity < 0 || item4.Progress < 0) { list.Add("contract " + item4.Id + " has negative quantity or progress"); } if ((item4.Kind == ContractKind.Delivery || item4.Kind == ContractKind.SettlementSupply) && checkContent && !hashSet.Contains(item4.GoodId)) { list.Add("contract " + item4.Id + " has unknown trade good " + item4.GoodId); } } HashSet hashSet4 = new HashSet(StringComparer.Ordinal); HashSet hashSet5 = new HashSet(StringComparer.Ordinal); foreach (CaravanState item5 in state.Caravans ?? new List()) { if (item5 == null) { list.Add("caravan list has a null entry"); continue; } if (string.IsNullOrEmpty(item5.Id) || !hashSet4.Add(item5.Id)) { list.Add("caravan has missing or duplicate id " + item5.Id); } if (string.IsNullOrEmpty(item5.PartyId) || !hashSet5.Add(item5.PartyId)) { list.Add("caravan has missing or duplicate party " + item5.PartyId); } if (string.IsNullOrEmpty(item5.Status) || item5.LastArrivalMinute < -1 || item5.StartedMinute < 0) { list.Add("caravan " + item5.Id + " has bad start/end data"); } if (item5.CargoCosts != null) { foreach (KeyValuePair cargoCost in item5.CargoCosts) { if (cargoCost.Value < 0) { list.Add("caravan " + item5.Id + " has negative cargo cost"); } if (checkContent && !hashSet.Contains(cargoCost.Key)) { list.Add("caravan " + item5.Id + " has unknown trade good " + cargoCost.Key); } } } Party party = state.Parties.Get(item5.PartyId); if (item5.IsActive) { if (!state.Clans.Contains(item5.OwnerClanId)) { list.Add("caravan " + item5.Id + " has no valid owner"); } if (party == null || party.Kind != PartyKind.Caravan || party.ClanId != item5.OwnerClanId || party.State == PartyState.Destroyed || party.State == PartyState.Disbanded) { list.Add("caravan " + item5.Id + " has no valid active party"); } else if (item5.Merchant) { Settlement settlement = state.Settlements.Get(item5.HomeSettlementId); if (settlement == null || party.MerchantTownId != settlement.Id) { list.Add("merchant caravan " + item5.Id + " has no valid home town"); } if (!string.IsNullOrEmpty(party.LeaderHeroId) || party.Troops.Heroes.Count > 0) { list.Add("merchant caravan " + item5.Id + " has a hero aboard"); } if (party.Gold < 0) { list.Add("caravan " + item5.Id + " has negative operating capital"); } } else if (item5.ClanCaravan) { if (item5.OwnerClanId == state.PlayerClanId) { list.Add("clan caravan " + item5.Id + " belongs to the player"); } if (!state.Settlements.Contains(item5.HomeSettlementId)) { list.Add("clan caravan " + item5.Id + " has no valid home town"); } if (!string.IsNullOrEmpty(party.LeaderHeroId) || party.Troops.Heroes.Count > 0) { list.Add("clan caravan " + item5.Id + " has a hero aboard"); } if (!string.IsNullOrEmpty(party.MerchantTownId) || item5.Merchant) { list.Add("clan caravan " + item5.Id + " is marked as a town merchants' caravan"); } if (party.Gold < 0) { list.Add("caravan " + item5.Id + " has negative operating capital"); } } else { Hero hero = state.Heroes.Get(party.LeaderHeroId); if (hero == null || hero.Occupation != HeroOccupation.Companion || hero.State != HeroState.Active || hero.ClanId != item5.OwnerClanId || hero.PartyId != party.Id || !party.Troops.Heroes.Contains(hero.Id)) { list.Add("caravan " + item5.Id + " has no valid travelling commander"); } if (party.Gold < 0) { list.Add("caravan " + item5.Id + " has negative operating capital"); } if (!string.IsNullOrEmpty(party.MerchantTownId)) { list.Add("caravan " + item5.Id + " is marked as a town merchants' caravan"); } } } else { if (party == null) { continue; } if (party.Gold == 0L) { SortedDictionary cargo = party.Cargo; if (cargo == null || !cargo.Any((KeyValuePair x) => x.Value > 0)) { SortedDictionary equipment2 = party.Equipment; if ((equipment2 == null || !equipment2.Any((KeyValuePair x) => x.Value > 0)) && (party.State == PartyState.Destroyed || party.State == PartyState.Disbanded)) { continue; } } } list.Add("ended caravan " + item5.Id + " still has a party or money"); } } foreach (Party party2 in state.Parties.Where((Party p) => !string.IsNullOrEmpty(p.MerchantTownId) && p.State != PartyState.Destroyed && p.State != PartyState.Disbanded)) { if (party2.Kind != PartyKind.Caravan || (state.Caravans ?? new List()).Count((CaravanState c) => c != null && c.Merchant && c.IsActive && c.PartyId == party2.Id) != 1) { list.Add("party " + party2.Id + " is marked as a merchant caravan without one active merchant record"); } } return list; } public static List CheckSettlementState(CampaignState state, bool checkContent = true) { List list = new List(); Dictionary dictionary = new Dictionary(StringComparer.Ordinal); HashSet hashSet = new HashSet(StringComparer.Ordinal); foreach (NotableState item in state.Notables ?? new List()) { if (item == null) { list.Add("notable list has a null entry"); continue; } if (string.IsNullOrEmpty(item.Id) || dictionary.ContainsKey(item.Id)) { list.Add("notable has missing or duplicate id " + item.Id); } else { dictionary.Add(item.Id, item); } Settlement settlement = state.Settlements.Get(item.SettlementId); if (settlement == null || settlement.Type == SettlementType.Hideout) { list.Add("notable " + item.Id + " has no valid settlement"); } if (!state.Clans.Contains(item.OwnerClanId)) { list.Add("notable " + item.Id + " has no valid owner"); } if (item.PlayerRelation < -100 || item.PlayerRelation > 100) { list.Add("notable " + item.Id + " has invalid relation"); } if (item.Generation < 0 || item.PredecessorId == item.Id) { list.Add("notable " + item.Id + " has invalid succession data"); } if (item.LastRecruitRefillDay < -1 || item.LastRecruitRefillDay > state.Clock.Day) { list.Add("notable " + item.Id + " has invalid recruit refill day"); } if (item.IsAlive && !hashSet.Add(item.SettlementId)) { list.Add("settlement " + item.SettlementId + " has several living recruitment providers"); } } foreach (Settlement settlement2 in state.Settlements) { if (double.IsNaN(settlement2.Security) || double.IsInfinity(settlement2.Security) || settlement2.Security < 0.0 || settlement2.Security > 100.0) { list.Add("settlement " + settlement2.Id + " has invalid security"); } if (double.IsNaN(settlement2.Loyalty) || double.IsInfinity(settlement2.Loyalty) || settlement2.Loyalty < 0.0 || settlement2.Loyalty > 100.0) { list.Add("settlement " + settlement2.Id + " has invalid loyalty"); } if (double.IsNaN(settlement2.Prosperity) || double.IsInfinity(settlement2.Prosperity) || settlement2.Prosperity < 0.0) { list.Add("settlement " + settlement2.Id + " has invalid prosperity"); } if (double.IsNaN(settlement2.FoodStock) || double.IsInfinity(settlement2.FoodStock) || settlement2.FoodStock < -1E-06 || (settlement2.FoodInMarket && Math.Abs(settlement2.FoodStock) > 1E-06)) { list.Add("settlement " + settlement2.Id + " has invalid food stores"); } if (double.IsNaN(settlement2.FoodPart) || double.IsInfinity(settlement2.FoodPart) || settlement2.FoodPart < -1E-06 || settlement2.FoodPart > 1.000001) { list.Add("settlement " + settlement2.Id + " has an invalid part of a food unit"); } if (settlement2.StatsDay < -1 || settlement2.StatsDay > state.Clock.Day || settlement2.StarvingDays < 0) { list.Add("settlement " + settlement2.Id + " has an invalid daily statistics record"); } bool flag = settlement2.Type == SettlementType.Town || settlement2.Type == SettlementType.Castle; if (settlement2.WallLevel < 0 || settlement2.WallLevel > 3 || (!flag && settlement2.WallLevel != 0)) { list.Add("settlement " + settlement2.Id + " has an invalid wall level"); } if (!string.IsNullOrEmpty(settlement2.Product) && (settlement2.Type != SettlementType.Village || (checkContent && VillageProducts.Get(settlement2.Product) == null))) { list.Add("settlement " + settlement2.Id + " has an invalid village product " + settlement2.Product); } foreach (RecruitSlot item2 in settlement2.Recruits ?? new List()) { if (item2 != null) { if (item2.RequiredRelation < -100 || item2.RequiredRelation > 100) { list.Add("settlement " + settlement2.Id + " has invalid recruit relation requirement"); } if (!string.IsNullOrEmpty(item2.ProviderId) && (!dictionary.TryGetValue(item2.ProviderId, out var value) || value.SettlementId != settlement2.Id)) { list.Add("settlement " + settlement2.Id + " has invalid recruit provider " + item2.ProviderId); } } } SettlementManagementState management = settlement2.Management; if (management == null) { continue; } if (!Enum.IsDefined(typeof(TaxPolicy), management.Policy)) { list.Add("settlement " + settlement2.Id + " has unknown tax policy"); } if (management.GranaryLevel < 0 || management.GranaryLevel > 3 || management.WatchtowerLevel < 0 || management.WatchtowerLevel > 3) { list.Add("settlement " + settlement2.Id + " has invalid building level"); } if (management.LastDay < -1 || management.LastDay > state.Clock.Day) { list.Add("settlement " + settlement2.Id + " has invalid management day"); } if ((!string.IsNullOrEmpty(management.OwnerClanId) || (management.Initialized && settlement2.Type != SettlementType.Hideout)) && !state.Clans.Contains(management.OwnerClanId)) { list.Add("settlement " + settlement2.Id + " has invalid management owner"); } bool flag2 = settlement2.Type == SettlementType.Town || settlement2.Type == SettlementType.Castle; if (!flag2 && (management.GranaryLevel != 0 || management.WatchtowerLevel != 0 || management.Policy != TaxPolicy.Balanced)) { list.Add("settlement " + settlement2.Id + " cannot hold buildings or a tax policy"); } if (settlement2.Type != SettlementType.Town && management.GranaryLevel != 0) { list.Add("settlement " + settlement2.Id + " cannot hold a granary"); } if (string.IsNullOrEmpty(management.ProjectId)) { if (management.ProjectRemainingDays != 0 || !string.IsNullOrEmpty(management.ProjectOwnerClanId)) { list.Add("settlement " + settlement2.Id + " has project data without an active project"); } } else { if (checkContent && !TabsBannerlord.Core.Campaign.Campaign.IsSettlementProject(management.ProjectId)) { list.Add("settlement " + settlement2.Id + " has unknown settlement project " + management.ProjectId); } if (!flag2 || (management.ProjectId == "project.granary" && settlement2.Type != SettlementType.Town)) { list.Add("settlement " + settlement2.Id + " cannot build this project"); } if (management.ProjectRemainingDays < 1 || management.ProjectRemainingDays > TabsBannerlord.Core.Campaign.Campaign.ProjectDays(management.ProjectId)) { list.Add("settlement " + settlement2.Id + " has invalid project progress"); } if (!state.Clans.Contains(management.ProjectOwnerClanId)) { list.Add("settlement " + settlement2.Id + " has invalid project funding owner"); } } List list2 = management.ProjectQueue ?? new List(); if (list2.Count > 3 || (list2.Count > 0 && !flag2) || (checkContent && list2.Any((string id) => !TabsBannerlord.Core.Campaign.Campaign.IsSettlementProject(id)))) { list.Add("settlement " + settlement2.Id + " has an invalid build queue"); } if (management.GarrisonWageLimit < 0 || management.GovernorBudget < 0 || management.GovernorSpentToday < 0 || (management.GarrisonAutoRecruit && management.GarrisonWageLimit == 0L && (management.GarrisonOrders?.Target ?? 0) <= 0)) { list.Add("settlement " + settlement2.Id + " has invalid budgets"); } if (management.GarrisonOrders != null && (management.GarrisonOrders.Target < 0 || management.GarrisonOrders.TierCap < 0 || management.GarrisonOrders.TierCap > 6 || management.GarrisonOrders.UpgradePaths == null)) { list.Add("settlement " + settlement2.Id + " has invalid garrison orders"); } if (double.IsNaN(management.Hardship) || management.Hardship < 0.0 || management.Hardship > 100.0 || (settlement2.Type != SettlementType.Town && management.Hardship != 0.0)) { list.Add("settlement " + settlement2.Id + " has invalid hardship"); } } foreach (ContractState item3 in state.Contracts ?? new List()) { if (item3 == null || (item3.Status != ContractStatus.Offered && item3.Status != ContractStatus.Active)) { continue; } NotableState value2; if (string.IsNullOrEmpty(item3.IssuerNotableId)) { if (item3.Kind == ContractKind.SettlementSupply) { list.Add("contract " + item3.Id + " has no settlement issue provider"); } } else if (!dictionary.TryGetValue(item3.IssuerNotableId, out value2) || value2.SettlementId != item3.IssuerSettlementId) { list.Add("contract " + item3.Id + " has invalid notable provider " + item3.IssuerNotableId); } } return list; } public static Dictionary CountAllTroops(CampaignState s) { Dictionary d = new Dictionary(StringComparer.Ordinal); foreach (Party party in s.Parties) { if (party.State != PartyState.Destroyed) { Add(party.Troops); Add(party.Prisoners); } } foreach (Settlement settlement in s.Settlements) { Add(settlement.Garrison); Add(settlement.Prisoners); } if (s.Player?.LastReport?.RescuedTroops != null) { Add(s.Player.LastReport.RescuedTroops); } return d; void Add(TroopRoster r) { foreach (TroopStack stack in r.Stacks) { d.TryGetValue(stack.UnitId, out var value); d[stack.UnitId] = value + stack.Total; } } } } public static class MilitaryPartyValidation { public static List Check(CampaignState state) { List list = new List(); HashSet hashSet = new HashSet(StringComparer.Ordinal); HashSet hashSet2 = new HashSet(StringComparer.Ordinal); HashSet hashSet3 = new HashSet(StringComparer.Ordinal); int num = 0; foreach (MilitaryPartyState record in state.MilitaryParties ?? new List()) { if (record == null) { list.Add("null military party record"); continue; } string text = "military party " + record.Id; if (string.IsNullOrEmpty(record.Id) || !hashSet.Add(record.Id)) { list.Add(text + " has a duplicate or missing id"); } if (string.IsNullOrEmpty(record.PartyId) || !hashSet2.Add(record.PartyId)) { list.Add(text + " has a duplicate or missing party"); } if (record.Status != "Active" && record.Status != "Lost" && record.Status != "Disbanded") { list.Add(text + " has an unknown status"); } if (!Enum.IsDefined(typeof(MilitaryPartyDirective), record.Directive)) { list.Add(text + " has an unknown directive"); } if (record.StartedMinute < 0 || record.StartedMinute > state.Clock.Minute) { list.Add(text + " has a bad start date"); } if (record.RecruitmentTarget < 0 || record.RecruitmentTarget > 1000 || record.DailyRecruitBudget < 0 || record.DailyFoodBudget < -1 || record.RecruitmentWageLimit < -1 || record.TreasuryReserve < 0) { list.Add(text + " has invalid recruitment or supply budgets"); } if (record.SpendingDay < -1 || record.SpendingDay > state.Clock.Day || (record.SpendingDay >= 0 && record.SpendingDay < record.StartedMinute / 1440)) { list.Add(text + " has a bad spending date"); } if (record.RecruitmentSpentToday < 0 || record.FoodSpentToday < 0 || record.RecruitsToday < 0 || record.RecruitsToday > 3 || (record.RecruitmentSpentToday > 0 && record.RecruitsToday == 0) || (record.SpendingDay == -1 && (record.RecruitmentSpentToday != 0L || record.FoodSpentToday != 0L || record.RecruitsToday != 0))) { list.Add(text + " daily spending doesn't add up"); } Clan clan = state.Clans.Get(record.OwnerClanId); if (clan == null || clan.IsBandit || record.OwnerClanId != state.PlayerClanId) { list.Add(text + " isn't owned by the player clan"); } Settlement settlement = state.Settlements.Get(record.HomeSettlementId); if (settlement == null || (settlement.Type != SettlementType.Town && settlement.Type != SettlementType.Castle)) { list.Add(text + " has no known home town or castle"); } Hero hero = state.Heroes.Get(record.LeaderHeroId); if (hero == null || hero.Occupation != HeroOccupation.Companion) { list.Add(text + " has no known companion commander"); } Party party = state.Parties.Get(record.PartyId); if (record.IsActive) { num++; if (!hashSet3.Add(record.LeaderHeroId ?? "")) { list.Add(text + " shares its commander with another military party"); } if (party == null || party.Kind != PartyKind.Lord || party.ClanId != record.OwnerClanId || party.LeaderHeroId != record.LeaderHeroId || party.HomeSettlementId != record.HomeSettlementId) { list.Add(text + " has the wrong party id"); } if (hero != null && hero.ClanId != record.OwnerClanId) { list.Add(text + " has a commander from another clan"); } if (hero != null && hero.State == HeroState.Active && party != null && party.State != PartyState.Destroyed && party.State != PartyState.Disbanded && (hero.PartyId != party.Id || !party.Troops.Heroes.Contains(hero.Id) || !string.IsNullOrEmpty(hero.SettlementId))) { list.Add(text + " commander is in the wrong place"); } if (hero != null && hero.State == HeroState.Active) { if (!string.IsNullOrEmpty(hero.CaptorPartyId) || !string.IsNullOrEmpty(hero.CaptorSettlementId)) { list.Add(text + " has an active commander with a captor"); } int num2 = state.Parties.Sum((Party p) => p.Troops.Heroes.Count((string id) => id == hero.Id) + p.Prisoners.Heroes.Count((string id) => id == hero.Id)) + state.Settlements.Sum((Settlement s) => s.Garrison.Heroes.Count((string id) => id == hero.Id) + s.Prisoners.Heroes.Count((string id) => id == hero.Id)); if (num2 > 1 || (party != null && party.State != PartyState.Destroyed && party.State != PartyState.Disbanded && num2 != 1)) { list.Add(text + " has duplicated or missing commander membership"); } } List caravans = state.Caravans; if (caravans != null && caravans.Any((CaravanState c) => c != null && c.IsActive && (c.PartyId == record.PartyId || state.Parties.Get(c.PartyId)?.LeaderHeroId == record.LeaderHeroId))) { list.Add(text + " shares a party or commander with a caravan"); } if (state.Settlements.Any((Settlement s) => s.Management?.GovernorHeroId == record.LeaderHeroId)) { list.Add(text + " has a commander assigned as governor"); } } else { if (party == null) { continue; } if ((party.State == PartyState.Destroyed || party.State == PartyState.Disbanded) && party.Troops.IsEmpty && party.Prisoners.IsEmpty && party.Gold == 0L && party.Food == 0.0) { SortedDictionary cargo = party.Cargo; if (cargo == null || !cargo.Any((KeyValuePair g) => g.Value != 0)) { SortedDictionary equipment = party.Equipment; if (equipment == null || !equipment.Any((KeyValuePair item) => item.Value != 0)) { continue; } } } list.Add(text + " still has a party or money after closure"); } } if (num > 2) { list.Add("more military parties than the clan can command"); } return list; } } public static class NamedCustodyValidation { public static List Check(CampaignState state) { List errors = new List(); Dictionary places = new Dictionary(StringComparer.Ordinal); foreach (Party party2 in state.Parties) { Count(party2.Troops, prisoners: false); Count(party2.Prisoners, prisoners: true); } foreach (Settlement settlement2 in state.Settlements) { Count(settlement2.Garrison, prisoners: false); Count(settlement2.Prisoners, prisoners: true); } foreach (Hero hero in state.Heroes) { bool flag = !string.IsNullOrEmpty(hero.CaptorPartyId); bool flag2 = !string.IsNullOrEmpty(hero.CaptorSettlementId); if (hero.State != HeroState.Captive) { if (flag || flag2) { errors.Add("named custody still on a hero who isn't captive: " + hero.Id); } continue; } string text = "named custody of " + hero.Id; if (flag == flag2 || !string.IsNullOrEmpty(hero.PartyId) || !string.IsNullOrEmpty(hero.SettlementId)) { errors.Add(text + " holder and travelling refs don't agree"); } if (!places.TryGetValue(hero.Id, out var value) || value != 1) { errors.Add(text + " must appear in exactly one roster"); } if (hero.CaptiveSinceMinute < 0 || hero.CaptiveSinceMinute > state.Clock.Minute) { errors.Add(text + " has a bad capture date"); } if (flag) { Party party = state.Parties.Get(hero.CaptorPartyId); if (party != null && party.State != PartyState.Destroyed && party.State != PartyState.Disbanded && state.Clans.Contains(party.ClanId)) { TroopRoster prisoners = party.Prisoners; if (prisoners != null && prisoners.Heroes?.Count((string id) => id == hero.Id) == 1) { goto IL_02d9; } } errors.Add(text + " has no matching live party holder"); } goto IL_02d9; IL_0387: if (hero.IsPlayer && (state.Player.Activity != PlayerActivity.Captive || state.Player.CaptorPartyId != hero.CaptorPartyId || state.Player.CaptorSettlementId != hero.CaptorSettlementId || state.Player.CaptiveSinceMinute != hero.CaptiveSinceMinute)) { errors.Add(text + " doesn't match whether the player is captive"); } continue; IL_02d9: if (flag2) { Settlement settlement = state.Settlements.Get(hero.CaptorSettlementId); if (settlement != null && settlement.Type != SettlementType.Hideout && state.Clans.Contains(settlement.OwnerClanId)) { TroopRoster prisoners2 = settlement.Prisoners; if (prisoners2 != null && prisoners2.Heroes?.Count((string id) => id == hero.Id) == 1) { goto IL_0387; } } errors.Add(text + " has no matching settlement holder"); } goto IL_0387; } return errors; void Count(TroopRoster roster, bool flag3) { foreach (string item in roster?.Heroes ?? new List()) { if (string.IsNullOrEmpty(item)) { if (flag3) { errors.Add("named custody has no hero id"); } } else { places[item] = ((!places.TryGetValue(item, out var value2)) ? 1 : (value2 + 1)); Hero hero2 = state.Heroes.Get(item); if (flag3 && (hero2 == null || hero2.State != HeroState.Captive)) { errors.Add("named custody lists a non-captive or unknown hero " + item); } } } } } } public static class PoliticsValidation { public static List Check(CampaignState state) { List list = new List(); foreach (Clan clan6 in state.Clans) { if (double.IsNaN(clan6.Influence) || double.IsInfinity(clan6.Influence) || clan6.Influence < 0.0) { list.Add("politics clan " + clan6.Id + " has invalid influence"); } } PoliticsState politics = state.Politics; if (politics == null) { return list; } if (!politics.Initialized) { if (politics.LastInfluenceDay == -1) { List decisions = politics.Decisions; if (decisions == null || decisions.Count == 0) { List kingdomPolicies = politics.KingdomPolicies; if (kingdomPolicies == null || kingdomPolicies.Count == 0) { List relations = politics.Relations; if (relations == null || relations.Count == 0) { goto IL_00e4; } } } } list.Add("politics was never set up but has data in it"); goto IL_00e4; } if (politics.LastInfluenceDay < 0 || politics.LastInfluenceDay > state.Clock.Day) { list.Add("politics has an invalid influence day"); } if (politics.KingdomPolicies == null) { list.Add("politics has no policy list"); } else { HashSet hashSet = new HashSet(StringComparer.Ordinal); foreach (KingdomPolicyState kingdomPolicy in politics.KingdomPolicies) { if (kingdomPolicy == null) { list.Add("politics contains an empty policy"); continue; } if (!state.Kingdoms.Contains(kingdomPolicy.KingdomId) || !hashSet.Add(kingdomPolicy.KingdomId ?? "")) { list.Add("politics has an unknown or duplicate policy kingdom"); } if (!Enum.IsDefined(typeof(RealmPolicy), kingdomPolicy.Policy) || kingdomPolicy.ChangedMinute < 0 || kingdomPolicy.ChangedMinute > state.Clock.Minute) { list.Add("politics policy has a bad rule or date"); } } } if (politics.Laws == null) { list.Add("politics has no kingdom policy list"); } else { HashSet hashSet2 = new HashSet(StringComparer.Ordinal); foreach (KingdomLawState law in politics.Laws) { if (law == null) { list.Add("politics contains an empty kingdom policy"); continue; } if (!state.Kingdoms.Contains(law.KingdomId) || law.Law == KingdomLaw.None || !Enum.IsDefined(typeof(KingdomLaw), law.Law) || !hashSet2.Add(law.KingdomId + "\n" + law.Law)) { list.Add("politics has an unknown or duplicate kingdom policy"); } if (law.EnactedMinute < 0 || law.EnactedMinute > state.Clock.Minute) { list.Add("politics kingdom policy has a bad date"); } } foreach (KingdomLawState item in politics.Laws.Where((KingdomLawState l) => l != null)) { KingdomLawDef kingdomLawDef = KingdomLaws.Get(item.Law); if (kingdomLawDef != null && kingdomLawDef.Excludes != KingdomLaw.None && hashSet2.Contains(item.KingdomId + "\n" + kingdomLawDef.Excludes)) { list.Add("politics has policies in force that rule each other out"); } } } if (politics.Relations == null) { list.Add("politics has no clan relation list"); } else { HashSet hashSet3 = new HashSet(StringComparer.Ordinal); foreach (ClanRelationState relation in politics.Relations) { if (relation == null) { list.Add("politics contains an empty clan relation"); continue; } if (state.Clans.Contains(relation.A) && state.Clans.Contains(relation.B) && string.CompareOrdinal(relation.A, relation.B) < 0) { Clan clan = state.Clans.Get(relation.A); if (clan == null || !clan.IsBandit) { Clan clan2 = state.Clans.Get(relation.B); if (clan2 == null || !clan2.IsBandit) { goto IL_0484; } } } list.Add("politics clan relation has bad clan ids"); goto IL_0484; IL_0484: if (!hashSet3.Add(relation.A + "\n" + relation.B)) { list.Add("politics has duplicate clan relations"); } if (relation.Value < -100 || relation.Value > 100 || relation.LastGiftDay < -1 || relation.LastGiftDay > state.Clock.Day) { list.Add("politics clan relation has invalid value or gift day"); } } } if (politics.Decisions == null) { list.Add("politics has no decision list"); return list; } HashSet hashSet4 = new HashSet(StringComparer.Ordinal); HashSet hashSet5 = new HashSet(StringComparer.Ordinal); HashSet hashSet6 = new HashSet(StringComparer.Ordinal); int num = 0; foreach (KingdomDecision decision in politics.Decisions) { if (decision == null) { list.Add("politics contains an empty decision"); continue; } string text = "council decision " + decision.Id; int num2; if (decision.Status != KingdomDecisionStatus.Resolved) { num2 = ((decision.Status == KingdomDecisionStatus.Cancelled) ? 1 : 0); if (num2 == 0) { goto IL_05a8; } } else { num2 = 1; } num++; goto IL_05a8; IL_0946: long num3 = ((decision.Kind == KingdomDecisionKind.MakePeace) ? 1000 : 0); if (decision.TreatyPayment != num3) { list.Add(text + " has an invalid treaty payment"); } if (decision.TargetStanceSinceMinute < -1 || decision.TargetStanceSinceMinute > decision.CreatedMinute || (decision.Kind == KingdomDecisionKind.MakePeace && decision.TargetStanceSinceMinute < 0)) { list.Add(text + " has a bad diplomatic stance date"); } goto IL_09ff; IL_0aff: if (decision.Kind == KingdomDecisionKind.RulerElection) { if (!state.Clans.Contains(decision.CandidateClanId) || !state.Clans.Contains(decision.RivalClanId) || decision.CandidateClanId == decision.RivalClanId || decision.Policy != RealmPolicy.Balanced || decision.Law != KingdomLaw.None) { list.Add(text + " has invalid claimants"); } } else if (!string.IsNullOrEmpty(decision.CandidateClanId) || !string.IsNullOrEmpty(decision.RivalClanId) || decision.Abdication) { list.Add(text + " carries claimants in another proposal"); } bool flag; if (decision.Status == KingdomDecisionStatus.Queued && (flag || (decision.Kind != KingdomDecisionKind.RulerElection && (decision.Kind != KingdomDecisionKind.FiefGrant || string.IsNullOrEmpty(decision.SourceSiegeId))))) { list.Add(text + " isn't a queued capture"); } if (decision.Status == KingdomDecisionStatus.Voting && !hashSet5.Add(decision.KingdomId ?? "")) { list.Add(text + " duplicates a live council in its kingdom"); } if (num2 != 0) { if (decision.ResolvedMinute < decision.CreatedMinute || decision.ResolvedMinute > state.Clock.Minute || (flag && decision.ResolvedMinute < decision.OpenedMinute) || (decision.Status == KingdomDecisionStatus.Resolved && decision.ResolvedMinute < decision.ClosesMinute)) { list.Add(text + " has a bad resolution date"); } if (decision.Status == KingdomDecisionStatus.Cancelled && decision.Passed) { list.Add(text + " passes a cancelled proposal"); } } else if (decision.ResolvedMinute != -1 || decision.Passed || !string.IsNullOrEmpty(decision.Result)) { list.Add(text + " has a result before resolution"); } HashSet hashSet7 = new HashSet(StringComparer.Ordinal); if (decision.EligibleClanIds == null) { list.Add(text + " has no electorate list"); } else { foreach (string eligibleClanId in decision.EligibleClanIds) { if (state.Clans.Contains(eligibleClanId)) { Clan clan3 = state.Clans.Get(eligibleClanId); if ((clan3 == null || !clan3.IsBandit) && hashSet7.Add(eligibleClanId ?? "")) { continue; } } list.Add(text + " has an unknown or duplicate elector"); } } if (flag && hashSet7.Count == 0) { list.Add(text + " opened without an electorate"); } HashSet hashSet8 = new HashSet(StringComparer.Ordinal); if (decision.Ballots == null) { list.Add(text + " has no ballot list"); } else { foreach (CouncilBallot ballot in decision.Ballots) { if (ballot == null) { list.Add(text + " contains an empty ballot"); continue; } if (!hashSet7.Contains(ballot.ClanId ?? "") || !hashSet8.Add(ballot.ClanId ?? "")) { list.Add(text + " has a duplicate ballot or one from a clan that can't vote"); } if (ballot.InfluenceSpent != 0 && ballot.InfluenceSpent != 10 && ballot.InfluenceSpent != 30) { list.Add(text + " has an invalid influence commitment"); } } } if (decision.FinalSupportWeight < 0 || decision.FinalOppositionWeight < 0) { list.Add(text + " has negative vote totals"); } if (decision.Status != KingdomDecisionStatus.Resolved) { if (decision.FinalSupportWeight != 0 || decision.FinalOppositionWeight != 0) { list.Add(text + " has vote totals but no result"); } continue; } long num4 = 0L; long num5 = 0L; foreach (CouncilBallot item2 in decision.Ballots ?? new List()) { if (item2 != null && (item2.InfluenceSpent == 0 || item2.InfluenceSpent == 10 || item2.InfluenceSpent == 30)) { int num6 = (1 + item2.InfluenceSpent / 10) * ((!(item2.ClanId == decision.RulerClanId)) ? 1 : 2); if (item2.Support) { num4 += num6; } else { num5 += num6; } } } if (decision.FinalSupportWeight > num4 || decision.FinalOppositionWeight > num5 || decision.Passed != decision.FinalSupportWeight > decision.FinalOppositionWeight) { list.Add(text + " vote totals don't match its ballots or result"); } continue; IL_0692: bool num7; if (num7 != 0) { goto IL_0694; } goto IL_06a6; IL_06a6: if (!state.Kingdoms.Contains(decision.KingdomId) || !state.Clans.Contains(decision.ProposerClanId) || !state.Clans.Contains(decision.RulerClanId)) { list.Add(text + " has an unknown realm or clan"); } if (decision.CreatedMinute < 0 || decision.CreatedMinute > state.Clock.Minute) { list.Add(text + " has a bad creation date"); } if (decision.Kind == KingdomDecisionKind.FiefGrant) { Settlement settlement = state.Settlements.Get(decision.SettlementId); if (settlement == null || (settlement.Type != SettlementType.Town && settlement.Type != SettlementType.Castle) || !state.Clans.Contains(decision.OwnerClanId) || !state.Clans.Contains(decision.RecipientClanId)) { list.Add(text + " has an unknown fief, owner or recipient"); } } else if (!string.IsNullOrEmpty(decision.SettlementId) || !string.IsNullOrEmpty(decision.OwnerClanId) || !string.IsNullOrEmpty(decision.RecipientClanId) || !string.IsNullOrEmpty(decision.SourceSiegeId)) { list.Add(text + " carries fief data in a non-fief proposal"); } if (decision.Kind == KingdomDecisionKind.ClanExpulsion) { if (state.Clans.Contains(decision.TargetClanId)) { Clan clan4 = state.Clans.Get(decision.TargetClanId); if ((clan4 == null || !clan4.IsBandit) && !(decision.TargetClanId == decision.RulerClanId) && !(decision.TargetClanId == decision.ProposerClanId) && !(decision.ProposerClanId != decision.RulerClanId) && decision.Policy == RealmPolicy.Balanced) { goto IL_089d; } } list.Add(text + " has a bad expulsion target or proposer"); } else if (!string.IsNullOrEmpty(decision.TargetClanId)) { list.Add(text + " carries an expulsion target in another proposal"); } goto IL_089d; IL_09ff: if (!string.IsNullOrEmpty(decision.SourceSiegeId) && !hashSet6.Add(decision.SourceSiegeId)) { list.Add(text + " queues the same capture twice"); } flag = decision.OpenedMinute != -1; if (!flag) { if (decision.ClosesMinute == -1 && decision.Status != KingdomDecisionStatus.Voting && decision.Status != KingdomDecisionStatus.Resolved) { List eligibleClanIds = decision.EligibleClanIds; if (eligibleClanIds == null || eligibleClanIds.Count == 0) { List ballots = decision.Ballots; if (ballots == null || ballots.Count == 0) { goto IL_0aff; } } } list.Add(text + " has votes before it opened"); } else if (decision.OpenedMinute < decision.CreatedMinute || decision.OpenedMinute > state.Clock.Minute || decision.OpenedMinute > 9223372036854772927L || decision.ClosesMinute != decision.OpenedMinute + 2880) { list.Add(text + " has an invalid voting window"); } goto IL_0aff; IL_0694: list.Add(text + " terms don't match its kind"); goto IL_06a6; IL_05a8: if (string.IsNullOrEmpty(decision.Id) || !hashSet4.Add(decision.Id)) { list.Add(text + " has a duplicate or missing id"); } if (!Enum.IsDefined(typeof(KingdomDecisionKind), decision.Kind) || !Enum.IsDefined(typeof(KingdomDecisionStatus), decision.Status) || !Enum.IsDefined(typeof(RealmPolicy), decision.Policy) || !Enum.IsDefined(typeof(KingdomLaw), decision.Law)) { list.Add(text + " has an unknown kind, status or policy"); } if (decision.Kind != KingdomDecisionKind.Law) { if (decision.Law == KingdomLaw.None) { num7 = decision.Repeal; goto IL_0692; } } else if (decision.Law != KingdomLaw.None) { num7 = decision.Policy != RealmPolicy.Balanced; goto IL_0692; } goto IL_0694; IL_089d: if (decision.Kind == KingdomDecisionKind.DeclareWar || decision.Kind == KingdomDecisionKind.MakePeace) { if (state.Kingdoms.Contains(decision.TargetKingdomId) && !(decision.TargetKingdomId == decision.KingdomId) && state.Clans.Contains(decision.TargetRulerClanId)) { Clan clan5 = state.Clans.Get(decision.TargetRulerClanId); if ((clan5 == null || !clan5.IsBandit) && !(decision.TargetRulerClanId == decision.RulerClanId) && decision.Policy == RealmPolicy.Balanced) { goto IL_0946; } } list.Add(text + " has a bad diplomatic target or ruler"); goto IL_0946; } if (!string.IsNullOrEmpty(decision.TargetKingdomId) || !string.IsNullOrEmpty(decision.TargetRulerClanId) || decision.TreatyPayment != 0L || decision.TargetStanceSinceMinute != -1) { list.Add(text + " has diplomatic terms on a non-diplomatic proposal"); } goto IL_09ff; } if (num > 24) { list.Add("politics contains too much resolved council history"); } return list; IL_00e4: return list; } } public static class QuestValidation { public static List Check(CampaignState state) { List list = new List(); QuestsState qs = state?.Quests; if (qs == null) { return list; } if (qs.Quests == null || qs.Sites == null || qs.GiverNextDay == null || qs.StoriesTold == null) { list.Add("quests are missing their lists"); return list; } HashSet hashSet = new HashSet(TabsBannerlord.Core.Campaign.Campaign.QuestTemplateIds, StringComparer.Ordinal); HashSet hashSet2 = new HashSet(StringComparer.Ordinal); foreach (QuestState q in qs.Quests) { if (q == null) { list.Add("a quest record is missing"); continue; } string text = "quest " + q.Id; if (string.IsNullOrEmpty(q.Id) || !hashSet2.Add(q.Id)) { list.Add(text + " has a missing or repeated id"); } if (!hashSet.Contains(q.TemplateId)) { list.Add(text + " is of an unknown kind " + q.TemplateId); } if (!Enum.IsDefined(typeof(QuestStatus), q.Status) || !Enum.IsDefined(typeof(QuestSource), q.Source)) { list.Add(text + " has an unknown status or source"); } if (q.Escrow < 0 || q.Reward < 0) { list.Add(text + " has negative escrow or reward"); } if (q.Escrow > 0 && string.IsNullOrEmpty(q.EscrowFrom)) { list.Add(text + " holds escrow from nobody"); } if (q.Status == QuestStatus.Offered && q.Escrow > 0) { list.Add(text + " holds escrow before it was accepted"); } if (q.Log == null) { list.Add(text + " has no log"); } if (q.Status == QuestStatus.Active) { if (q.AcceptedMinute < 0 || q.AcceptedMinute > state.Clock.Minute) { list.Add(text + " was accepted at an impossible time"); } if (q.EndedMinute >= 0 || q.Result.Length > 0) { list.Add(text + " is under way but has an ending"); } if (!string.IsNullOrEmpty(q.GiverHeroId) && !state.Heroes.Contains(q.GiverHeroId)) { list.Add(text + " names an unknown giver " + q.GiverHeroId); } if (!string.IsNullOrEmpty(q.GiverNotableId)) { List notables = state.Notables; if (notables == null || !notables.Any((NotableState n) => n.Id == q.GiverNotableId)) { list.Add(text + " names an unknown notable " + q.GiverNotableId); } } string[] array = new string[3] { q.GiverSettlementId, q.TargetSettlementId, q.OtherSettlementId }; foreach (string text2 in array) { if (!string.IsNullOrEmpty(text2) && !state.Settlements.Contains(text2)) { list.Add(text + " names an unknown settlement " + text2); } } array = new string[2] { q.TargetSiteId, q.OtherSiteId }; foreach (string s in array) { if (!string.IsNullOrEmpty(s) && !qs.Sites.Any((DiscoverySite x) => x.Id == s)) { list.Add(text + " names an unknown site " + s); } } if (q.Hours < 0 || q.Progress < 0) { list.Add(text + " has negative progress"); } } else if (q.Status != QuestStatus.Offered && q.EndedMinute < 0) { list.Add(text + " ended at no time"); } } if (qs.Quests.Count((QuestState questState) => questState != null && questState.Status == QuestStatus.Active) > 4) { list.Add("more than " + 4 + " quests are under way"); } if (!string.IsNullOrEmpty(qs.TrackedQuestId) && !qs.Quests.Any((QuestState questState) => questState != null && questState.Id == qs.TrackedQuestId && questState.Status == QuestStatus.Active)) { list.Add("the tracked quest " + qs.TrackedQuestId + " is not under way"); } HashSet hashSet3 = new HashSet(StringComparer.Ordinal); foreach (DiscoverySite s2 in qs.Sites) { if (s2 == null) { list.Add("a discovery site is missing"); continue; } if (string.IsNullOrEmpty(s2.Id) || !hashSet3.Add(s2.Id)) { list.Add("discovery site " + s2.Id + " has a missing or repeated id"); } if (double.IsNaN(s2.Position.X) || double.IsNaN(s2.Position.Y) || double.IsInfinity(s2.Position.X) || double.IsInfinity(s2.Position.Y)) { list.Add("discovery site " + s2.Id + " has no position"); } if (s2.Explored && !s2.Found) { list.Add("discovery site " + s2.Id + " was explored but never found"); } if (!string.IsNullOrEmpty(s2.QuestId) && !qs.Quests.Any((QuestState questState) => questState != null && questState.Id == s2.QuestId) && !s2.Explored) { list.Add("discovery site " + s2.Id + " belongs to an unknown quest " + s2.QuestId); } } StoryEventsState storyEvents = state.StoryEvents; if (storyEvents != null) { if (storyEvents.CooldownUntilDay == null || storyEvents.History == null) { list.Add("random events are missing their lists"); } HashSet hashSet4 = new HashSet(TabsBannerlord.Core.Campaign.Campaign.StoryEventIds, StringComparer.Ordinal); if (storyEvents.Pending != null && (!hashSet4.Contains(storyEvents.Pending.EventId) || string.IsNullOrEmpty(storyEvents.Pending.InstanceId))) { list.Add("the waiting random event " + storyEvents.Pending.EventId + " is unknown"); } if (storyEvents.Started && storyEvents.NextDay < 0) { list.Add("random events have no next day"); } } return list; } } public static class RaidValidation { public static List Check(CampaignState state) { List list = new List(); long minute = state.Clock.Minute; long day = state.Clock.Day; foreach (Settlement settlement3 in state.Settlements) { VillageRecoveryState villageRecovery = settlement3.VillageRecovery; if (villageRecovery == null) { continue; } string text = "village recovery at " + settlement3.Id; if (villageRecovery.Damage < 0 || villageRecovery.Damage > 100) { list.Add(text + " has invalid damage"); } if (villageRecovery.LastRecoveryDay < -1 || villageRecovery.LastRecoveryDay > day || villageRecovery.LastAidDay < -1 || villageRecovery.LastAidDay > day || villageRecovery.LastPlayerRaidDay < -1 || villageRecovery.LastPlayerRaidDay > day || villageRecovery.LastRaidMinute < -1 || villageRecovery.LastRaidMinute > minute) { list.Add(text + " has bad accounting dates"); } if (!villageRecovery.Initialized) { if (villageRecovery.Damage != 0 || villageRecovery.LastRecoveryDay != -1 || villageRecovery.LastAidDay != -1 || villageRecovery.LastPlayerRaidDay != -1 || villageRecovery.LastRaidMinute != -1 || (villageRecovery.ProductionRemainders != null && villageRecovery.ProductionRemainders.Count > 0)) { list.Add(text + " has progress before it started"); } } else if (villageRecovery.LastRecoveryDay < 0 || (villageRecovery.LastRaidMinute >= 0 && villageRecovery.LastRecoveryDay < villageRecovery.LastRaidMinute / 1440)) { list.Add(text + " has no daily recovery limit set"); } if (settlement3.Type != SettlementType.Village && (villageRecovery.Damage != 0 || villageRecovery.LastAidDay != -1 || villageRecovery.LastPlayerRaidDay != -1 || villageRecovery.LastRaidMinute != -1 || (villageRecovery.ProductionRemainders != null && villageRecovery.ProductionRemainders.Count > 0))) { list.Add(text + " applies village effects to another settlement type"); } if (villageRecovery.ProductionRemainders == null) { continue; } foreach (KeyValuePair remainder in villageRecovery.ProductionRemainders) { if (!TradeGoods.All.Any((TradeGoodDef g) => g.Id == remainder.Key)) { list.Add(text + " references an unknown production good " + remainder.Key); } if (!Finite(remainder.Value) || remainder.Value < 0.0 || remainder.Value >= 1.0) { list.Add(text + " has an invalid production remainder for " + remainder.Key); } } } HashSet hashSet = new HashSet(StringComparer.Ordinal); foreach (Party party in state.Parties) { MovementOrder order = party.Order; RaidState activeRaid = party.ActiveRaid; if (order != null && order.Kind == OrderKind.Raid) { Settlement settlement = state.Settlements.Get(order.TargetId); if (settlement == null || settlement.Type != SettlementType.Village) { list.Add("raid order for " + party.Id + " has no known village"); } if (order.IssuedAtMinute < 0 || order.IssuedAtMinute > minute) { list.Add("raid order for " + party.Id + " has a bad issue date"); } if (order.PathIndex < 0 || order.PathIndex > (order.Path?.Count ?? 0)) { list.Add("raid order for " + party.Id + " has an invalid path position"); } } if (activeRaid != null) { string text2 = "raid by " + party.Id; Settlement settlement2 = state.Settlements.Get(activeRaid.SettlementId); if (settlement2 == null || settlement2.Type != SettlementType.Village) { list.Add(text2 + " has no known village"); } if (string.IsNullOrEmpty(activeRaid.OwnerClanId) || !state.Clans.Contains(activeRaid.OwnerClanId)) { list.Add(text2 + " has no recorded owner"); } if (!hashSet.Add(activeRaid.SettlementId ?? "")) { list.Add(text2 + " duplicates a raid on the same village"); } if ((party.Kind != PartyKind.Player && party.Kind != PartyKind.Lord) || party.State != PartyState.Active || !string.IsNullOrEmpty(party.CurrentSettlementId) || !string.IsNullOrEmpty(party.EncounterId) || string.IsNullOrEmpty(party.ClanId) || !state.Clans.Contains(party.ClanId)) { list.Add(text2 + " is not a free field warband"); } if (order == null || order.Kind != OrderKind.Raid || order.TargetId != activeRaid.SettlementId || order.HasPath) { list.Add(text2 + " does not match a stationary raid order"); } if (!Finite(party.Position.X) || !Finite(party.Position.Y) || (settlement2 != null && (!Finite(settlement2.Position.X) || !Finite(settlement2.Position.Y) || Vec2.Distance(party.Position, settlement2.Position) > 0.01))) { list.Add(text2 + " is not physically at the village"); } if (activeRaid.StartedAtMinute < 0 || activeRaid.StartedAtMinute > minute || activeRaid.LastProgressMinute < activeRaid.StartedAtMinute || activeRaid.LastProgressMinute > minute || (order != null && order.IssuedAtMinute > activeRaid.StartedAtMinute)) { list.Add(text2 + " has bad progress dates"); } if (activeRaid.RequiredMinutes < 360 || activeRaid.RequiredMinutes > 1440 || activeRaid.ProgressMinutes < 0 || activeRaid.ProgressMinutes >= activeRaid.RequiredMinutes || (activeRaid.StartedAtMinute >= 0 && activeRaid.LastProgressMinute >= activeRaid.StartedAtMinute && activeRaid.ProgressMinutes != activeRaid.LastProgressMinute - activeRaid.StartedAtMinute)) { list.Add(text2 + " has invalid elapsed progress"); } } } return list; } private static bool Finite(double value) { if (!double.IsNaN(value)) { return !double.IsInfinity(value); } return false; } } public static class RealmValidation { public static List Check(CampaignState state) { List list = new List(); ClanServiceState clanService = state.ClanService; long day = state.Clock.Day; if (clanService != null) { if (!Enum.IsDefined(typeof(ClanServiceKind), clanService.Kind)) { list.Add("clan service has an unknown kind"); } if (clanService.LastPayment < 0 || clanService.LastPayment > 50) { list.Add("clan service has an invalid last payment"); } if (clanService.StartedDay < 0 || clanService.StartedDay > day || clanService.LastPaidDay < -1 || clanService.LastPaidDay > day) { list.Add("clan service has a bad accounting day"); } if (!clanService.Initialized) { if (clanService.Kind != ClanServiceKind.Independent || !string.IsNullOrEmpty(clanService.KingdomId) || clanService.StartedDay != 0L || clanService.EndsDay != -1 || clanService.LastPaidDay != -1 || clanService.LastPayment != 0L) { list.Add("clan service was never started but has a contract"); } } else { if (clanService.LastPaidDay < clanService.StartedDay) { list.Add("clan service accounts start before the service does"); } if (state.PlayerClan == null) { list.Add("clan service has no player clan"); } else if (clanService.KingdomId != state.PlayerClan.KingdomId) { list.Add("clan service does not match the player's allegiance"); } if (clanService.Kind == ClanServiceKind.Independent) { if (!string.IsNullOrEmpty(clanService.KingdomId)) { list.Add("independent clan service names a kingdom"); } } else if (string.IsNullOrEmpty(clanService.KingdomId) || !state.Kingdoms.Contains(clanService.KingdomId)) { list.Add("clan service names an unknown kingdom"); } if (clanService.Kind == ClanServiceKind.Ruler && state.Kingdoms.Get(clanService.KingdomId)?.RulerClanId != state.PlayerClanId) { list.Add("ruler service does not belong to the kingdom's ruling clan"); } if (clanService.Kind == ClanServiceKind.Mercenary) { if (clanService.EndsDay != clanService.StartedDay + 7) { list.Add("mercenary service has an invalid term"); } } else if (clanService.EndsDay != -1 || clanService.LastPayment != 0L) { list.Add("non-mercenary service still has a payment or deadline"); } } } HashSet hashSet = new HashSet(StringComparer.Ordinal); foreach (Settlement settlement in state.Settlements) { SettlementManagementState management = settlement.Management; if (management == null) { continue; } string text = "governor at " + settlement.Id; if (management.LastGovernorDay < -1 || management.LastGovernorDay > day || management.GovernorPaidDay < -1 || management.GovernorPaidDay > management.LastGovernorDay) { list.Add(text + " has invalid payroll days"); } if (string.IsNullOrEmpty(management.GovernorHeroId)) { if (management.GovernorPaidDay != -1) { list.Add(text + " has salary credited to an empty appointment"); } continue; } if (!management.Initialized || management.LastGovernorDay < 0) { list.Add(text + " has no appointment set up"); } if (settlement.Type != SettlementType.Town && settlement.Type != SettlementType.Castle) { list.Add(text + " is outside a town or castle"); } if (!hashSet.Add(management.GovernorHeroId)) { list.Add(text + " is appointed to several settlements"); } Hero hero = state.Heroes.Get(management.GovernorHeroId); if (hero == null) { list.Add(text + " names an unknown hero"); continue; } if (hero.Occupation != HeroOccupation.Companion) { list.Add(text + " is not a companion"); } if (string.IsNullOrEmpty(hero.ClanId) || !state.Clans.Contains(hero.ClanId) || (hero.ClanId != settlement.OwnerClanId && hero.ClanId != management.OwnerClanId)) { list.Add(text + " has no owning clan affiliation"); } if (hero.State != HeroState.Dead && hero.State != HeroState.Captive) { if (hero.State != HeroState.Active || hero.SettlementId != settlement.Id || !string.IsNullOrEmpty(hero.PartyId) || !string.IsNullOrEmpty(hero.CaptorPartyId) || !string.IsNullOrEmpty(hero.CaptorSettlementId)) { list.Add(text + " is not resident and free at the settlement"); } if (state.Parties.Any((Party p) => p.Troops.Heroes.Contains(hero.Id) || p.Prisoners.Heroes.Contains(hero.Id) || (p.LeaderHeroId == hero.Id && p.State != PartyState.Destroyed && p.State != PartyState.Disbanded)) || state.Settlements.Any((Settlement s) => s.Garrison.Heroes.Contains(hero.Id) || s.Prisoners.Heroes.Contains(hero.Id))) { list.Add(text + " is also assigned to a roster or party command"); } } } return list; } } public static class RebellionValidation { public static List Check(CampaignState state) { List list = new List(); if (state?.Settlements == null) { return list; } foreach (Settlement settlement in state.Settlements) { if (double.IsNaN(settlement.Unrest) || double.IsInfinity(settlement.Unrest) || settlement.Unrest < 0.0 || settlement.Unrest > 30.000000001) { list.Add("settlement " + settlement.Id + " has unrest out of bounds (" + settlement.Unrest + ")"); } } RebellionState rebellions = state.Rebellions; if (rebellions == null) { return list; } if (rebellions.Records == null) { list.Add("rebellions have no record list"); return list; } HashSet hashSet = new HashSet(StringComparer.Ordinal); HashSet hashSet2 = new HashSet(StringComparer.Ordinal); foreach (RebellionRecord record in rebellions.Records) { if (record == null) { list.Add("a rebellion record is missing"); continue; } string text = "rebellion " + record.Id; if (string.IsNullOrEmpty(record.Id) || !hashSet.Add(record.Id)) { list.Add(text + " has a missing or repeated id"); } Clan clan = state.Clans.Get(record.ClanId); if (clan == null) { list.Add(text + " names an unknown clan " + record.ClanId); } if (!state.Settlements.Contains(record.SettlementId)) { list.Add(text + " names an unknown settlement " + record.SettlementId); } if (!Enum.IsDefined(typeof(RebellionOutcome), record.Outcome)) { list.Add(text + " has an unknown outcome"); } if (record.Outcome == RebellionOutcome.Holding) { if (record.EndedDay >= 0) { list.Add(text + " is still holding but has an end day"); } if (clan != null && clan.IsEliminated) { list.Add(text + " is still holding but its clan is no more"); } if (!hashSet2.Add(record.ClanId)) { list.Add(text + " repeats a standing rebel clan"); } } else if (record.EndedDay < record.RoseDay) { list.Add(text + " ended before it began"); } if (record.Outcome == RebellionOutcome.JoinedKingdom && !state.Kingdoms.Contains(record.KingdomId)) { list.Add(text + " joined an unknown kingdom " + record.KingdomId); } } return list; } } public static class RescueValidation { public static List Check(CampaignState state) { List list = new List(); BattleReport battleReport = state.Player?.LastReport; if (battleReport == null) { return list; } if (battleReport.RescuedRecruited < 0 || battleReport.RescuedReleased < 0) { list.Add("battle rescue has negative resolved counts"); } TroopRoster rescuedTroops = battleReport.RescuedTroops; long num = 0L; if (rescuedTroops != null) { if (rescuedTroops.Stacks == null || rescuedTroops.Heroes == null) { list.Add("battle rescue has missing roster collections"); } if (rescuedTroops.Heroes != null && rescuedTroops.Heroes.Count != 0) { list.Add("battle rescue must not contain named heroes"); } HashSet hashSet = new HashSet(StringComparer.Ordinal); foreach (TroopStack item in rescuedTroops.Stacks ?? new List()) { if (item == null) { list.Add("battle rescue has a missing troop stack"); continue; } if (string.IsNullOrEmpty(item.UnitId) || !hashSet.Add(item.UnitId)) { list.Add("battle rescue has a missing or duplicate troop id"); } long num2 = (long)item.Healthy + (long)item.Wounded; if (item.Healthy < 0 || item.Wounded < 0 || num2 <= 0 || num2 > int.MaxValue || item.Xp < 0) { list.Add("battle rescue has invalid counts or experience for " + item.UnitId); } if (item.PrisonerRecruitment != 0.0) { list.Add("battle rescue still holds prisoner willingness for " + item.UnitId); } num += num2; } } long num3 = (long)battleReport.RescuedRecruited + (long)battleReport.RescuedReleased; if (num > int.MaxValue || num + num3 > int.MaxValue) { list.Add("battle rescue has more troops than allowed"); } if (num > 0 && state.Player.LastReportSeen) { list.Add("battle rescue remains after the report was closed"); } if (num > 0 || num3 > 0) { if (string.IsNullOrEmpty(battleReport.EncounterId) || !state.CommittedEncounters.Contains(battleReport.EncounterId)) { list.Add("battle rescue has no committed origin"); } if (!battleReport.PlayerWon || battleReport.PlayerCaptured || (battleReport.EndKind != BattleEndKind.Victory && battleReport.EndKind != BattleEndKind.Surrender) || (battleReport.Winner != WinnerSide.Attacker && battleReport.Winner != WinnerSide.Defender)) { list.Add("battle rescue has a result that isn't allowed"); } List list2 = battleReport.Parties?.Where((PartyBattleReport p) => p != null && p.PartyId == state.PlayerPartyId).ToList(); BattleSide battleSide = ((battleReport.Winner != WinnerSide.Attacker) ? BattleSide.Defender : BattleSide.Attacker); if (list2 == null || list2.Count != 1 || list2[0].Side != battleSide || list2[0].Destroyed) { list.Add("battle rescue has no surviving player participant on the winning side"); } if (battleReport.RescueMinute < 0 || battleReport.RescueMinute > state.Clock.Minute) { list.Add("battle rescue has a bad offer date"); } if (!Finite(battleReport.RescuePosition.X) || !Finite(battleReport.RescuePosition.Y)) { list.Add("battle rescue has an invalid battlefield position"); } } return list; } private static bool Finite(double value) { if (!double.IsNaN(value)) { return !double.IsInfinity(value); } return false; } } public static class ScoutingValidation { public static List Check(CampaignState state) { List list = new List(); ScoutingState scoutingState = state?.Scouting; if (scoutingState == null) { return list; } HashSet hashSet = new HashSet(StringComparer.Ordinal); foreach (ScoutMissionState item in scoutingState.Missions ?? new List()) { if (item == null) { list.Add("a scout's mission is empty"); continue; } string text = "scout " + item.Id; if (string.IsNullOrEmpty(item.Id) || !hashSet.Add(item.Id)) { list.Add(text + " has a missing or repeated id"); } if (!Fortified(state, item.TargetId)) { list.Add(text + " is not sent to a town or castle"); } if (item.Rating < 1 || item.Rating > 5) { list.Add(text + " has a rating out of range"); } if (item.Price < 0) { list.Add(text + " was paid a negative fee"); } if (item.ObserveMinute < item.HiredMinute || item.ReturnMinute < item.ObserveMinute) { list.Add(text + " comes back before setting out"); } if (item.Report != null) { CheckReport(state, item.Report, text, list); } } foreach (KeyValuePair item2 in scoutingState.Reports ?? new SortedDictionary(StringComparer.Ordinal)) { string text2 = "scout report on " + item2.Key; if (item2.Value == null) { list.Add(text2 + " is empty"); continue; } if (item2.Value.SettlementId != item2.Key) { list.Add(text2 + " is filed under another settlement"); } CheckReport(state, item2.Value, text2, list); } return list; } private static bool Fortified(CampaignState state, string id) { Settlement settlement = state.Settlements.Get(id ?? ""); if (settlement != null) { if (settlement.Type != SettlementType.Town) { return settlement.Type == SettlementType.Castle; } return true; } return false; } private static void CheckReport(CampaignState state, ScoutReportState r, string label, List errors) { if (!Fortified(state, r.SettlementId)) { errors.Add(label + " is not about a town or castle"); } if (r.Rating < 1 || r.Rating > 5) { errors.Add(label + " has a rating out of range"); } if (r.FoodLow < 0 || r.FoodHigh < r.FoodLow || r.DefendersLow < 0 || r.DefendersHigh < r.DefendersLow || r.OthersLow < 0 || r.OthersHigh < r.OthersLow) { errors.Add(label + " has a broken range"); } if (r.WallLevel < 1 || r.WallLevel > 3) { errors.Add(label + " has walls of an unknown level"); } foreach (ScoutedUnitState item in r.Units ?? new List()) { if (item == null || string.IsNullOrEmpty(item.UnitId) || item.Low < 0 || item.High < item.Low) { errors.Add(label + " counts a troop wrongly"); } } } } public static class SiegeValidation { public static List Check(CampaignState state) { List list = new List(); List list2 = state.Sieges ?? new List(); HashSet hashSet = new HashSet(StringComparer.Ordinal); HashSet hashSet2 = new HashSet(StringComparer.Ordinal); HashSet hashSet3 = new HashSet(StringComparer.Ordinal); HashSet hashSet4 = new HashSet(StringComparer.Ordinal); long minute = state.Clock.Minute; foreach (Settlement settlement3 in state.Settlements) { if (settlement3.Militia < 0 || settlement3.WoundedMilitia < 0 || (long)settlement3.Militia + (long)settlement3.WoundedMilitia > int.MaxValue) { list.Add("siege militia at " + settlement3.Id + " has invalid healthy or wounded counts"); } } foreach (SiegeState item in list2) { if (item == null) { list.Add("siege list contains an empty record"); continue; } string text = "siege " + item.Id; Settlement settlement = state.Settlements.Get(item.SettlementId ?? ""); int wallLevel = ((settlement == null) ? 1 : Math.Max(1, Math.Min(3, settlement.WallLevel))); CheckWorks(item.Works, SiegeWorksRules.WallMaxHealthFor(wallLevel), text, list); if (string.IsNullOrEmpty(item.Id) || !hashSet.Add(item.Id)) { list.Add(text + " has a duplicate or missing id"); } if (!Enum.IsDefined(typeof(SiegeStage), item.Stage) || !Enum.IsDefined(typeof(SiegeCapturePolicy), item.CapturePolicy)) { list.Add(text + " has an unknown stage or capture policy"); } Settlement settlement2 = state.Settlements.Get(item.SettlementId); if (settlement2 == null || (settlement2.Type != SettlementType.Town && settlement2.Type != SettlementType.Castle)) { list.Add(text + " has no known town or castle"); } if (string.IsNullOrEmpty(item.OwnerClanId) || !state.Clans.Contains(item.OwnerClanId)) { list.Add(text + " has no recorded owner"); } if (string.IsNullOrEmpty(item.BesiegerPartyId)) { list.Add(text + " has no besieger id"); } if (item.StartedMinute < 0 || item.StartedMinute > minute || item.LastProcessedMinute < item.StartedMinute || item.LastProcessedMinute > minute || item.LastSupplyDay < -1 || item.LastSupplyDay > state.Clock.Day || item.StarvationDays < 0) { list.Add(text + " has bad progress or supply dates"); } if (!Finite(item.PreparationMinutes) || item.PreparationMinutes < 0.0 || item.PreparationMinutes > 360.0) { list.Add(text + " has invalid preparation progress"); } item.KeepTroops?.Validate(text + " keep guard", list); if (item.KeepPending) { list.Add(text + " was saved between the walls and the keep"); } if (item.Stage == SiegeStage.Ended) { if (item.EndedMinute < item.StartedMinute || item.EndedMinute > minute || item.LastProcessedMinute > item.EndedMinute) { list.Add(text + " has a bad end date"); } if (string.IsNullOrEmpty(item.SortieEncounterId) && string.IsNullOrEmpty(item.KeepPartyId)) { TroopRoster keepTroops = item.KeepTroops; if (keepTroops == null || keepTroops.TotalTroops <= 0) { continue; } } list.Add(text + " ended with soldiers still lent out"); continue; } if (item.EndedMinute != -1) { list.Add(text + " ended before its live stage"); } if (!hashSet2.Add(item.SettlementId ?? "") || !hashSet3.Add(item.BesiegerPartyId ?? "")) { list.Add(text + " duplicates a live settlement or besieger"); } Party party = state.Parties.Get(item.BesiegerPartyId); if (party == null || (party.Kind != PartyKind.Player && party.Kind != PartyKind.Lord) || !state.Clans.Contains(party.ClanId)) { list.Add(text + " has no valid field warband"); } if ((item.Stage == SiegeStage.Marching && item.PreparationMinutes != 0.0) || (item.Stage == SiegeStage.Preparing && item.PreparationMinutes >= 360.0) || ((item.Stage == SiegeStage.Ready || item.Stage == SiegeStage.Assault) && item.PreparationMinutes != 360.0)) { list.Add(text + " progress doesn't match its stage"); } if (item.Stage != SiegeStage.Marching && item.StartedMinute >= 0 && item.LastProcessedMinute >= item.StartedMinute && item.PreparationMinutes > (double)(item.LastProcessedMinute - item.StartedMinute)) { list.Add(text + " has preparation before its elapsed campaign time"); } Encounter encounter; bool keepStage; bool num; if (item.Stage == SiegeStage.Assault) { encounter = state.Encounters.Get(item.EncounterId); keepStage = item.KeepStage; if (encounter != null && encounter.Kind == EncounterKind.Siege && !(encounter.SiegeId != item.Id) && encounter.IsKeepBattle == keepStage && !(encounter.InitiatorPartyId != item.BesiegerPartyId) && Enum.IsDefined(typeof(EncounterPhase), encounter.Phase) && Live(encounter) && encounter.AttackerParties != null && encounter.AttackerParties.Contains(item.BesiegerPartyId) && encounter.DefenderParties != null) { if (!keepStage) { if (encounter.DefenderParties.Contains(item.GarrisonPartyId) && encounter.DefenderParties.Contains(item.MilitiaPartyId)) { num = !string.IsNullOrEmpty(item.KeepPartyId); goto IL_06bf; } } else if (encounter.DefenderParties.Contains(item.KeepPartyId) && string.IsNullOrEmpty(item.GarrisonPartyId)) { num = !string.IsNullOrEmpty(item.MilitiaPartyId); goto IL_06bf; } } goto IL_06c1; } if (string.IsNullOrEmpty(item.EncounterId) && string.IsNullOrEmpty(item.GarrisonPartyId) && string.IsNullOrEmpty(item.MilitiaPartyId) && string.IsNullOrEmpty(item.KeepPartyId) && !item.KeepStage) { TroopRoster keepTroops2 = item.KeepTroops; if (keepTroops2 == null || keepTroops2.TotalTroops <= 0) { goto IL_094c; } } list.Add(text + " has defender leases outside an assault"); goto IL_094c; IL_06bf: if (num) { goto IL_06c1; } goto IL_06d3; IL_06d3: if (keepStage) { TroopRoster keepTroops3 = item.KeepTroops; if (keepTroops3 != null && keepTroops3.TotalTroops > 0) { list.Add(text + " holds keep guards outside the keep's fight"); } } if (encounter != null && encounter.AttackerParties != null && encounter.DefenderParties != null && (encounter.AttackerParties.Distinct(StringComparer.Ordinal).Count() != encounter.AttackerParties.Count || encounter.DefenderParties.Distinct(StringComparer.Ordinal).Count() != encounter.DefenderParties.Count || encounter.AttackerParties.Intersect(encounter.DefenderParties, StringComparer.Ordinal).Any())) { list.Add(text + " duplicates a party across its assault sides"); } if (encounter != null && (!Finite(encounter.Position.X) || !Finite(encounter.Position.Y) || (settlement2 != null && Vec2.Distance(encounter.Position, settlement2.Position) > 0.01))) { list.Add(text + " has an assault away from the settlement"); } if (party != null && (party.State != PartyState.Engaged || party.EncounterId != item.EncounterId)) { list.Add(text + " assault leader isn't reserved for it"); } if (settlement2 != null && (settlement2.Garrison == null || !settlement2.Garrison.IsEmpty || settlement2.Militia != 0 || settlement2.WoundedMilitia != 0)) { list.Add(text + " duplicates defenders between settlement and assault"); } if (keepStage) { CheckProxy(state, item, item.KeepPartyId, settlement2, hashSet4, list); } else { CheckProxy(state, item, item.GarrisonPartyId, settlement2, hashSet4, list); CheckProxy(state, item, item.MilitiaPartyId, settlement2, hashSet4, list); } if (!string.IsNullOrEmpty(item.SortieEncounterId)) { list.Add(text + " fights outside the walls during its assault"); } continue; IL_06c1: list.Add(text + " has no reciprocal live assault encounter"); goto IL_06d3; IL_094c: if (!string.IsNullOrEmpty(item.SortieEncounterId)) { CheckSortie(state, item, settlement2, hashSet4, list); } else if (!string.IsNullOrEmpty(item.Sortie) || !string.IsNullOrEmpty(item.SortiePartyId)) { list.Add(text + " has a sortie without its fight"); } bool flag = party != null && (party.State == PartyState.Engaged || !string.IsNullOrEmpty(party.EncounterId) || state.Encounters.Any((Encounter e) => Live(e) && Involves(e, party.Id))); if (party != null && !flag && party.State != PartyState.Destroyed && party.State != PartyState.Disbanded) { MovementOrder order = party.Order; if (party.State != PartyState.Active || !string.IsNullOrEmpty(party.CurrentSettlementId) || order == null || order.Kind != OrderKind.Besiege || order.TargetId != item.SettlementId) { list.Add(text + " has no reciprocal field siege order"); } if (order != null && (order.IssuedAtMinute < 0 || order.IssuedAtMinute > minute || order.PathIndex < 0 || order.PathIndex > (order.Path?.Count ?? 0))) { list.Add(text + " has a bad order date or path"); } if (!Finite(party.Position.X) || !Finite(party.Position.Y) || (item.Stage != SiegeStage.Marching && ((order != null && order.HasPath) || (settlement2 != null && Vec2.Distance(party.Position, settlement2.Position) > 0.01)))) { list.Add(text + " is not physically at its siege camp"); } } } foreach (Party party2 in state.Parties) { if (party2.Kind == PartyKind.SiegeDefender && !hashSet4.Contains(party2.Id)) { list.Add("siege defender " + party2.Id + " has no live assault lease"); } MovementOrder order2 = party2.Order; if (order2 != null && order2.Kind == OrderKind.Besiege && !list2.Any((SiegeState s) => s != null && s.Stage != SiegeStage.Ended && s.BesiegerPartyId == party2.Id && s.SettlementId == party2.Order.TargetId)) { list.Add("siege order for " + party2.Id + " has no live record"); } } foreach (Encounter encounter2 in state.Encounters) { if (Live(encounter2) && !string.IsNullOrEmpty(encounter2.SortieSiegeId) && !list2.Any((SiegeState s) => s != null && s.Id == encounter2.SortieSiegeId && s.Stage != SiegeStage.Ended && s.SortieEncounterId == encounter2.Id && s.Sortie == encounter2.Sortie)) { list.Add("siege sortie " + encounter2.Id + " has no reciprocal live siege"); } if (Live(encounter2) && (encounter2.Kind == EncounterKind.Siege || !string.IsNullOrEmpty(encounter2.SiegeId))) { SiegeState siegeState = list2.FirstOrDefault((SiegeState s) => s != null && s.Id == encounter2.SiegeId); if (encounter2.Kind != EncounterKind.Siege || siegeState == null || siegeState.Stage != SiegeStage.Assault || siegeState.EncounterId != encounter2.Id) { list.Add("siege encounter " + encounter2.Id + " has no reciprocal live siege"); } } } return list; } private static void CheckWorks(SiegeWorksState works, double wallMax, string context, List errors) { if (works != null) { if (!Finite(works.LeftWallHealth) || works.LeftWallHealth < 0.0 || works.LeftWallHealth > wallMax || !Finite(works.RightWallHealth) || works.RightWallHealth < 0.0 || works.RightWallHealth > wallMax) { errors.Add(context + " has invalid siege wall health"); } if (!Finite(works.BombardmentMinutes) || works.BombardmentMinutes < 0.0 || works.BombardmentMinutes >= 30.0) { errors.Add(context + " has a bad siege bombardment date"); } CheckEngines(works.Attackers, 7, defender: false, context, errors); CheckEngines(works.Defenders, 4, defender: true, context, errors); } } private static void CheckEngines(List engines, int count, bool defender, string context, List errors) { if (engines == null || engines.Count != count) { errors.Add(context + " has invalid siege engine slots"); return; } for (int i = 0; i < engines.Count; i++) { SiegeEngineState siegeEngineState = engines[i]; if (siegeEngineState == null || siegeEngineState.Slot != i || !Enum.IsDefined(typeof(SiegeEngineKind), siegeEngineState.Kind)) { errors.Add(context + " has a bad siege engine id"); continue; } bool num = (defender ? (siegeEngineState.Kind == SiegeEngineKind.Catapult) : (siegeEngineState.Kind == SiegeEngineKind.None || ((i >= 4) ? ((i < 6) ? (siegeEngineState.Kind == SiegeEngineKind.SiegeTower) : (siegeEngineState.Kind == SiegeEngineKind.BatteringRam)) : (siegeEngineState.Kind == SiegeEngineKind.Ballista || siegeEngineState.Kind == SiegeEngineKind.Catapult || siegeEngineState.Kind == SiegeEngineKind.Trebuchet)))); double num2 = SiegeWorksRules.MaxHealth(siegeEngineState.Kind); double num3 = SiegeWorksRules.BuildMinutes(siegeEngineState.Kind); if (!num || !Finite(siegeEngineState.Health) || siegeEngineState.Health < 0.0 || siegeEngineState.Health > num2 || !Finite(siegeEngineState.BuildProgress) || siegeEngineState.BuildProgress < 0.0 || siegeEngineState.BuildProgress > num3 || (siegeEngineState.BuildProgress < num3 && siegeEngineState.Health > 0.0)) { errors.Add(context + " has invalid siege engine health, construction or placement"); } } } private static void CheckProxy(CampaignState state, SiegeState siege, string id, Settlement settlement, HashSet proxies, List errors) { string text = "siege " + siege.Id + " defender " + id; Party party = state.Parties.Get(id); if (string.IsNullOrEmpty(id) || !proxies.Add(id) || party == null || party.Kind != PartyKind.SiegeDefender || party.ClanId != siege.OwnerClanId || party.HomeSettlementId != siege.SettlementId || !string.IsNullOrEmpty(party.CurrentSettlementId) || party.State != PartyState.Engaged || party.EncounterId != siege.EncounterId || !party.AiFrozen || !string.IsNullOrEmpty(party.LeaderHeroId)) { errors.Add(text + " has a bad id or reservation"); } if (party == null) { return; } if (!Finite(party.Position.X) || !Finite(party.Position.Y) || (settlement != null && Vec2.Distance(party.Position, settlement.Position) > 0.01)) { errors.Add(text + " is not physically at the settlement"); } if (party.Troops != null && party.Troops.Heroes != null && party.Troops.Heroes.Count == 0 && party.Prisoners != null && party.Prisoners.IsEmpty && party.Gold == 0L && party.Food == 0.0) { SortedDictionary cargo = party.Cargo; if (cargo == null || !cargo.Any((KeyValuePair g) => g.Value != 0)) { SortedDictionary equipment = party.Equipment; if (equipment == null || !equipment.Any((KeyValuePair item) => item.Value != 0)) { MovementOrder order = party.Order; if (order != null && order.Kind == OrderKind.None && party.ActiveRaid == null) { Dictionary roleAssignments = party.RoleAssignments; if (roleAssignments == null || roleAssignments.Count <= 0) { goto IL_024a; } } } } } errors.Add(text + " contains assets or orders outside its defender lease"); goto IL_024a; IL_024a: if (state.Encounters.Count((Encounter e) => Live(e) && Involves(e, id)) != 1) { errors.Add(text + " has duplicate or missing encounter reservations"); } } private static void CheckSortie(CampaignState state, SiegeState siege, Settlement settlement, HashSet proxies, List errors) { string text = "siege " + siege.Id + " sortie " + siege.SortieEncounterId; Encounter encounter = state.Encounters.Get(siege.SortieEncounterId); if (siege.Sortie != "sally" && siege.Sortie != "breakout" && siege.Sortie != "breakin") { errors.Add(text + " has an unknown kind"); } if (encounter == null || !Live(encounter) || encounter.SortieSiegeId != siege.Id || encounter.Sortie != siege.Sortie || encounter.Kind == EncounterKind.Siege) { errors.Add(text + " has no reciprocal live fight"); } if (string.IsNullOrEmpty(siege.SortiePartyId)) { return; } Party party = state.Parties.Get(siege.SortiePartyId); Party party2 = state.Parties.Get(siege.BesiegerPartyId); string text2 = ((siege.Sortie == "sally") ? siege.OwnerClanId : (party2?.ClanId ?? "")); if (party == null || !proxies.Add(party.Id) || party.Kind != PartyKind.SiegeDefender || party.ClanId != text2 || party.HomeSettlementId != siege.SettlementId || party.State != PartyState.Engaged || party.EncounterId != siege.SortieEncounterId || !party.AiFrozen || !string.IsNullOrEmpty(party.LeaderHeroId) || !string.IsNullOrEmpty(party.CurrentSettlementId)) { errors.Add(text + " has a bad lent party"); return; } if (settlement != null && Vec2.Distance(party.Position, settlement.Position) > 0.01) { errors.Add(text + "'s lent party is not at the settlement"); } if (party.Troops.Heroes.Count == 0) { MovementOrder order = party.Order; if (order != null && order.Kind == OrderKind.None && party.ActiveRaid == null) { Dictionary roleAssignments = party.RoleAssignments; if (roleAssignments == null || roleAssignments.Count <= 0) { goto IL_029c; } } } errors.Add(text + "'s lent party has heroes or orders"); goto IL_029c; IL_029c: if (state.Encounters.Count((Encounter e) => Live(e) && Involves(e, party.Id)) != 1) { errors.Add(text + "'s lent party has duplicate or missing encounter reservations"); } } private static bool Live(Encounter encounter) { if (encounter.Phase != EncounterPhase.Committed) { return encounter.Phase != EncounterPhase.Cancelled; } return false; } private static bool Involves(Encounter encounter, string id) { if (!(encounter.InitiatorPartyId == id)) { List attackerParties = encounter.AttackerParties; if (attackerParties == null || !attackerParties.Contains(id)) { return encounter.DefenderParties?.Contains(id) ?? false; } } return true; } private static bool Finite(double value) { if (!double.IsNaN(value)) { return !double.IsInfinity(value); } return false; } } public static class SmithingValidation { public static List Check(CampaignState state) { List list = new List(); SmithingState smithingState = state?.Smithing; if (smithingState == null) { return list; } foreach (KeyValuePair item in smithingState.Stamina ?? new SortedDictionary(StringComparer.Ordinal)) { if (state.Heroes?.Get(item.Key) == null || double.IsNaN(item.Value) || double.IsInfinity(item.Value) || item.Value < 0.0 || item.Value > Smithing.MaximumStamina(300)) { list.Add("smithing stamina for " + item.Key + " is invalid"); } } foreach (string item2 in smithingState.UnlockedParts ?? new SortedSet(StringComparer.Ordinal)) { if (Smithing.Part(item2) == null) { list.Add("smithing has learned an unknown part " + item2); } } foreach (KeyValuePair item3 in smithingState.Research ?? new SortedDictionary(StringComparer.Ordinal)) { if (!Smithing.TryParseClass(item3.Key, out var _) || item3.Value < 0) { list.Add("smithing research for " + item3.Key + " is invalid"); } } long num = 0L; foreach (KeyValuePair item4 in smithingState.Weapons ?? new SortedDictionary(StringComparer.Ordinal)) { CraftedWeaponState value = item4.Value; string text = "forged weapon " + item4.Key; if (value == null || value.Id != item4.Key || !Smithing.IsCraftedId(value.Id)) { list.Add(text + " is malformed"); continue; } if (long.TryParse(value.Id.Substring("crafted.".Length), NumberStyles.None, CultureInfo.InvariantCulture, out var result)) { num = Math.Max(num, result); } else { list.Add(text + " has an invalid id"); } if (Smithing.DesignReason(value.Class, value.Parts).Length > 0) { list.Add(text + " has an invalid design"); } if (!Enum.IsDefined(typeof(WeaponQuality), value.Quality)) { list.Add(text + " has an invalid quality"); } if (string.IsNullOrWhiteSpace(value.Name) || value.Name.Length > 40) { list.Add(text + " has an invalid name"); } if (value.Value < 1 || value.Tier < 1 || value.Tier > 6 || !(value.TierScore >= 1.0) || !(value.TierScore <= 6.0) || value.Difficulty < 0) { list.Add(text + " has invalid tier or value"); } WeaponStats stats = value.Stats; if (stats == null || !(stats.Weight > 0.0) || !(stats.Length > 0.0) || new double[12] { stats.SwingDamage, stats.SwingSpeed, stats.ThrustDamage, stats.ThrustSpeed, stats.Handling, stats.MissileDamage, stats.MissileSpeed, stats.Accuracy, stats.HitPoints, stats.Breadth, stats.DrawSpeed, stats.Range }.Any((double v) => double.IsNaN(v) || double.IsInfinity(v) || v < 0.0)) { list.Add(text + " has invalid stats"); } } if (smithingState.NextWeaponNumber <= num) { list.Add("smithing would reuse a forged weapon id"); } HashSet hashSet = new HashSet(StringComparer.Ordinal); HashSet hashSet2 = new HashSet(StringComparer.Ordinal); long num2 = 0L; foreach (CraftingOrderState item5 in smithingState.Orders ?? new List()) { if (item5 == null) { list.Add("smithing has an empty crafting order"); continue; } string text2 = "crafting order " + item5.Id; if (!hashSet.Add(item5.Id ?? "")) { list.Add(text2 + " is duplicated"); } if ((item5.Id ?? "").StartsWith("order.", StringComparison.Ordinal) && long.TryParse(item5.Id.Substring(6), NumberStyles.None, CultureInfo.InvariantCulture, out var result2)) { num2 = Math.Max(num2, result2); } else { list.Add(text2 + " has an invalid id"); } Settlement settlement = state.Settlements?.Get(item5.SettlementId ?? ""); if (settlement == null || settlement.Type != SettlementType.Town) { list.Add(text2 + " is posted outside a town"); } if (item5.Slot < 0 || item5.Slot >= 6 || !hashSet2.Add(item5.SettlementId + "#" + item5.Slot)) { list.Add(text2 + " has an invalid slot"); } if (!item5.Valid) { list.Add(text2 + " has an invalid reference design"); } if (item5.BaseReward < 1) { list.Add(text2 + " has an invalid reward"); } if ((item5.IssuerKind != "notable" && item5.IssuerKind != "lord") || string.IsNullOrEmpty(item5.IssuerId) || string.IsNullOrWhiteSpace(item5.IssuerName)) { list.Add(text2 + " has an invalid customer"); } } if (smithingState.NextOrderNumber <= num2) { list.Add("smithing would reuse a crafting order id"); } return list; } } public static class TournamentValidation { public static List Check(CampaignState state) { List list = new List(); if (state == null) { return list; } SortedDictionary sortedDictionary = state.Abilities?.Known; if (sortedDictionary != null) { foreach (KeyValuePair item in sortedDictionary) { if (item.Value == null || item.Value.Id != item.Key || !Tournaments.IsAbilityId(item.Key)) { list.Add("ability " + item.Key + " is malformed"); } } } foreach (Hero hero in state.Heroes) { List list2 = hero.Abilities ?? new List(); if (list2.Distinct(StringComparer.Ordinal).Count() != list2.Count) { list.Add("hero " + hero.Id + " learned an ability twice"); } foreach (string item2 in list2) { if (!Tournaments.IsAbilityId(item2) || (sortedDictionary != null && sortedDictionary.Count > 0 && !sortedDictionary.ContainsKey(item2))) { list.Add("hero " + hero.Id + " knows an unknown ability " + item2); } } foreach (string item3 in hero.Loadout?.Abilities ?? new List()) { if (!list2.Contains(item3)) { list.Add("hero " + hero.Id + " uses an ability they have not learned: " + item3); } } } TournamentsState tournaments = state.Tournaments; if (tournaments?.Active == null) { return list; } HashSet hashSet = new HashSet(StringComparer.Ordinal); HashSet hashSet2 = new HashSet(StringComparer.Ordinal); int num = 0; foreach (TournamentState item4 in tournaments.Active) { if (item4 == null) { list.Add("a tournament record is empty"); continue; } string text = "tournament " + item4.Id; if (string.IsNullOrEmpty(item4.Id) || !hashSet.Add(item4.Id)) { list.Add(text + " has a missing or repeated id"); } Settlement settlement = state.Settlements.Get(item4.TownId ?? ""); if (settlement == null || settlement.Type != SettlementType.Town) { list.Add(text + " is not held at a town"); } else if (!hashSet2.Add(settlement.Id)) { list.Add(text + " is the second tournament at " + settlement.Id); } if (item4.EndMinute < item4.AnnouncedMinute) { list.Add(text + " ends before it was announced"); } TournamentPrizeState prize = item4.Prize; if (prize == null) { list.Add(text + " has no prize"); } else if (prize.Kind == TournamentPrizeKind.Weapon && (prize.Weapon == null || Smithing.DesignReason(prize.Weapon.Class, prize.Weapon.Parts).Length > 0)) { list.Add(text + " offers an invalid weapon"); } else if (prize.Kind == TournamentPrizeKind.Horse && (prize.Horse == null || Horses.Breed(prize.Horse.BreedId) == null)) { list.Add(text + " offers an invalid horse"); } else if (prize.Kind == TournamentPrizeKind.Ability && !Tournaments.IsAbilityId(prize.AbilityId)) { list.Add(text + " offers an invalid ability"); } if (item4.Run == null) { continue; } num++; TournamentRunState run = item4.Run; if (run.Fighters == null || run.Matches == null) { list.Add(text + " has an incomplete bracket"); continue; } if (run.Round < 0 || run.Round >= Tournaments.Rounds) { list.Add(text + " is in an unknown round " + run.Round); } if (run.Fighters.Count != 16 || run.Fighters.Select((TournamentFighterState f) => f.Id).Distinct().Count() != run.Fighters.Count || run.Fighters.Any((TournamentFighterState f) => f.Id < 1 || f.Id > 16)) { list.Add(text + " does not have sixteen numbered fighters"); } TournamentFighterState tournamentFighterState = run.Fighters.FirstOrDefault((TournamentFighterState f) => f.Id == 1); if (tournamentFighterState == null || tournamentFighterState.Kind != TournamentFighterKind.Player || tournamentFighterState.HeroId != state.PlayerHeroId) { list.Add(text + " does not list your character first"); } if (run.Fighters.Count((TournamentFighterState f) => f.Kind == TournamentFighterKind.Player) != 1) { list.Add(text + " lists your character more than once"); } foreach (TournamentMatchState match in run.Matches) { if (match.Winner < -1 || match.Winner > 1) { list.Add(text + " has a match with an unknown winner"); } if (match.TeamA.Concat(match.TeamB).Any((int id) => !run.Fighters.Any((TournamentFighterState f) => f.Id == id))) { list.Add(text + " has a match with unknown fighters"); } } if (run.BetThisRound < 0 || run.BetThisRound > 150 || run.BetTotal < 0 || run.BetPayout < 0) { list.Add(text + " has invalid bets"); } if (state.PlayerParty != null && (state.PlayerParty.State != PartyState.InSettlement || state.PlayerParty.CurrentSettlementId != item4.TownId)) { list.Add(text + ": you left the town during your tournament"); } } if (num > 1) { list.Add("you are in several tournaments at once"); } return list; } } } namespace TabsBannerlord.Core.Content { public sealed class CampaignRules { public int StepMinutes = 10; public double NormalHoursPerSecond = 1.0; public double FastHoursPerSecond = 4.0; public double CaptiveHoursPerSecond = 24.0; public int MaxStepsPerFrame = 48; public double MaxBacklogHours = 6.0; public double BaseSpeed = 5.0; public double MinSpeed = 1.0; public double MaxSpeed = 9.0; public double SmallPartyBonus = 0.06; public double SizePenaltyMax = 0.3; public double SizePenaltyHalfSize = 60.0; public double TroopPaceSpread = 1.5; public double WoundedPenaltyMax = 0.25; public double PrisonerPenaltyMax = 0.2; public double MountedBonusMax = 0.25; public double StarvingPenalty = 0.25; public double LowMoralePenalty = 0.15; public double ContactRadius = 0.6; public double SettlementEnterRadius = 0.35; public double BaseSightRange = 7.0; public double SightingExpiryHours = 24.0; public double DisengageHours = 3.0; public double RepathDistance = 1.0; public double JoinBattleRadius = 3.0; public double FoodPerTroopPerDay = 0.05; public double PrisonerFoodFactor = 0.5; public double FoodPrice = 12.0; public int StarvationGraceDays = 2; public double StarvationDesertionRate = 0.04; public int UnpaidGraceDays = 2; public double UnpaidDesertionRate = 0.05; public double DailyHealFraction = 0.12; public double SettlementHealMultiplier = 2.0; public double HeroDailyHeal = 0.12; public double BaseMorale = 50.0; public double MoraleDriftPerDay = 4.0; public double RecruitRefillChancePerDay = 0.35; public double VillageDailyTax = 14.0; public double TownDailyTax = 60.0; public double CastleDailyTax = 30.0; public double GarrisonWageFactor = 0.4; public double RansomPerTier = 25.0; public int PartyBaseSize = 30; public int PartySizePerRenown100 = 5; public int PrisonerBaseLimit = 10; public int CompanionBaseLimit = 3; public int CompanionMaxLimit = 8; public int MaxBanditsPerHideout = 3; public double BanditSpawnChancePerDay = 0.5; public int BanditPartyMinSize = 8; public int BanditPartyMaxSize = 28; public double AiThinkIntervalHours = 1.0; public double EngageStrengthRatio = 1.2; public double FleeStrengthRatio = 0.8; public int LordRecruitThreshold = 12; public int LordEmergencyLevy = 6; public double PatrolRadius = 10.0; public int ActiveUnitBudget = 120; public double MinSideShare = 0.3; public double ReinforcementIntervalSeconds = 8.0; public double ArrivalCountdownSeconds = 3.0; public int MinReinforcementBatch = 6; public int MaxSpawnPerFrame = 4; public double WorkloadBudgetFactor = 1.6; public double EntryBlockedTimeoutSeconds = 30.0; public double QueueAgingSeconds = 20.0; public double BaseWoundSurvival = 0.55; public bool HeroesCanDie; public double ReserveXpFactor = 0.25; public double XpPerEnemyTier = 12.0; public double LootPerEnemyTier = 6.0; public double RenownPerEnemyTier = 0.4; public int AutoResolveMaxRounds = 400; public double EscapeChancePerDay = 0.06; public double EscapeChanceGrowthPerDay = 0.03; public int BanditMaxCaptivityDays = 4; public int LordMaxCaptivityDays = 12; public double PrisonerRecruitmentBaseDays = 2.0; public double PrisonerRecruitmentMoraleCost = 2.0; public double PrisonerRecruitmentMinMorale = 20.0; public int DungeonPrisonerLimit = 100; } public sealed class CharacterChoiceDef { public string Id = ""; public string Name = ""; public string Description = ""; public SortedDictionary SkillBonuses = new SortedDictionary(StringComparer.Ordinal); } public sealed class LifeStageDef { public string Id = ""; public string Name = ""; public string Prompt = ""; public List Choices = new List(); } public sealed class StartingAgeDef { public int Age; public string Name = ""; public string Description = ""; public int FreeFocus; public long Gold; } public static class CharacterCreation { public const int FocusPerStage = 1; public const int MaximumCreationClothingTier = 3; public static readonly List LifeStages = new List { Stage("stage.family", "Family", "Your family were…", Choice("family.retainers", "A lord's retainers", "Your parents served in a lord's household guard, and you grew up among drills and stables.", "leadership", 10, "riding", 5), Choice("family.merchants", "Market traders", "Your family kept a stall and a storehouse, and every coin was counted twice.", "trade", 10, "stewardship", 5), Choice("family.freeholders", "Freeholders", "Your family farmed their own fields, and you were behind the plough and up the hayricks from dawn to dusk.", "athletics", 10, "stewardship", 5), Choice("family.smiths", "Smiths", "You grew up beside the forge, fetching coal and selling blades on market day.", "smithing", 10, "trade", 5), Choice("family.foresters", "Foresters", "Your family hunted and kept the woods, and you could put an arrow through a hare at fifty paces.", "bow", 10, "scouting", 5), Choice("family.healers", "Travelling healers", "Your family went village to village with herbs, bandages and gossip.", "medicine", 10, "charm", 5)), Stage("stage.childhood", "Childhood", "As a child you were…", Choice("childhood.leader", "A leader among friends", "The other children followed your games and your plans.", "leadership", 10, "tactics", 5), Choice("childhood.builder", "A little builder", "You built dams, forts and towers out of anything you could find.", "engineering", 10, "smithing", 5), Choice("childhood.animals", "Good with animals", "Horses, dogs and goats trusted you more than they trusted anyone.", "riding", 10, "medicine", 5), Choice("childhood.wanderer", "Always wandering", "You explored every field, hill and ditch for miles around.", "scouting", 10, "athletics", 5), Choice("childhood.talker", "A charming talker", "You could talk your way out of any chore and into any kitchen.", "charm", 10, "trade", 5), Choice("childhood.wargames", "Fond of war games", "You marshalled armies of sticks and studied how every battle was won.", "tactics", 10, "leadership", 5)), Stage("stage.adolescence", "Adolescence", "As a youth you…", Choice("adolescence.forge", "Worked at a forge", "You pumped the bellows, swung the big hammer and learned how good steel is made.", "smithing", 10, "two_handed", 5), Choice("adolescence.market", "Ran errands in the market", "You carried goods and messages, and learned which of them never passed the toll-gate.", "roguery", 10, "trade", 5), Choice("adolescence.healer", "Helped the local healer", "You boiled bandages, set splints and learned the herbs.", "medicine", 10, "stewardship", 5), Choice("adolescence.mason", "Laboured on the walls", "You hauled stone for the town walls all summer and watched the engineers at work.", "athletics", 10, "engineering", 5), Choice("adolescence.herds", "Rode with the herds", "You drove horses and cattle across the hills from dawn to dusk.", "riding", 10, "scouting", 5), Choice("adolescence.militia", "Drilled with the militia", "You stood in the spear line with the local militia every market day.", "polearm", 10, "tactics", 5)), Stage("stage.youth", "Youth", "As a young adult you…", Choice("youth.patrol", "Rode with a road patrol", "Sword in hand, you kept the roads with a handful of guards and brought them all home.", "one_handed", 10, "leadership", 5), Choice("youth.outrider", "Rode as an outrider", "You scouted ahead of an army, reading the land for its commanders.", "scouting", 10, "riding", 5), Choice("youth.quartermaster", "Kept a quartermaster's books", "You fed and supplied a garrison through a long, hungry winter.", "stewardship", 10, "trade", 5), Choice("youth.envoy", "Served an envoy", "You attended a lord's envoy at feasts, councils and hard negotiations.", "diplomacy", 10, "charm", 5), Choice("youth.surgeon", "Served as a camp surgeon", "You stitched wounds after skirmishes and kept the sick alive.", "medicine", 10, "stewardship", 5), Choice("youth.sapper", "Worked with the siege crews", "You wound the crossbows and raised the mantlets before stubborn walls.", "crossbow", 10, "engineering", 5)), Stage("stage.adulthood", "Adulthood", "Your greatest deed was that you…", Choice("adulthood.bridge", "Held a bridge against raiders", "With a great axe you held the bridge until help arrived, and songs were sung about it.", "two_handed", 10, "tactics", 5), Choice("adulthood.peace", "Ended a feud", "You brokered peace between two feuding villages without a drop of blood.", "diplomacy", 10, "charm", 5), Choice("adulthood.venture", "Made a fortune trading", "A risky trading venture paid off handsomely, at least for a while.", "trade", 10, "roguery", 5), Choice("adulthood.blade", "Forged a famous blade", "A lord still carries the sword you forged and boasts about its maker.", "smithing", 10, "one_handed", 5), Choice("adulthood.fever", "Saw a town through a fever", "You nursed a whole town back to health after its healers had fled.", "medicine", 10, "leadership", 5), Choice("adulthood.pass", "Crossed the high passes", "You guided a caravan over the mountains in winter, and kept the wolves and robbers off with your javelins.", "throwing", 10, "scouting", 5)) }; public static readonly List Ages = new List { new StartingAgeDef { Age = 20, Name = "Young", FreeFocus = 1, Gold = 400L, Description = "Little experience yet, but some savings from home." }, new StartingAgeDef { Age = 30, Name = "Adult", FreeFocus = 2, Gold = 200L, Description = "Seasoned enough to know what you are good at, with a little put by." }, new StartingAgeDef { Age = 40, Name = "Middle-aged", FreeFocus = 3, Description = "A long road behind you and much learned on it." }, new StartingAgeDef { Age = 50, Name = "Elder", FreeFocus = 4, Description = "A lifetime of lessons learned, and no savings put by." } }; public const int DefaultAge = 30; public const int AttributePerStage = 1; public static readonly List Backgrounds = new List { Choice("background.retainer", "Retainers", "Raised in a household that drilled its guards and counted every sack of grain.", "leadership", 10, "stewardship", 5), Choice("background.woodlander", "Woodlanders", "Raised along forest trails, finding safe paths and tending minor injuries.", "scouting", 10, "medicine", 5), Choice("background.healer", "Healers", "Raised among travelling healers who knew the roads as well as their remedies.", "medicine", 10, "scouting", 5), Choice("background.merchant", "Merchants", "Raised around storehouses and caravans, organising provisions and their guards.", "stewardship", 10, "leadership", 5), Choice("background.craftsperson", "Craftspeople", "Raised in workshops, organising materials and tending the injuries of a working day.", "stewardship", 10, "medicine", 5), Choice("background.outrider", "Outriders", "Raised among patrols, reading the land and keeping a scattered company together.", "scouting", 10, "leadership", 5) }; public static readonly List Trainings = new List { Choice("training.command", "Command", "You learned to lead a company, and to tell a fight you could win from one you couldn't.", "leadership", 10, "tactics", 5), Choice("training.scouting", "Scouting", "You found the roads, and got a company down them.", "scouting", 10, "leadership", 5), Choice("training.medicine", "Medicine", "Field medicine, and keeping the supplies for it.", "medicine", 10, "stewardship", 5), Choice("training.stewardship", "Stewardship", "You learned to feed a warband and patch up its wounded.", "stewardship", 10, "medicine", 5) }; public static readonly List Traits = new List { Choice("trait.brave", "Brave", "Out front on patrol, you stopped being afraid of it.", "leadership", 5, "scouting", 5), Choice("trait.compassionate", "Compassionate", "Looking after people became a habit.", "medicine", 5, "stewardship", 5), Choice("trait.resourceful", "Resourceful", "You learned to find a path and make supplies stretch.", "scouting", 5, "stewardship", 5), Choice("trait.steadfast", "Steadfast", "When things went wrong, people came to you.", "leadership", 5, "medicine", 5) }; public static readonly string[] BannerColors = new string[8] { "#d9a441", "#3f6fb5", "#b5413f", "#56865c", "#498d91", "#8564a6", "#c6c0a5", "#ad633f" }; public static readonly string[] BannerSymbols = new string[24] { "★", "◆", "▲", "●", "✚", "☾", "■", "✦", "crown", "shield", "sword", "axe", "spear", "arrow", "tower", "mountain", "pine", "leaf", "flame", "sun", "anchor", "hourglass", "lightning", "trident" }; public static int MaximumOriginFocus => LifeStages.Count + Ages.Max((StartingAgeDef age) => age.FreeFocus); public static StartingAgeDef StartingAge(int age) { return Ages.FirstOrDefault((StartingAgeDef candidate) => candidate.Age == age); } public static string PrimarySkill(CharacterChoiceDef choice) { return (from pair in choice?.SkillBonuses orderby pair.Value descending, Array.IndexOf(SkillIds.All, pair.Key) select pair.Key).FirstOrDefault() ?? ""; } public static CharacterChoiceDef LifeStageChoice(string stageId, string choiceId) { return LifeStages.FirstOrDefault((LifeStageDef stage) => stage.Id == stageId)?.Choices.FirstOrDefault((CharacterChoiceDef choice) => choice.Id == choiceId); } public static int OriginFocus(int age) { return LifeStages.Count + (StartingAge(age)?.FreeFocus ?? 0); } public static int FreeFocusPool(int age) { return TabsBannerlord.Core.Campaign.Campaign.HeroFocusPointsForLevel(1) + (StartingAge(age)?.FreeFocus ?? 0); } public static string LifeStagesReason(IDictionary choices) { if (choices == null) { return "Choose your life story."; } foreach (LifeStageDef lifeStage in LifeStages) { if (!choices.TryGetValue(lifeStage.Id, out var value) || LifeStageChoice(lifeStage.Id, value) == null) { return "Choose your " + lifeStage.Name.ToLowerInvariant() + "."; } } if (choices.Keys.Any((string key) => LifeStages.All((LifeStageDef stage) => stage.Id != key))) { return "Your life story has an unknown step."; } return ""; } public static SortedDictionary LifeStageSkills(IDictionary choices) { string text = LifeStagesReason(choices); if (text.Length > 0) { throw new ArgumentException(text, "choices"); } SortedDictionary sortedDictionary = BaseSkills(); foreach (LifeStageDef lifeStage in LifeStages) { foreach (KeyValuePair skillBonuse in LifeStageChoice(lifeStage.Id, choices[lifeStage.Id]).SkillBonuses) { sortedDictionary[skillBonuse.Key] += skillBonuse.Value; } } return sortedDictionary; } public static SortedDictionary LifeStageAttributes(IDictionary choices) { string text = LifeStagesReason(choices); if (text.Length > 0) { throw new ArgumentException(text, "choices"); } SortedDictionary sortedDictionary = new SortedDictionary(StringComparer.Ordinal); string[] all = AttributeIds.All; foreach (string key in all) { sortedDictionary[key] = 2; } foreach (LifeStageDef lifeStage in LifeStages) { string text2 = Skills.AttributeOf(PrimarySkill(LifeStageChoice(lifeStage.Id, choices[lifeStage.Id]))); if (text2.Length > 0) { sortedDictionary[text2] = Math.Min(10, sortedDictionary[text2] + 1); } } return sortedDictionary; } public static SortedDictionary LifeStageFocus(IDictionary choices) { string text = LifeStagesReason(choices); if (text.Length > 0) { throw new ArgumentException(text, "choices"); } SortedDictionary sortedDictionary = new SortedDictionary(StringComparer.Ordinal); foreach (LifeStageDef lifeStage in LifeStages) { string key = PrimarySkill(LifeStageChoice(lifeStage.Id, choices[lifeStage.Id])); sortedDictionary[key] = (sortedDictionary.TryGetValue(key, out var value) ? value : 0) + 1; } return sortedDictionary; } public static string FocusReason(IDictionary choices, int age, IDictionary placed) { string text = LifeStagesReason(choices); if (text.Length > 0) { return text; } if (StartingAge(age) == null) { return "Choose your starting age."; } if (placed == null) { return ""; } long num = 0L; SortedDictionary sortedDictionary = LifeStageFocus(choices); foreach (KeyValuePair item in placed) { if (!SkillIds.All.Contains(item.Key)) { return "Focus was placed in an unknown skill."; } if (item.Value < 0) { return "Focus cannot be negative."; } if ((sortedDictionary.TryGetValue(item.Key, out var value) ? value : 0) + item.Value > 5) { return "A skill can hold at most " + 5 + " focus points."; } num += item.Value; } int num2 = FreeFocusPool(age); if (num <= num2) { return ""; } return "You can place at most " + num2 + " focus points at this age."; } public static SortedSet CultureClothing(ContentDatabase content, IDictionary> unitPieces, string cultureId) { SortedSet sortedSet = new SortedSet(StringComparer.Ordinal); if (content == null || unitPieces == null || string.IsNullOrEmpty(cultureId)) { return sortedSet; } foreach (KeyValuePair> unitPiece in unitPieces) { if (unitPiece.Value == null || content.Units.Get(unitPiece.Key)?.Culture != cultureId) { continue; } foreach (string item in unitPiece.Value) { if (Wardrobe.IsPieceId(item)) { sortedSet.Add(item); } } } return sortedSet; } private static SortedDictionary BaseSkills() { SortedDictionary sortedDictionary = new SortedDictionary(StringComparer.Ordinal); string[] all = SkillIds.All; foreach (string text in all) { sortedDictionary[text] = ((text == "riding") ? 15 : 5); } return sortedDictionary; } private static LifeStageDef Stage(string id, string name, string prompt, params CharacterChoiceDef[] choices) { return new LifeStageDef { Id = id, Name = name, Prompt = prompt, Choices = choices.ToList() }; } public static bool IsBannerColor(string color) { if (color == null || color.Length != 7 || color[0] != '#') { return false; } for (int i = 1; i < 7; i++) { if ((color[i] < '0' || color[i] > '9') && (color[i] < 'a' || color[i] > 'f')) { return false; } } return true; } public static bool IsEmblemColor(string color) { if (!string.IsNullOrEmpty(color)) { return IsBannerColor(color); } return true; } public static SortedDictionary StartingSkills(string backgroundId, string trainingId, string traitId) { CharacterChoiceDef characterChoiceDef = RequireChoice(Backgrounds, backgroundId, "background"); CharacterChoiceDef characterChoiceDef2 = RequireChoice(Trainings, trainingId, "training"); CharacterChoiceDef characterChoiceDef3 = RequireChoice(Traits, traitId, "trait"); SortedDictionary sortedDictionary = new SortedDictionary(StringComparer.Ordinal); string[] all = SkillIds.All; foreach (string text in all) { sortedDictionary[text] = ((text == "riding") ? 15 : 5); } CharacterChoiceDef[] array = new CharacterChoiceDef[3] { characterChoiceDef, characterChoiceDef2, characterChoiceDef3 }; for (int i = 0; i < array.Length; i++) { foreach (KeyValuePair skillBonuse in array[i].SkillBonuses) { sortedDictionary[skillBonuse.Key] += skillBonuse.Value; } } return sortedDictionary; } public static List Archetypes(ContentDatabase content, string cultureId, PlayerStartDef start) { if (content == null || start == null || string.IsNullOrEmpty(cultureId) || !content.Cultures.Contains(cultureId)) { return new List(); } int maximumTier = ((start.Kind == StartKind.Commander) ? 4 : 2); return (from unit in content.Units where unit.Culture == cultureId && unit.Tier >= 1 && unit.Tier <= maximumTier && !unit.Mounted && !string.IsNullOrEmpty(unit.TabsUnitId) && (unit.Role == TroopRole.Infantry || unit.Role == TroopRole.Ranged || unit.Role == TroopRole.Support) orderby unit.Role, unit.Tier select unit).ThenBy((UnitDef unit) => unit.Id, StringComparer.Ordinal).ToList(); } public static string DefaultArchetype(ContentDatabase content, string cultureId, PlayerStartDef start) { List source = Archetypes(content, cultureId, start); UnitDef unitDef = source.FirstOrDefault((UnitDef unit) => unit.Id == start?.HeroUnit); if (unitDef != null) { return unitDef.Id; } return (from unit in source orderby (unit.Role != TroopRole.Infantry) ? 1 : 0, unit.Tier descending select unit).ThenBy((UnitDef unit) => unit.Id, StringComparer.Ordinal).FirstOrDefault()?.Id ?? ""; } private static CharacterChoiceDef RequireChoice(List choices, string id, string kind) { return choices.FirstOrDefault((CharacterChoiceDef candidate) => candidate.Id == id) ?? throw new ArgumentException("Choose a valid " + kind + ".", kind + "Id"); } private static CharacterChoiceDef Choice(string id, string name, string description, string firstSkill, int firstBonus, string secondSkill, int secondBonus) { return new CharacterChoiceDef { Id = id, Name = name, Description = description, SkillBonuses = { [firstSkill] = firstBonus, [secondSkill] = secondBonus } }; } } public sealed class ContentManifest { public List Packs = new List(); public string Hash = ""; } public sealed class ContentDatabase { public ContentPackInfo Pack = new ContentPackInfo(); public CampaignRules Rules = new CampaignRules(); public readonly EntityTable Units = new EntityTable(); public readonly EntityTable Cultures = new EntityTable(); public readonly EntityTable Scenarios = new EntityTable(); public readonly EntityTable BattleMaps = new EntityTable(); public readonly Dictionary Worlds = new Dictionary(StringComparer.Ordinal); public ContentManifest Manifest = new ContentManifest(); public UnitDef Unit(string id) { return Units.Require(id); } public CultureDef Culture(string id) { return Cultures.Require(id); } public WorldDef World(string id) { if (!Worlds.TryGetValue(id, out var value)) { throw new KeyNotFoundException("No world '" + id + "'"); } return value; } public static ContentDatabase LoadDirectory(string directory) { if (!Directory.Exists(directory)) { throw new DirectoryNotFoundException("Content directory not found: " + directory); } List list = Directory.GetFiles(directory, "*.json").OrderBy((string f) => Path.GetFileName(f), StringComparer.Ordinal).ToList(); Dictionary dictionary = new Dictionary(StringComparer.Ordinal); foreach (string item in list) { dictionary[Path.GetFileName(item)] = File.ReadAllText(item, Encoding.UTF8); } return LoadFromTexts(dictionary); } public static ContentDatabase LoadFromTexts(IDictionary texts) { return Build(texts, new List()); } public static ContentDatabase LoadWithMods(IDictionary texts, IList mods, out List results) { results = new List(); mods = mods ?? new List(); List accepted = new List(); ContentDatabase result = Build(texts, accepted); if (mods.Count == 0) { return result; } try { ContentDatabase result2 = Build(texts, mods.ToList()); foreach (ModContent mod in mods) { results.Add(new ModLoadResult { Id = mod.Pack.Id, Loaded = true }); } return result2; } catch (ContentException) { } foreach (ModContent mod2 in mods) { string text = (mod2.Pack.Requires ?? new List()).FirstOrDefault((string id) => accepted.All((ModContent a) => a.Pack.Id != id)) ?? ""; if (text.Length > 0) { results.Add(new ModLoadResult { Id = mod2.Pack.Id, Error = "needs the mod '" + text + "' loaded before it" }); continue; } try { result = Build(texts, accepted.Concat(new ModContent[1] { mod2 }).ToList()); accepted.Add(mod2); results.Add(new ModLoadResult { Id = mod2.Pack.Id, Loaded = true }); } catch (ContentException ex2) { results.Add(new ModLoadResult { Id = mod2.Pack.Id, Error = ex2.Message }); } } return result; } private static ContentDatabase Build(IDictionary texts, IList mods) { ContentDatabase contentDatabase = new ContentDatabase(); JsonSerializer ser = new JsonSerializer(); StringBuilder stringBuilder = new StringBuilder(); foreach (KeyValuePair item in texts.OrderBy, string>((KeyValuePair k) => k.Key, StringComparer.Ordinal)) { Apply(contentDatabase, ser, item.Key, item.Value, stringBuilder, null); } foreach (ModContent mod in mods) { if (string.IsNullOrEmpty(mod.Pack.Id)) { throw new ContentException("a mod has no id"); } foreach (string id in mod.Pack.Requires ?? new List()) { if (mods.TakeWhile((ModContent m) => m != mod).All((ModContent m) => m.Pack.Id != id)) { throw new ContentException(mod.Pack.Id + ": needs the mod '" + id + "' loaded before it"); } } stringBuilder.Append("mod:").Append(mod.Pack.Id).Append(':') .Append(mod.Pack.Version) .Append('\n'); foreach (KeyValuePair item2 in mod.Texts.OrderBy, string>((KeyValuePair k) => k.Key, StringComparer.Ordinal)) { Apply(contentDatabase, ser, mod.Pack.Id + "/" + item2.Key, item2.Value, stringBuilder, mod); } } ProceduralWorld.Register(contentDatabase); stringBuilder.Append("procedural-world:").Append(4).Append('\n'); contentDatabase.Manifest = new ContentManifest { Packs = new List { contentDatabase.Pack }.Concat(mods.Select((ModContent m) => m.Pack)).ToList(), Hash = StableHash.Fnv1a64(stringBuilder.ToString()).ToString("x16") }; ResolveLooks(contentDatabase); foreach (BattleMapDef battleMap in contentDatabase.BattleMaps) { if (!string.IsNullOrEmpty(battleMap.Prefab) && battleMap.TabsMapMatch.Count == 0) { battleMap.TabsMapMatch.Add("00_simulation_day"); } } List list = ContentValidator.Validate(contentDatabase); if (list.Count > 0) { throw new ContentException("Content validation failed:\n " + string.Join("\n ", list)); } return contentDatabase; } private static void ResolveLooks(ContentDatabase db) { foreach (UnitDef unit in db.Units) { if (!string.IsNullOrEmpty(unit.LooksLike)) { UnitDef unitDef = db.Units.Get(unit.LooksLike); if (unitDef != null && string.IsNullOrEmpty(unitDef.LooksLike) && unitDef != unit) { unit.TabsUnitId = unitDef.TabsUnitId; unit.TabsFaction = unitDef.TabsFaction; unit.TabsCost = unitDef.TabsCost; unit.Slots = unitDef.Slots; unit.Workload = unitDef.Workload; unit.Mounted = unitDef.Mounted; } } } } private static void Apply(ContentDatabase db, JsonSerializer ser, string file, string text, StringBuilder hashInput, ModContent mod) { JsonNode jsonNode; try { jsonNode = JsonParser.Parse(text); } catch (JsonException ex) { throw new ContentException(file + ": " + ex.Message); } hashInput.Append(file).Append('\n').Append(jsonNode.ToJson(indented: false)) .Append('\n'); JsonObject asObject; try { asObject = jsonNode.AsObject; } catch (JsonException ex2) { throw new ContentException(file + ": " + ex2.Message); } string text2 = asObject.GetString("kind") ?? Path.GetFileNameWithoutExtension(file); bool flag = mod != null; try { switch (text2) { case "pack": if (flag) { throw new ContentException(file + ": a mod describes itself in its mod.json, not in a pack file"); } db.Pack = ser.FromJson(asObject.GetObject("pack")); break; case "rules": db.Rules = (flag ? Patch(ser, db.Rules, asObject.GetObject("rules")) : ser.FromJson(asObject.GetObject("rules"))); break; case "units": Entries(db.Units, ser, asObject, "units", flag); break; case "cultures": Entries(db.Cultures, ser, asObject, "cultures", flag); break; case "scenarios": Entries(db.Scenarios, ser, asObject, "scenarios", flag); break; case "battlemaps": Entries(db.BattleMaps, ser, asObject, "battlemaps", flag); break; case "world": { JsonObject jsonObject = asObject.GetObject("world"); string key = jsonObject?.GetString("Id") ?? ""; db.Worlds[key] = ((flag && db.Worlds.TryGetValue(key, out var value)) ? Patch(ser, value, jsonObject) : ser.FromJson(jsonObject)); if (!flag) { break; } foreach (string item in Ids(asObject.GetArray("remove"))) { db.Worlds.Remove(item); } break; } default: throw new ContentException(file + ": unknown content kind '" + text2 + "'"); } } catch (ContentException ex3) { throw new ContentException(ex3.Message.StartsWith(file, StringComparison.Ordinal) ? ex3.Message : (file + ": " + ex3.Message)); } catch (InvalidOperationException ex4) { throw new ContentException(file + ": " + ex4.Message); } catch (JsonException ex5) { throw new ContentException(file + ": " + ex5.Message); } using List.Enumerator enumerator2 = ser.Warnings.GetEnumerator(); if (enumerator2.MoveNext()) { string current2 = enumerator2.Current; throw new ContentException(file + ": " + current2); } } private static void Entries(EntityTable table, JsonSerializer ser, JsonObject obj, string key, bool modding) where T : class, IEntity { foreach (JsonNode item in obj.GetArray(key)?.Items ?? new List()) { string id = item.AsObject.GetString("Id") ?? ""; T val = (modding ? table.Get(id) : null); if (val != null) { table.Replace(Patch(ser, val, item.AsObject)); } else { table.Add(ser.FromJson(item)); } } if (!modding) { return; } foreach (string item2 in Ids(obj.GetArray("remove"))) { if (!table.Remove(item2)) { throw new ContentException("can't remove '" + item2 + "': there is no such " + key.TrimEnd(new char[1] { 's' })); } } } private static IEnumerable Ids(JsonArray array) { return (array?.Items ?? new List()).Select((JsonNode n) => n.AsString); } private static T Patch(JsonSerializer ser, T existing, JsonObject patch) { if (patch == null) { return existing; } JsonObject asObject = ser.ToNode(existing, typeof(T)).AsObject; Merge(asObject, patch); return ser.FromJson(asObject); } private static void Merge(JsonObject into, JsonObject from) { foreach (string item in from.Keys.ToList()) { JsonNode jsonNode = from[item]; if (jsonNode is JsonObject jsonObject && into[item] is JsonObject jsonObject2) { Merge(jsonObject2, jsonObject); } else { into[item] = jsonNode; } } } } public sealed class ContentException : Exception { public ContentException(string message) : base(message) { } } public static class ContentValidator { public static List Validate(ContentDatabase db) { List list = new List(); if (string.IsNullOrEmpty(db.Pack.Id)) { list.Add("pack.json is missing or has no id"); } if (db.Rules.CompanionBaseLimit < 0 || db.Rules.CompanionMaxLimit < db.Rules.CompanionBaseLimit) { list.Add("rules: companion limits must be non-negative and maximum must cover the base limit"); } if (new double[3] { db.Rules.PrisonerRecruitmentBaseDays, db.Rules.PrisonerRecruitmentMoraleCost, db.Rules.PrisonerRecruitmentMinMorale }.Any((double num) => double.IsNaN(num) || double.IsInfinity(num) || num < 0.0) || db.Rules.PrisonerRecruitmentMinMorale > 100.0 || db.Rules.DungeonPrisonerLimit < 0) { list.Add("rules: prisoner learning, morale and dungeon limits must be finite and non-negative, with minimum morale at most 100"); } foreach (UnitDef unit in db.Units) { if (string.IsNullOrEmpty(unit.Name)) { list.Add("unit " + unit.Id + ": missing name"); } if (!string.IsNullOrEmpty(unit.LooksLike)) { UnitDef unitDef = db.Units.Get(unit.LooksLike); if (unitDef == null) { list.Add("unit " + unit.Id + ": LooksLike names unknown unit " + unit.LooksLike); } else if (unitDef == unit) { list.Add("unit " + unit.Id + ": LooksLike can't name itself"); } else if (!string.IsNullOrEmpty(unitDef.LooksLike)) { list.Add("unit " + unit.Id + ": LooksLike must name a unit with its own TABS unit, not " + unit.LooksLike + " (which looks like " + unitDef.LooksLike + ")"); } } if (string.IsNullOrEmpty(unit.TabsUnitId)) { list.Add("unit " + unit.Id + ": missing TabsUnitId"); } if (!string.IsNullOrEmpty(unit.Culture) && !db.Cultures.Contains(unit.Culture)) { list.Add("unit " + unit.Id + ": unknown culture " + unit.Culture); } if (unit.Slots < 1) { list.Add("unit " + unit.Id + ": Slots must be >= 1"); } if (unit.Workload <= 0.0) { list.Add("unit " + unit.Id + ": Workload must be > 0"); } if (unit.RecruitCost < 0 || unit.DailyWage < 0.0 || unit.FoodUse < 0.0) { list.Add("unit " + unit.Id + ": negative cost/wage/food"); } if (unit.Health <= 0.0 || unit.Attack < 0.0 || unit.Defense < 0.0) { list.Add("unit " + unit.Id + ": invalid auto-resolve ratings"); } if (unit.Access.Count == 0) { list.Add("unit " + unit.Id + ": no access path declared (use NotYetAssigned explicitly)"); } foreach (UpgradeDef upgrade in unit.Upgrades) { if (!db.Units.Contains(upgrade.To)) { list.Add("unit " + unit.Id + ": upgrade to unknown unit " + upgrade.To); } else if (db.Units.Get(upgrade.To).Tier <= unit.Tier) { list.Add("unit " + unit.Id + ": upgrade to " + upgrade.To + " does not increase tier"); } if (upgrade.Xp <= 0) { list.Add("unit " + unit.Id + ": upgrade to " + upgrade.To + " needs positive XP"); } } } Dictionary dictionary = new Dictionary(StringComparer.Ordinal); foreach (UnitDef item in db.Units.Where((UnitDef x) => string.IsNullOrEmpty(x.LooksLike))) { if (dictionary.TryGetValue(item.TabsUnitId, out var value)) { list.Add("units " + value + " and " + item.Id + " share TabsUnitId " + item.TabsUnitId + "; to reuse a TABS unit, give the new troop \"LooksLike\": \"" + value + "\" instead"); } else { dictionary[item.TabsUnitId] = item.Id; } } foreach (CultureDef culture in db.Cultures) { if (!db.Units.Contains(culture.BasicTroop)) { list.Add("culture " + culture.Id + ": unknown basic troop " + culture.BasicTroop); } if (!string.IsNullOrEmpty(culture.HeroUnit) && !db.Units.Contains(culture.HeroUnit)) { list.Add("culture " + culture.Id + ": unknown hero unit " + culture.HeroUnit); } foreach (WeightedUnit item2 in culture.VillageRecruits.Concat(culture.TownRecruits)) { if (!db.Units.Contains(item2.Unit)) { list.Add("culture " + culture.Id + ": unknown recruit " + item2.Unit); } } foreach (WeightedUnit lordUnit in culture.LordUnits) { if (!db.Units.Contains(lordUnit.Unit)) { list.Add("culture " + culture.Id + ": unknown lord unit " + lordUnit.Unit); } if (!(lordUnit.Weight > 0.0)) { list.Add("culture " + culture.Id + ": lord unit " + lordUnit.Unit + " needs a positive weight"); } } if (string.IsNullOrEmpty(culture.Symbol)) { list.Add("culture " + culture.Id + ": needs a symbol (colour must never be the only cue)"); } } foreach (WorldDef value3 in db.Worlds.Values) { ValidateWorld(db, value3, list); } foreach (ScenarioDef scenario in db.Scenarios) { if (!db.Worlds.ContainsKey(scenario.World)) { list.Add("scenario " + scenario.Id + ": unknown world " + scenario.World); continue; } WorldDef worldDef = db.Worlds[scenario.World]; HashSet hashSet = new HashSet(worldDef.Locations.Select((LocationDef l) => l.Id), StringComparer.Ordinal); HashSet hashSet2 = new HashSet(scenario.Clans.Select((ClanStartDef c) => c.Id), StringComparer.Ordinal); HashSet hashSet3 = new HashSet(scenario.Kingdoms.Select((KingdomStartDef k) => k.Id), StringComparer.Ordinal); Dictionary dictionary2 = new Dictionary(StringComparer.Ordinal); HashSet hashSet4 = new HashSet(StringComparer.Ordinal); if (scenario.Companions == null) { list.Add("scenario " + scenario.Id + ": companions must be a list"); } foreach (CompanionDef h in scenario.Companions ?? new List()) { if (h == null) { list.Add("scenario " + scenario.Id + ": null companion definition"); continue; } if (string.IsNullOrWhiteSpace(h.Id) || !h.Id.StartsWith("hero.companion.", StringComparison.Ordinal) || h.Id.Length == "hero.companion.".Length) { list.Add("scenario " + scenario.Id + ": companion id " + h.Id + " must begin with hero.companion. and have a stable name"); } if (!hashSet4.Add(h.Id)) { list.Add("scenario " + scenario.Id + ": duplicate companion id " + h.Id); } if (string.IsNullOrWhiteSpace(h.Name)) { list.Add("scenario " + scenario.Id + ": companion " + h.Id + " missing name"); } if (!db.Cultures.Contains(h.Culture)) { list.Add("scenario " + scenario.Id + ": companion " + h.Id + " unknown culture " + h.Culture); } if (!db.Units.Contains(h.Unit)) { list.Add("scenario " + scenario.Id + ": companion " + h.Id + " unknown unit " + h.Unit); } LocationDef locationDef = worldDef.Locations.FirstOrDefault((LocationDef l) => l.Id == h.Settlement); if (locationDef == null || locationDef.Type != SettlementType.Town) { list.Add("scenario " + scenario.Id + ": companion " + h.Id + " must start at a known town"); } if (h.HireCost < 0 || h.DailyWage < 0) { list.Add("scenario " + scenario.Id + ": companion " + h.Id + " negative hiring fee or wage"); } if (h.Skills == null) { list.Add("scenario " + scenario.Id + ": companion " + h.Id + " skills must be an object"); continue; } foreach (KeyValuePair skill in h.Skills) { if (!SkillIds.All.Contains(skill.Key)) { list.Add("scenario " + scenario.Id + ": companion " + h.Id + " unknown skill " + skill.Key); } if (skill.Value < 0) { list.Add("scenario " + scenario.Id + ": companion " + h.Id + " negative skill " + skill.Key); } } } foreach (KingdomStartDef kingdom in scenario.Kingdoms) { if (!hashSet2.Contains(kingdom.RulerClan)) { list.Add("scenario " + scenario.Id + ": kingdom " + kingdom.Id + " ruler clan " + kingdom.RulerClan + " missing"); } if (!db.Cultures.Contains(kingdom.Culture)) { list.Add("scenario " + scenario.Id + ": kingdom " + kingdom.Id + " unknown culture " + kingdom.Culture); } } foreach (ClanStartDef clan in scenario.Clans) { if (!string.IsNullOrEmpty(clan.Kingdom) && !hashSet3.Contains(clan.Kingdom)) { list.Add("scenario " + scenario.Id + ": clan " + clan.Id + " unknown kingdom " + clan.Kingdom); } if (!db.Cultures.Contains(clan.Culture)) { list.Add("scenario " + scenario.Id + ": clan " + clan.Id + " unknown culture " + clan.Culture); } foreach (string settlement in clan.Settlements) { string value2; if (!hashSet.Contains(settlement)) { list.Add("scenario " + scenario.Id + ": clan " + clan.Id + " owns unknown settlement " + settlement); } else if (dictionary2.TryGetValue(settlement, out value2)) { list.Add("scenario " + scenario.Id + ": settlement " + settlement + " owned by both " + value2 + " and " + clan.Id); } else { dictionary2[settlement] = clan.Id; } } foreach (LordStartDef lord in clan.Lords) { if (!string.IsNullOrEmpty(lord.Unit) && !db.Units.Contains(lord.Unit)) { list.Add("scenario " + scenario.Id + ": lord " + lord.Name + " unknown unit " + lord.Unit); } foreach (RosterEntryDef troop in lord.Troops) { if (!db.Units.Contains(troop.Unit)) { list.Add("scenario " + scenario.Id + ": lord " + lord.Name + " unknown troop " + troop.Unit); } } } foreach (WeightedUnit banditTroop in clan.BanditTroops) { if (!db.Units.Contains(banditTroop.Unit)) { list.Add("scenario " + scenario.Id + ": bandit clan " + clan.Id + " unknown troop " + banditTroop.Unit); } } if (clan.IsBandit && clan.BanditTroops.Count == 0) { list.Add("scenario " + scenario.Id + ": bandit clan " + clan.Id + " has no troop pool"); } } foreach (LocationDef location in worldDef.Locations) { if (location.Type != SettlementType.Hideout && !dictionary2.ContainsKey(location.Id) && (location.Type != SettlementType.Village || string.IsNullOrEmpty(location.BoundTo) || !dictionary2.ContainsKey(location.BoundTo))) { list.Add("scenario " + scenario.Id + ": settlement " + location.Id + " has no owner clan"); } } foreach (LocationDef item3 in worldDef.Locations.Where((LocationDef l) => l.Type == SettlementType.Hideout)) { if (!hashSet2.Contains(item3.BanditClan)) { list.Add("scenario " + scenario.Id + ": hideout " + item3.Id + " bandit clan " + item3.BanditClan + " missing"); } } foreach (StanceDef stance in scenario.Stances) { if ((!hashSet3.Contains(stance.A) && !hashSet2.Contains(stance.A)) || (!hashSet3.Contains(stance.B) && !hashSet2.Contains(stance.B))) { list.Add("scenario " + scenario.Id + ": stance " + stance.A + "/" + stance.B + " references unknown faction"); } } foreach (GarrisonStartDef garrison in scenario.Garrisons) { if (!hashSet.Contains(garrison.Settlement)) { list.Add("scenario " + scenario.Id + ": garrison at unknown settlement " + garrison.Settlement); } foreach (RosterEntryDef troop2 in garrison.Troops) { if (!db.Units.Contains(troop2.Unit)) { list.Add("scenario " + scenario.Id + ": garrison troop " + troop2.Unit + " unknown"); } } } if (scenario.PlayerStarts.Count == 0) { list.Add("scenario " + scenario.Id + ": no player starts"); } foreach (PlayerStartDef playerStart in scenario.PlayerStarts) { if (!hashSet.Contains(playerStart.StartLocation)) { list.Add("scenario " + scenario.Id + ": start " + playerStart.Id + " unknown location " + playerStart.StartLocation); } if (!db.Cultures.Contains(playerStart.Culture)) { list.Add("scenario " + scenario.Id + ": start " + playerStart.Id + " unknown culture " + playerStart.Culture); } if (!string.IsNullOrEmpty(playerStart.Kingdom) && !hashSet3.Contains(playerStart.Kingdom)) { list.Add("scenario " + scenario.Id + ": start " + playerStart.Id + " unknown kingdom " + playerStart.Kingdom); } if (!string.IsNullOrEmpty(playerStart.HeroUnit) && !db.Units.Contains(playerStart.HeroUnit)) { list.Add("scenario " + scenario.Id + ": start " + playerStart.Id + " unknown hero unit " + playerStart.HeroUnit); } foreach (RosterEntryDef troop3 in playerStart.Troops) { if (!db.Units.Contains(troop3.Unit)) { list.Add("scenario " + scenario.Id + ": start " + playerStart.Id + " unknown troop " + troop3.Unit); } } if (playerStart.Kind != StartKind.Commander) { continue; } if (playerStart.OwnedSettlements.Count == 0) { list.Add("scenario " + scenario.Id + ": commander start " + playerStart.Id + " needs owned settlements"); } foreach (string ownedSettlement in playerStart.OwnedSettlements) { if (!hashSet.Contains(ownedSettlement)) { list.Add("scenario " + scenario.Id + ": start " + playerStart.Id + " owns unknown settlement " + ownedSettlement); } } if (!playerStart.Garrisons.Any((GarrisonStartDef g) => g.Troops.Sum((RosterEntryDef t) => t.Count) > 0)) { list.Add("scenario " + scenario.Id + ": commander start " + playerStart.Id + " needs an actual garrison"); } foreach (GarrisonStartDef garrison2 in playerStart.Garrisons) { if (!playerStart.OwnedSettlements.Contains(garrison2.Settlement)) { list.Add("scenario " + scenario.Id + ": start " + playerStart.Id + " garrisons unowned " + garrison2.Settlement); } foreach (RosterEntryDef troop4 in garrison2.Troops) { if (!db.Units.Contains(troop4.Unit)) { list.Add("scenario " + scenario.Id + ": start " + playerStart.Id + " unknown garrison troop " + troop4.Unit); } } } } } foreach (BattleMapDef battleMap in db.BattleMaps) { if (battleMap.TabsMapMatch.Count == 0) { list.Add("battle map " + battleMap.Id + ": needs at least one TabsMapMatch fragment"); } if (!string.IsNullOrEmpty(battleMap.Prefab) && battleMap.EncounterKinds.Contains(EncounterKind.Siege)) { list.Add("battle map " + battleMap.Id + ": a mod's own battle scene can't be used for sieges"); } if (battleMap.EncounterKinds.Count == 0) { list.Add("battle map " + battleMap.Id + ": needs encounter kinds"); } if (battleMap.MaxActiveUnits < 10) { list.Add("battle map " + battleMap.Id + ": MaxActiveUnits too small"); } } if (!db.BattleMaps.Any((BattleMapDef m) => m.EncounterKinds.Contains(EncounterKind.FieldBattle))) { list.Add("battle maps: at least one map must support FieldBattle (fallback)"); } return list; } private static void ValidateWorld(ContentDatabase db, WorldDef w, List errors) { if (w.Rows.Count == 0) { errors.Add("world " + w.Id + ": no terrain rows"); return; } int length = w.Rows[0].Length; Dictionary dictionary = new Dictionary(); foreach (TerrainDef item in w.Terrain) { if (item.Symbol.Length != 1) { errors.Add("world " + w.Id + ": terrain symbol '" + item.Symbol + "' must be one character"); continue; } if (dictionary.ContainsKey(item.Symbol[0])) { errors.Add("world " + w.Id + ": duplicate terrain symbol '" + item.Symbol + "'"); } dictionary[item.Symbol[0]] = item; if (item.Passable && item.Speed <= 0.0) { errors.Add("world " + w.Id + ": passable terrain '" + item.Symbol + "' needs positive speed"); } } for (int i = 0; i < w.Rows.Count; i++) { if (w.Rows[i].Length != length) { errors.Add($"world {w.Id}: row {i} has length {w.Rows[i].Length}, expected {length}"); } string text = w.Rows[i]; foreach (char c in text) { if (!dictionary.ContainsKey(c)) { errors.Add($"world {w.Id}: row {i} uses unknown terrain symbol '{c}'"); break; } } } HashSet hashSet = new HashSet(StringComparer.Ordinal); foreach (LocationDef location in w.Locations) { if (!hashSet.Add(location.Id)) { errors.Add("world " + w.Id + ": duplicate location id " + location.Id); } int num = (int)Math.Floor(location.X / w.CellSize); int num2 = (int)Math.Floor(location.Y / w.CellSize); if (num2 < 0 || num2 >= w.Rows.Count || num < 0 || num >= length) { errors.Add("world " + w.Id + ": location " + location.Id + " outside map"); continue; } char c2 = w.Rows[num2][num]; if (dictionary.TryGetValue(c2, out var value) && !value.Passable) { errors.Add($"world {w.Id}: location {location.Id} sits on impassable terrain '{c2}'"); } if (!db.Cultures.Contains(location.Culture) && location.Type != SettlementType.Hideout) { errors.Add("world " + w.Id + ": location " + location.Id + " unknown culture " + location.Culture); } } foreach (LocationDef l in w.Locations.Where((LocationDef x) => x.Type == SettlementType.Village)) { LocationDef locationDef = w.Locations.FirstOrDefault((LocationDef x) => x.Id == l.BoundTo); if (locationDef == null || (locationDef.Type != SettlementType.Town && locationDef.Type != SettlementType.Castle)) { errors.Add("world " + w.Id + ": village " + l.Id + " must be bound to a town or castle"); } if (!string.IsNullOrEmpty(l.Product) && VillageProducts.Get(l.Product) == null) { errors.Add("world " + w.Id + ": village " + l.Id + " has unknown product " + l.Product); } } foreach (LocationDef location2 in w.Locations) { if (location2.Type != SettlementType.Village && !string.IsNullOrEmpty(location2.Product)) { errors.Add("world " + w.Id + ": location " + location2.Id + " is not a village but has a product"); } if (location2.WallLevel < 0 || location2.WallLevel > 3 || (location2.WallLevel != 0 && location2.Type != SettlementType.Town && location2.Type != SettlementType.Castle)) { errors.Add("world " + w.Id + ": location " + location2.Id + " has an invalid wall level"); } } } } public sealed class CustomFactionDef { public string Key = ""; public string Name = ""; public string Color = "#888888"; public string Source = ""; public List Units = new List(); } public sealed class CustomUnitInfo { public string TabsUnitId = ""; public string Name = ""; public double Cost; public double Health; public double Size = 1.0; public double Range; public bool Mounted; } public static class CustomFactions { public const string Prefix = "custom."; public const int MaxUnits = 40; private const double RangedReach = 15.0; private static readonly double[] Attack = new double[6] { 1.3, 1.95, 2.6, 4.5, 8.0, 13.0 }; private static readonly double[] Defense = new double[6] { 1.0, 1.4, 1.8, 2.5, 3.0, 5.0 }; private static readonly double[] Health = new double[6] { 1.3, 1.8, 2.3, 4.5, 9.0, 15.0 }; private static readonly double[] RangedRating = new double[6] { 1.5, 1.9, 2.3, 1.4, 1.5, 1.6 }; private static readonly int[] RecruitCost = new int[6] { 50, 95, 140, 250, 650, 1600 }; private static readonly double[] Wage = new double[6] { 1.5, 2.5, 3.5, 5.0, 10.0, 20.0 }; private static readonly double[] TypicalCost = new double[6] { 70.0, 150.0, 250.0, 500.0, 1000.0, 2500.0 }; private static readonly int[] UpgradeXp = new int[5] { 50, 80, 120, 180, 260 }; private static readonly double[] TownWeight = new double[6] { 5.0, 3.0, 2.0, 1.0, 0.3, 0.2 }; private static readonly UnitRarity[] Rarity = new UnitRarity[6] { UnitRarity.Common, UnitRarity.Common, UnitRarity.Common, UnitRarity.Uncommon, UnitRarity.Rare, UnitRarity.Elite }; private static readonly string[] Symbols = new string[15] { "shield", "sword", "axe", "spear", "arrow", "tower", "mountain", "pine", "flame", "sun", "anchor", "hourglass", "lightning", "trident", "crown" }; private static readonly string[] Starts = new string[24] { "Ash", "Bram", "Cold", "Dun", "Elm", "Fen", "Glen", "High", "Iron", "Kings", "Long", "Mill", "North", "Oak", "Red", "Salt", "Stone", "Thorn", "West", "Wolf", "Amber", "Bright", "Copper", "Lark" }; private static readonly string[] Ends = new string[14] { "ford", "mere", "wick", "holm", "bury", "gate", "haven", "moor", "stead", "watch", "field", "reach", "crest", "fall" }; public static string CultureId(CustomFactionDef faction) { return "custom." + Slug(faction?.Key ?? ""); } public static bool IsCustom(string cultureId) { return cultureId?.StartsWith("custom.", StringComparison.Ordinal) ?? false; } public static List UsableUnits(CustomFactionDef faction) { return (from g in (faction?.Units ?? new List()).Where((CustomUnitInfo u) => u != null && !string.IsNullOrEmpty(u.TabsUnitId)).GroupBy((CustomUnitInfo u) => u.TabsUnitId, StringComparer.Ordinal) select g.First() into u orderby Math.Max(0.0, u.Cost) select u).ThenBy((CustomUnitInfo u) => u.Name ?? "", StringComparer.Ordinal).ThenBy((CustomUnitInfo u) => u.TabsUnitId, StringComparer.Ordinal).Take(40) .ToList(); } public static string Reason(CustomFactionDef faction) { if (faction == null || string.IsNullOrWhiteSpace(faction.Key)) { return "This faction has no id."; } if (string.IsNullOrWhiteSpace(faction.Name)) { return "This faction has no name."; } if (UsableUnits(faction).Count == 0) { return faction.Name + " has no units."; } return ""; } public static void Build(CustomFactionDef faction, out CultureDef culture, out List units) { string text = Reason(faction); if (text.Length > 0) { throw new ArgumentException(text); } string text2 = CultureId(faction); List list = UsableUnits(faction); int count = list.Count; int num = Math.Min(6, count); units = new List(); HashSet hashSet = new HashSet(StringComparer.Ordinal); for (int i = 0; i < count; i++) { CustomUnitInfo customUnitInfo = list[i]; int num2 = 1 + i * num / count; double num3 = Math.Max(10.0, customUnitInfo.Cost); double num4 = Math.Max(0.75, Math.Min(1.35, Math.Sqrt(num3 / TypicalCost[num2 - 1]))); double num5 = Math.Max(0.3, (customUnitInfo.Size <= 0.0) ? 1.0 : customUnitInfo.Size); bool flag = customUnitInfo.Range >= 15.0; bool flag2 = !customUnitInfo.Mounted && num5 >= 1.8; TroopRole role = (customUnitInfo.Mounted ? TroopRole.Cavalry : (flag2 ? TroopRole.Monster : (flag ? TroopRole.Ranged : TroopRole.Infantry))); string text3 = text2 + "." + Slug(customUnitInfo.Name); if (text3 == text2 + ".") { text3 = text2 + ".unit"; } string text4 = text3; int num6 = 2; while (hashSet.Contains(text4)) { text4 = text3 + num6.ToString(CultureInfo.InvariantCulture); num6++; } hashSet.Add(text4); UnitDef unitDef = new UnitDef { Id = text4, Name = (string.IsNullOrWhiteSpace(customUnitInfo.Name) ? "Soldier" : customUnitInfo.Name.Trim()), TabsUnitId = customUnitInfo.TabsUnitId, TabsFaction = faction.Name, Culture = text2, Tier = num2, Role = role, Rarity = Rarity[num2 - 1], TabsCost = (int)Math.Round(num3), RecruitCost = (int)Math.Round((double)RecruitCost[num2 - 1] * num4), DailyWage = Math.Round(Wage[num2 - 1] * num4 * 2.0) / 2.0, FoodUse = (customUnitInfo.Mounted ? 2 : ((!flag2) ? 1 : 3)), Slots = 1, Workload = Math.Max(1.2, Math.Min(8.0, 1.2 * num5 * num5 * (double)((!customUnitInfo.Mounted) ? 1 : 2))), MapSpeed = (customUnitInfo.Mounted ? 1.15 : (flag2 ? 0.9 : 1.0)), Mounted = customUnitInfo.Mounted, Attack = Math.Round(Attack[num2 - 1] * num4, 2), Defense = Math.Round(Defense[num2 - 1] * num4, 2), Health = Math.Round(Health[num2 - 1] * num4 * (flag2 ? 2.0 : (customUnitInfo.Mounted ? 1.3 : 1.0)), 2), Ranged = (flag ? RangedRating[num2 - 1] : 0.0), Notes = "From the custom faction " + faction.Name + "; ratings estimated from its TABS cost." }; unitDef.Access.Add((num2 != 1) ? AccessKind.Upgrade : AccessKind.VillageRecruit); unitDef.Access.Add(AccessKind.TownRecruit); units.Add(unitDef); } foreach (UnitDef unit in units) { List list2 = units.Where((UnitDef u) => u.Tier == unit.Tier + 1).ToList(); if (list2.Count == 0) { continue; } List list3 = (from u in list2 where u.TabsCost >= unit.TabsCost orderby u.TabsCost select u).ThenBy((UnitDef u) => u.Id, StringComparer.Ordinal).Take(2).ToList(); if (list3.Count == 0) { list3 = list2.OrderByDescending((UnitDef u) => u.TabsCost).ThenBy((UnitDef u) => u.Id, StringComparer.Ordinal).Take(1) .ToList(); } foreach (UnitDef item in list3) { unit.Upgrades.Add(new UpgradeDef { To = item.Id, Xp = UpgradeXp[unit.Tier - 1], Gold = Math.Max(10, item.RecruitCost - unit.RecruitCost) }); } } HashSet reachable = new HashSet(from x in units.SelectMany((UnitDef u) => u.Upgrades) select x.To, StringComparer.Ordinal); foreach (UnitDef item2 in units.Where((UnitDef u) => u.Tier > 1 && !reachable.Contains(u.Id))) { item2.Access.Remove(AccessKind.Upgrade); } UnitDef unitDef2 = (from u in units where u.Tier == 1 orderby (!Walker(u)) ? 1 : 0, u.TabsCost select u).First(); UnitDef unitDef3 = (from u in units where Walker(u) && u.Tier >= 2 && u.Tier <= 3 orderby (u.Role != TroopRole.Infantry) ? 1 : 0, u.TabsCost select u).FirstOrDefault() ?? (from u in units.Where(Walker) orderby u.Tier descending, u.TabsCost select u).FirstOrDefault() ?? unitDef2; culture = new CultureDef { Id = text2, Name = faction.Name.Trim(), TabsFaction = faction.Name.Trim(), Color = Colour(faction.Color), Symbol = Symbols[(uint)(StableHash.Fnv1a64(text2) % (ulong)Symbols.Length)], BasicTroop = unitDef2.Id, HeroUnit = unitDef3.Id }; foreach (UnitDef item3 in units.Where((UnitDef u) => u.Tier == 1 && Walker(u)).DefaultIfEmpty(unitDef2)) { culture.VillageRecruits.Add(new WeightedUnit { Unit = item3.Id, Weight = 10.0 }); } foreach (IGrouping item4 in from u in units group u by u.Tier) { foreach (UnitDef item5 in item4) { culture.TownRecruits.Add(new WeightedUnit { Unit = item5.Id, Weight = Math.Round(TownWeight[item4.Key - 1] / (double)item4.Count(), 3) }); } } static bool Walker(UnitDef u) { if (!u.Mounted && u.Role != TroopRole.Monster) { return u.Role != TroopRole.Siege; } return false; } } public static void Register(ContentDatabase content, CustomContentState custom, bool replace) { if (content == null) { return; } if (replace) { foreach (string item in (from c in content.Cultures where IsCustom(c.Id) select c.Id).ToList()) { content.Cultures.Remove(item); } foreach (string item2 in (from u in content.Units where IsCustom(u.Id) select u.Id).ToList()) { content.Units.Remove(item2); } } if (custom == null) { return; } foreach (CultureDef item3 in custom.Cultures ?? new List()) { if (item3 != null && IsCustom(item3.Id)) { content.Cultures.Remove(item3.Id); content.Cultures.Add(item3); } } foreach (UnitDef item4 in custom.Units ?? new List()) { if (item4 != null && IsCustom(item4.Id)) { content.Units.Remove(item4.Id); content.Units.Add(item4); } } } public static RealmSpec Realm(CustomFactionDef faction) { string text = CultureId(faction); ulong num = StableHash.Fnv1a64(text); RealmSpec realmSpec = new RealmSpec(); realmSpec.Culture = text; realmSpec.Name = Trim(faction.Name, 28); realmSpec.Capital = PlaceName(num, 0); realmSpec.MarketTown = PlaceName(num, 1); realmSpec.Biome = (new string[5] { "grassland", "grassland", "autumn", "golden", "coast" })[(uint)(num % 5)]; return realmSpec; } private static string PlaceName(ulong hash, int which) { ulong num = StableHash.Combine(hash, (ulong)((which + 1) * -7046029254386353131L)); return Starts[(uint)(num % (ulong)Starts.Length)] + Ends[(uint)(num / 31 % (ulong)Ends.Length)]; } private static string Trim(string s, int n) { s = (s ?? "").Trim(); if (s.Length > n) { return s.Substring(0, n).TrimEnd(Array.Empty()); } return s; } internal static string Slug(string s) { StringBuilder stringBuilder = new StringBuilder(); string text = (s ?? "").ToLowerInvariant(); foreach (char c in text) { if ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')) { stringBuilder.Append(c); } else if (stringBuilder.Length > 0 && stringBuilder[stringBuilder.Length - 1] != '-') { stringBuilder.Append('-'); } if (stringBuilder.Length >= 40) { break; } } string text2 = stringBuilder.ToString().Trim(new char[1] { '-' }); if (text2.Length <= 0) { return "x" + StableHash.Fnv1a64(s ?? "").ToString("x8", CultureInfo.InvariantCulture).Substring(0, 8); } return text2; } private static string Colour(string colour) { string text = (colour ?? "").Trim(); if (!text.StartsWith("#", StringComparison.Ordinal)) { text = "#" + text; } if (text.Length == 9) { text = text.Substring(0, 7); } if (text.Length != 7 || !text.Skip(1).All(Uri.IsHexDigit)) { return "#888888"; } return text.ToLowerInvariant(); } } public static class DayNight { public const int MinutesPerDay = 1440; public const int DawnStart = 300; public const int DawnEnd = 420; public const int DuskStart = 1080; public const int DuskEnd = 1200; public const double NightSightPenalty = 0.5; public const double PenaltyReductionPerScouting = 0.0015; public const double MinimumNightSightPenalty = 0.1; public static int TimeOfDay(long minute) { return (int)((minute % 1440 + 1440) % 1440); } public static double Daylight(long minute) { int num = TimeOfDay(minute); if (num >= 420 && num < 1080) { return 1.0; } if (num >= 1200 || num < 300) { return 0.0; } double num2 = ((num < 420) ? ((double)(num - 300) / 120.0) : (1.0 - (double)(num - 1080) / 120.0)); return num2 * num2 * (3.0 - 2.0 * num2); } public static string Phase(long minute) { int num = TimeOfDay(minute); if (num >= 420 && num < 1080) { return "Day"; } if (num >= 1080 && num < 1200) { return "Dusk"; } if (num >= 300 && num < 420) { return "Dawn"; } return "Night"; } public static double NightPenalty(int scouting) { return Math.Max(0.1, 0.5 - (double)Math.Max(0, scouting) * 0.0015); } public static double SightFactor(long minute, int scouting) { return 1.0 - NightPenalty(scouting) * (1.0 - Daylight(minute)); } } public static class DefenderTroops { private static double TierWeight(int tier) { if (tier > 1) { return tier switch { 3 => 1.0, 2 => 4.0, _ => 0.4, }; } return 10.0; } public static List Line(ContentDatabase content, string cultureId) { List list = new List(); CultureDef cultureDef = content?.Cultures.Get(cultureId ?? ""); UnitDef unitDef = ((cultureDef == null) ? null : content.Units.Get(cultureDef.BasicTroop ?? "")); if (unitDef == null) { return list; } HashSet hashSet = new HashSet(StringComparer.Ordinal); List list2 = new List { unitDef }; for (int i = 0; i < 4; i++) { if (list2.Count <= 0) { break; } List list3 = new List(); foreach (UnitDef item in list2) { if (!hashSet.Add(item.Id)) { continue; } if (item.Id == unitDef.Id || Defends(item, cultureDef)) { list.Add(new WeightedUnit { Unit = item.Id, Weight = TierWeight(item.Tier) }); } foreach (UpgradeDef item2 in item.Upgrades ?? new List()) { UnitDef unitDef2 = content.Units.Get(item2.To ?? ""); if (unitDef2 != null && !hashSet.Contains(unitDef2.Id)) { list3.Add(unitDef2); } } } list2 = list3; } return list; } private static bool Defends(UnitDef unit, CultureDef culture) { if (!unit.Mounted && unit.Slots == 1 && unit.Id != culture.HeroUnit && unit.Role != TroopRole.Monster) { return unit.Role != TroopRole.Siege; } return false; } public static List> Split(List line, int count) { List> list = new List>(); if (line == null || line.Count == 0 || count <= 0) { return list; } double total = line.Sum((WeightedUnit w) => Math.Max(0.0, w.Weight)); if (total <= 0.0) { return list; } List exact = line.Select((WeightedUnit w) => (double)count * Math.Max(0.0, w.Weight) / total).ToList(); List whole = exact.Select((double x) => (int)Math.Floor(x)).ToList(); int count2 = count - whole.Sum(); foreach (int item in (from i in Enumerable.Range(0, line.Count) orderby exact[i] - (double)whole[i] descending, i select i).Take(count2)) { whole[item]++; } for (int num = 0; num < line.Count; num++) { if (whole[num] > 0) { list.Add(new KeyValuePair(line[num].Unit, whole[num])); } } return list.OrderByDescending((KeyValuePair e) => e.Value).ToList(); } } public enum TroopRole { Infantry, Ranged, Cavalry, Support, Monster, Siege } public enum UnitRarity { Common, Uncommon, Rare, Elite, Unique } public enum AccessKind { VillageRecruit, TownRecruit, Upgrade, Mercenary, Bandit, Discovery, Quest, LordOnly, NotYetAssigned } public sealed class UnitDef : IEntity { public string Name = ""; public string TabsUnitId = ""; public string TabsFaction = ""; public string LooksLike = ""; public string Culture = ""; public int Tier = 1; public TroopRole Role; public UnitRarity Rarity; public List Access = new List(); public int TabsCost; public int RecruitCost = 10; public double DailyWage = 1.0; public double FoodUse = 1.0; public int Slots = 1; public double Workload = 1.0; public double MapSpeed = 1.0; public bool Mounted; public double Attack = 1.0; public double Defense = 1.0; public double Health = 1.0; public double Ranged; public List Upgrades = new List(); public string Notes = ""; public string Id { get; set; } = ""; } public sealed class UpgradeDef { public string To = ""; public int Xp = 100; public int Gold = 10; public string RequiresSettlement = ""; } public sealed class WeightedUnit { public string Unit = ""; public double Weight = 1.0; } public sealed class CultureDef : IEntity { public string Name = ""; public string TabsFaction = ""; public string Color = "#888888"; public string Symbol = "?"; public string BasicTroop = ""; public List VillageRecruits = new List(); public List TownRecruits = new List(); public List HeroNames = new List(); public List ClanNames = new List(); public string HeroUnit = ""; public List LordUnits = new List(); public string Id { get; set; } = ""; } public enum TerrainType { Plains, Forest, Hills, Mountains, Water, River, Road, Ford, Bridge, Swamp, Snow, Desert, Beach } public sealed class TerrainDef { public string Symbol = "."; public TerrainType Type; public bool Passable = true; public double Speed = 1.0; public string Biome = "grassland"; public double Sight = 1.0; } public enum SettlementType { Village, Town, Castle, Hideout } public sealed class LocationDef : IEntity { public string Name = ""; public SettlementType Type; public double X; public double Y; public string Culture = ""; public string BoundTo = ""; [NotSaved] public string Product = ""; [NotSaved] public int WallLevel; public double Prosperity = 500.0; public int RecruitSlots = 4; public string BanditClan = ""; public string Description = ""; public string Id { get; set; } = ""; } public sealed class WorldDef { public string Id = ""; public string Name = ""; public double CellSize = 1.0; public List Rows = new List(); public List Terrain = new List(); public List Locations = new List(); public int GenerationVersion; public ulong GenerationSeed; public List Regions = new List(); } public sealed class WorldRegionDef { public string Id = ""; public string Name = ""; public string Culture = ""; public string Biome = "grassland"; public double X; public double Y; } public sealed class RosterEntryDef { public string Unit = ""; public int Count; } public sealed class KingdomStartDef { public string Id = ""; public string Name = ""; public string Culture = ""; public string RulerClan = ""; public string Color = "#888888"; public string Symbol = "?"; } public sealed class LordStartDef { public string Name = ""; public string Unit = ""; public int PartyTroops = 20; public List Troops = new List(); } public sealed class ClanStartDef { public string Id = ""; public string Name = ""; public string Kingdom = ""; public string Culture = ""; public int Gold = 5000; public double Renown = 100.0; public bool IsBandit; public string Color = "#888888"; public string Symbol = "?"; public List Lords = new List(); public List Settlements = new List(); public List BanditTroops = new List(); } public sealed class GarrisonStartDef { public string Settlement = ""; public List Troops = new List(); } public enum StartKind { SmallWarband, Commander } public sealed class PlayerStartDef { public string Id = ""; public string Name = ""; public string Description = ""; public StartKind Kind; public string Culture = ""; public string StartLocation = ""; public string Kingdom = ""; public string ClanName = ""; public int Gold = 1000; public double Food = 10.0; public double Renown; public string HeroUnit = ""; public List Troops = new List(); public List OwnedSettlements = new List(); public List Garrisons = new List(); } public sealed class StanceDef { public string A = ""; public string B = ""; public bool War = true; } public sealed class CompanionDef { public string Id = ""; public string Name = ""; public string Culture = ""; public string Unit = ""; public string Settlement = ""; public string Description = ""; public long HireCost; public int DailyWage; public SortedDictionary Skills = new SortedDictionary(StringComparer.Ordinal); } public sealed class ScenarioDef : IEntity { public string Name = ""; public string Description = ""; public string World = ""; public List Kingdoms = new List(); public List Clans = new List(); public List Stances = new List(); public List PlayerStarts = new List(); public List Garrisons = new List(); public List Companions = new List(); public int VillagerPartiesPerVillage = 1; public string Id { get; set; } = ""; } public enum EncounterKind { FieldBattle, BanditAmbush, SettlementDefense, HideoutRaid, Siege, Tournament, TownVisit } public sealed class EntryZoneDef { public string Id = ""; public string Side = "Attacker"; public double X; public double Z; public double Radius = 6.0; public double FacingDegrees; } public sealed class BattleMapDef : IEntity { public string Name = ""; public int ContentVersion = 1; public List TabsMapMatch = new List(); public List Biomes = new List(); public List EncounterKinds = new List(); public int MaxActiveUnits = 150; public bool GenericStandIn = true; public List EntryZones = new List(); public string Restrictions = ""; public string Prefab = ""; public string Id { get; set; } = ""; } public sealed class ContentPackInfo { public string Id = ""; public string Name = ""; public int Version = 1; public string Description = ""; public string Author = ""; public List Requires = new List(); } public sealed class ModContent { public ContentPackInfo Pack = new ContentPackInfo(); public Dictionary Texts = new Dictionary(StringComparer.Ordinal); } public sealed class ModLoadResult { public string Id = ""; public bool Loaded; public string Error = ""; } public sealed class EncyclopediaConceptDef { public string Id = ""; public string Title = ""; public string Topic = ""; public string Text = ""; public string[] See = new string[0]; } public static class EncyclopediaConcepts { public static readonly IReadOnlyList All = new EncyclopediaConceptDef[31] { new EncyclopediaConceptDef { Id = "travel", Title = "Travel and time", Topic = "Campaign map", Text = "Right-click the ground to travel there, a settlement to go in, or a hostile party to chase it. Routes go round water and impassable ground and cross rivers only at bridges and fords.\n\nSpeed depends on the ground, party size, wounded, prisoners and horses: riders and spare horses help, loose animals and heavy cargo don't. Hover the speed on the resource bar for the details.\n\nTime only passes while you travel or wait, at normal (1) or fast (2) speed. Menus and this encyclopedia pause it.", See = new string[3] { "sightings", "party", "horses" } }, new EncyclopediaConceptDef { Id = "sightings", Title = "Scouting and sightings", Topic = "Campaign map", Text = "You know where every settlement is, but you only see parties within sight, plus those near your fiefs, your own caravans and clan parties, and warbands you've called to your army. A party that leaves your sight leaves a last-known marker behind for a while.\n\nOther parties' strengths are guesses: exact up to 5 men, to the nearest 5 up to 20, to the nearest 10 beyond. Your own are exact.\n\nA good Scout sees further. Everyone sees less at night.\n\nThe encyclopedia plays by the same rules: lords are where you last saw them (or unknown), and strengths are the same guesses. A hero's skills read N/A until you've met them: in the same settlement, when your parties meet, or with them in your party or your cells. Your own clan's you always know.", See = new string[2] { "travel", "companions" } }, new EncyclopediaConceptDef { Id = "party", Title = "Your warband", Topic = "Party", Text = "Your party size limit grows with renown and Leadership. Every troop costs a daily wage and eats every day. Late pay and hunger sap morale, and if it goes on they desert; starving parties lose men outright.\n\nFood is your provisions plus any food goods in your cargo (grain, fish, meat, olives, grapes, dates), bought at any village or town. Provisions go first, then the cheapest goods. Hover the food on the resource bar to see how many days you have.\n\nThe wounded heal with time, faster with a good Surgeon. Overload your cargo and you'll crawl.", See = new string[4] { "troops", "prisoners", "companions", "trade" } }, new EncyclopediaConceptDef { Id = "troops", Title = "Troops, tiers and upgrades", Topic = "Party", Text = "Troops are TABS units. Each has a culture, a tier (1 to 6), a role (infantry, ranged, cavalry, support, monster or siege), and a cost, wage and appetite. Battle ratings decide auto-resolved fights and AI guesses; in a played battle they're just their TABS unit.\n\nTroops gain experience in battle and upgrade along their culture's tree for experience and gold. Some branches split, so one recruit can go two ways. The Units page has every tree.\n\nVolunteers come from the notables of a settlement's own culture. Rarer troops only come from upgrades or other routes; each troop's page says which.", See = new string[3] { "notables", "party", "battles" } }, new EncyclopediaConceptDef { Id = "prisoners", Title = "Prisoners and ransom", Topic = "Party", Text = "Win, and you take prisoners up to your limit. Ordinary prisoners heal and, travelling with a fed party, slowly come round to joining you; recruiting them costs morale. Release them, move them in and out of a dungeon you own, or sell them to a friendly town's merchants.\n\nNamed prisoners (lords and companions) are kept apart. Release them, lock them in your dungeon, or ransom them for 300 denars at a friendly town. Your own captured companions can be bought back through Characters.", See = new string[2] { "party", "battles" } }, new EncyclopediaConceptDef { Id = "heroes", Title = "Heroes, skills, focus and perks", Topic = "Characters", Text = "Heroes are the campaign's named people: you, your companions, every clan's lords and the outlaw chiefs. They have levels and ten skills: Leadership, Tactics, Scouting, Stewardship, Medicine, Trade, Engineering, Diplomacy, Smithing and Riding. You get better by doing. Scouts learn on the road, surgeons by healing, quartermasters by feeding the troops, engineers by building engines.\n\nFocus makes learning faster. Two points at level 1, then one more at 3, 5, 7 and so on. A skill takes up to five, each worth +20%, so at most double speed.\n\nPerks come in pairs as skills grow: role perks at 25, Smithing and Riding perks along the way. Retrain at a friendly town (500 denars) to clear a present hero's focus and perks; skills stay.", See = new string[3] { "companions", "smithing", "horses" } }, new EncyclopediaConceptDef { Id = "companions", Title = "Companions, roles and governors", Topic = "Characters", Text = "Wanderers hang about in town taverns for five to twelve days, then move on to a nearby town. New ones turn up while there are fewer than about three for every five towns. Hire one for a one-off fee and a daily wage after that; they fight in your battles with their own skills and gear.\n\nGive companions party roles: the Scout sees further and speeds travel, the Surgeon heals and saves the wounded, the Quartermaster stretches food and wages. They have to be healthy and present.\n\nA companion can govern a town or castle you own (+10% tax and +0.5 loyalty a day while paid), lead one of up to two clan parties of your soldiers, or captain one of up to two trading caravans.", See = new string[3] { "heroes", "armies", "trade" } }, new EncyclopediaConceptDef { Id = "families", Title = "Families, marriage and heirs", Topic = "Characters", Text = "A year is 84 days. People age; children come of age at 18. Lords and ladies marry, and a wife joins her husband's clan unless she leads her own. Couples have children, mostly while the mother is under 35; a child arrives 36 days after the news and grows up at the family home.\n\nTo marry, court an unmarried lord or lady of another clan in person. In a town or castle you're both in, go to the Keep and talk (the guards let in your own clan and realm; anyone else bribes them). Good conversations win their favour, helped by Diplomacy and your clans' relation; bad ones can put them off for a while. Then ask for their hand. Their clan leader says yes if your clans get on and you pay the marriage gift. Your spouse joins your clan and travels with you. You can match your family's grown members the same way.\n\nYour children's upbringing (at 5, 10 and 15) shapes their skills. When they come of age they wait at home for you to fetch them, and serve like companions without a wage.\n\nFrom about 50, old age can kill. When you die you pick an heir from the clan's grown family and play on; if there's nobody, that's the end. A clan whose leader dies goes to the eldest grown child, then the spouse, then a sibling; a clan running short of grown members gets a cousin. Each family rule can be turned off in the family screen.", See = new string[3] { "heroes", "companions", "clans" } }, new EncyclopediaConceptDef { Id = "clans", Title = "Clans, renown and tiers", Topic = "Politics", Text = "Every lord belongs to a clan. A clan has a leader, a treasury, renown and influence, and may belong to a kingdom or stand independent. Clans hold the towns, castles and villages.\n\nRenown comes from victories and tournaments, and sets the clan's tier: tier 1 at 50 renown, 2 at 150, 3 at 350, 4 at 900, 5 at 2,350 and 6 at 6,150. Higher tiers let a clan field larger parties.\n\nClans have relations with each other, from −100 to 100. Gifts of 100 or 500 denars improve them by 2 or 10, once a day per clan; fief awards and council votes change them too. A vassal clan whose relation with its ruler falls to −40 may leave the kingdom.", See = new string[3] { "kingdoms", "council", "diplomacy" } }, new EncyclopediaConceptDef { Id = "kingdoms", Title = "Kingdom service and founding", Topic = "Politics", Text = "Kingdoms are ruled by one clan and joined by others. A landless clan can sign on as mercenaries for seven days at up to 50 denars a day from the ruler, or swear vassalage with 100 renown. Members share the kingdom's wars and peace.\n\nLeave service and you lose your influence. A landed vassal can hand its fiefs back peacefully, or keep them and break away, which means war with the old kingdom.\n\nAn independent clan leader with 200 renown and 1,000 denars can found a kingdom at a town or castle they hold, becoming its ruler.", See = new string[3] { "clans", "council", "diplomacy" } }, new EncyclopediaConceptDef { Id = "council", Title = "The council, influence and policies", Topic = "Politics", Text = "Vassals and rulers sit on the council and earn one influence a day (up to 1,000), plus a share of battles won. A proposal costs 10 influence and runs for 48 hours. Each clan votes once, spending 0, 10 or 30 influence for a weight of 1, 2 or 4. A tie fails.\n\nThe council decides fief awards, policies, expulsions, war and peace. Tax policy covers every settlement: Balanced changes nothing, Local Charters is −10% tax and +0.5 loyalty a day, War Levy +15% tax and −0.5 loyalty a day.\n\nBeside it stand the kingdom policies, adapted from Bannerlord's: Road Tolls, Serfdom, Debasement of the Currency, Grazing Rights, Hunting Rights, Magistrates, Bailiffs, Trial by Jury, Citizenship, Cantons, Council of the Commons, Tribunes of the People, Noble Retinues, Royal Guard, Military Coronae, Marches, Castle Charters, Land Grants for Veterans, Royal Privilege, Sacred Majesty and Senate. Any number can stand at once (a few rule each other out), each voted in or out by the council. Between them they touch taxes, loyalty, security, prosperity, hearths, militia, garrison wages, party sizes, food, influence, ballots and proposal costs. Clans vote for whatever suits their holdings, and bring their own proposals about once a week.", See = new string[4] { "kingdoms", "diplomacy", "clans", "rebellions" } }, new EncyclopediaConceptDef { Id = "rebellions", Title = "Unrest and rebellions", Topic = "Politics", Text = "A town or castle whose loyalty stays below 25 builds up unrest, a day for each day (half as fast under Bailiffs); above it unrest calms by two a day. After seven days of unrest the people may rise at any dawn, unless a lord of the realm (or you) is inside or the garrison is a match for the militia.\n\nThe rising makes a new rebel clan of the settlement's own people, with a leader and kin, a party in the field and the militia on the walls. It takes the town or castle and its villages, cuts down the old garrison and is at war with the realm it left. Your own fiefs can rebel too.\n\nRetake the fort and the rebellion is crushed: its villages go back, its parties scatter and its surviving lords flee into exile. If the rebels hold out for thirty days they may swear to a kingdom of their own culture; after sixty days the realm they left (if it is not yours) recognises them and makes peace. The campaign rule Rebellions, chosen when the campaign begins, can leave risings out altogether.", See = new string[3] { "settlements", "council", "sieges" } }, new EncyclopediaConceptDef { Id = "diplomacy", Title = "War, peace and truces", Topic = "Politics", Text = "Kingdoms and independent clans are at war or at peace with each other. At war, their parties attack each other, their villages can be raided and their forts besieged.\n\nMake peace (as an independent leader, a ruler, or through the council) and your side pays 1,000 denars to the other ruler, and a seven-day truce begins. Other rulers make at most one decision a week: a war 21 days old can end, and after 14 days of peace a stronger neighbour may attack. Peace doesn't free prisoners.", See = new string[3] { "council", "raids", "sieges" } }, new EncyclopediaConceptDef { Id = "settlements", Title = "Settlements and their statistics", Topic = "Settlements", Text = "Towns are the richest settlements, with markets, taverns, arenas and smithies. Castles guard the land, and each town and castle has its own villages, which grow food and make one product. Hideouts shelter outlaws.\n\nProsperity (hearths, for villages) grows with surplus food and good security and falls with raids, sieges and hunger; it stays between 100 and 10,000. Loyalty and security rise and fall with the owner's policies and buildings. Militia grows a little each day towards a size set by prosperity, and helps defend.\n\nA town or castle you own can build granaries, watchtowers and walls (three levels each). Wall levels 1 to 3 give each wall section 1,200, 1,800 or 2,400 health in a siege. Up to three more projects can wait in a build queue: each starts when the one before it is done and is paid for then, its hardwood and tools bought in the town's market or carted in at twice the price.\n\nEach holding has budgets: a limit on what its garrison costs a day (the costliest soldiers over it are sent home at dawn), volunteers recruited up to that limit, and what its governor may spend a day on relief: grain carted in when the stores run low, then alms and public works.\n\nHardship measures how hard life is in a town. Hunger, siege, refugees from raided villages, lawlessness, heavy taxes and poverty push it up; it climbs quickly and eases slowly. Strained (25+), suffering (50+) and desperate (75+) towns lose loyalty, prosperity, security and taxes, and a desperate town under 50 loyalty can riot.", See = new string[4] { "food", "notables", "sieges", "raids" } }, new EncyclopediaConceptDef { Id = "food", Title = "Food in settlements", Topic = "Settlements", Text = "A settlement's food is the food goods in its market: grain, fish, meat, olives, grapes and dates. Its people eat them every day, cheapest first: three a day per 900 prosperity in a town, one for a castle household, and a little for every soldier and militiaman. A town's fields add 4 grain a day, a castle's 2, and the bound villages send their food.\n\nBuying a town's food can leave it hungry, and selling food feeds it. When the food runs out, prosperity and security fall, militia leaves and soldiers fall sick. In a siege nothing reaches the market, so the defenders slowly starve.", See = new string[3] { "settlements", "sieges", "trade" } }, new EncyclopediaConceptDef { Id = "notables", Title = "Notables and volunteers", Topic = "Settlements", Text = "Every village and town has a notable who offers volunteers. Get on with them and more open up, at 0, 10 and 20; the owner gets them all. Volunteers come back over time.\n\nNotables also offer work: deliveries, supply requests and bounties on outlaw leaders. Completing one gives +5 relation; abandoning one or letting it expire costs 2. Raiding their village costs 10.", See = new string[2] { "troops", "settlements" } }, new EncyclopediaConceptDef { Id = "trade", Title = "Trade, workshops and caravans", Topic = "Economy", Text = "There are 27 trade goods: food, raw materials from the villages, and workshop goods from the towns. Markets hold real stocks and real money, so prices rise as goods run short and fall as they pile up.\n\nYour clan can own up to three workshops (one of each kind per town), which turn a village product into goods using the town's materials. A companion can captain one of up to two caravans that buy and sell between towns with their own capital.\n\nEvery town also sends out its merchants' caravan under the colours of whoever holds the town.", See = new string[2] { "food", "companions" } }, new EncyclopediaConceptDef { Id = "raids", Title = "Raiding villages", Topic = "Warfare", Text = "At war, you can raid an enemy village with at least five fit fighters who outnumber its militia and garrison. The raid takes time, during which you stay on the map; it costs 10 relation with the village's notable. A finished raid carries off up to 100 denars, 20 food and some of the village's goods, within your carrying capacity.\n\nRaids damage the village without capturing it. Damage cuts its production and taxes, and at 50 or more it gives no volunteers; it recovers by 20 each dawn.", See = new string[3] { "diplomacy", "sieges", "settlements" } }, new EncyclopediaConceptDef { Id = "sieges", Title = "Sieges", Topic = "Warfare", Text = "At war with a town or castle's owner, select it and choose Besiege. You need a fit commander and at least five fit fighters. The camp takes six hours to prepare. Then build siege works: ballistae, catapults or trebuchets in four artillery slots, two siege towers and a battering ram. Artillery fires every half hour at the defenders' engines and walls.\n\nAssault when ready: the battle is fought in TABS on a fortress with walls, towers, a gate and a keep, with ladders, siege towers and the ram. You can demand surrender of an undefended fort at once; otherwise only after the camp has stood a day, the defenders' food is gone and you have twice their strength.\n\nA captured fort and its villages pass to the besieger's clan. Before the assault you choose to occupy it (−10 loyalty, −5 security) or pillage it (up to 300 denars, −15% prosperity, −30 loyalty, −20 security).", See = new string[3] { "battles", "food", "diplomacy" } }, new EncyclopediaConceptDef { Id = "battles", Title = "Battles in TABS", Topic = "Warfare", Text = "When parties meet, nearby allies join and you choose: fight in TABS, auto-resolve, leave if you can, sacrifice troops to escape, or surrender. The campaign stands still during a battle.\n\nOnly part of each army is on the field at once; the rest wait as reserves and arrive in announced waves as the fight goes on. You choose your opening troops and place them before the battle. In the fight you give group orders (1–6 groups, 0 all; F1 hold, F2 attack, F3 move, F4 retreat), can slow time, and can take control of any of your soldiers.\n\nEvery battle's result is final: casualties, wounds, prisoners, loot, experience and renown. Auto-resolve plays by the same rules.", See = new string[4] { "troops", "prisoners", "sieges", "armies" } }, new EncyclopediaConceptDef { Id = "armies", Title = "Armies", Topic = "Warfare", Text = "You can gather your companions' clan parties around your own warband as an army. A sworn vassal or ruler at war can also call up to three other clans' warbands from the kingdom: each call costs 20 influence and 2 a day while they serve, for up to seven days.\n\nAn army marches at the pace of its slowest member and shares food at dawn. Cohesion falls on campaign and recovers when everyone rests supplied at a friendly town or castle; Rally spends 10 influence for up to 20 cohesion once a day. At zero cohesion the army breaks up.", See = new string[3] { "companions", "council", "battles" } }, new EncyclopediaConceptDef { Id = "tournaments", Title = "Tournaments and special abilities", Topic = "Pastimes", Text = "Towns hold tournaments for sixteen fighters: three rounds of two against two, then a one-against-one final. You fight your own matches in the town's arena in TABS, controlling your hero; nobody is killed or wounded. You may bet up to 150 denars on winning the whole tournament before each of your matches.\n\nThe winner takes the prize, shown before you enter: a fine forged weapon, a war horse in its prime, or a TABS special ability, plus 3 renown. A hero keeps a learned ability for life and can have up to five switched on at once.", See = new string[3] { "smithing", "horses", "clans" } }, new EncyclopediaConceptDef { Id = "smithing", Title = "Smithing", Topic = "Pastimes", Text = "Any hero can work at a friendly town's smithy, limited by their stamina. Refine hardwood and iron ore into charcoal and iron, forge weapons from parts (blade or head, guard, handle, pommel) in twelve weapon classes, and smelt spare weapons to recover metal and learn their parts.\n\nHarder designs need more Smithing; a smith far below the difficulty is likely to make a poor weapon. Forged weapons can be equipped by your heroes, sold or used to fill the orders of the town's customers.", See = new string[2] { "heroes", "trade" } }, new EncyclopediaConceptDef { Id = "horses", Title = "Horses and riding", Topic = "Pastimes", Text = "Your heroes can each own a horse with its own breed, stats, temper, age, training and bond with its rider. Every horse needs a certain Riding skill to ride. In battle a mounted hero rides a TABS horse matching their own; sieges are fought on foot.\n\nHorses are sold in towns and horse-ranch villages; stock changes weekly. A stud farm at a ranch rests, heals and trains your horses and lets you breed them. On the march riders speed the party up and spare horses carry footmen and cargo.", See = new string[2] { "heroes", "travel" } }, new EncyclopediaConceptDef { Id = "townvisits", Title = "Walking round towns and castles", Topic = "Pastimes", Text = "In a town or castle you're staying in, choose Walk in town (or castle) and walk round it in TABS: guards, stallholders, the smith, a priest, a bard and townsfolk going about their day. Nobody can attack anyone, and nothing in your campaign changes.\n\nWalk out through the gate or press Tab to leave.", See = new string[1] { "settlements" } }, new EncyclopediaConceptDef { Id = "quests", Title = "Quests and the journal", Topic = "Quests and events", Text = "Notables have troubles; lords and ladies have tasks. Ask a notable on a settlement's Locals tab, or a lord or lady in conversation. Offers are fixed for the week, so asking again just gets you the same one.\n\nVillage elders deal with rustlers and their lord's levy; town stewards with a stolen ledger and old debts; castellans with an untrained levy and crumbling walls. Each trouble has two or three ways to go about it: fight, pay, lend men, speak to a lord, or something less honest, each with its own costs and consequences. Lords and ladies ask you to carry a letter, raid an enemy village, bring them an enemy lord as a prisoner, raise troops for their retinue or clear their lands of bandits; you hand those in to them in person.\n\nLonger stories run over several stages in different places and branch on your choices: a stranger in a town's tavern may tell of a stolen heirloom or a lost legion, and a village elder of a feud with the next village. Each is told once a campaign.\n\nThe reward sits with whoever's paying (a clan treasury or a market purse) until the job's done. Every quest has a deadline; miss it, or give up, and the giver thinks a little less of you. If the giver dies, someone else gets the target, or a war makes it impossible, it closes with no blame and the money goes back. Four quests at once is the limit. The journal (L) lists them and your contracts; the tracked one sits in the map's corner, with its next step ringed.", See = new string[3] { "notables", "discoveries", "events" } }, new EncyclopediaConceptDef { Id = "discoveries", Title = "Hidden places", Topic = "Quests and events", Text = "Ruins, old battlefields, shrines, wrecks, caves, abandoned camps, barrows and towers lie hidden about the land. Your party finds one by passing near it: the better your Scouting (or your scout's), the sooner. A found place is marked on the map and in the journal's Places tab.\n\nTravel there and explore it, once: searching carefully takes six hours; sending scouts in first takes three, needs 30 Scouting, is safer and finds more. A place may hold old coins, goods, a relic weapon, soldiers living rough who ask to join you, lore to learn from, nothing at all, or an ambush.", See = new string[2] { "quests", "sightings" } }, new EncyclopediaConceptDef { Id = "events", Title = "Random events", Topic = "Quests and events", Text = "About once a fortnight (ten to eighteen days apart) something happens: on the road, in camp, in a settlement or after a battle you won. Time stops and you choose. The results run through the normal rules: treasury, a village's volunteers, morale, wounds, relations, renown. An event then won't come round again for 120 days.\n\nAn unanswered event is saved and waits for you after a load. The Random events rule, chosen at the start, can turn them off.", See = new string[1] { "quests" } }, new EncyclopediaConceptDef { Id = "hideouts", Title = "Bandit hideouts", Topic = "Quests and events", Text = "Outlaws keep camps in the wilds, and each camp's gang stays at home while its raiders roam. A camp is hidden until your party passes near enough to spot it (sight and Scouting help); then it is marked on your map.\n\nStand at a camp to assault it. Only a squad goes in: at most 8, two more for each clan tier and one more for every 30 Tactics (up to 24), heroes included. The rest of your party waits outside. Beat the gang and its chief steps out: face them alone, fight on with your survivors, or let them run. Some chiefs are legends, and a legend beaten in a fair fight may join you.\n\nA cleared camp pays out the gang's hoard, renown and the thanks of the villages around it. It lies empty for four to six weeks, then a new gang moves in. Lose, and the gang keeps its camp (and any of your people it caught).", See = new string[3] { "legends", "battles", "prisoners" } }, new EncyclopediaConceptDef { Id = "legends", Title = "Secret and Legacy units", Topic = "Quests and events", Text = "Rare and legendary fighters live outside the kingdoms' recruiting halls. Some live at hidden places: a legend there joins once a campaign, for a price, and only a clan of high enough tier; an enclave keeps a few rare troops for hire and is restocked every two weeks. Some lead bandit gangs from their hideouts and must be beaten first. Others will follow you as the reward for a quest, usually bringing goods or beating bandits who wronged them.\n\nA legend comes only once a campaign. Four of the game's joke and test units (Tank, Super Boxer, Dark Peasant, Super Peasant) are not part of the campaign.", See = new string[3] { "hideouts", "discoveries", "quests" } }, new EncyclopediaConceptDef { Id = "ironman", Title = "Ironman", Topic = "Campaign rules", Text = "A rule chosen at the start. Ironman keeps one save and writes it itself: each day, when an encounter begins, before and after battles, and whenever you leave. No manual saves, no going back; loading another campaign saves this one first.\n\nQuit or crash mid-battle and you come back to the decision, but it still has to be settled: fight, auto-resolve or surrender. No leaving, no buying your way out with men.", See = new string[1] { "battles" } } }; public static EncyclopediaConceptDef Get(string id) { return All.FirstOrDefault((EncyclopediaConceptDef c) => c.Id == id); } } public enum EquipmentSlot { Weapon, Outfit, Shield, Ammo } public enum EquipmentHand { Both, Main, Off } public sealed class EquipmentDef { public readonly string Id; public readonly string Name; public readonly EquipmentSlot Slot; public readonly string SourceUnitId; public readonly long Price; public readonly double Weight; public readonly EquipmentHand Hand; public readonly double ShieldDefense; public readonly WeaponClass? Class; public readonly int Tier; public readonly WeaponClass? SecondClass; public readonly string Shape; public bool IsArmament { get { if (Slot != EquipmentSlot.Weapon) { return Slot == EquipmentSlot.Shield; } return true; } } public EquipmentDef(string id, string name, EquipmentSlot slot, string sourceUnitId, long price, double weight, EquipmentHand hand = EquipmentHand.Both, double shieldDefense = 0.0, WeaponClass? weaponClass = null, int tier = 1, WeaponClass? secondClass = null, string shape = "") { Id = id; Name = name; Slot = slot; SourceUnitId = sourceUnitId; Price = price; Weight = weight; Hand = hand; ShieldDefense = shieldDefense; Class = weaponClass; Tier = Math.Max(1, Math.Min(5, tier)); SecondClass = secondClass; Shape = shape ?? ""; } } public static class EquipmentCatalog { public const int InventoryLimit = 100; public static readonly IReadOnlyList All = Array.AsReadOnly(new EquipmentDef[20] { new EquipmentDef("eq.weapon.club", "Wooden club", EquipmentSlot.Weapon, "tribal.clubber", 80L, 3.0, EquipmentHand.Both, 0.0, WeaponClass.Mace), new EquipmentDef("eq.weapon.sword", "Squire's sword", EquipmentSlot.Weapon, "medieval.squire", 140L, 3.0, EquipmentHand.Both, 0.0, WeaponClass.OneHandedSword, 2), new EquipmentDef("eq.weapon.bow", "Hunting bow", EquipmentSlot.Weapon, "medieval.archer", 180L, 4.0, EquipmentHand.Both, 0.0, WeaponClass.Bow, 1, WeaponClass.Arrows, "Hunting"), new EquipmentDef("eq.weapon.javelin", "Throwing spear", EquipmentSlot.Weapon, "tribal.spearthrower", 160L, 4.0, EquipmentHand.Both, 0.0, WeaponClass.Javelin, 2), new EquipmentDef("eq.weapon.axe_shield", "Axe and shield", EquipmentSlot.Weapon, "viking.brawler", 260L, 6.0, EquipmentHand.Both, 0.0, WeaponClass.OneHandedAxe, 2, WeaponClass.Shield), new EquipmentDef("eq.weapon.knight_kit", "Knight's sword and shield", EquipmentSlot.Weapon, "medieval.knight", 550L, 7.0, EquipmentHand.Both, 0.0, WeaponClass.OneHandedSword, 3, WeaponClass.Shield, "Heater"), new EquipmentDef("eq.outfit.traveller", "Traveller's garb", EquipmentSlot.Outfit, "medieval.bard", 60L, 2.0), new EquipmentDef("eq.outfit.guard", "Guard's uniform", EquipmentSlot.Outfit, "medieval.squire", 120L, 3.0), new EquipmentDef("eq.outfit.raider", "Raider's garb", EquipmentSlot.Outfit, "viking.brawler", 150L, 3.0), new EquipmentDef("eq.outfit.knight", "Knight's armour", EquipmentSlot.Outfit, "medieval.knight", 320L, 5.0), new EquipmentDef("eq.weapon.knight_sword", "Knight's sword", EquipmentSlot.Weapon, "medieval.knight", 380L, 4.0, EquipmentHand.Main, 0.0, WeaponClass.OneHandedSword, 3), new EquipmentDef("eq.shield.knight", "Knight's shield", EquipmentSlot.Shield, "medieval.knight", 210L, 4.0, EquipmentHand.Off, 0.18, WeaponClass.Shield, 3, null, "Heater"), new EquipmentDef("eq.weapon.bearded_axe", "Bearded axe", EquipmentSlot.Weapon, "viking.brawler", 170L, 3.0, EquipmentHand.Main, 0.0, WeaponClass.OneHandedAxe, 2), new EquipmentDef("eq.shield.round", "Round shield", EquipmentSlot.Shield, "viking.brawler", 110L, 3.0, EquipmentHand.Off, 0.12, WeaponClass.Shield, 1, null, "Round"), new EquipmentDef("eq.weapon.berserker_axes", "Berserker's axes", EquipmentSlot.Weapon, "viking.berserker", 340L, 6.0, EquipmentHand.Both, 0.0, WeaponClass.OneHandedAxe, 3, WeaponClass.OneHandedAxe), new EquipmentDef("eq.weapon.halberd", "Halberd", EquipmentSlot.Weapon, "renaissance.halberd", 320L, 5.0, EquipmentHand.Both, 0.0, WeaponClass.TwoHandedPolearm, 3), new EquipmentDef("eq.weapon.pike", "Pike", EquipmentSlot.Weapon, "legacy.pike", 220L, 6.0, EquipmentHand.Both, 0.0, WeaponClass.Pike, 2), new EquipmentDef("eq.weapon.katana", "Samurai's katana", EquipmentSlot.Weapon, "dynasty.samurai", 620L, 4.0, EquipmentHand.Both, 0.0, WeaponClass.TwoHandedSword, 4), new EquipmentDef("eq.weapon.executioner_axe", "Executioner's axe", EquipmentSlot.Weapon, "secret.executioner", 480L, 7.0, EquipmentHand.Both, 0.0, WeaponClass.TwoHandedAxe, 4), new EquipmentDef("eq.weapon.repeating_crossbow", "Repeating crossbow", EquipmentSlot.Weapon, "secret.chukonu", 450L, 5.0, EquipmentHand.Both, 0.0, WeaponClass.Crossbow, 3, WeaponClass.Bolts) }); public static readonly IReadOnlyList FirstStock = Array.AsReadOnly(new string[10] { "eq.weapon.club", "eq.weapon.sword", "eq.weapon.bow", "eq.weapon.javelin", "eq.weapon.axe_shield", "eq.weapon.knight_kit", "eq.outfit.traveller", "eq.outfit.guard", "eq.outfit.raider", "eq.outfit.knight" }); public const double OffHandAttackShare = 0.3; public static bool OffHandKit(EquipmentDef item) { if (item != null && item.Slot == EquipmentSlot.Weapon) { return item.Hand == EquipmentHand.Main; } return false; } public static EquipmentDef Find(string id) { if (id != null) { return All.FirstOrDefault((EquipmentDef item) => item.Id == id); } return null; } public static bool SupportsArchetype(UnitDef unit) { if (unit != null && !unit.Mounted && unit.Slots == 1 && !string.IsNullOrEmpty(unit.TabsUnitId)) { if (unit.Role != TroopRole.Infantry) { return unit.Role == TroopRole.Ranged; } return true; } return false; } } public sealed class EducationStageDef { public string StageId = ""; public int Age; } public static class Families { public const int YearDays = 84; public const int AdultAge = 18; public const int PregnancyDays = 36; public const int MaxChildrenPerCouple = 5; public const int MaxClanMembers = 12; public const int LordPartiesPerClan = 2; public const int MinimumGrownMembers = 2; public const int RelativeIntervalDays = 28; public const double LordMatchChancePerDay = 0.005; public const int LordMarryingAge = 55; public const int MaxAgeGap = 12; public const int CourtshipTalksNeeded = 3; public const int CourtshipPatience = 3; public const int CourtshipTalkDays = 2; public const int CourtshipRetryDays = 28; public const int CourtRelation = -10; public const int MarryRelation = 0; public const int MarriageRelation = 15; public const int DivorceRelation = 20; public const double CourtshipDiplomacyXp = 15.0; public static readonly EducationStageDef[] EducationStages = new EducationStageDef[3] { new EducationStageDef { StageId = "stage.childhood", Age = 5 }, new EducationStageDef { StageId = "stage.adolescence", Age = 10 }, new EducationStageDef { StageId = "stage.youth", Age = 15 } }; private static readonly Dictionary MaleNames = new Dictionary(StringComparer.Ordinal) { { "medieval", new string[14] { "Bertram", "Cedric", "Godfrey", "Jory", "Osric", "Wat", "Aldric", "Baldwin", "Edmund", "Gilbert", "Hugh", "Ranulf", "Tobias", "Walter" } }, { "viking", new string[16] { "Arne", "Egil", "Gunnar", "Ivar", "Kari", "Leif", "Sten", "Bjarni", "Erik", "Harald", "Knut", "Olaf", "Ragnar", "Thorvald", "Bjorn", "Ulf" } }, { "tribal", new string[12] { "Ugg", "Mog", "Thud", "Nub", "Brak", "Pok", "Hoot", "Grug", "Bonk", "Krag", "Dug", "Thog" } }, { "farmer", new string[14] { "Barley", "Clem", "Fen", "Hob", "Ned", "Rowan", "Dob", "Alfie", "Bert", "Jem", "Seth", "Tam", "Will", "Gus" } }, { "ancient", new string[14] { "Castor", "Galen", "Leander", "Nikos", "Theron", "Cleon", "Aristo", "Darius", "Linus", "Marcus", "Philo", "Silvanus", "Titus", "Xeno" } }, { "dynasty", new string[14] { "Akio", "Bao", "Jin", "Kenta", "Ren", "Tao", "Shen", "Chen", "Hiro", "Kai", "Long", "Ming", "Wei", "Yong" } }, { "renaissance", new string[14] { "Carlo", "Dante", "Fabio", "Lorenzo", "Marco", "Silvio", "Alessio", "Bruno", "Cosimo", "Enzo", "Matteo", "Paolo", "Piero", "Tommaso" } }, { "pirate", new string[14] { "Barnaby", "Calico", "Davy", "Flint", "Jonah", "Silas", "Morgan", "Bart", "Hector", "Jack", "Toby", "Jasper", "Rufus", "Quint" } }, { "spooky", new string[14] { "Bones", "Clatter", "Ebon", "Grimsby", "Hollis", "Mortimer", "Ossie", "Rattle", "Barnabas", "Crispin", "Igor", "Vlad", "Edgar", "Ambrose" } }, { "wildwest", new string[14] { "Abner", "Cassidy", "Dusty", "Eli", "Jeb", "Lou", "Rusty", "Wyatt", "Zeke", "Amos", "Cody", "Hank", "Jesse", "Virgil" } }, { "fantasygood", new string[14] { "Aurel", "Gideon", "Lumen", "Orin", "Caelan", "Seraph", "Alaric", "Cedran", "Eldric", "Faelan", "Lucian", "Soren", "Theo", "Corin" } }, { "fantasyevil", new string[14] { "Ash", "Drav", "Grisk", "Nox", "Scorch", "Vile", "Rusk", "Bane", "Gorth", "Kragg", "Malek", "Mordrin", "Skarn", "Vorn" } } }; private static readonly Dictionary FemaleNames = new Dictionary(StringComparer.Ordinal) { { "medieval", new string[14] { "Alda", "Edda", "Hilde", "Maud", "Rowena", "Tamsin", "Agnes", "Beatrix", "Cecily", "Elinor", "Joan", "Margery", "Matilda", "Sybil" } }, { "viking", new string[14] { "Brynja", "Dagny", "Halla", "Runa", "Tova", "Astrid", "Freya", "Gudrun", "Helga", "Ingrid", "Sigrid", "Solveig", "Thora", "Ylva" } }, { "tribal", new string[12] { "Rokka", "Garra", "Okka", "Zuzu", "Grunna", "Ooga", "Mabba", "Lulla", "Tikka", "Wunna", "Ruga", "Zogga" } }, { "farmer", new string[14] { "Daisy", "Marigold", "Poppy", "Tilly", "Hazel", "Clover", "Hetty", "Lettie", "Mabel", "Primrose", "Rosie", "Winnie", "Elsie", "Dot" } }, { "ancient", new string[14] { "Aelia", "Daphne", "Iona", "Myra", "Phoebe", "Thalia", "Cassia", "Doria", "Helena", "Livia", "Lydia", "Octavia", "Selene", "Zoe" } }, { "dynasty", new string[14] { "Hana", "Lian", "Mei", "Suki", "Yuna", "Ai", "Fei", "Jia", "Lan", "Lin", "Rin", "Xiu", "Yan", "Yue" } }, { "renaissance", new string[14] { "Beatrice", "Elena", "Giulia", "Paola", "Rosa", "Vera", "Bianca", "Caterina", "Chiara", "Isabella", "Lucia", "Marta", "Nora", "Sofia" } }, { "pirate", new string[14] { "Anne", "Grace", "Mags", "Peg", "Bess", "Ada", "Jenny", "Kate", "Mary", "Molly", "Polly", "Sadie", "Tess", "Bonny" } }, { "spooky", new string[14] { "Nell", "Mab", "Shade", "Wisp", "Agatha", "Drusilla", "Elvira", "Hester", "Lenore", "Ophelia", "Raven", "Wilhelmina", "Winifred", "Gloom" } }, { "wildwest", new string[14] { "Belle", "Hattie", "Clara", "Annie", "Dolly", "Etta", "Ida", "Josie", "Lottie", "Mae", "Opal", "Pearl", "Ruby", "Calamity" } }, { "fantasygood", new string[14] { "Celestine", "Elara", "Ilys", "Talia", "Vesper", "Isolde", "Aria", "Elowen", "Liora", "Lyra", "Mirelle", "Seraphine", "Sylva", "Yvaine" } }, { "fantasyevil", new string[14] { "Cinder", "Ember", "Hex", "Morda", "Sable", "Ashka", "Draxa", "Malva", "Nyx", "Raxa", "Sevra", "Thessa", "Vexa", "Zora" } } }; private static readonly string[] AnyMale = new string[8] { "Bram", "Dell", "Finn", "Hal", "Jasper", "Kit", "Pip", "Rolf" }; private static readonly string[] AnyFemale = new string[8] { "Ada", "Cora", "Emry", "Gwen", "Ines", "Lark", "Wren", "Ivy" }; private static readonly string[] MaleTitles = new string[10] { "Sir", "Lord", "King", "Jarl", "Prince", "Duke", "Count", "Baron", "Chief", "Master" }; private static readonly string[] FemaleTitles = new string[8] { "Lady", "Dame", "Queen", "Princess", "Duchess", "Countess", "Baroness", "Mistress" }; private static readonly Lazy> KnownNames = new Lazy>(delegate { Dictionary dictionary = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (string[] item in MaleNames.Values.Concat(new string[1][] { AnyMale })) { foreach (string key in item) { dictionary[key] = HeroSex.Male; } } foreach (string[] item2 in FemaleNames.Values.Concat(new string[1][] { AnyFemale })) { foreach (string key2 in item2) { dictionary[key2] = HeroSex.Female; } } return dictionary; }); public static double CrowdingFactor(int members) { return Math.Max(0.0, Math.Min(1.0, 2.0 * (1.0 - (double)members / 12.0))); } public static long MarriageGift(int clanTier) { return 500 + 500L * (long)Math.Max(0, clanTier); } public static double CourtshipChance(int charm, int relation) { return Math.Max(0.2, Math.Min(0.9, 0.5 + (double)Math.Max(0, charm) / 400.0 + (double)relation / 200.0)); } public static double YearlyChildChance(double motherAge) { if (motherAge < 18.0) { return 0.0; } if (motherAge < 30.0) { return 0.3; } if (motherAge < 35.0) { return 0.22; } if (motherAge < 40.0) { return 0.12; } if (motherAge < 45.0) { return 0.04; } return 0.0; } public static double YearlyDeathChance(double age) { if (!(age < 50.0)) { return Math.Min(1.0, 0.005 * Math.Exp(0.12 * (age - 50.0))); } return 0.0; } public static double DailyChance(double yearly) { return Math.Max(0.0, Math.Min(1.0, yearly)) / 84.0; } public static LifeStageDef EducationStage(string stageId) { return CharacterCreation.LifeStages.FirstOrDefault((LifeStageDef s) => s.Id == stageId); } public static SortedDictionary GrownSkills(IDictionary education, RandomStream rng) { SortedDictionary sortedDictionary = new SortedDictionary(StringComparer.Ordinal); string[] original = SkillIds.Original; foreach (string key in original) { sortedDictionary[key] = 5 + rng.Range(0, 11); } sortedDictionary["riding"] = Math.Max(10, sortedDictionary["riding"]); EducationStageDef[] educationStages = EducationStages; foreach (EducationStageDef educationStageDef in educationStages) { if (education == null || !education.TryGetValue(educationStageDef.StageId, out var value)) { continue; } CharacterChoiceDef characterChoiceDef = CharacterCreation.LifeStageChoice(educationStageDef.StageId, value); if (characterChoiceDef == null) { continue; } foreach (KeyValuePair skillBonuse in characterChoiceDef.SkillBonuses) { sortedDictionary[skillBonuse.Key] = (sortedDictionary.TryGetValue(skillBonuse.Key, out var value2) ? value2 : 0) + skillBonuse.Value; } } return sortedDictionary; } public static HeroSex SexOfName(string name) { string[] array = (name ?? "").Split(new char[1] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (array.Length == 0) { return HeroSex.Unspecified; } if (MaleTitles.Contains(array[0], StringComparer.OrdinalIgnoreCase)) { return HeroSex.Male; } if (FemaleTitles.Contains(array[0], StringComparer.OrdinalIgnoreCase)) { return HeroSex.Female; } if (!KnownNames.Value.TryGetValue(array[0], out var value)) { return HeroSex.Unspecified; } return value; } public static IList FirstNames(string cultureId, HeroSex sex) { if (!((sex == HeroSex.Female) ? FemaleNames : MaleNames).TryGetValue(cultureId ?? "", out var value)) { if (sex != HeroSex.Female) { return AnyMale; } return AnyFemale; } return value; } public static string Name(string cultureId, HeroSex sex, string surname, RandomStream rng, ICollection taken) { IList items = FirstNames(cultureId, sex); string text = (string.IsNullOrWhiteSpace(surname) ? "" : (" " + surname.Trim())); for (int i = 0; i < 30; i++) { string text2 = rng.Pick(items) + text; if (!taken.Contains(text2)) { return text2; } } int num = 2; string text3; while (true) { text3 = rng.Pick(items) + text + " " + num.ToString(CultureInfo.InvariantCulture); if (!taken.Contains(text3)) { break; } num++; } return text3; } public static string SurnameOf(string name) { string[] array = (name ?? "").Split(new char[1] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (array.Length < 2) { return ""; } string text = array[^1]; if (text.Length < 3 || char.IsDigit(text[0]) || !char.IsUpper(text[0])) { return ""; } if (MaleTitles.Contains(array[0], StringComparer.OrdinalIgnoreCase) || FemaleTitles.Contains(array[0], StringComparer.OrdinalIgnoreCase)) { if (array.Length <= 2) { return ""; } return text; } return text; } public static string Noun(HeroSex sex, string male, string female, string unknown) { return sex switch { HeroSex.Male => male, HeroSex.Female => female, _ => unknown, }; } } public sealed class HeroPerkDef { public string Id = ""; public string Name = ""; public string Skill = ""; public int RequiredSkill = 25; public string Group = ""; public string Description = ""; public List Mods = new List(); } public static class HeroPerks { public const string Pathfinder = "perk.scout.pathfinder"; public const string KeenEye = "perk.scout.keen_eye"; public const string FieldMedic = "perk.surgeon.field_medic"; public const string Survivor = "perk.surgeon.survivor"; public const string Frugal = "perk.quartermaster.frugal"; public const string Paymaster = "perk.quartermaster.paymaster"; public static readonly List All = (from p in RolePerks().Concat(Smithing.Perks).Concat(PerkTrees.SmithingAdditions()).Concat(Horses.Perks) .Concat(PerkTrees.RidingAdditions()) .Concat(PerkTrees.All) orderby SkillOrder(p.Skill), p.RequiredSkill select p).ToList(); public static readonly Dictionary ById = All.ToDictionary((HeroPerkDef p) => p.Id, StringComparer.Ordinal); public static HeroPerkDef Get(string id) { if (id == null || !ById.TryGetValue(id, out var value)) { return null; } return value; } private static int SkillOrder(string skill) { int num = Array.IndexOf(SkillIds.All, skill); if (num >= 0) { return num; } return int.MaxValue; } public static List> Tiers(string skill) { return (from p in All where p.Skill == skill group p by p.Group into g select g.ToList() into g orderby g[0].RequiredSkill select g).ToList(); } private static List RolePerks() { return new List { new HeroPerkDef { Id = "perk.scout.pathfinder", Name = "Pathfinder", Skill = "scouting", Group = "scout", Description = "+5% map speed while serving as the party's scout." }, new HeroPerkDef { Id = "perk.scout.keen_eye", Name = "Keen Eye", Skill = "scouting", Group = "scout", Description = "+20% sight range while serving as the party's scout." }, new HeroPerkDef { Id = "perk.surgeon.field_medic", Name = "Field Medic", Skill = "medicine", Group = "surgeon", Description = "+20% daily troop and hero healing while serving as the party's surgeon." }, new HeroPerkDef { Id = "perk.surgeon.survivor", Name = "Survivor", Skill = "medicine", Group = "surgeon", Description = "+5 percentage points to troop wound survival, up to 95%, while serving as the party's surgeon." }, new HeroPerkDef { Id = "perk.quartermaster.frugal", Name = "Frugal", Skill = "stewardship", Group = "quartermaster", Description = "-10% food consumption after skill bonuses while serving as the party's quartermaster." }, new HeroPerkDef { Id = "perk.quartermaster.paymaster", Name = "Paymaster", Skill = "stewardship", Group = "quartermaster", Description = "-10% party wages while serving as the party's quartermaster." } }; } } public enum HorseKind { Riding, War, Pack } public enum HorseSex { Stallion, Mare, Gelding } public enum HorseInjury { None, Bruised, Lame, Grave } public enum HorsePlace { Party, Stud, Market } public sealed class HorseBreedDef { public string Id = ""; public string Name = ""; public string Description = ""; public HorseKind Kind; public string[] Cultures = new string[0]; public double Speed; public double Manoeuvre; public double Charge; public double HitPoints; public double Stamina; public int Temperament; public int Difficulty; public double Spread = 0.07; public double Size = 1.0; public double Feed = 0.08; public double PackCapacity; public long BasePrice; public int[] Coats = new int[3] { 0, 1, 2 }; public double DesertGrazing = 1.0; public double SnowGrazing = 1.0; public bool Heavy; } public sealed class HorseCoatDef { public string Name = ""; public string Color = "#FFFFFF"; } public static class Horses { public const string Skill = "riding"; public const string HorseIdPrefix = "horse."; public const int YearDays = 84; public const int NameMaximumLength = 24; public const int StartingRiding = 15; public const int LegacyRiding = 15; public static readonly List Breeds = new List { Breed("breed.destrier", "Destrier", HorseKind.War, new string[2] { "medieval", "renaissance" }, 42.0, 38.0, 30.0, 300.0, 55.0, 70, 85, 2400L, 1.12, "A great-hearted war horse bred to carry armour into a charge. Slow to turn and hard to master.", heavy: true, new int[4] { 0, 2, 3, 9 }, 0.0, 0.11), Breed("breed.courser", "Courser", HorseKind.War, new string[3] { "medieval", "renaissance", "fantasygood" }, 52.0, 48.0, 18.0, 210.0, 62.0, 60, 45, 1300L, 1.03, "Fast and light, the knight's horse for pursuit and the flanking charge.", heavy: false, new int[4] { 0, 1, 2, 3 }, 0.0, 0.09), Breed("breed.rouncey", "Rouncey", HorseKind.Riding, new string[4] { "medieval", "farmer", "renaissance", "pirate" }, 44.0, 44.0, 12.0, 170.0, 65.0, 35, 5, 450L, 1.0, "An honest all-rounder: cheap, sound and willing.", heavy: false, new int[5] { 0, 1, 2, 5, 7 }), Breed("breed.palfrey", "Palfrey", HorseKind.Riding, new string[4] { "medieval", "renaissance", "fantasygood", "farmer" }, 47.0, 52.0, 8.0, 150.0, 72.0, 20, 0, 700L, 0.98, "A smooth-gaited travelling horse. It tires little and its rider learns quickly.", heavy: false, new int[4] { 3, 4, 6, 9 }), Breed("breed.fjordpony", "Frost Pony", HorseKind.Riding, new string[1] { "viking" }, 40.0, 50.0, 10.0, 165.0, 88.0, 30, 5, 380L, 0.9, "A stocky northern pony that forages under snow and never seems to tire.", heavy: false, new int[3] { 5, 10, 3 }, 0.0, 0.07, 1.0, 3.0), Breed("breed.northwar", "Northland Warhorse", HorseKind.War, new string[1] { "viking" }, 41.0, 40.0, 26.0, 270.0, 72.0, 55, 65, 1800L, 1.08, "A heavy-boned warhorse of the cold coasts, as hardy as its riders.", heavy: true, new int[3] { 2, 5, 8 }, 0.0, 0.1, 1.0, 2.0), Breed("breed.highland", "Highland Pony", HorseKind.Riding, new string[3] { "tribal", "viking", "farmer" }, 41.0, 55.0, 9.0, 150.0, 80.0, 35, 10, 350L, 0.88, "Sure-footed in hill and bog, small enough to slip through the trees.", heavy: false, new int[4] { 5, 0, 8, 10 }, 0.0, 0.07), Breed("breed.steppe", "Steppe Horse", HorseKind.Riding, new string[2] { "tribal", "dynasty" }, 49.0, 56.0, 12.0, 170.0, 90.0, 50, 30, 650L, 0.95, "Tough and quick, raised in great herds on open grassland. A horse archer's mount.", heavy: false, new int[5] { 5, 0, 1, 7, 10 }, 0.0, 0.07), Breed("breed.jade", "Jade Charger", HorseKind.War, new string[1] { "dynasty" }, 50.0, 50.0, 22.0, 230.0, 70.0, 65, 70, 1900L, 1.02, "A proud charger of the eastern courts, fast and strong but famously temperamental.", heavy: false, new int[4] { 1, 6, 4, 9 }), Breed("breed.sunrunner", "Sun-runner", HorseKind.Riding, new string[3] { "ancient", "wildwest", "pirate" }, 55.0, 60.0, 12.0, 165.0, 76.0, 75, 60, 1500L, 0.97, "A fine-boned desert horse of legendary speed that finds forage where others starve.", heavy: false, new int[4] { 3, 4, 1, 9 }, 0.0, 0.08, 3.0), Breed("breed.marble", "Marble Charger", HorseKind.War, new string[1] { "ancient" }, 45.0, 42.0, 24.0, 250.0, 62.0, 50, 60, 1600L, 1.06, "A powerful horse bred for chariot and charge on the old empire's roads.", heavy: false, new int[3] { 4, 3, 9 }), Breed("breed.draught", "Draught Horse", HorseKind.Pack, new string[2] { "farmer", "medieval" }, 34.0, 30.0, 20.0, 320.0, 72.0, 10, 10, 500L, 1.2, "A gentle giant for the plough and the wagon. It carries a heavy load.", heavy: false, new int[3] { 1, 2, 0 }, 20.0, 0.12), Breed("breed.mustang", "Mustang", HorseKind.Riding, new string[1] { "wildwest" }, 50.0, 58.0, 12.0, 175.0, 86.0, 82, 45, 600L, 0.96, "A wild-caught horse of the frontier: cheap, tireless and barely broken.", heavy: false, new int[5] { 7, 5, 10, 8, 1 }, 0.0, 0.08, 2.0), Breed("breed.ranch", "Ranch Horse", HorseKind.Riding, new string[2] { "wildwest", "farmer" }, 51.0, 62.0, 14.0, 180.0, 72.0, 40, 25, 900L, 1.0, "Quick off the mark and nimble, bred for working cattle.", heavy: false, new int[5] { 0, 1, 10, 6, 7 }), Breed("breed.cob", "Harbour Cob", HorseKind.Riding, new string[2] { "pirate", "farmer" }, 40.0, 42.0, 12.0, 175.0, 70.0, 30, 10, 400L, 0.95, "A sturdy dock horse, unbothered by gulls, cannon or crowds.", heavy: false, new int[3] { 7, 2, 8 }), Breed("breed.gravesteed", "Gravesteed", HorseKind.War, new string[1] { "spooky" }, 47.0, 45.0, 24.0, 240.0, 100.0, 85, 90, 2200L, 1.05, "A gaunt black horse that never tires and is never quite still.", heavy: true, new int[2] { 11, 2 }, 0.0, 0.08, 1.5, 1.5), Breed("breed.dawn", "Dawn Charger", HorseKind.War, new string[1] { "fantasygood" }, 54.0, 55.0, 24.0, 250.0, 80.0, 45, 70, 2800L, 1.06, "A shining charger of the white citadels, bold and wise.", heavy: true, new int[3] { 12, 4, 3 }), Breed("breed.ember", "Ember Steed", HorseKind.War, new string[1] { "fantasyevil" }, 52.0, 48.0, 28.0, 260.0, 75.0, 90, 105, 2600L, 1.07, "A smouldering, savage war horse. Only the boldest riders stay in its saddle.", heavy: true, new int[2] { 13, 2 }, 0.0, 0.08, 2.0), Breed("breed.sumpter", "Sumpter Horse", HorseKind.Pack, new string[0], 38.0, 38.0, 6.0, 150.0, 70.0, 25, 0, 200L, 0.95, "A plain pack horse. Sold everywhere.", heavy: false, new int[4] { 0, 1, 5, 8 }, 18.0, 0.07), Breed("breed.mule", "Mule", HorseKind.Pack, new string[0], 34.0, 36.0, 4.0, 150.0, 95.0, 50, 0, 250L, 0.9, "Stubborn and strong, the best pack animal there is.", heavy: false, new int[3] { 1, 0, 2 }, 25.0, 0.06, 1.5) }; public static readonly HorseCoatDef[] Coats = new HorseCoatDef[14] { Coat("Bay", "#7A4426"), Coat("Chestnut", "#9A5328"), Coat("Black", "#2A2522"), Coat("Grey", "#9C9A96"), Coat("White", "#E8E4DC"), Coat("Dun", "#B89A68"), Coat("Palomino", "#D7B46A"), Coat("Piebald", "#D9D4CC"), Coat("Roan", "#8D6E66"), Coat("Dapple grey", "#B5B3AE"), Coat("Buckskin", "#C49A5A"), Coat("Ashen", "#5E5B5F"), Coat("Gilded", "#E3C76E"), Coat("Ember", "#5A1E14") }; private static readonly string[] Names = new string[99] { "Ash", "Bramble", "Cinder", "Dancer", "Ember", "Fable", "Gale", "Hazel", "Iron", "Juniper", "Kestrel", "Lark", "Maple", "Nettle", "Oakheart", "Pepper", "Quill", "Raven", "Saffron", "Thistle", "Umber", "Vesper", "Willow", "Yarrow", "Zephyr", "Acorn", "Blaze", "Clover", "Dusk", "Echo", "Flint", "Ginger", "Hawthorn", "Indigo", "Jasper", "Kingfisher", "Lantern", "Marigold", "Nimbus", "Onyx", "Pippin", "Quarry", "Rowan", "Sorrel", "Tempest", "Valour", "Warden", "Bracken", "Comet", "Drummer", "Falcon", "Granite", "Harrier", "Islay", "Jubilee", "Kindle", "Lodestar", "Merlin", "Nightjar", "Orion", "Pilgrim", "Rook", "Sable", "Tansy", "Thunder", "Wren", "Banner", "Cobble", "Duchess", "Fennel", "Gauntlet", "Heron", "Ivory", "Jester", "Larkspur", "Mistral", "Nutmeg", "Pebble", "Ranger", "Sparrow", "Tinder", "Whisper", "Bastion", "Chalice", "Drift", "Fortune", "Glimmer", "Hollow", "Marshal", "Oriel", "Puzzle", "Rampart", "Solstice", "Tallow", "Vagabond", "Wanderer", "Bellows", "Copper", "Dapple" }; public const string NimbleRider = "perk.riding.nimble_rider"; public const string SteadySeat = "perk.riding.steady_seat"; public const string HorseWhisperer = "perk.riding.horse_whisperer"; public const string Groom = "perk.riding.groom"; public const string TrailRider = "perk.riding.trail_rider"; public const string Packmaster = "perk.riding.packmaster"; public const string Cavalier = "perk.riding.cavalier"; public const string Lancer = "perk.riding.lancer"; public const string HorseTrader = "perk.riding.horse_trader"; public const string Breeder = "perk.riding.breeder"; public const string RoughRider = "perk.riding.rough_rider"; public const string Forager = "perk.riding.forager"; public const string Trainer = "perk.riding.trainer"; public const string Remount = "perk.riding.remount"; public const string WarRider = "perk.riding.war_rider"; public const string Endurance = "perk.riding.endurance"; public const string StudMaster = "perk.riding.stud_master"; public const string Veterinarian = "perk.riding.veterinarian"; public const string Centaur = "perk.riding.centaur"; public const string BornInTheSaddle = "perk.riding.born_in_the_saddle"; public static readonly List Perks = new List { Perk("perk.riding.nimble_rider", "Nimble Rider", 25, "ride25", "+5% speed and manoeuvre for this hero's horse in battle."), Perk("perk.riding.steady_seat", "Steady Seat", 25, "ride25", "Every horse is 15 points easier for this hero to ride."), Perk("perk.riding.horse_whisperer", "Horse Whisperer", 50, "ride50", "This hero bonds with horses half again as fast."), Perk("perk.riding.groom", "Groom", 50, "ride50", "Horses travelling with this hero recover from injury and fatigue 30% faster."), Perk("perk.riding.trail_rider", "Trail Rider", 75, "ride75", "+3% party map speed while this hero rides with your party."), Perk("perk.riding.packmaster", "Packmaster", 75, "ride75", "+20% capacity from your party's pack animals while this hero travels with it."), Perk("perk.riding.cavalier", "Cavalier", 100, "ride100", "+10% hit points for this hero's horse in battle."), Perk("perk.riding.lancer", "Lancer", 100, "ride100", "+15% charge (impact) for this hero's horse in battle."), Perk("perk.riding.horse_trader", "Horse Trader", 125, "ride125", "Horses cost 10% less to buy and sell for 70% of their value instead of 55%."), Perk("perk.riding.breeder", "Breeder", 125, "ride125", "Foals born at your stud farms inherit 4% better qualities on average."), Perk("perk.riding.rough_rider", "Rough Rider", 150, "ride150", "Battles fought mounted teach this hero twice the Riding experience."), Perk("perk.riding.forager", "Forager", 150, "ride150", "Your party's horses need 30% less feed while this hero travels with it."), Perk("perk.riding.trainer", "Trainer", 175, "ride175", "Horses this hero rides, and horses at your stud farms, gain experience 50% faster."), Perk("perk.riding.remount", "Remount", 175, "ride175", "Footmen riding spare horses add half as much again to party speed while this hero travels with it."), Perk("perk.riding.war_rider", "War Rider", 200, "ride200", "+10% speed and manoeuvre for this hero's horse in battle."), Perk("perk.riding.endurance", "Endurance", 200, "ride200", "The horse this hero rides does not tire on the map."), Perk("perk.riding.stud_master", "Stud Master", 250, "ride250", "Stud farms hold four more horses and pregnancies are a quarter shorter."), Perk("perk.riding.veterinarian", "Veterinarian", 250, "ride250", "Gravely hurt horses in your care never die of their wounds, and all injuries heal twice as fast."), Perk("perk.riding.centaur", "Centaur", 275, "ride275", "+10% hit points for this hero in battle while mounted."), Perk("perk.riding.born_in_the_saddle", "Born in the Saddle", 275, "ride275", "This hero can ride any horse, whatever its difficulty, and bonds twice as fast.") }; public static readonly int[] TrainingThresholds = new int[5] { 0, 100, 300, 700, 1500 }; public static readonly string[] TrainingNames = new string[5] { "Green", "Trained", "Seasoned", "Veteran", "War-proven" }; public const double MaximumBond = 100.0; public const double BondPerRiddenHour = 0.4; public const double BondPerBattle = 4.0; public const double BondDecayPerDay = 0.2; public const double HorseXpPerRiddenHour = 1.0; public const double HorseXpPerBattle = 25.0; public const double HorseXpPerStudDay = 2.0; public const double RidingXpPerRiddenHour = 1.5; public const double RidingXpDailyTravelCap = 40.0; public const double RidingXpPerBattle = 30.0; public const double RidingXpPerVictory = 15.0; public const double FatigueRecoveryPerHour = 0.06; public const int StudFarmCapacity = 6; public const int StudMasterCapacity = 4; public const long StudFarmPrice = 4000L; public const long StudFarmUpkeep = 15L; public const long StudUpkeepPerHorse = 2L; public const int GestationDays = 77; public const int FoalingRestDays = 30; public const double StableTownGrazing = 0.6; public const double SaleShare = 0.55; public const double HorseTraderSaleShare = 0.7; public const double HorseTraderDiscount = 0.9; public const int MarketPeriodDays = 7; public static HorseBreedDef Breed(string id) { return Breeds.FirstOrDefault((HorseBreedDef b) => b.Id == id); } private static HorseBreedDef Breed(string id, string name, HorseKind kind, string[] cultures, double speed, double manoeuvre, double charge, double hp, double stamina, int temperament, int difficulty, long price, double size, string description, bool heavy = false, int[] coats = null, double pack = 0.0, double feed = 0.08, double desert = 1.0, double snow = 1.0) { HorseBreedDef horseBreedDef = new HorseBreedDef(); horseBreedDef.Id = id; horseBreedDef.Name = name; horseBreedDef.Kind = kind; horseBreedDef.Cultures = cultures; horseBreedDef.Speed = speed; horseBreedDef.Manoeuvre = manoeuvre; horseBreedDef.Charge = charge; horseBreedDef.HitPoints = hp; horseBreedDef.Stamina = stamina; horseBreedDef.Temperament = temperament; horseBreedDef.Difficulty = difficulty; horseBreedDef.BasePrice = price; horseBreedDef.Size = size; horseBreedDef.Description = description; horseBreedDef.Heavy = heavy; horseBreedDef.Coats = coats ?? new int[3] { 0, 1, 2 }; horseBreedDef.PackCapacity = ((pack > 0.0) ? pack : ((double)((kind == HorseKind.Pack) ? 15 : 0))); horseBreedDef.Feed = feed; horseBreedDef.DesertGrazing = desert; horseBreedDef.SnowGrazing = snow; return horseBreedDef; } private static HorseCoatDef Coat(string name, string color) { return new HorseCoatDef { Name = name, Color = color }; } public static string CoatName(int coat) { if (coat < 0 || coat >= Coats.Length) { return "Bay"; } return Coats[coat].Name; } public static string RandomName(RandomStream rng) { return Names[rng.Range(0, Names.Length)]; } private static HeroPerkDef Perk(string id, string name, int skill, string group, string description) { return new HeroPerkDef { Id = id, Name = name, Skill = "riding", RequiredSkill = skill, Group = group, Description = description }; } public static double AgeYears(HorseState horse, long today) { if (horse != null) { return Math.Max(0.0, (double)(today - horse.BornDay) / 84.0); } return 0.0; } public static double AgeFactor(double years) { if (years < 1.0) { return 0.4 + 0.2 * years; } if (years < 2.0) { return 0.6 + 0.2 * (years - 1.0); } if (years < 4.0) { return 0.8 + 0.1 * (years - 2.0); } if (years <= 12.0) { return 1.0; } if (years <= 18.0) { return 1.0 - 0.025 * (years - 12.0); } if (years <= 25.0) { return 0.85 - 0.035 * (years - 18.0); } return 0.6; } public static string AgeStage(double years) { if (!(years < 1.0)) { if (!(years < 2.0)) { if (!(years < 4.0)) { if (!(years <= 12.0)) { if (!(years <= 18.0)) { return "Old"; } return "Mature"; } return "Prime"; } return "Young"; } return "Yearling"; } return "Foal"; } public static double WorkingAge(HorseKind kind) { return (kind == HorseKind.War) ? 3 : 2; } public static double OldAgeDeathChance(double years) { if (!(years <= 20.0)) { return Math.Min(0.02, (years - 20.0) * 0.0008); } return 0.0; } public static int TrainingLevel(double experience) { int result = 0; for (int i = 1; i < TrainingThresholds.Length; i++) { if (experience >= (double)TrainingThresholds[i]) { result = i; } } return result; } public static double TrainingBonus(int level) { return 1.0 + 0.03 * (double)Math.Max(0, level); } public static double FatiguePerHour(double stamina) { return 0.03 * (1.0 - Math.Max(0.0, Math.Min(100.0, stamina)) / 140.0); } public static double ConditionFactor(double condition, HorseInjury injury) { return (0.7 + 0.3 * Math.Max(0.0, Math.Min(1.0, condition))) * injury switch { HorseInjury.None => 1.0, HorseInjury.Bruised => 0.9, _ => 0.6, }; } public static bool Rideable(HorseInjury injury) { if (injury != HorseInjury.None) { return injury == HorseInjury.Bruised; } return true; } public static string InjuryName(HorseInjury injury) { return injury switch { HorseInjury.Grave => "Gravely hurt", HorseInjury.Lame => "Lame", HorseInjury.Bruised => "Bruised", _ => "Sound", }; } public static int Difficulty(HorseBreedDef breed, int temperament, int trainingLevel, double bond, bool steadySeat) { if (breed == null || breed.Kind == HorseKind.Pack) { return 0; } double a = (double)breed.Difficulty + (double)(temperament - breed.Temperament) * 0.6 + (double)Math.Max(0, temperament - 50) * 0.3 - (double)(trainingLevel * 6) - Math.Max(0.0, Math.Min(100.0, bond)) * 0.2 - (double)(steadySeat ? 15 : 0); return Math.Max(0, Math.Min(300, (int)Math.Round(a))); } public static double MapSpeedFactor(double speed, double fatigue) { return Math.Max(0.9, Math.Min(1.3, 1.0 + (speed - 36.0) / 120.0)) * (1.0 - 0.3 * Math.Max(0.0, Math.Min(1.0, fatigue))); } public static string QualityName(double ratio) { if (!(ratio >= 1.12)) { if (!(ratio >= 1.06)) { if (!(ratio >= 1.02)) { if (!(ratio >= 0.96)) { return "Poor"; } return "Common"; } return "Fine"; } return "Superb"; } return "Exceptional"; } public static double Grazing(TerrainType terrain, HorseBreedDef breed) { double val; switch (terrain) { case TerrainType.Plains: val = 1.0; break; case TerrainType.Hills: val = 0.8; break; case TerrainType.Road: val = 0.75; break; case TerrainType.River: case TerrainType.Ford: case TerrainType.Bridge: val = 0.7; break; case TerrainType.Forest: val = 0.5; break; case TerrainType.Swamp: val = 0.4; break; case TerrainType.Mountains: case TerrainType.Beach: val = 0.3; break; case TerrainType.Desert: val = 0.15 * (breed?.DesertGrazing ?? 1.0); break; case TerrainType.Snow: val = 0.1 * (breed?.SnowGrazing ?? 1.0); break; default: val = 0.0; break; } return Math.Max(0.0, Math.Min(1.0, val)); } public static double HerdingFactor(int looseAnimals, int people) { if (looseAnimals > people && people > 0) { return Math.Max(0.8, 1.0 - 0.2 * (double)(looseAnimals - people) / (double)Math.Max(1, people)); } return 1.0; } } public sealed class KingdomLawDef { public KingdomLaw Law; public string Name = ""; public string Group = ""; public string Summary = ""; public string Effects = ""; public KingdomLaw Excludes; } public static class KingdomLaws { public const string Economy = "Economy"; public const string Order = "Order and the people"; public const string War = "War"; public const string Crown = "Crown and council"; public static readonly KingdomLawDef[] All = new KingdomLawDef[21] { new KingdomLawDef { Law = KingdomLaw.RoadTolls, Name = "Road Tolls", Group = "Economy", Summary = "Tolls on every road into the realm's towns.", Effects = "Town taxes +10%. Town prosperity −0.5 a day." }, new KingdomLawDef { Law = KingdomLaw.Serfdom, Name = "Serfdom", Group = "Economy", Summary = "Villagers are bound to the land and owe their lord labour.", Effects = "Village taxes +25%. Village hearths −0.25 a day." }, new KingdomLawDef { Law = KingdomLaw.DebasementOfTheCurrency, Name = "Debasement of the Currency", Group = "Economy", Summary = "The crown mints lighter coin and keeps the difference.", Effects = "The ruling clan gains 20 denars a day for every town and castle of the realm. Loyalty −0.5 a day in every fief." }, new KingdomLawDef { Law = KingdomLaw.GrazingRights, Name = "Grazing Rights", Group = "Economy", Summary = "Villagers may graze their herds on the lords' commons.", Effects = "Village hearths +0.25 a day. Castle taxes −10%." }, new KingdomLawDef { Law = KingdomLaw.HuntingRights, Name = "Hunting Rights", Group = "Economy", Summary = "Lords and their men may hunt in any forest of the realm.", Effects = "Lords' parties of the realm eat 10% less. Village hearths −0.1 a day." }, new KingdomLawDef { Law = KingdomLaw.Magistrates, Name = "Magistrates", Group = "Order and the people", Summary = "Paid magistrates keep the peace in towns and castles.", Effects = "Security +1 a day in towns and castles. Their taxes −5%." }, new KingdomLawDef { Law = KingdomLaw.Bailiffs, Name = "Bailiffs", Group = "Order and the people", Summary = "Bailiffs hunt down troublemakers before unrest can spread.", Effects = "Unrest builds half as fast (rebellions are slower to start). Security +0.5 a day in towns and castles. Garrison wages +10%." }, new KingdomLawDef { Law = KingdomLaw.TrialByJury, Name = "Trial by Jury", Group = "Order and the people", Summary = "No one is punished without the judgement of their peers.", Effects = "Town security +0.5 a day. Executing a captive costs the clan of the realm 30 influence." }, new KingdomLawDef { Law = KingdomLaw.Citizenship, Name = "Citizenship", Group = "Order and the people", Excludes = KingdomLaw.Cantons, Summary = "The realm's own people are its citizens, with rights in law.", Effects = "Loyalty +0.75 a day in fiefs of the realm's culture. Council clans earn 0.25 less influence a day." }, new KingdomLawDef { Law = KingdomLaw.Cantons, Name = "Cantons", Group = "Order and the people", Excludes = KingdomLaw.Citizenship, Summary = "Conquered peoples keep their own customs and courts.", Effects = "The loyalty lost under a lord of another culture is halved. Town taxes −5%." }, new KingdomLawDef { Law = KingdomLaw.CouncilOfTheCommons, Name = "Council of the Commons", Group = "Order and the people", Excludes = KingdomLaw.SacredMajesty, Summary = "The towns send their own speakers to the court.", Effects = "Town loyalty +0.5 a day. The ruling clan earns 0.5 less influence a day." }, new KingdomLawDef { Law = KingdomLaw.TribunesOfThePeople, Name = "Tribunes of the People", Group = "Order and the people", Summary = "Tribunes may veto a lord's levy in the people's name.", Effects = "Town loyalty +0.5 a day. The realm's parties are 10% smaller." }, new KingdomLawDef { Law = KingdomLaw.NobleRetinues, Name = "Noble Retinues", Group = "War", Summary = "Every lord keeps a standing retinue at the fiefs' expense.", Effects = "The realm's parties are 15% larger. Town and castle taxes −5%." }, new KingdomLawDef { Law = KingdomLaw.RoyalGuard, Name = "Royal Guard", Group = "War", Summary = "The crown keeps its own guard, paid by the realm.", Effects = "The ruling clan's parties are 25% larger. Other council clans earn 0.25 less influence a day." }, new KingdomLawDef { Law = KingdomLaw.MilitaryCoronae, Name = "Military Coronae", Group = "War", Summary = "Crowns of honour for those who win the realm's battles.", Effects = "Influence from battles +50%. Town and castle taxes −5%." }, new KingdomLawDef { Law = KingdomLaw.Marches, Name = "Marches", Group = "War", Summary = "Castle lords hold the borders with wide powers.", Effects = "Castle security +1 a day; castle garrison wages −25%. Castle taxes −10%." }, new KingdomLawDef { Law = KingdomLaw.CastleCharters, Name = "Castle Charters", Group = "War", Summary = "Castles grant their lands to settlers in return for service.", Effects = "Castle loyalty +1 and prosperity +0.5 a day. The ruling clan earns 0.25 less influence a day." }, new KingdomLawDef { Law = KingdomLaw.LandGrantsForVeterans, Name = "Land Grants for Veterans", Group = "War", Summary = "Old soldiers are given land and stand in the militia.", Effects = "Militia +25% in every fief. Town and castle taxes −5%." }, new KingdomLawDef { Law = KingdomLaw.RoyalPrivilege, Name = "Royal Privilege", Group = "Crown and council", Excludes = KingdomLaw.Senate, Summary = "The ruler's voice weighs more than any lord's.", Effects = "The ruling clan's council ballot counts double. The ruling clan earns 0.5 more influence a day." }, new KingdomLawDef { Law = KingdomLaw.SacredMajesty, Name = "Sacred Majesty", Group = "Crown and council", Excludes = KingdomLaw.CouncilOfTheCommons, Summary = "The ruler is above the law and anointed by the gods.", Effects = "The ruling clan earns 1 more influence a day; loyalty +0.25 a day in every fief. Proposals by other clans cost 5 more influence." }, new KingdomLawDef { Law = KingdomLaw.Senate, Name = "Senate", Group = "Crown and council", Excludes = KingdomLaw.RoyalPrivilege, Summary = "The great clans meet as a senate that checks the ruler.", Effects = "Every council clan earns 0.5 more influence a day; the ruling clan earns 1 less." } }; public static KingdomLawDef Get(KingdomLaw law) { return All.FirstOrDefault((KingdomLawDef d) => d.Law == law); } public static string Name(KingdomLaw law) { return Get(law)?.Name ?? law.ToString(); } } public enum LegendRoute { Site, Chief, Quest } public sealed class LegendDef { public string Unit = ""; public LegendRoute Route; public bool Unique; public string Place = ""; public string Culture = ""; public string Enclave = ""; public string Story = ""; public int MinClanTier; public string QuestGiver = ""; public string QuestTitle = ""; public string QuestTask = ""; public string QuestGood = ""; public int QuestJoin = 2; } public static class Legends { public static readonly string[] LeftOut = new string[4] { "UNIT_LEGACY_LEG_TANK", "UNIT_LEGACY_LEG_SUPERBOXER", "UNIT_LEGACY_LEG_DARKP", "UNIT_LEGACY_LEG_SUPERPEASANT" }; public const string LegionCamp = "the Old Legion Camp"; public const string PoachersHollow = "Poachers' Hollow"; public const string RaptorValley = "Raptor Valley"; public const string BalloonField = "the Balloon Field"; public static readonly LegendDef[] All = new LegendDef[50] { Site("legacy.thor", "the Thunder Stones", "viking", 3, "Thunder rolls out of a clear sky. On the tallest stone sits a very large man with a hammer, eating a whole goose."), Site("legacy.pharaoh", "the Sunken Pyramid", "ancient", 2, "Sand pours off the steps of a buried pyramid. A pharaoh in faded gold waits on a throne for someone worth commanding."), Site("legacy.wizard", "the Leaning Tower of Hm", "medieval", 2, "Smoke of six colours from the chimney. The wizard inside has been waiting for an apprentice for ninety years and will settle for a warlord."), Site("secret.icemage", "the Ice Cave", "viking", 2, "Icicles like spears, and in the middle of the cave a mage sculpting snowmen that move."), Site("secret.witch", "the Witch's Hut", "spooky", 2, "A hut on chicken legs, which sits down as you approach. A broom leans by the door, humming."), Site("secret.banshee", "the Wailing Barrow", "spooky", 3, "A scream from inside the barrow loud enough to curdle the milk in the next village."), Site("secret.necromancer", "the Bone Crypt", "spooky", 3, "Neatly stacked bones, labelled. A man in black is teaching a skeleton to wave."), Site("secret.solararchitect", "the Sun Temple", "ancient", 3, "Mirrors on every pillar, all turned to one spot on the floor, which is on fire."), Site("secret.vlad", "Castle Dracul", "spooky", 3, "A ruined castle that is somehow always in shadow. Its lord invites you in for dinner. He does not eat."), Site("secret.samuraigiant", "the Giant's Shrine", "dynasty", 4, "A shrine built for someone four times your height. Its keeper fits it exactly."), Site("secret.ullr", "the Frozen Lodge", "viking", 3, "Skis by the door and a bow taller than a man. The hunter inside has not missed a shot in four hundred years."), Site("secret.redjade", "the Jade Pavilion", "dynasty", 4, "A pavilion of green stone. A swordswoman in red practises alone, and the leaves never reach the ground."), Site("secret.sensei", "the Mountain Dojo", "dynasty", 4, "Ten thousand steps up a mountain. At the top, an old master sweeping a floor that is already clean."), Site("secret.shogun", "the Silent Fortress", "dynasty", 4, "A fortress with no guards, because nobody has dared to try the gate. The shogun inside is bored."), Site("secret.artemis", "the Moonlit Grove", "ancient", 4, "Silver trees and a silver deer. A huntress watches you over an arrow she has not yet decided to loose."), Enclave("legacy.pike", "the Old Legion Camp", "medieval", "Veterans of wars nobody remembers, still drilling in a camp nobody remembers either."), Enclave("legacy.boxer", "the Old Legion Camp", "medieval", "Old soldiers of a forgotten war, still keeping watches nobody asked for."), Enclave("legacy.barrelroller", "the Old Legion Camp", "medieval", "A camp of greybeards who drill at dawn as if the enemy were over the next hill. It never is."), Enclave("legacy.bannerbearer", "the Old Legion Camp", "medieval", "Veterans who never got word the war was over, and wouldn't believe it if they did."), Enclave("legacy.flagbearer", "the Old Legion Camp", "medieval", "An old company, still polishing kit for a campaign that ended before their grandchildren were born."), Enclave("legacy.poacher", "Poachers' Hollow", "tribal", "A hollow full of snares, smoke and men who know exactly where your deer went."), Enclave("legacy.blowdart", "Poachers' Hollow", "tribal", "Woodsmen who can follow a deer for three days and a bandit for a week."), Enclave("secret.raptor", "Raptor Valley", "", "A valley of ferns and very fast lizards, and the people brave or silly enough to ride them."), Enclave("secret.raptorrider", "Raptor Valley", "", "Lizard riders, mostly still in one piece. Mostly."), Enclave("secret.ballooner", "the Balloon Field", "renaissance", "Patched balloons tethered in a field, and archers in the baskets practising on crows."), Chief("secret.ballandchain", "a brute swinging an iron ball on a chain"), Chief("secret.executioner", "a hooded executioner who misses his old job"), Chief("secret.shouter", "a chief who gives his orders at a volume that knocks men over"), Chief("secret.taekwondo", "a master of kicks who learned them on other people"), Chief("secret.macespinner", "a whirlwind of maces"), Chief("secret.infernalwhip", "a chief with a burning whip and a worse temper"), Chief("secret.skeletongiant", "a giant skeleton nobody can remember hiring"), Chief("secret.blackbeard", "Blackbeard himself, run aground and running a gang on land"), Chief("secret.treegiant", "a walking tree that has taken up banditry"), Chief("secret.icegiant", "an ice giant who came down from the mountains for the plunder"), Quest("secret.teacher", "village", "The Village School", "deliver", "good.tools", 2, "The schoolteacher will teach your soldiers to read, or at least to stand in straight lines."), Quest("secret.jester", "castle", "A Fool for the Castle", "hunt", "", 2, "The castle's jesters were taken by bandits. Get them back and two will follow you, juggling."), Quest("secret.cheerleader", "town", "The Big Match", "deliver", "good.velvet", 2, "The town's cheering squad needs new costumes for the big match. They cheer for whoever pays."), Quest("secret.cupid", "town", "A Matter of the Heart", "deliver", "good.jewelry", 2, "Two winged archers have lost their way and their arrows. Help them home and they will follow you."), Quest("secret.clamthrower", "village", "The Clam Beds", "hunt", "", 2, "Wreckers are raiding the clam beds. The clam throwers will throw clams at whoever you point at."), Quest("secret.presentthrower", "town", "The Midwinter Feast", "deliver", "good.wine", 2, "The feast needs wine. Its gift-givers throw their presents hard enough to stun an ox."), Quest("secret.safethrower", "town", "The Bank Job", "hunt", "", 2, "Thieves cracked the town's safe and ran. The safe throwers would like a word with them, and then with your enemies."), Quest("secret.fanbearer", "lord", "A Summer Court", "deliver", "good.velvet", 2, "A lady's court wants silk for its fans; her fan bearers blow men off their feet."), Quest("secret.chukonu", "lord", "Repeating Crossbows", "deliver", "good.tools", 3, "A lord's armoury makes repeating crossbows and needs tools. The crossbowmen come with the order."), Quest("secret.bombonastick", "tavern", "Too Much Gunpowder", "hunt", "", 3, "Some lunatics with bombs on sticks want to blow up the bandits who stole their sticks."), Quest("secret.firewheelbarrow", "village", "The Burning Barrows", "deliver", "good.timber", 2, "The farmers set their wheelbarrows on fire to scare the wolves. They need timber, and then they need a war."), Quest("secret.bombcannon", "castle", "The Great Gun", "deliver", "good.ore", 1, "The castellan's gunners built a cannon that fires bombs. They need ore to cast another."), Quest("secret.gatlinggun", "lord", "The Turning Gun", "deliver", "good.ore", 1, "A lord's engineers built a gun that never stops firing. Bring them iron and they will build you one."), Quest("secret.cavalry", "lord", "Horses for the Cavalry", "deliver", "good.horses", 3, "A company of old cavalry lost its mounts. Bring horses and the troopers ride with you."), Quest("legacy.chariot", "lord", "The Charioteers", "hunt", "", 2, "Charioteers from an older war have lost their wheels to bandits. Recover them and the chariots roll for you.") }; public static IEnumerable Chiefs => All.Where((LegendDef l) => l.Route == LegendRoute.Chief); public static IEnumerable Places => (from l in All where l.Route == LegendRoute.Site select l.Place).Distinct(StringComparer.Ordinal); private static LegendDef Site(string unit, string place, string culture, int tier, string story) { return new LegendDef { Unit = unit, Route = LegendRoute.Site, Unique = true, Place = place, Culture = culture, MinClanTier = tier, Story = story }; } private static LegendDef Enclave(string unit, string enclave, string culture, string story) { return new LegendDef { Unit = unit, Route = LegendRoute.Site, Unique = false, Place = enclave, Enclave = enclave, Culture = culture, MinClanTier = 0, Story = story }; } private static LegendDef Chief(string unit, string story) { return new LegendDef { Unit = unit, Route = LegendRoute.Chief, Unique = true, Story = story }; } private static LegendDef Quest(string unit, string giver, string title, string task, string good, int join, string story) { return new LegendDef { Unit = unit, Route = LegendRoute.Quest, Unique = false, QuestGiver = giver, QuestTitle = title, QuestTask = task, QuestGood = good, QuestJoin = join, Story = story }; } public static LegendDef For(string unitId) { return All.FirstOrDefault((LegendDef l) => l.Unit == unitId); } } public sealed class NotableDef { public string SettlementId = ""; public string Name = ""; public string SuccessorName = ""; public string Occupation = ""; } public static class Notables { public static readonly NotableDef[] All = new NotableDef[11] { new NotableDef { SettlementId = "town.wobbleton", Name = "Merrin Copperkettle", SuccessorName = "Tessa Copperkettle", Occupation = "Guild steward" }, new NotableDef { SettlementId = "town.skaldhavn", Name = "Siv Ropebraid", SuccessorName = "Orri Ropebraid", Occupation = "Harbour factor" }, new NotableDef { SettlementId = "village.mudbury", Name = "Hob Fenboot", SuccessorName = "Nell Fenboot", Occupation = "Village elder" }, new NotableDef { SettlementId = "village.hayfield", Name = "Ada Strawbell", SuccessorName = "Tobin Strawbell", Occupation = "Village elder" }, new NotableDef { SettlementId = "village.turniphollow", Name = "Pella Rootwhistle", SuccessorName = "Garen Rootwhistle", Occupation = "Village elder" }, new NotableDef { SettlementId = "village.gooseby", Name = "Orrin Featherlock", SuccessorName = "Mina Featherlock", Occupation = "Village elder" }, new NotableDef { SettlementId = "village.fjordby", Name = "Edda Netbinder", SuccessorName = "Sten Netbinder", Occupation = "Village elder" }, new NotableDef { SettlementId = "village.sealrock", Name = "Bruni Tidebutton", SuccessorName = "Ylva Tidebutton", Occupation = "Village elder" }, new NotableDef { SettlementId = "castle.faceplant", Name = "Berra Stonecap", SuccessorName = "Aldo Stonecap", Occupation = "Castellan" }, new NotableDef { SettlementId = "castle.duckwall", Name = "Milo Reedshield", SuccessorName = "Cora Reedshield", Occupation = "Castellan" }, new NotableDef { SettlementId = "castle.hornhold", Name = "Torvi Bellhorn", SuccessorName = "Hald Bellhorn", Occupation = "Castellan" } }; public static NotableDef Get(string settlementId) { return All.FirstOrDefault((NotableDef x) => x.SettlementId == settlementId); } public static string NameFor(string settlementId, string settlementName, int generation) { NotableDef notableDef = Get(settlementId); string text = ((generation != 0) ? notableDef?.SuccessorName : notableDef?.Name); if (string.IsNullOrEmpty(text)) { text = settlementName + " Steward"; } if (generation <= 1) { return text; } return text + " " + generation.ToString(CultureInfo.InvariantCulture); } } public enum PerkScope { Personal, Leader, Scout, Surgeon, Quartermaster, Engineer, Governor, ClanLeader } public enum PerkEffect { HeroDamage, HeroHealth, HeroDamageTaken, Learning, TradePrices, Persuasion, RelationBonus, CrimeDecay, SneakChance, EscapeChance, SmithStamina, SmithRecovery, PartySpeed, FootSpeed, TerrainSpeed, Sight, FoodUse, Wages, PartySize, PrisonerLimit, Cargo, Morale, TroopDailyXp, TroopBattleXp, Healing, WoundSurvival, RecruitCost, UpgradeCost, Ransom, BattleRenown, AutoResolve, TroopDamage, TroopHealth, RaidSpeed, RaidLoot, SiegeBuild, Tax, GarrisonWages, Prosperity, Loyalty, Security, Militia, BuildSpeed, GarrisonXp, DefenderSiegeBuild, Influence, CaravanTrade } public sealed class PerkMod { public PerkEffect Effect; public PerkScope Scope; public double Value; public string Target = ""; } public static class PerkTrees { private sealed class P { public string Name; public PerkMod[] Mods; public P(string name, params PerkMod[] mods) { Name = name; Mods = mods; } } public const int Step = 25; public const int Tiers = 11; private const string Inf = "Infantry"; private const string Rng = "Ranged"; private const string Cav = "Cavalry"; public static readonly List All = Build().ToList(); public static string Group(string skill, int required) { return skill + required.ToString(CultureInfo.InvariantCulture); } private static PerkMod M(PerkEffect e, PerkScope s, double v, string target = "") { return new PerkMod { Effect = e, Scope = s, Value = v, Target = (target ?? "") }; } private static PerkMod Me(PerkEffect e, double v, string target = "") { return M(e, PerkScope.Personal, v, target); } private static PerkMod Lead(PerkEffect e, double v, string target = "") { return M(e, PerkScope.Leader, v, target); } private static PerkMod Scout(PerkEffect e, double v) { return M(e, PerkScope.Scout, v); } private static PerkMod Surg(PerkEffect e, double v, string target = "") { return M(e, PerkScope.Surgeon, v, target); } private static PerkMod Qm(PerkEffect e, double v) { return M(e, PerkScope.Quartermaster, v); } private static PerkMod Eng(PerkEffect e, double v, string target = "") { return M(e, PerkScope.Engineer, v, target); } private static PerkMod Gov(PerkEffect e, double v) { return M(e, PerkScope.Governor, v); } private static PerkMod Clan(PerkEffect e, double v) { return M(e, PerkScope.ClanLeader, v); } private static IEnumerable Tree(string skill, int firstTier, params P[] perks) { for (int i = 0; i < perks.Length; i++) { int num = (firstTier + i / 2) * 25; P p = perks[i]; HeroPerkDef heroPerkDef = new HeroPerkDef { Id = "perk." + skill + "." + Slug(p.Name), Name = p.Name, Skill = skill, RequiredSkill = num, Group = Group(skill, num), Mods = p.Mods.ToList() }; heroPerkDef.Description = Describe(heroPerkDef.Mods); yield return heroPerkDef; } } internal static string Slug(string name) { return new string((from ch in name.ToLowerInvariant() select (!char.IsLetterOrDigit(ch)) ? '_' : ch).ToArray()).Trim(new char[1] { '_' }); } private static IEnumerable Build() { string text = "one_handed"; string text2 = "two_handed"; string text3 = "polearm"; string text4 = "bow"; string text5 = "crossbow"; string text6 = "throwing"; PerkEffect e = PerkEffect.HeroDamage; return Enumerable.Empty().Concat(Tree(text, 1, new P("Blade Drill", Me(e, 0.05, text)), new P("Shieldmate", Lead(PerkEffect.TroopHealth, 0.04, "Infantry")), new P("Single Combat", Me(PerkEffect.HeroDamageTaken, 0.04)), new P("Rank and File", Lead(PerkEffect.TroopDamage, 0.03, "Infantry")), new P("Fast Hands", Me(e, 0.05, text)), new P("Sword Practice", Lead(PerkEffect.TroopBattleXp, 0.05)), new P("Hard Guard", Me(PerkEffect.HeroHealth, 0.05)), new P("Infantry Captain", Lead(PerkEffect.TroopHealth, 0.04, "Infantry")), new P("Riposte", Me(PerkEffect.HeroDamageTaken, 0.05)), new P("Arms Instructor", Lead(PerkEffect.TroopDailyXp, 1.0)), new P("Cutting Edge", Me(e, 0.06, text)), new P("Steady Ranks", Lead(PerkEffect.Morale, 3.0)), new P("Battle Hardened", Me(PerkEffect.HeroHealth, 0.06)), new P("Vanguard", Lead(PerkEffect.TroopDamage, 0.04, "Infantry")), new P("Learned Hand", Me(PerkEffect.Learning, 0.15, text)), new P("Shield Bearers", Lead(PerkEffect.TroopHealth, 0.05, "Infantry")), new P("Bladestorm", Me(e, 0.07, text)), new P("Footmen's Pride", Lead(PerkEffect.PartySize, 5.0)), new P("Unbroken", Me(PerkEffect.HeroDamageTaken, 0.06)), new P("Sergeant's Eye", Lead(PerkEffect.UpgradeCost, 0.1)), new P("Swordmaster", Me(e, 0.1, text)), new P("Champion's Banner", Lead(PerkEffect.TroopDamage, 0.05, "Infantry")))).Concat(Tree(text2, 1, new P("Heavy Swing", Me(e, 0.05, text2)), new P("Breakers", Lead(PerkEffect.TroopDamage, 0.03, "Infantry")), new P("Broad Shoulders", Me(PerkEffect.HeroHealth, 0.04)), new P("Shock Troops", Lead(PerkEffect.TroopHealth, 0.03, "Infantry")), new P("Cleaver", Me(e, 0.05, text2)), new P("War Cry", Lead(PerkEffect.Morale, 3.0)), new P("Iron Grip", Me(PerkEffect.HeroDamageTaken, 0.04)), new P("Frenzied Ranks", Lead(PerkEffect.TroopDamage, 0.04, "Infantry")), new P("Momentum", Me(e, 0.05, text2)), new P("Heavy Drill", Lead(PerkEffect.TroopBattleXp, 0.05)), new P("Thick Skin", Me(PerkEffect.HeroHealth, 0.06)), new P("Spoils of War", Lead(PerkEffect.BattleRenown, 0.1)), new P("Crushing Blow", Me(e, 0.06, text2)), new P("Fearsome", Lead(PerkEffect.AutoResolve, 0.04)), new P("Studied Swings", Me(PerkEffect.Learning, 0.15, text2)), new P("Great Weapons", Lead(PerkEffect.TroopDamage, 0.04, "Infantry")), new P("Relentless", Me(PerkEffect.HeroDamageTaken, 0.06)), new P("Lean Column", Lead(PerkEffect.FoodUse, 0.05)), new P("Juggernaut", Me(PerkEffect.HeroHealth, 0.08)), new P("Warband", Lead(PerkEffect.PartySize, 5.0)), new P("Titan's Reach", Me(e, 0.1, text2)), new P("Dread Host", Lead(PerkEffect.TroopDamage, 0.05, "Infantry")))) .Concat(Tree(text3, 1, new P("Long Reach", Me(e, 0.05, text3)), new P("Pike Square", Lead(PerkEffect.TroopHealth, 0.03, "Infantry")), new P("Planted Feet", Me(PerkEffect.HeroDamageTaken, 0.04)), new P("Spear Hedge", Lead(PerkEffect.TroopDamage, 0.03, "Infantry")), new P("Thrust", Me(e, 0.05, text3)), new P("Lance Drill", Lead(PerkEffect.TroopDamage, 0.03, "Cavalry")), new P("Steady Footing", Me(PerkEffect.HeroHealth, 0.05)), new P("Halberdiers", Lead(PerkEffect.TroopHealth, 0.04, "Infantry")), new P("Run Through", Me(e, 0.05, text3)), new P("Horse Breakers", Lead(PerkEffect.AutoResolve, 0.03)), new P("Polearm Study", Me(PerkEffect.Learning, 0.15, text3)), new P("Couched Lances", Lead(PerkEffect.TroopDamage, 0.04, "Cavalry")), new P("Wide Guard", Me(PerkEffect.HeroDamageTaken, 0.05)), new P("Spear Drill", Lead(PerkEffect.TroopDailyXp, 1.0)), new P("Impaler", Me(e, 0.06, text3)), new P("Spear Wall", Lead(PerkEffect.TroopHealth, 0.05, "Infantry")), new P("Hardened Shaft", Me(PerkEffect.HeroHealth, 0.06)), new P("Lancers' Pride", Lead(PerkEffect.TroopHealth, 0.04, "Cavalry")), new P("Sweeping Blade", Me(e, 0.07, text3)), new P("Long Column", Lead(PerkEffect.PartySpeed, 0.02)), new P("Master of the Spear", Me(e, 0.1, text3)), new P("Forest of Points", Lead(PerkEffect.TroopDamage, 0.05, "Infantry")))) .Concat(Tree(text4, 1, new P("Draw Weight", Me(e, 0.05, text4)), new P("Volley", Lead(PerkEffect.TroopDamage, 0.03, "Ranged")), new P("Steady Aim", Me(e, 0.04, text4)), new P("Bowyers", Lead(PerkEffect.TroopHealth, 0.03, "Ranged")), new P("Hunting Party", Lead(PerkEffect.FoodUse, 0.05)), new P("Archery Butts", Lead(PerkEffect.TroopBattleXp, 0.05)), new P("Deadeye", Me(e, 0.05, text4)), new P("Skirmishers", Lead(PerkEffect.TroopDamage, 0.03, "Ranged")), new P("Light Step", Me(PerkEffect.HeroDamageTaken, 0.04)), new P("Longbowmen", Lead(PerkEffect.TroopHealth, 0.04, "Ranged")), new P("Quiver Study", Me(PerkEffect.Learning, 0.15, text4)), new P("Massed Arrows", Lead(PerkEffect.AutoResolve, 0.03)), new P("Piercer", Me(e, 0.06, text4)), new P("Archer Drill", Lead(PerkEffect.TroopDailyXp, 1.0)), new P("Eagle Eyes", Lead(PerkEffect.Sight, 0.05)), new P("Rain of Arrows", Lead(PerkEffect.TroopDamage, 0.04, "Ranged")), new P("Nimble Archer", Me(PerkEffect.HeroHealth, 0.06)), new P("Bow Company", Lead(PerkEffect.TroopHealth, 0.05, "Ranged")), new P("Heartseeker", Me(e, 0.07, text4)), new P("Woodland Archers", Lead(PerkEffect.TerrainSpeed, 0.04)), new P("Master Archer", Me(e, 0.1, text4)), new P("Arrowstorm", Lead(PerkEffect.TroopDamage, 0.05, "Ranged")))) .Concat(Tree(text5, 1, new P("Heavy Bolts", Me(e, 0.05, text5)), new P("Crossbow Line", Lead(PerkEffect.TroopDamage, 0.03, "Ranged")), new P("Shield Cover", Me(PerkEffect.HeroDamageTaken, 0.04)), new P("Mantlet Men", Lead(PerkEffect.TroopHealth, 0.03, "Ranged")), new P("Quick Winch", Me(e, 0.04, text5)), new P("Siege Crossbows", Eng(PerkEffect.SiegeBuild, 0.05)), new P("Armour Piercer", Me(e, 0.05, text5)), new P("Arbalesters", Lead(PerkEffect.TroopDamage, 0.03, "Ranged")), new P("Steady Rest", Me(PerkEffect.HeroHealth, 0.05)), new P("Wall Guards", Gov(PerkEffect.Security, 0.5)), new P("Bolt Study", Me(PerkEffect.Learning, 0.15, text5)), new P("Garrison Crossbows", Gov(PerkEffect.GarrisonXp, 1.0)), new P("Punch Through", Me(e, 0.06, text5)), new P("Crossbow Drill", Lead(PerkEffect.TroopDailyXp, 1.0)), new P("Covered", Me(PerkEffect.HeroDamageTaken, 0.05)), new P("Shielded Shooters", Lead(PerkEffect.TroopHealth, 0.05, "Ranged")), new P("Deadly Bolt", Me(e, 0.07, text5)), new P("Hired Marksmen", Lead(PerkEffect.Wages, 0.04)), new P("Iron Nerve", Me(PerkEffect.HeroHealth, 0.06)), new P("Rampart", Lead(PerkEffect.AutoResolve, 0.04)), new P("Master Crossbowman", Me(e, 0.1, text5)), new P("Killing Field", Lead(PerkEffect.TroopDamage, 0.05, "Ranged")))) .Concat(Tree(text6, 1, new P("Strong Throw", Me(e, 0.05, text6)), new P("Javelin Men", Lead(PerkEffect.TroopDamage, 0.03, "Infantry")), new P("Spare Javelins", Me(e, 0.04, text6)), new P("Skirmish Line", Lead(PerkEffect.TroopDamage, 0.03, "Ranged")), new P("Light Load", Lead(PerkEffect.Cargo, 0.05)), new P("Throwers' Drill", Lead(PerkEffect.TroopBattleXp, 0.05)), new P("Quick Release", Me(e, 0.05, text6)), new P("Peltasts", Lead(PerkEffect.TroopHealth, 0.03, "Ranged")), new P("Agile", Me(PerkEffect.HeroDamageTaken, 0.04)), new P("Horse Darters", Lead(PerkEffect.TroopDamage, 0.03, "Cavalry")), new P("Throwing Study", Me(PerkEffect.Learning, 0.15, text6)), new P("Harriers", Lead(PerkEffect.PartySpeed, 0.02)), new P("Splitter", Me(e, 0.06, text6)), new P("Ambushers", Lead(PerkEffect.AutoResolve, 0.03)), new P("Hardy", Me(PerkEffect.HeroHealth, 0.06)), new P("Raiding Darts", Lead(PerkEffect.RaidSpeed, 0.1)), new P("Long Throw", Me(e, 0.07, text6)), new P("Skirmish Drill", Lead(PerkEffect.TroopDailyXp, 1.0)), new P("Unshaken", Me(PerkEffect.HeroDamageTaken, 0.06)), new P("Hail of Spears", Lead(PerkEffect.TroopDamage, 0.04, "Infantry")), new P("Master Thrower", Me(e, 0.1, text6)), new P("Deadly Rain", Lead(PerkEffect.TroopDamage, 0.05, "Ranged")))) .Concat(Tree("athletics", 1, new P("Dawn Laps", Me(PerkEffect.HeroHealth, 0.03)), new P("Marching Feet", Lead(PerkEffect.FootSpeed, 0.03)), new P("Light Footed", Me(PerkEffect.HeroDamageTaken, 0.03)), new P("Road Discipline", Lead(PerkEffect.PartySpeed, 0.02)), new P("Strong Back", Lead(PerkEffect.Cargo, 0.1)), new P("Fit Recruits", Lead(PerkEffect.TroopHealth, 0.02)), new P("Endurance Training", Me(PerkEffect.HeroHealth, 0.04)), new P("Forced March", Lead(PerkEffect.FootSpeed, 0.04)), new P("Runner's Lungs", Me(PerkEffect.Learning, 0.2, "athletics")), new P("Hill Walkers", Lead(PerkEffect.TerrainSpeed, 0.04)), new P("Second Wind", Me(PerkEffect.HeroDamageTaken, 0.04)), new P("Healthy Camp", Lead(PerkEffect.Healing, 0.05)), new P("Iron Legs", Me(PerkEffect.HeroHealth, 0.05)), new P("Long Strides", Lead(PerkEffect.FootSpeed, 0.04)), new P("Escape Artist", Me(PerkEffect.EscapeChance, 0.05)), new P("Porters", Lead(PerkEffect.Cargo, 0.1)), new P("Tireless", Me(PerkEffect.HeroDamageTaken, 0.05)), new P("Hardened Column", Lead(PerkEffect.TroopHealth, 0.03)), new P("Peak Form", Me(PerkEffect.HeroHealth, 0.06)), new P("Quick March", Lead(PerkEffect.PartySpeed, 0.03)), new P("Unstoppable", Me(e, 0.05)), new P("Iron Host", Lead(PerkEffect.TroopHealth, 0.04)))) .Concat(Tree("scouting", 2, new P("Spoor Readers", Scout(PerkEffect.Sight, 0.1)), new P("Forest Paths", Scout(PerkEffect.TerrainSpeed, 0.05)), new P("Wild Larder", Scout(PerkEffect.FoodUse, 0.05)), new P("Lookouts", Scout(PerkEffect.Sight, 0.08)), new P("Shortcuts", Scout(PerkEffect.PartySpeed, 0.03)), new P("Game Hunters", Scout(PerkEffect.Morale, 2.0)), new P("Wayfinder", Scout(PerkEffect.TerrainSpeed, 0.06)), new P("Stealthy Approach", Me(PerkEffect.SneakChance, 0.05)), new P("Scout's Learning", Me(PerkEffect.Learning, 0.2, "scouting")), new P("Outriders", Scout(PerkEffect.Sight, 0.1)), new P("Fast Riders", Scout(PerkEffect.PartySpeed, 0.03)), new P("Pathclearers", Scout(PerkEffect.TerrainSpeed, 0.06)), new P("Ambush Sense", Scout(PerkEffect.AutoResolve, 0.03)), new P("Spring Finders", Scout(PerkEffect.Morale, 3.0)), new P("Swift Camp", Scout(PerkEffect.PartySpeed, 0.03)), new P("Far Sight", Scout(PerkEffect.Sight, 0.12)), new P("Shadow Walk", Me(PerkEffect.SneakChance, 0.08)), new P("Raiders' Trail", Lead(PerkEffect.RaidSpeed, 0.15)), new P("Master Scout", Scout(PerkEffect.PartySpeed, 0.05)), new P("All-Seeing", Scout(PerkEffect.Sight, 0.2)))) .Concat(Tree("tactics", 1, new P("Battle Plans", Lead(PerkEffect.AutoResolve, 0.03)), new P("Lying in Wait", Lead(PerkEffect.TroopDamage, 0.02)), new P("Squad Drills", Lead(PerkEffect.TroopHealth, 0.02)), new P("Battle Study", Me(PerkEffect.Learning, 0.2, "tactics")), new P("Pincer", Lead(PerkEffect.TroopDamage, 0.03, "Cavalry")), new P("Stand Fast", Lead(PerkEffect.TroopHealth, 0.03, "Infantry")), new P("Planner", Lead(PerkEffect.AutoResolve, 0.04)), new P("Rout Them", Lead(PerkEffect.BattleRenown, 0.1)), new P("Covering Fire", Lead(PerkEffect.TroopHealth, 0.03, "Ranged")), new P("Supply Lines", Lead(PerkEffect.FoodUse, 0.05)), new P("Shield Screen", Lead(PerkEffect.TroopHealth, 0.03)), new P("Hammer Stroke", Lead(PerkEffect.TroopDamage, 0.03)), new P("Field Triage", Lead(PerkEffect.WoundSurvival, 0.03)), new P("Siege Planner", Eng(PerkEffect.SiegeBuild, 0.08)), new P("Veteran Officers", Lead(PerkEffect.TroopBattleXp, 0.1)), new P("Feint", Lead(PerkEffect.AutoResolve, 0.05)), new P("Prisoner Handling", Lead(PerkEffect.PrisonerLimit, 10.0)), new P("Captains' Council", Lead(PerkEffect.PartySize, 5.0)), new P("Combined Arms", Lead(PerkEffect.TroopDamage, 0.04)), new P("Fortified Camp", Lead(PerkEffect.TroopHealth, 0.04)), new P("Warmaster", Lead(PerkEffect.AutoResolve, 0.08)), new P("Art of War", Lead(PerkEffect.TroopDamage, 0.05)))) .Concat(Tree("roguery", 1, new P("Light Fingers", Lead(PerkEffect.RaidLoot, 0.2)), new P("Back Alleys", Me(PerkEffect.SneakChance, 0.05)), new P("Captive Dealer", Lead(PerkEffect.Ransom, 0.1)), new P("Fast Raiders", Lead(PerkEffect.RaidSpeed, 0.1)), new P("Smugglers", Me(PerkEffect.TradePrices, 0.02)), new P("Forgotten Faces", Me(PerkEffect.CrimeDecay, 0.3)), new P("Heavy Chains", Lead(PerkEffect.PrisonerLimit, 10.0)), new P("Cutthroats", Lead(PerkEffect.TroopDamage, 0.03)), new P("Thieves' Cant", Me(PerkEffect.Learning, 0.2, "roguery")), new P("Bribed Guards", Me(PerkEffect.SneakChance, 0.05)), new P("Plunder", Lead(PerkEffect.RaidLoot, 0.3)), new P("Slippery", Me(PerkEffect.EscapeChance, 0.05)), new P("Rule by Fear", Lead(PerkEffect.AutoResolve, 0.03)), new P("Clean Record", Me(PerkEffect.CrimeDecay, 0.5)), new P("Fence", Lead(PerkEffect.Ransom, 0.15)), new P("Lean Crew", Lead(PerkEffect.Wages, 0.05)), new P("Swift Plunder", Lead(PerkEffect.RaidSpeed, 0.2)), new P("Brigands' Gear", Lead(PerkEffect.TroopHealth, 0.03)), new P("Escape Route", Me(PerkEffect.EscapeChance, 0.1)), new P("Black Market", Me(PerkEffect.TradePrices, 0.03)), new P("King of Thieves", Lead(PerkEffect.RaidLoot, 0.5)), new P("Ghost", Me(PerkEffect.SneakChance, 0.1)))) .Concat(Tree("charm", 1, new P("Easy Smile", Me(PerkEffect.Persuasion, 0.03)), new P("Good Company", Lead(PerkEffect.Morale, 2.0)), new P("Warm Greeting", Me(PerkEffect.RelationBonus, 1.0)), new P("Charming", Me(PerkEffect.Learning, 0.2, "charm")), new P("Smooth Talker", Me(PerkEffect.Persuasion, 0.04)), new P("Friendly Recruiter", Lead(PerkEffect.RecruitCost, 0.05)), new P("Admired", Clan(PerkEffect.Influence, 0.05)), new P("Generous Host", Lead(PerkEffect.Morale, 3.0)), new P("Good Word", Me(PerkEffect.RelationBonus, 1.0)), new P("Inspiring Talk", Lead(PerkEffect.TroopBattleXp, 0.05)), new P("Honeyed Words", Me(PerkEffect.Persuasion, 0.05)), new P("Popular", Gov(PerkEffect.Loyalty, 0.5)), new P("Beloved", Gov(PerkEffect.Prosperity, 0.5)), new P("Flatterer", Clan(PerkEffect.Influence, 0.05)), new P("Trusted Voice", Me(PerkEffect.Persuasion, 0.05)), new P("Local Hero", Lead(PerkEffect.RecruitCost, 0.08)), new P("Gracious", Me(PerkEffect.RelationBonus, 1.0)), new P("Fair Lord", Gov(PerkEffect.Loyalty, 0.5)), new P("Captivating", Me(PerkEffect.Persuasion, 0.06)), new P("Open Hand", Clan(PerkEffect.Influence, 0.1)), new P("Irresistible", Me(PerkEffect.Persuasion, 0.08)), new P("Living Legend", Lead(PerkEffect.BattleRenown, 0.2)))) .Concat(Tree("leadership", 1, new P("Rallying Voice", Lead(PerkEffect.Morale, 3.0)), new P("Drill Yard", Lead(PerkEffect.TroopDailyXp, 1.0)), new P("Recruiter", Lead(PerkEffect.RecruitCost, 0.05)), new P("Disciplined Ranks", Lead(PerkEffect.TroopHealth, 0.02)), new P("Command Presence", Lead(PerkEffect.PartySize, 5.0)), new P("Field Lessons", Lead(PerkEffect.TroopBattleXp, 0.05)), new P("Leader's Learning", Me(PerkEffect.Learning, 0.2, "leadership")), new P("Proud Banner", Lead(PerkEffect.TroopDamage, 0.02)), new P("Trusted Captain", Lead(PerkEffect.Wages, 0.05)), new P("Veteran Drill", Lead(PerkEffect.TroopDailyXp, 1.0)), new P("Prisoner Keepers", Lead(PerkEffect.PrisonerLimit, 10.0)), new P("Brotherhood", Lead(PerkEffect.Morale, 5.0)), new P("Promotion", Lead(PerkEffect.UpgradeCost, 0.1)), new P("Large Retinue", Lead(PerkEffect.PartySize, 8.0)), new P("Stirring Words", Lead(PerkEffect.TroopDamage, 0.03)), new P("Loyal Men", Lead(PerkEffect.Wages, 0.05)), new P("Garrison Commander", Gov(PerkEffect.GarrisonWages, 0.1)), new P("Training Yard", Gov(PerkEffect.GarrisonXp, 2.0)), new P("Famed Leader", Lead(PerkEffect.BattleRenown, 0.15)), new P("Army of Many", Lead(PerkEffect.PartySize, 10.0)), new P("Lord of Hosts", Lead(PerkEffect.TroopDailyXp, 2.0)), new P("Warlord's Guard", Lead(PerkEffect.TroopHealth, 0.05)))) .Concat(Tree("trade", 1, new P("Hard Bargain", Me(PerkEffect.TradePrices, 0.03)), new P("Market Sense", Me(PerkEffect.Learning, 0.2, "trade")), new P("Bulk Buyer", Me(PerkEffect.TradePrices, 0.02)), new P("Mule Train", Lead(PerkEffect.Cargo, 0.1)), new P("Caravan Patron", Clan(PerkEffect.CaravanTrade, 15.0)), new P("Penny Pincher", Qm(PerkEffect.Wages, 0.03)), new P("Valuer", Lead(PerkEffect.Ransom, 0.1)), new P("Supply Chain", Qm(PerkEffect.FoodUse, 0.05)), new P("Tax Farmer", Clan(PerkEffect.Tax, 0.05)), new P("Shrewd Hiring", Lead(PerkEffect.RecruitCost, 0.05)), new P("Merchant Lord", Me(PerkEffect.TradePrices, 0.03)), new P("Long Haul", Clan(PerkEffect.CaravanTrade, 20.0)), new P("Market Charter", Gov(PerkEffect.Prosperity, 0.5)), new P("Bridge Fees", Gov(PerkEffect.Tax, 0.08)), new P("Guild Ties", Clan(PerkEffect.Influence, 0.05)), new P("Silver Purse", Lead(PerkEffect.UpgradeCost, 0.1)), new P("Rich Markets", Clan(PerkEffect.Tax, 0.05)), new P("Well Stocked", Lead(PerkEffect.Cargo, 0.15)), new P("Golden Touch", Me(PerkEffect.TradePrices, 0.04)), new P("Trade Empire", Clan(PerkEffect.CaravanTrade, 30.0)), new P("Merchant Prince", Me(PerkEffect.TradePrices, 0.05)), new P("Banker", Clan(PerkEffect.Tax, 0.1)))) .Concat(Tree("diplomacy", 1, new P("Envoy", Clan(PerkEffect.Influence, 0.05)), new P("Polite", Me(PerkEffect.RelationBonus, 1.0)), new P("Negotiator", Me(PerkEffect.Persuasion, 0.03)), new P("Ransom Talks", Lead(PerkEffect.Ransom, 0.1)), new P("Court Manners", Me(PerkEffect.Learning, 0.2, "diplomacy")), new P("Peacemaker", Gov(PerkEffect.Loyalty, 0.5)), new P("Statesman", Clan(PerkEffect.Influence, 0.05)), new P("Mediator", Me(PerkEffect.RelationBonus, 1.0)), new P("Treaty Writer", Me(PerkEffect.Persuasion, 0.04)), new P("Hostage Exchange", Me(PerkEffect.EscapeChance, 0.05)), new P("Safe Conduct", Me(PerkEffect.CrimeDecay, 0.3)), new P("Honoured Guest", Clan(PerkEffect.Influence, 0.05)), new P("Ambassador", Me(PerkEffect.Persuasion, 0.05)), new P("Good Neighbour", Gov(PerkEffect.Security, 0.5)), new P("Fair Terms", Lead(PerkEffect.Ransom, 0.15)), new P("Court Favourite", Clan(PerkEffect.Influence, 0.08)), new P("Councillor", Gov(PerkEffect.Loyalty, 0.75)), new P("Kinship", Me(PerkEffect.RelationBonus, 1.0)), new P("Kingmaker", Clan(PerkEffect.Influence, 0.1)), new P("Masterful Envoy", Me(PerkEffect.Persuasion, 0.06)), new P("Voice of the Realm", Clan(PerkEffect.Influence, 0.15)), new P("Grand Diplomat", Me(PerkEffect.RelationBonus, 2.0)))) .Concat(Tree("stewardship", 2, new P("Careful Accounts", Qm(PerkEffect.Wages, 0.05)), new P("Ration Keeper", Qm(PerkEffect.FoodUse, 0.05)), new P("Large Wagons", Qm(PerkEffect.Cargo, 0.1)), new P("Bigger Camp", Qm(PerkEffect.PartySize, 5.0)), new P("Steward's Study", Me(PerkEffect.Learning, 0.2, "stewardship")), new P("Contented Troops", Qm(PerkEffect.Morale, 3.0)), new P("Bailiff", Gov(PerkEffect.Tax, 0.05)), new P("Granary Keeper", Gov(PerkEffect.Prosperity, 0.5)), new P("Builder", Gov(PerkEffect.BuildSpeed, 0.2)), new P("Clerk", Qm(PerkEffect.UpgradeCost, 0.1)), new P("Garrison Pay", Gov(PerkEffect.GarrisonWages, 0.1)), new P("Militia Muster", Gov(PerkEffect.Militia, 0.5)), new P("Wagon Master", Qm(PerkEffect.PartySize, 8.0)), new P("Supply Officer", Qm(PerkEffect.FoodUse, 0.08)), new P("Treasurer", Clan(PerkEffect.Tax, 0.05)), new P("Reeve", Gov(PerkEffect.Security, 0.5)), new P("Chancellor", Clan(PerkEffect.GarrisonWages, 0.1)), new P("Wealth of Lands", Clan(PerkEffect.Prosperity, 0.3)), new P("Grand Steward", Qm(PerkEffect.PartySize, 15.0)), new P("Coin Keeper", Qm(PerkEffect.Wages, 0.1)))) .Concat(Tree("medicine", 2, new P("Bandages", Surg(PerkEffect.Healing, 0.1)), new P("Clean Wounds", Surg(PerkEffect.WoundSurvival, 0.03)), new P("Herbalist", Surg(PerkEffect.Healing, 0.1)), new P("Physician's Study", Me(PerkEffect.Learning, 0.2, "medicine")), new P("Bonesetter", Surg(PerkEffect.WoundSurvival, 0.04)), new P("Camp Hygiene", Surg(PerkEffect.Morale, 2.0)), new P("Field Hospital", Surg(PerkEffect.Healing, 0.15)), new P("Healthy Body", Me(PerkEffect.HeroHealth, 0.03)), new P("Battlefield Triage", Surg(PerkEffect.WoundSurvival, 0.04)), new P("Town Physician", Gov(PerkEffect.Prosperity, 0.5)), new P("Surgeon's Hands", Surg(PerkEffect.Healing, 0.15)), new P("Healthy Militia", Gov(PerkEffect.Militia, 0.5)), new P("Quick Recovery", Surg(PerkEffect.Healing, 0.2)), new P("Doctor's Orders", Surg(PerkEffect.TroopHealth, 0.02)), new P("Pain Relief", Surg(PerkEffect.WoundSurvival, 0.05)), new P("Sickbay", Gov(PerkEffect.Loyalty, 0.5)), new P("Chief Surgeon", Surg(PerkEffect.Healing, 0.25)), new P("Resilience", Me(PerkEffect.HeroDamageTaken, 0.05)), new P("Miracle Worker", Surg(PerkEffect.WoundSurvival, 0.06)), new P("Healer's Grace", Surg(PerkEffect.Healing, 0.3)))) .Concat(Tree("engineering", 1, new P("Scaffolding Crews", Eng(PerkEffect.SiegeBuild, 0.1)), new P("Builder's Eye", Gov(PerkEffect.BuildSpeed, 0.1)), new P("Sappers", Eng(PerkEffect.SiegeBuild, 0.1)), new P("Engineer's Study", Me(PerkEffect.Learning, 0.2, "engineering")), new P("Stonecutters", Gov(PerkEffect.BuildSpeed, 0.15)), new P("Wall Repairers", Gov(PerkEffect.DefenderSiegeBuild, 0.1)), new P("Siege Train", Eng(PerkEffect.SiegeBuild, 0.15)), new P("Watch Posts", Gov(PerkEffect.Security, 0.5)), new P("Wagon Wrights", Eng(PerkEffect.Cargo, 0.1)), new P("Counter-Engines", Gov(PerkEffect.DefenderSiegeBuild, 0.15)), new P("Fast Assembly", Eng(PerkEffect.SiegeBuild, 0.2)), new P("Masons' Guild", Gov(PerkEffect.Prosperity, 0.5)), new P("Sturdy Camp", Eng(PerkEffect.TroopHealth, 0.02)), new P("Arsenal", Gov(PerkEffect.GarrisonXp, 1.0)), new P("Siegewright", Eng(PerkEffect.SiegeBuild, 0.25)), new P("Fortifier", Gov(PerkEffect.DefenderSiegeBuild, 0.2)), new P("Road Builders", Eng(PerkEffect.PartySpeed, 0.02)), new P("Town Planner", Gov(PerkEffect.BuildSpeed, 0.25)), new P("Chief Architect", Clan(PerkEffect.BuildSpeed, 0.2)), new P("Breaching Crews", Eng(PerkEffect.AutoResolve, 0.03)), new P("Grand Engineer", Eng(PerkEffect.SiegeBuild, 0.4)), new P("Impregnable", Gov(PerkEffect.DefenderSiegeBuild, 0.3)))); } internal static IEnumerable SmithingAdditions() { return new HeroPerkDef[6] { Single("smithing", 150, "Iron Lungs", Me(PerkEffect.SmithStamina, 0.2)), Single("smithing", 150, "Quick Rest", Me(PerkEffect.SmithRecovery, 0.5)), Single("smithing", 200, "Smith's Study", Me(PerkEffect.Learning, 0.2, "smithing")), Single("smithing", 225, "Tireless Smith", Me(PerkEffect.SmithStamina, 0.3)), Single("smithing", 225, "Hammer Arm", Me(PerkEffect.HeroDamage, 0.03)), Single("smithing", 275, "Forge Master", Me(PerkEffect.SmithRecovery, 1.0)) }; } internal static IEnumerable RidingAdditions() { return new HeroPerkDef[2] { Single("riding", 225, "Cavalry Officer", Lead(PerkEffect.TroopDamage, 0.04, "Cavalry")), Single("riding", 225, "Saddle Hardened", Lead(PerkEffect.TroopHealth, 0.04, "Cavalry")) }; } private static HeroPerkDef Single(string skill, int required, string name, params PerkMod[] mods) { string text = ((skill == "smithing") ? "smith" : "ride") + required.ToString(CultureInfo.InvariantCulture); HeroPerkDef obj = new HeroPerkDef { Id = "perk." + ((skill == "smithing") ? "smith" : "riding") + "." + Slug(name), Name = name, Skill = skill, RequiredSkill = required, Group = text, Mods = mods.ToList() }; obj.Description = Describe(obj.Mods); return obj; } public static string Describe(IEnumerable mods) { return string.Join(" ", mods.Select((PerkMod m) => Sentence(m)).ToArray()); } private static string Pct(double v) { return (v * 100.0).ToString("0.#", CultureInfo.InvariantCulture) + "%"; } private static string Pts(double v) { return v.ToString("0.##", CultureInfo.InvariantCulture); } private static string WeaponPhrase(string skill) { return skill switch { "one_handed" => " with one-handed weapons", "two_handed" => " with two-handed weapons", "polearm" => " with polearms", "bow" => " with bows", "crossbow" => " with crossbows", "throwing" => " with thrown weapons", _ => "", }; } private static string RolePhrase(string role) { return role switch { "Cavalry" => "cavalry", "Ranged" => "ranged troops", "Infantry" => "infantry", _ => "troops", }; } public static string ScopePhrase(PerkScope scope) { return scope switch { PerkScope.Leader => "while leading a party", PerkScope.Scout => "as the party's scout", PerkScope.Surgeon => "as the party's surgeon", PerkScope.Quartermaster => "as the party's quartermaster", PerkScope.Engineer => "as the party's engineer", PerkScope.Governor => "in the town or castle this hero governs", PerkScope.ClanLeader => "as clan leader", _ => "", }; } public static string Effect(PerkMod m) { double value = m.Value; return m.Effect switch { PerkEffect.HeroDamage => "+" + Pct(value) + " damage in battle" + WeaponPhrase(m.Target), PerkEffect.HeroHealth => "+" + Pct(value) + " hit points in battle", PerkEffect.HeroDamageTaken => "-" + Pct(value) + " damage taken in battle", PerkEffect.Learning => "+" + Pct(value) + " " + ((m.Target.Length == 0) ? "skill" : Skills.Name(m.Target)) + " experience", PerkEffect.TradePrices => Pct(value) + " better prices when buying and selling goods", PerkEffect.Persuasion => "+" + Pts(value * 100.0) + " points to the chance of every persuasion argument", PerkEffect.RelationBonus => "+" + Pts(value) + " to every relation gain with notables and lords", PerkEffect.CrimeDecay => "Your crime ratings fade " + Pct(value) + " faster", PerkEffect.SneakChance => "+" + Pts(value * 100.0) + " points to the chance of sneaking into a hostile town", PerkEffect.EscapeChance => "+" + Pts(value * 100.0) + " points to the daily chance of escaping captivity", PerkEffect.SmithStamina => "+" + Pct(value) + " smithing stamina", PerkEffect.SmithRecovery => "Smithing stamina returns " + Pct(value) + " faster", PerkEffect.PartySpeed => "+" + Pct(value) + " party speed on the map", PerkEffect.FootSpeed => "Up to +" + Pct(value) + " party speed, in proportion to the troops on foot", PerkEffect.TerrainSpeed => "+" + Pct(value) + " party speed on forest, hills and other slow ground", PerkEffect.Sight => "+" + Pct(value) + " sight range", PerkEffect.FoodUse => "-" + Pct(value) + " food eaten", PerkEffect.Wages => "-" + Pct(value) + " party wages", PerkEffect.PartySize => "+" + Pts(value) + " party size", PerkEffect.PrisonerLimit => "+" + Pts(value) + " prisoner limit", PerkEffect.Cargo => "+" + Pct(value) + " carrying capacity", PerkEffect.Morale => "+" + Pts(value) + " morale", PerkEffect.TroopDailyXp => "Every troop in the party gains " + Pts(value) + " experience a day", PerkEffect.TroopBattleXp => "+" + Pct(value) + " troop experience from battles", PerkEffect.Healing => "+" + Pct(value) + " healing of troops and heroes", PerkEffect.WoundSurvival => "+" + Pts(value * 100.0) + " points to the chance that downed troops survive", PerkEffect.RecruitCost => "-" + Pct(value) + " recruitment cost", PerkEffect.UpgradeCost => "-" + Pct(value) + " troop upgrade cost", PerkEffect.Ransom => "+" + Pct(value) + " ransom for prisoners sold", PerkEffect.BattleRenown => "+" + Pct(value) + " renown from battles", PerkEffect.AutoResolve => "+" + Pct(value) + " strength when a battle is resolved without you fighting it", PerkEffect.TroopDamage => "+" + Pct(value) + " damage for " + RolePhrase(m.Target) + " in battle", PerkEffect.TroopHealth => "+" + Pct(value) + " hit points for " + RolePhrase(m.Target) + " in battle", PerkEffect.RaidSpeed => "Raids take " + Pct(value) + " less time", PerkEffect.RaidLoot => "+" + Pct(value) + " gold from raids", PerkEffect.SiegeBuild => "+" + Pct(value) + " siege engine building speed", PerkEffect.Tax => "+" + Pct(value) + " tax", PerkEffect.GarrisonWages => "-" + Pct(value) + " garrison wages", PerkEffect.Prosperity => "+" + Pts(value) + " prosperity a day", PerkEffect.Loyalty => "+" + Pts(value) + " loyalty a day", PerkEffect.Security => "+" + Pts(value) + " security a day", PerkEffect.Militia => "+" + Pts(value) + " militia a day", PerkEffect.BuildSpeed => "Projects build " + Pct(value) + " faster", PerkEffect.GarrisonXp => "The garrison's drill gives " + Pts(value) + " more experience a day", PerkEffect.DefenderSiegeBuild => "+" + Pct(value) + " siege engine building speed when besieged", PerkEffect.Influence => "+" + Pct(value) + " influence gained", PerkEffect.CaravanTrade => "Your caravans trade as if their captain had " + Pts(value) + " more Trade", _ => m.Effect.ToString(), }; } public static string Short(PerkMod m) { if (m == null) { return ""; } double value = m.Value; string text = ((m.Target == "Infantry") ? "infantry " : ((m.Target == "Ranged") ? "ranged " : ((m.Target == "Cavalry") ? "cavalry " : "troop "))); return m.Effect switch { PerkEffect.HeroDamage => "+" + Pct(value) + ((m.Target.Length == 0) ? " damage" : (" " + Skills.Name(m.Target).ToLowerInvariant() + " damage")), PerkEffect.HeroHealth => "+" + Pct(value) + " hit points", PerkEffect.HeroDamageTaken => "-" + Pct(value) + " damage taken", PerkEffect.Learning => "+" + Pct(value) + " " + ((m.Target.Length == 0) ? "learning" : (Skills.Name(m.Target) + " XP")), PerkEffect.TradePrices => Pct(value) + " better prices", PerkEffect.Persuasion => "+" + Pts(value * 100.0) + " persuasion", PerkEffect.RelationBonus => "+" + Pts(value) + " relation gains", PerkEffect.CrimeDecay => "Crime fades " + Pct(value) + " faster", PerkEffect.SneakChance => "+" + Pts(value * 100.0) + " sneaking", PerkEffect.EscapeChance => "+" + Pts(value * 100.0) + " escape", PerkEffect.SmithStamina => "+" + Pct(value) + " stamina", PerkEffect.SmithRecovery => "+" + Pct(value) + " stamina recovery", PerkEffect.PartySpeed => "+" + Pct(value) + " speed", PerkEffect.FootSpeed => "+" + Pct(value) + " speed on foot", PerkEffect.TerrainSpeed => "+" + Pct(value) + " rough-ground speed", PerkEffect.Sight => "+" + Pct(value) + " sight", PerkEffect.FoodUse => "-" + Pct(value) + " food", PerkEffect.Wages => "-" + Pct(value) + " wages", PerkEffect.PartySize => "+" + Pts(value) + " party size", PerkEffect.PrisonerLimit => "+" + Pts(value) + " prisoners", PerkEffect.Cargo => "+" + Pct(value) + " capacity", PerkEffect.Morale => "+" + Pts(value) + " morale", PerkEffect.TroopDailyXp => "+" + Pts(value) + " troop XP a day", PerkEffect.TroopBattleXp => "+" + Pct(value) + " troop battle XP", PerkEffect.Healing => "+" + Pct(value) + " healing", PerkEffect.WoundSurvival => "+" + Pts(value * 100.0) + " pts survival", PerkEffect.RecruitCost => "-" + Pct(value) + " recruit cost", PerkEffect.UpgradeCost => "-" + Pct(value) + " upgrade cost", PerkEffect.Ransom => "+" + Pct(value) + " ransom", PerkEffect.BattleRenown => "+" + Pct(value) + " battle renown", PerkEffect.AutoResolve => "+" + Pct(value) + " simulated strength", PerkEffect.TroopDamage => "+" + Pct(value) + " " + text + "damage", PerkEffect.TroopHealth => "+" + Pct(value) + " " + text + "hit points", PerkEffect.RaidSpeed => Pct(value) + " faster raids", PerkEffect.RaidLoot => "+" + Pct(value) + " raid gold", PerkEffect.SiegeBuild => "+" + Pct(value) + " siege building", PerkEffect.Tax => "+" + Pct(value) + " tax", PerkEffect.GarrisonWages => "-" + Pct(value) + " garrison wages", PerkEffect.Prosperity => "+" + Pts(value) + " prosperity/day", PerkEffect.Loyalty => "+" + Pts(value) + " loyalty/day", PerkEffect.Security => "+" + Pts(value) + " security/day", PerkEffect.Militia => "+" + Pts(value) + " militia/day", PerkEffect.BuildSpeed => Pct(value) + " faster projects", PerkEffect.GarrisonXp => "+" + Pts(value) + " garrison drill", PerkEffect.DefenderSiegeBuild => "+" + Pct(value) + " defence building", PerkEffect.Influence => "+" + Pct(value) + " influence", PerkEffect.CaravanTrade => "+" + Pts(value) + " caravan Trade", _ => m.Effect.ToString(), }; } public static string ScopeShort(PerkScope scope) { return scope switch { PerkScope.Leader => "Leader", PerkScope.Scout => "Scout", PerkScope.Surgeon => "Surgeon", PerkScope.Quartermaster => "Quartermaster", PerkScope.Engineer => "Engineer", PerkScope.Governor => "Governor", PerkScope.ClanLeader => "Clan leader", _ => "Personal", }; } private static string Sentence(PerkMod m) { string text = Effect(m); string text2 = ScopePhrase(m.Scope); if (m.Scope == PerkScope.ClanLeader && IsSettlementEffect(m.Effect)) { text2 = "in every fief, as clan leader"; } return text + ((text2.Length > 0) ? (" " + text2) : "") + "."; } public static bool IsSettlementEffect(PerkEffect e) { if (e != PerkEffect.Tax && e != PerkEffect.GarrisonWages && e != PerkEffect.Prosperity && e != PerkEffect.Loyalty && e != PerkEffect.Security && e != PerkEffect.Militia && e != PerkEffect.BuildSpeed && e != PerkEffect.GarrisonXp) { return e == PerkEffect.DefenderSiegeBuild; } return true; } } public sealed class AttributeDef { public string Id = ""; public string Name = ""; public string Description = ""; } public sealed class SkillDef { public string Id = ""; public string Name = ""; public string Attribute = ""; public string Description = ""; public string Learning = ""; public WeaponClass[] Weapons = new WeaponClass[0]; } public static class Skills { public const int BaseAttribute = 2; public const int MaximumAttribute = 10; public const int LevelsPerAttribute = 4; public static readonly List Attributes = new List { new AttributeDef { Id = "vigor", Name = "Vigor", Description = "Strength and a sure hand with melee weapons: One Handed, Two Handed and Polearm." }, new AttributeDef { Id = "control", Name = "Control", Description = "A steady eye and a cool head with missiles: Bow, Crossbow and Throwing." }, new AttributeDef { Id = "endurance", Name = "Endurance", Description = "Stamina and toughness: Riding, Athletics and Smithing." }, new AttributeDef { Id = "cunning", Name = "Cunning", Description = "Wits and nerve: Scouting, Tactics and Roguery." }, new AttributeDef { Id = "social", Name = "Social", Description = "Dealing with people: Charm, Leadership, Trade and Diplomacy." }, new AttributeDef { Id = "intelligence", Name = "Intelligence", Description = "Learning and planning: Stewardship, Medicine and Engineering." } }; public static readonly List All = new List { S("one_handed", "One Handed", "vigor", "Swords, axes, maces and daggers held in one hand: a hero fighting with one deals more damage.", "Fighting with a one-handed weapon in battle, and kills made with one.", WeaponClass.OneHandedSword, WeaponClass.Dagger, WeaponClass.OneHandedAxe, WeaponClass.Mace), S("two_handed", "Two Handed", "vigor", "Great swords, axes and hammers: a hero fighting with one deals more damage.", "Fighting with a two-handed weapon in battle, and kills made with one.", WeaponClass.TwoHandedSword, WeaponClass.TwoHandedAxe, WeaponClass.TwoHandedMace), S("polearm", "Polearm", "vigor", "Spears, pikes, glaives and halberds: a hero fighting with one deals more damage.", "Fighting with a polearm in battle, and kills made with one.", WeaponClass.Pike, WeaponClass.TwoHandedPolearm), S("bow", "Bow", "control", "Bows: a hero shooting one deals more damage.", "Shooting a bow in battle, and kills made with one.", WeaponClass.Bow), S("crossbow", "Crossbow", "control", "Crossbows: a hero shooting one deals more damage.", "Shooting a crossbow in battle, and kills made with one.", WeaponClass.Crossbow), S("throwing", "Throwing", "control", "Javelins, throwing axes and knives: a hero throwing them deals more damage.", "Throwing weapons in battle, and kills made with them.", WeaponClass.Javelin, WeaponClass.ThrowingAxe, WeaponClass.ThrowingKnife), S("riding", "Riding", "endurance", "Horses: harder horses to ride, faster travel, and fighting from the saddle.", "Riding on the map, fighting mounted, and the stable."), S("athletics", "Athletics", "endurance", "Running, marching and carrying: its perks bring toughness in battle and a quicker march on foot.", "Marching on foot on the map, and fighting on foot."), S("smithing", "Smithing", "endurance", "Refining, smelting and forging at a smithy.", "Work at the smithy."), S("scouting", "Scouting", "cunning", "Finding the way and seeing far: sight and speed on the map.", "Serving as the party's scout; travelling the map."), S("tactics", "Tactics", "cunning", "Winning battles: better odds when a battle is resolved without you fighting it.", "Battles, above all against the odds."), S("roguery", "Roguery", "cunning", "The underworld: raiding, crime, sneaking into towns and dealing in prisoners.", "Raiding villages, sneaking into towns, the underworld's work, and selling or recruiting prisoners."), S("charm", "Charm", "social", "Winning people over: persuasion, courtship and friendships.", "Conversations, persuasion, courtship, gifts and making friends."), S("leadership", "Leadership", "social", "Leading soldiers: morale, a larger party and better-trained troops.", "Leading a party, and winning its battles."), S("trade", "Trade", "social", "Buying and selling: better prices, and your caravans' bargains.", "Buying and selling goods at a profit."), S("diplomacy", "Diplomacy", "social", "Statecraft: the council, war and peace, service and ransoms.", "Council business, war and peace, service and ransoms. Only you learn it."), S("stewardship", "Stewardship", "intelligence", "Running a party and a fief: food, wages, party size and a town's prosperity.", "Serving as the party's quartermaster; governing."), S("medicine", "Medicine", "intelligence", "Healing the wounded, and keeping the gravely hurt alive.", "Serving as the party's surgeon; healing."), S("engineering", "Engineering", "intelligence", "Siege engines, walls and buildings.", "Serving as the party's engineer; sieges and building.") }; private static SkillDef S(string id, string name, string attribute, string description, string learning, params WeaponClass[] weapons) { return new SkillDef { Id = id, Name = name, Attribute = attribute, Description = description, Learning = learning, Weapons = weapons }; } public static SkillDef Get(string id) { return All.FirstOrDefault((SkillDef s) => s.Id == id); } public static AttributeDef Attribute(string id) { return Attributes.FirstOrDefault((AttributeDef a) => a.Id == id); } public static string AttributeOf(string skill) { return Get(skill)?.Attribute ?? ""; } public static IEnumerable Of(string attribute) { return All.Where((SkillDef s) => s.Attribute == attribute); } public static string Name(string skill) { object obj = Get(skill)?.Name; if (obj == null) { if (!string.IsNullOrEmpty(skill)) { return char.ToUpperInvariant(skill[0]) + skill.Substring(1); } obj = ""; } return (string)obj; } public static string WeaponSkill(WeaponClass c) { return All.FirstOrDefault((SkillDef s) => s.Weapons.Contains(c))?.Id ?? "one_handed"; } } public enum WeaponClass { OneHandedSword, TwoHandedSword, Dagger, OneHandedAxe, TwoHandedAxe, Mace, TwoHandedMace, Pike, TwoHandedPolearm, Javelin, ThrowingKnife, ThrowingAxe, Shield, Bow, Crossbow, Arrows, Bolts } public enum WeaponFamily { Melee, Thrown, Shield, Bow, Crossbow, Ammo } public enum PartSlot { Blade, Guard, Handle, Pommel } public enum DamageKind { None, Cut, Pierce, Blunt } public enum SmithingMaterial { Hardwood, IronOre, Charcoal, CrudeIron, WroughtIron, Iron, Steel, FineSteel, Thamaskene, Hides, Flax, Wool } public enum WeaponQuality { Poor, Inferior, Common, Fine, Masterwork, Legendary } public sealed class WeaponClassDef { public WeaponClass Class; public string Name = ""; public bool TwoHanded; public bool Thrown; public WeaponFamily Family; public PartSlot[] Slots = new PartSlot[0]; public string[] SlotNames = new string[4]; public DamageKind Swing; public DamageKind Thrust; public DamageKind Missile; public double Grip; public double InertiaScale = 1.0; public double BaseValue; public TroopRole Role { get { if (!Thrown && Family != WeaponFamily.Bow && Family != WeaponFamily.Crossbow) { return TroopRole.Infantry; } return TroopRole.Ranged; } } public bool Launcher { get { if (Family != WeaponFamily.Bow) { return Family == WeaponFamily.Crossbow; } return true; } } public bool BothHands { get { if (!TwoHanded) { return Launcher; } return true; } } public bool OffHand { get { if (Family == WeaponFamily.Melee) { return !TwoHanded; } return false; } } public EquipmentSlot Slot { get { if (Family != WeaponFamily.Shield) { if (Family != WeaponFamily.Ammo) { return EquipmentSlot.Weapon; } return EquipmentSlot.Ammo; } return EquipmentSlot.Shield; } } public bool Uses(PartSlot slot) { return Slots.Contains(slot); } } public sealed class SmithingPartDef { public string Id = ""; public string Name = ""; public WeaponClass Class; public PartSlot Slot; public string Shape = ""; public int ShapeIndex; public int Tier = 1; public double Length; public double Weight; public double Width = 1.0; public double Cut; public double Pierce; public double Blunt; public double Balance = 0.4; public double Handling; public double Breadth; public double Toughness; public double Draw; public double Accuracy; public double Cap; public bool GivenByDefault; public SortedDictionary Materials = new SortedDictionary(); } public sealed class WeaponStats { public double Length; public double Weight; public double SwingSpeed; public double SwingDamage; public double ThrustSpeed; public double ThrustDamage; public double Handling; public double MissileSpeed; public double MissileDamage; public double Accuracy; public DamageKind SwingKind; public DamageKind ThrustKind; public DamageKind MissileKind; public double HitPoints; public double Breadth; public double DrawSpeed; public double Range; public WeaponStats Copy() { return (WeaponStats)MemberwiseClone(); } } public sealed class RefiningRecipe { public string Id = ""; public string Name = ""; public SortedDictionary Inputs = new SortedDictionary(); public SortedDictionary Outputs = new SortedDictionary(); public string RequiredPerk = ""; } public static class Smithing { private sealed class Shape { public string Name; public double Length; public double Weight; public double Width = 1.0; public double Cut; public double Pierce; public double Blunt; public double Balance = 0.4; public double Handling; public double Breadth; public double Toughness; public double Draw; public double Accuracy; public double Cap; public SmithingMaterial[] Made; } public const string Skill = "smithing"; public const string MaterialPrefix = "mat."; public const string CraftedPrefix = "crafted."; public const int MaterialLimit = 999; public const int MaximumNameLength = 40; public const int OrdersPerTown = 6; public const int OrderDifficultyGap = 50; public const double RefiningStamina = 6.0; public const double SmeltingStamina = 10.0; public const double OrderFillChancePerDay = 0.25; public const double OrderReplaceChancePerDay = 0.05; public const double CraftedSaleShare = 0.3; public const double ArtisanSaleShare = 0.65; public const string EfficientCharcoalMaker = "perk.smith.charcoal"; public const string EfficientIronMaker = "perk.smith.iron"; public const string CuriousSmelter = "perk.smith.curious_smelter"; public const string SteelMaker = "perk.smith.steel"; public const string CuriousSmith = "perk.smith.curious_smith"; public const string SteelMaker2 = "perk.smith.steel2"; public const string ExperiencedSmith = "perk.smith.experienced"; public const string SteelMaker3 = "perk.smith.steel3"; public const string PracticalRefiner = "perk.smith.practical_refiner"; public const string PracticalSmelter = "perk.smith.practical_smelter"; public const string ArtisanSmith = "perk.smith.artisan"; public const string PracticalSmith = "perk.smith.practical_smith"; public const string MasterSmith = "perk.smith.master"; public const string SharpenedEdge = "perk.smith.edge"; public const string SharpenedTip = "perk.smith.tip"; public const string LegendarySmith = "perk.smith.legendary"; public static readonly List Perks = new List { Perk("perk.smith.charcoal", "Efficient Charcoal Maker", 25, "smith25", "Refining two hardwood makes three charcoal instead of one."), Perk("perk.smith.iron", "Efficient Iron Maker", 25, "smith25", "Refining one iron ore makes three crude iron instead of two."), Perk("perk.smith.curious_smelter", "Curious Smelter", 50, "smith50", "Smelting teaches new part designs twice as fast."), Perk("perk.smith.steel", "Steel Maker", 50, "smith50", "Learn to refine two iron into one steel (and one crude iron)."), Perk("perk.smith.curious_smith", "Curious Smith", 75, "smith75", "Forging teaches new part designs twice as fast."), Perk("perk.smith.steel2", "Steel Maker II", 75, "smith75", "Learn to refine two steel into one fine steel (and one crude iron)."), Perk("perk.smith.experienced", "Experienced Smith", 100, "smith100", "+5% forging score on designs within your skill; completed notable orders give +2 relation."), Perk("perk.smith.steel3", "Steel Maker III", 100, "smith100", "Learn to refine two fine steel into one Thamaskene steel; completed lord orders give +4 clan relation."), Perk("perk.smith.practical_refiner", "Practical Refiner", 125, "smith125", "Refining costs half the stamina."), Perk("perk.smith.practical_smelter", "Practical Smelter", 125, "smith125", "Smelting costs half the stamina."), Perk("perk.smith.artisan", "Artisan Smith", 175, "smith175", "Merchants pay 65% of a smithed weapon's value instead of 30%."), Perk("perk.smith.practical_smith", "Practical Smith", 175, "smith175", "Forging costs half the stamina."), Perk("perk.smith.master", "Master Smith", 200, "smith200", "Hammer blows have a 20% wider window at the anvil."), Perk("perk.smith.edge", "Sharpened Edge", 250, "smith250", "+2% swing damage on weapons you forge."), Perk("perk.smith.tip", "Sharpened Tip", 250, "smith250", "+2% thrust and thrown damage on weapons you forge."), Perk("perk.smith.legendary", "Legendary Smith", 275, "smith275", "Legendary work needs 25 less skill above a design's difficulty; blow windows widen 1% per 5 skill above 275.") }; private static readonly string[] MaterialNames = new string[12] { "Hardwood", "Iron ore", "Charcoal", "Crude iron", "Wrought iron", "Iron", "Steel", "Fine steel", "Thamaskene steel", "Hides", "Flax", "Wool" }; private static readonly string[] MaterialKeys = new string[12] { "", "", "charcoal", "crude_iron", "wrought_iron", "iron", "steel", "fine_steel", "thamaskene", "", "", "" }; private static readonly double[] MaterialXpValue = new double[12] { 0.0, 0.0, 50.0, 20.0, 30.0, 60.0, 100.0, 160.0, 260.0, 0.0, 0.0, 0.0 }; private static readonly long[] MaterialValues = new long[12] { 14L, 22L, 20L, 12L, 24L, 48L, 95L, 180L, 360L, 0L, 0L, 0L }; public const double MaterialWeight = 0.5; public static readonly SmithingMaterial[] AllMaterials = (SmithingMaterial[])Enum.GetValues(typeof(SmithingMaterial)); public static readonly SmithingMaterial[] StockMaterials = AllMaterials.Where((SmithingMaterial m) => !IsCargoMaterial(m)).ToArray(); public static readonly List Recipes = new List { Recipe("refine.charcoal", "Burn charcoal", SmithingMaterial.Hardwood, 2, SmithingMaterial.Charcoal, 0, SmithingMaterial.Charcoal, 1), Recipe("refine.crude", "Smelt iron ore", SmithingMaterial.IronOre, 1, SmithingMaterial.Charcoal, 1, SmithingMaterial.CrudeIron, 2), Recipe("refine.wrought", "Work crude iron", SmithingMaterial.CrudeIron, 1, SmithingMaterial.Charcoal, 1, SmithingMaterial.WroughtIron, 1), Recipe("refine.iron", "Fold wrought iron", SmithingMaterial.WroughtIron, 2, SmithingMaterial.Charcoal, 1, SmithingMaterial.Iron, 1, SmithingMaterial.CrudeIron, 1), Recipe("refine.steel", "Make steel", SmithingMaterial.Iron, 2, SmithingMaterial.Charcoal, 1, SmithingMaterial.Steel, 1, SmithingMaterial.CrudeIron, 1, "perk.smith.steel"), Recipe("refine.fine", "Make fine steel", SmithingMaterial.Steel, 2, SmithingMaterial.Charcoal, 1, SmithingMaterial.FineSteel, 1, SmithingMaterial.CrudeIron, 1, "perk.smith.steel2"), Recipe("refine.thamaskene", "Make Thamaskene steel", SmithingMaterial.FineSteel, 2, SmithingMaterial.Charcoal, 1, SmithingMaterial.Thamaskene, 1, SmithingMaterial.CrudeIron, 1, "perk.smith.steel3") }; public static readonly List Classes = new List { Class(WeaponClass.OneHandedSword, "One-handed sword", twoHanded: false, thrown: false, 4, DamageKind.Cut, DamageKind.Pierce, 0.5, 1.0, 40.0), Class(WeaponClass.TwoHandedSword, "Two-handed sword", twoHanded: true, thrown: false, 4, DamageKind.Cut, DamageKind.Pierce, 0.35, 1.0, 60.0), Class(WeaponClass.Dagger, "Dagger", twoHanded: false, thrown: false, 4, DamageKind.Cut, DamageKind.Pierce, 0.5, 1.0, 25.0), Class(WeaponClass.OneHandedAxe, "One-handed axe", twoHanded: false, thrown: false, 3, DamageKind.Cut, DamageKind.None, 0.85, 1.0, 35.0), Class(WeaponClass.TwoHandedAxe, "Two-handed axe", twoHanded: true, thrown: false, 3, DamageKind.Cut, DamageKind.None, 0.75, 1.0, 55.0), Class(WeaponClass.Mace, "Mace", twoHanded: false, thrown: false, 3, DamageKind.Blunt, DamageKind.None, 0.85, 1.0, 35.0), Class(WeaponClass.TwoHandedMace, "Two-handed mace", twoHanded: true, thrown: false, 3, DamageKind.Blunt, DamageKind.None, 0.75, 1.0, 55.0), Class(WeaponClass.Pike, "Pike", twoHanded: true, thrown: false, 3, DamageKind.None, DamageKind.Pierce, 0.62, 4.0, 45.0), Class(WeaponClass.TwoHandedPolearm, "Two-handed polearm", twoHanded: true, thrown: false, 3, DamageKind.Cut, DamageKind.Pierce, 0.6, 4.0, 55.0), Class(WeaponClass.Javelin, "Javelin", twoHanded: false, thrown: true, 3, DamageKind.None, DamageKind.None, 0.55, 1.0, 20.0, DamageKind.Pierce), Class(WeaponClass.ThrowingKnife, "Throwing knives", twoHanded: false, thrown: true, 4, DamageKind.None, DamageKind.None, 0.5, 1.0, 15.0, DamageKind.Pierce), Class(WeaponClass.ThrowingAxe, "Throwing axe", twoHanded: false, thrown: true, 3, DamageKind.None, DamageKind.None, 0.8, 1.0, 20.0, DamageKind.Cut), Arms(WeaponClass.Shield, "Shield", WeaponFamily.Shield, new string[4] { "Board", "Rim", "Facing", "Boss" }, 35.0), Arms(WeaponClass.Bow, "Bow", WeaponFamily.Bow, new string[4] { "Stave", "Grip", "String", "Tips" }, 50.0), Arms(WeaponClass.Crossbow, "Crossbow", WeaponFamily.Crossbow, new string[4] { "Prod", "Lock", "Stock", "String" }, 70.0), Arms(WeaponClass.Arrows, "Arrows", WeaponFamily.Ammo, new string[4] { "Head", "Fletching", "Shaft", "Nock" }, 15.0), Arms(WeaponClass.Bolts, "Bolts", WeaponFamily.Ammo, new string[4] { "Head", "Vanes", "Shaft", "Nock" }, 18.0) }; private static readonly string[] MetalTierWords = new string[5] { "Crude", "Simple", "Sturdy", "Tempered", "Damascened" }; private static readonly string[] WoodTierWords = new string[5] { "Rough", "Plain", "Bound", "Lacquered", "Inlaid" }; private static readonly string[] FittingTierWords = new string[5] { "Crude", "Simple", "Sturdy", "Tempered", "Gilded" }; private static readonly double[] TierDamage = new double[5] { 0.85, 0.95, 1.05, 1.12, 1.2 }; private static readonly double[] TierWeight = new double[5] { 1.12, 1.05, 1.0, 0.95, 0.9 }; private static readonly SmithingMaterial[] FittingMetal = new SmithingMaterial[5] { SmithingMaterial.CrudeIron, SmithingMaterial.WroughtIron, SmithingMaterial.Iron, SmithingMaterial.Steel, SmithingMaterial.FineSteel }; public static readonly List Parts = BuildParts(); private static readonly Dictionary PartIndex = Parts.ToDictionary((SmithingPartDef p) => p.Id, StringComparer.Ordinal); private static readonly double[] SlotDifficultyWeight = new double[4] { 100.0, 20.0, 60.0, 20.0 }; private static readonly Dictionary AttackRange = BuildAttackRanges(); private static readonly double[] QualityPriceFactor = new double[6] { 0.3, 0.6, 1.0, 1.2, 1.5, 1.8 }; private static readonly double[] QualityDamageFactor = new double[6] { 0.85, 0.93, 1.0, 1.06, 1.12, 1.2 }; private static readonly double[] QualitySpeedFactor = new double[6] { 0.95, 0.98, 1.0, 1.02, 1.04, 1.06 }; public static readonly int[] OrderBandLow = new int[5] { 40, 80, 120, 160, 200 }; private static SmithingMaterial[] _noMaterials; private const SmithingMaterial Wood = SmithingMaterial.Hardwood; private const SmithingMaterial Hide = SmithingMaterial.Hides; private const SmithingMaterial Flax = SmithingMaterial.Flax; private const SmithingMaterial Wool = SmithingMaterial.Wool; private const SmithingMaterial Metal = SmithingMaterial.Iron; public static readonly double[] QualityThresholds = new double[5] { 0.3, 0.5, 0.7, 0.85, 0.95 }; private static SmithingMaterial[] NoMaterials => _noMaterials ?? (_noMaterials = new SmithingMaterial[0]); private static string[] HideTierWords => new string[5] { "Raw", "Cured", "Stitched", "Boiled", "Fine" }; private static string[] ClothTierWords => new string[5] { "Coarse", "Plain", "Sewn", "Fine", "Embroidered" }; private static string[] BowTierWords => new string[5] { "Rough", "Plain", "Seasoned", "Lacquered", "Masterwork" }; private static HeroPerkDef Perk(string id, string name, int skill, string group, string description) { return new HeroPerkDef { Id = id, Name = name, Skill = "smithing", RequiredSkill = skill, Group = group, Description = description }; } public static long MaterialValue(SmithingMaterial m) { return MaterialValues[(int)m]; } public static bool IsMetal(SmithingMaterial m) { if (m >= SmithingMaterial.CrudeIron) { return m <= SmithingMaterial.Thamaskene; } return false; } public static string MaterialName(SmithingMaterial m) { return MaterialNames[(int)m]; } public static string MaterialItemId(SmithingMaterial m) { return m switch { SmithingMaterial.Wool => "good.wool", SmithingMaterial.Flax => "good.flax", SmithingMaterial.Hides => "good.hides", SmithingMaterial.IronOre => "good.ore", SmithingMaterial.Hardwood => "good.timber", _ => "mat." + MaterialKeys[(int)m], }; } public static bool IsCargoMaterial(SmithingMaterial m) { if (m != SmithingMaterial.Hardwood && m != SmithingMaterial.IronOre && m != SmithingMaterial.Hides && m != SmithingMaterial.Flax) { return m == SmithingMaterial.Wool; } return true; } public static bool TryMaterialForItem(string itemId, out SmithingMaterial material) { SmithingMaterial[] stockMaterials = StockMaterials; foreach (SmithingMaterial smithingMaterial in stockMaterials) { if (MaterialItemId(smithingMaterial) == itemId) { material = smithingMaterial; return true; } } material = SmithingMaterial.Charcoal; return false; } public static bool IsMaterialId(string id) { SmithingMaterial material; return TryMaterialForItem(id, out material); } public static bool IsCraftedId(string id) { if (id != null && id.StartsWith("crafted.", StringComparison.Ordinal)) { return id.Length > "crafted.".Length; } return false; } private static RefiningRecipe Recipe(string id, string name, SmithingMaterial input, int inputCount, SmithingMaterial fuel, int fuelCount, SmithingMaterial output, int outputCount, SmithingMaterial byproduct = SmithingMaterial.Hardwood, int byproductCount = 0, string perk = "") { RefiningRecipe refiningRecipe = new RefiningRecipe { Id = id, Name = name, RequiredPerk = perk }; refiningRecipe.Inputs[input] = inputCount; if (fuelCount > 0) { refiningRecipe.Inputs[fuel] = fuelCount; } refiningRecipe.Outputs[output] = outputCount; if (byproductCount > 0) { refiningRecipe.Outputs[byproduct] = byproductCount; } return refiningRecipe; } public static RefiningRecipe EffectiveRecipe(RefiningRecipe recipe, Func hasPerk) { RefiningRecipe refiningRecipe = new RefiningRecipe { Id = recipe.Id, Name = recipe.Name, RequiredPerk = recipe.RequiredPerk, Inputs = new SortedDictionary(recipe.Inputs), Outputs = new SortedDictionary(recipe.Outputs) }; if (recipe.Id == "refine.charcoal" && hasPerk("perk.smith.charcoal")) { refiningRecipe.Outputs[SmithingMaterial.Charcoal] = 3; } if (recipe.Id == "refine.crude" && hasPerk("perk.smith.iron")) { refiningRecipe.Outputs[SmithingMaterial.CrudeIron] = 3; } return refiningRecipe; } public static double RefiningXp(RefiningRecipe effective) { SmithingMaterial smithingMaterial = effective.Outputs.Keys.Max(); return 0.3 * MaterialXpValue[(int)smithingMaterial] * (double)effective.Outputs[smithingMaterial]; } public static SmithingMaterial MainOutput(RefiningRecipe recipe) { return recipe.Outputs.Keys.Max(); } private static WeaponClassDef Class(WeaponClass c, string name, bool twoHanded, bool thrown, int slots, DamageKind swing, DamageKind thrust, double grip, double inertiaScale, double baseValue, DamageKind missile = DamageKind.None) { bool flag = c == WeaponClass.Pike || c == WeaponClass.TwoHandedPolearm || c == WeaponClass.Javelin; bool flag2 = c == WeaponClass.OneHandedAxe || c == WeaponClass.TwoHandedAxe || c == WeaponClass.Mace || c == WeaponClass.TwoHandedMace || c == WeaponClass.ThrowingAxe; WeaponClassDef weaponClassDef = new WeaponClassDef(); weaponClassDef.Class = c; weaponClassDef.Name = name; weaponClassDef.TwoHanded = twoHanded; weaponClassDef.Thrown = thrown; weaponClassDef.Family = (thrown ? WeaponFamily.Thrown : WeaponFamily.Melee); weaponClassDef.Slots = ((slots != 4) ? new PartSlot[3] { PartSlot.Blade, PartSlot.Handle, PartSlot.Pommel } : new PartSlot[4] { PartSlot.Blade, PartSlot.Guard, PartSlot.Handle, PartSlot.Pommel }); weaponClassDef.SlotNames = ((!flag) ? ((!flag2) ? new string[4] { "Blade", "Guard", "Grip", "Pommel" } : new string[4] { "Head", "", "Handle", "Butt" }) : new string[4] { "Head", "", "Shaft", "Butt" }); weaponClassDef.Swing = swing; weaponClassDef.Thrust = thrust; weaponClassDef.Missile = missile; weaponClassDef.Grip = grip; weaponClassDef.InertiaScale = inertiaScale; weaponClassDef.BaseValue = baseValue; return weaponClassDef; } public static WeaponClassDef ClassDef(WeaponClass c) { return Classes[(int)c]; } public static string ClassKey(WeaponClass c) { return c.ToString(); } public static bool TryParseClass(string key, out WeaponClass c) { if (Enum.TryParse(key, ignoreCase: false, out c)) { return Enum.IsDefined(typeof(WeaponClass), c); } return false; } private static Shape S(string name, double length, double weight, double cut = 0.0, double pierce = 0.0, double blunt = 0.0, double balance = 0.4, double width = 1.0) { return new Shape { Name = name, Length = length, Weight = weight, Cut = cut, Pierce = pierce, Blunt = blunt, Balance = balance, Width = width }; } private static Shape H(string name, double length, double weight, double handling, double width = 1.0) { return new Shape { Name = name, Length = length, Weight = weight, Handling = handling, Width = width }; } private static Dictionary ShapeTable() { Shape[] array = new Shape[4] { H("Bar", 3.0, 0.15, 3.0), H("Curved", 3.0, 0.18, 4.0), H("Disc", 2.0, 0.12, 2.0), H("Winged", 4.0, 0.22, 5.0) }; Shape[] array2 = new Shape[4] { H("Wrapped", 12.0, 0.15, 2.0), H("Leather", 13.0, 0.16, 3.0), H("Corded", 11.0, 0.14, 2.0), H("Long", 16.0, 0.2, 1.0) }; Shape[] array3 = new Shape[4] { H("Wheel", 4.0, 0.15, 0.0), H("Disc", 3.0, 0.12, 0.0), H("Pear", 5.0, 0.18, 0.0), H("Knob", 3.0, 0.1, 0.0) }; Shape[] array4 = new Shape[4] { H("Plain", 3.0, 0.05, 0.0), H("Capped", 3.0, 0.08, 0.0), H("Knob", 4.0, 0.08, 0.0), H("Spike", 4.0, 0.07, 0.0) }; Shape[] array5 = new Shape[4] { H("Spike", 6.0, 0.2, 0.0), H("Cap", 5.0, 0.15, 0.0), H("Ring", 4.0, 0.12, 0.0), H("Knob", 5.0, 0.18, 0.0) }; Shape[] array6 = new Shape[4] { H("Ring", 2.0, 0.02, 0.0), H("Knob", 2.0, 0.03, 0.0), H("Disc", 2.0, 0.02, 0.0), H("Cap", 2.0, 0.02, 0.0) }; Dictionary dictionary = new Dictionary(); dictionary[WeaponClass.OneHandedSword] = new Shape[4][] { new Shape[6] { S("Leaf", 72.0, 0.95, 1.0, 1.05, 0.0, 0.38, 0.9), S("Arming", 80.0, 1.0, 1.0, 1.0, 0.0, 0.38), S("Broad", 78.0, 1.15, 1.1, 0.85, 0.0, 0.4, 1.2), S("Tapered", 84.0, 0.95, 0.92, 1.2, 0.0, 0.36, 0.85), S("Falchion", 74.0, 1.1, 1.2, 0.7, 0.0, 0.45, 1.3), S("Spatha", 88.0, 1.1, 1.02, 0.95, 0.0, 0.38) }, array, array2, array3 }; dictionary[WeaponClass.TwoHandedSword] = new Shape[4][] { new Shape[6] { S("Long", 105.0, 1.7, 1.0, 1.0, 0.0, 0.38), S("Great", 112.0, 1.9, 1.08, 0.9, 0.0, 0.4, 1.1), S("Bastard", 98.0, 1.55, 1.0, 1.05, 0.0, 0.38), S("Wavy", 108.0, 1.8, 1.12, 0.85, 0.0, 0.4, 1.1), S("Estoc", 110.0, 1.6, 0.8, 1.3, 0.0, 0.36, 0.8), S("Heavy", 115.0, 2.1, 1.15, 0.8, 0.0, 0.42, 1.2) }, new Shape[4] { H("Bar", 4.0, 0.25, 3.0), H("Swept", 5.0, 0.3, 4.0), H("Ringed", 4.0, 0.28, 4.0), H("Broad", 5.0, 0.32, 5.0) }, new Shape[4] { H("Long Wrapped", 28.0, 0.3, 2.0), H("Leather", 30.0, 0.32, 3.0), H("Hand-and-a-half", 24.0, 0.26, 2.0), H("Grand", 34.0, 0.38, 1.0) }, new Shape[4] { H("Wheel", 5.0, 0.25, 0.0), H("Pear", 6.0, 0.3, 0.0), H("Faceted", 5.0, 0.28, 0.0), H("Knob", 4.0, 0.2, 0.0) } }; dictionary[WeaponClass.Dagger] = new Shape[4][] { new Shape[6] { S("Leaf", 26.0, 0.22, 1.5, 1.3), S("Spike", 30.0, 0.2, 0.8, 1.7, 0.0, 0.38, 0.6), S("Broad", 24.0, 0.28, 1.7, 1.0, 0.0, 0.42, 1.3), S("Curved", 27.0, 0.24, 1.8, 0.9, 0.0, 0.45, 1.1), S("Needle", 32.0, 0.22, 0.7, 1.8, 0.0, 0.36, 0.5), S("Notched", 28.0, 0.26, 1.6, 1.1, 0.0, 0.42) }, new Shape[4] { H("Bar", 2.0, 0.06, 4.0), H("Lugged", 2.0, 0.07, 5.0), H("Disc", 2.0, 0.05, 3.0), H("Cross", 2.0, 0.08, 5.0) }, new Shape[4] { H("Wrapped", 10.0, 0.08, 3.0), H("Bone", 10.0, 0.09, 4.0), H("Corded", 9.0, 0.07, 3.0), H("Wooden", 11.0, 0.08, 2.0) }, new Shape[4] { H("Knob", 3.0, 0.06, 0.0), H("Disc", 3.0, 0.05, 0.0), H("Ring", 3.0, 0.04, 0.0), H("Cap", 2.0, 0.05, 0.0) } }; dictionary[WeaponClass.OneHandedAxe] = new Shape[4][] { new Shape[6] { S("Bearded", 15.0, 0.8, 1.25, 0.0, 0.0, 0.5), S("Narrow", 12.0, 0.7, 1.15, 0.0, 0.0, 0.5, 0.8), S("Broad", 18.0, 0.95, 1.35, 0.0, 0.0, 0.5, 1.3), S("Hooked", 14.0, 0.85, 1.2, 0.0, 0.0, 0.5), S("Crescent", 16.0, 0.9, 1.3, 0.0, 0.0, 0.5, 1.2), S("Spiked", 13.0, 0.85, 1.1, 0.0, 0.0, 0.5, 0.9) }, new Shape[0], new Shape[4] { H("Ash", 60.0, 0.4, 1.0), H("Oak", 62.0, 0.45, 1.0), H("Short", 52.0, 0.35, 2.0), H("Wrapped", 58.0, 0.4, 2.0) }, array4 }; dictionary[WeaponClass.TwoHandedAxe] = new Shape[4][] { new Shape[6] { S("Great Bearded", 20.0, 1.4, 1.3, 0.0, 0.0, 0.5), S("Long-Bladed", 22.0, 1.3, 1.35, 0.0, 0.0, 0.5, 1.1), S("Broad", 24.0, 1.6, 1.4, 0.0, 0.0, 0.5, 1.4), S("Crescent", 22.0, 1.5, 1.38, 0.0, 0.0, 0.5, 1.3), S("Narrow", 18.0, 1.2, 1.25, 0.0, 0.0, 0.5, 0.8), S("Hooked", 20.0, 1.45, 1.3, 0.0, 0.0, 0.5) }, new Shape[0], new Shape[4] { H("Long Ash", 95.0, 0.8, 1.0), H("Long Oak", 100.0, 0.9, 1.0), H("Banded", 90.0, 0.85, 2.0), H("Wrapped", 92.0, 0.8, 2.0) }, array4 }; dictionary[WeaponClass.Mace] = new Shape[4][] { new Shape[6] { S("Flanged", 14.0, 1.0, 0.0, 0.0, 0.85, 0.5), S("Knobbed", 12.0, 0.95, 0.0, 0.0, 0.8, 0.5), S("Spiked", 14.0, 1.05, 0.0, 0.0, 0.9, 0.5), S("Ball", 12.0, 1.1, 0.0, 0.0, 0.85, 0.5, 1.1), S("Studded", 13.0, 1.0, 0.0, 0.0, 0.82, 0.5), S("Winged", 15.0, 1.15, 0.0, 0.0, 0.95, 0.5, 1.2) }, new Shape[0], new Shape[4] { H("Wooden", 55.0, 0.35, 1.0), H("Iron-Bound", 55.0, 0.45, 1.0), H("Wrapped", 52.0, 0.35, 2.0), H("Long", 62.0, 0.4, 1.0) }, array4 }; dictionary[WeaponClass.TwoHandedMace] = new Shape[4][] { new Shape[6] { S("Great Flanged", 20.0, 1.8, 0.0, 0.0, 0.9, 0.5), S("Starred", 18.0, 1.7, 0.0, 0.0, 0.95, 0.5), S("Maul", 22.0, 2.1, 0.0, 0.0, 1.0, 0.5, 1.4), S("Knobbed", 18.0, 1.6, 0.0, 0.0, 0.88, 0.5), S("Spiked", 20.0, 1.85, 0.0, 0.0, 0.93, 0.5), S("Club", 30.0, 1.5, 0.0, 0.0, 0.8, 0.55, 0.9) }, new Shape[0], new Shape[4] { H("Long Wooden", 90.0, 0.8, 1.0), H("Iron-Bound", 88.0, 0.95, 1.0), H("Wrapped", 85.0, 0.8, 2.0), H("Long", 98.0, 0.9, 1.0) }, array4 }; dictionary[WeaponClass.Pike] = new Shape[4][] { new Shape[6] { S("Leaf", 25.0, 0.4, 0.0, 1.6), S("Spike", 28.0, 0.35, 0.0, 1.7, 0.0, 0.4, 0.6), S("Awl", 30.0, 0.38, 0.0, 1.75, 0.0, 0.4, 0.5), S("Broad", 24.0, 0.45, 0.0, 1.5, 0.0, 0.4, 1.3), S("Barbed", 26.0, 0.42, 0.0, 1.6), S("Lugged", 27.0, 0.46, 0.0, 1.55, 0.0, 0.4, 1.1) }, new Shape[0], new Shape[4] { H("Ash", 280.0, 2.6, 0.0), H("Long Ash", 320.0, 2.9, 0.0), H("Banded", 290.0, 2.8, 1.0), H("Light", 260.0, 2.3, 1.0) }, array5 }; dictionary[WeaponClass.TwoHandedPolearm] = new Shape[4][] { new Shape[6] { S("Glaive", 55.0, 1.5, 1.1, 1.0), S("Bill", 50.0, 1.6, 1.05, 1.1), S("Halberd", 45.0, 1.8, 1.2, 1.15, 0.0, 0.38, 1.3), S("Voulge", 55.0, 1.7, 1.15, 0.9, 0.0, 0.42, 1.2), S("Partisan", 50.0, 1.3, 0.95, 1.3, 0.0, 0.38, 0.9), S("Long Glaive", 58.0, 1.5, 1.12, 0.95, 0.0, 0.42) }, new Shape[0], new Shape[4] { H("Ash", 170.0, 1.6, 0.0), H("Oak", 175.0, 1.8, 0.0), H("Banded", 165.0, 1.7, 1.0), H("Long", 190.0, 1.8, 0.0) }, array5 }; dictionary[WeaponClass.Javelin] = new Shape[4][] { new Shape[6] { S("Leaf", 18.0, 0.25, 0.0, 1.6), S("Pyramid", 14.0, 0.2, 0.0, 1.7, 0.0, 0.4, 0.6), S("Barbed", 16.0, 0.25, 0.0, 1.75), S("Long Iron", 40.0, 0.45, 0.0, 1.85, 0.0, 0.45, 0.5), S("Socketed", 17.0, 0.22, 0.0, 1.65), S("Needle", 20.0, 0.22, 0.0, 1.8, 0.0, 0.4, 0.5) }, new Shape[0], new Shape[4] { H("Ash", 110.0, 0.6, 2.0), H("Light", 100.0, 0.5, 3.0), H("Heavy", 120.0, 0.75, 1.0), H("Wrapped", 105.0, 0.6, 3.0) }, new Shape[4] { H("Plain", 2.0, 0.03, 0.0), H("Weighted", 3.0, 0.08, 0.0), H("Capped", 2.0, 0.05, 0.0), H("Fletched", 4.0, 0.03, 1.0) } }; dictionary[WeaponClass.ThrowingKnife] = new Shape[4][] { new Shape[6] { S("Leaf", 16.0, 0.12, 0.0, 1.3), S("Spike", 18.0, 0.1, 0.0, 1.45, 0.0, 0.4, 0.6), S("Broad", 14.0, 0.14, 0.0, 1.25, 0.0, 0.42, 1.3), S("Curved", 16.0, 0.13, 0.0, 1.3, 0.0, 0.45, 1.1), S("Needle", 19.0, 0.1, 0.0, 1.5, 0.0, 0.38, 0.5), S("Notched", 15.0, 0.13, 0.0, 1.35, 0.0, 0.42) }, new Shape[4] { H("Bar", 1.0, 0.03, 4.0), H("Nub", 1.0, 0.01, 5.0), H("Disc", 1.0, 0.02, 4.0), H("Cross", 1.0, 0.03, 4.0) }, new Shape[4] { H("Wrapped", 8.0, 0.04, 3.0), H("Bone", 8.0, 0.05, 4.0), H("Corded", 7.0, 0.04, 3.0), H("Wooden", 9.0, 0.04, 2.0) }, array6 }; dictionary[WeaponClass.ThrowingAxe] = new Shape[4][] { new Shape[6] { S("Curved", 12.0, 0.5, 1.3, 0.0, 0.0, 0.5), S("Bearded", 12.0, 0.55, 1.25, 0.0, 0.0, 0.5), S("Narrow", 10.0, 0.45, 1.15, 0.0, 0.0, 0.5, 0.8), S("Broad", 14.0, 0.6, 1.35, 0.0, 0.0, 0.5, 1.3), S("Hooked", 12.0, 0.55, 1.2, 0.0, 0.0, 0.5), S("Small", 9.0, 0.4, 1.1, 0.0, 0.0, 0.5, 0.8) }, new Shape[0], new Shape[4] { H("Short Ash", 40.0, 0.25, 2.0), H("Oak", 42.0, 0.3, 1.0), H("Wrapped", 38.0, 0.25, 3.0), H("Curved", 41.0, 0.28, 2.0) }, array4 }; return dictionary.Concat(ArmsShapes()).ToDictionary((KeyValuePair x) => x.Key, (KeyValuePair x) => x.Value); } public static SmithingPartDef Part(string id) { if (id == null || !PartIndex.TryGetValue(id, out var value)) { return null; } return value; } public static IEnumerable PartsFor(WeaponClass c, PartSlot slot) { return Parts.Where((SmithingPartDef p) => p.Class == c && p.Slot == slot); } private static List BuildParts() { List list = new List(); foreach (KeyValuePair item in ShapeTable()) { WeaponClassDef weaponClassDef = ClassDef(item.Key); for (int i = 0; i < 4; i++) { PartSlot slot = (PartSlot)i; if (!weaponClassDef.Uses(slot)) { continue; } Shape[] array = item.Value[i]; for (int j = 0; j < array.Length; j++) { for (int k = 1; k <= 5; k++) { list.Add(MakePart(weaponClassDef, slot, array[j], j, k)); } } } } return list; } private static SmithingPartDef MakePart(WeaponClassDef def, PartSlot slot, Shape shape, int shapeIndex, int tier) { bool flag = slot == PartSlot.Handle; string[] array = ((def.Family >= WeaponFamily.Shield) ? ArmsTierWords(def, slot, shape) : ((slot == PartSlot.Blade) ? MetalTierWords : (flag ? WoodTierWords : FittingTierWords))); string text = def.SlotNames[(int)slot]; SmithingPartDef smithingPartDef = new SmithingPartDef(); string[] obj = new string[8] { "part.", ClassKey(def.Class).ToLowerInvariant(), ".", null, null, null, null, null }; int num = (int)slot; obj[3] = num.ToString(); obj[4] = "."; obj[5] = shapeIndex.ToString(); obj[6] = "."; obj[7] = tier.ToString(); smithingPartDef.Id = string.Concat(obj); smithingPartDef.Name = array[tier - 1] + " " + shape.Name + " " + text; smithingPartDef.Class = def.Class; smithingPartDef.Slot = slot; smithingPartDef.Shape = shape.Name; smithingPartDef.ShapeIndex = shapeIndex; smithingPartDef.Tier = tier; smithingPartDef.Length = shape.Length; smithingPartDef.Weight = Math.Round(shape.Weight * TierWeight[tier - 1], 3); smithingPartDef.Width = shape.Width; smithingPartDef.Cut = shape.Cut; smithingPartDef.Pierce = shape.Pierce; smithingPartDef.Blunt = shape.Blunt; smithingPartDef.Balance = shape.Balance; smithingPartDef.Handling = shape.Handling + ((slot == PartSlot.Blade) ? 0.0 : ((double)(tier - 1) * 0.75)); smithingPartDef.Breadth = shape.Breadth; smithingPartDef.Toughness = shape.Toughness; smithingPartDef.Draw = shape.Draw; smithingPartDef.Accuracy = shape.Accuracy; smithingPartDef.Cap = shape.Cap; smithingPartDef.GivenByDefault = tier == 1 && (shapeIndex == 0 || (slot == PartSlot.Blade && shapeIndex == 1)); SmithingPartDef smithingPartDef2 = smithingPartDef; if (def.Family >= WeaponFamily.Shield) { AddArmsMaterials(smithingPartDef2, def, shape); } else { AddPartMaterials(smithingPartDef2, def); } return smithingPartDef2; } private static void AddPartMaterials(SmithingPartDef part, WeaponClassDef def) { int tier = part.Tier; switch (part.Slot) { case PartSlot.Blade: { bool flag2 = def.Class == WeaponClass.Dagger || def.Class == WeaponClass.ThrowingKnife || def.Class == WeaponClass.Javelin || def.Class == WeaponClass.Pike || def.Class == WeaponClass.ThrowingAxe; bool flag3 = def.TwoHanded && !flag2; SmithingMaterial m; SmithingMaterial m2; switch (tier) { case 1: m = (m2 = SmithingMaterial.WroughtIron); break; case 2: m = (m2 = SmithingMaterial.Iron); break; case 3: m = SmithingMaterial.Iron; m2 = SmithingMaterial.Steel; break; case 4: m = SmithingMaterial.Steel; m2 = SmithingMaterial.FineSteel; break; default: m = SmithingMaterial.FineSteel; m2 = SmithingMaterial.Thamaskene; break; } if (flag2) { Add(m2, 1); break; } Add(m, 1); Add(m2, 1); if (flag3) { Add(m, 1); } break; } case PartSlot.Handle: { bool flag = def.Class == WeaponClass.Pike || def.Class == WeaponClass.TwoHandedPolearm; Add(SmithingMaterial.Hardwood, (def.Class == WeaponClass.Pike) ? 3 : ((!flag && !def.TwoHanded) ? 1 : 2)); if (tier >= 2) { Add(FittingMetal[tier - 2], 1); } break; } default: Add(FittingMetal[tier - 1], 1); break; } void Add(SmithingMaterial key, int n) { if (n > 0) { part.Materials[key] = (part.Materials.TryGetValue(key, out var value) ? value : 0) + n; } } } public static string DesignReason(WeaponClass c, IList partIds) { if (!Enum.IsDefined(typeof(WeaponClass), c)) { return "Unknown weapon type."; } if (partIds == null || partIds.Count != 4) { return "Choose every part of the weapon."; } WeaponClassDef weaponClassDef = ClassDef(c); for (int i = 0; i < 4; i++) { PartSlot partSlot = (PartSlot)i; string text = partIds[i] ?? ""; if (!weaponClassDef.Uses(partSlot)) { if (text.Length > 0) { return "This weapon type has no " + partSlot.ToString().ToLowerInvariant() + "."; } continue; } SmithingPartDef smithingPartDef = Part(text); if (smithingPartDef == null) { return "Choose a " + weaponClassDef.SlotNames[i].ToLowerInvariant() + "."; } if (smithingPartDef.Class != c || smithingPartDef.Slot != partSlot) { return smithingPartDef.Name + " does not fit this weapon."; } } return ""; } public static IEnumerable DesignParts(IList partIds) { return from p in (partIds ?? new string[0]).Select(Part) where p != null select p; } public static WeaponStats Stats(WeaponClass c, IList partIds) { WeaponClassDef weaponClassDef = ClassDef(c); if (weaponClassDef.Family >= WeaponFamily.Shield) { return ArmsStats(weaponClassDef, partIds); } SmithingPartDef smithingPartDef = Part(partIds[0]); SmithingPartDef smithingPartDef2 = (weaponClassDef.Uses(PartSlot.Guard) ? Part(partIds[1]) : null); SmithingPartDef smithingPartDef3 = Part(partIds[2]); SmithingPartDef smithingPartDef4 = Part(partIds[3]); double num = smithingPartDef.Length / 100.0; double num2 = (smithingPartDef2?.Length ?? 0.0) / 100.0; double num3 = smithingPartDef3.Length / 100.0; double num4 = smithingPartDef4.Length / 100.0; double grip = weaponClassDef.Grip; List<(double, double, double)> list = new List<(double, double, double)> { (smithingPartDef.Weight, grip * num3 + num2 + num * smithingPartDef.Balance, num), (smithingPartDef3.Weight, (0.5 - grip) * num3, num3), (smithingPartDef4.Weight, 0.0 - ((1.0 - grip) * num3 + num4 / 2.0), num4) }; if (smithingPartDef2 != null) { list.Add((smithingPartDef2.Weight, grip * num3 + num2 / 2.0, num2)); } double num5 = list.Sum<(double, double, double)>(((double m, double d, double l) tuple) => tuple.m); double num6 = list.Sum<(double, double, double)>(((double m, double d, double l) tuple) => tuple.m * tuple.d * tuple.d + tuple.m * tuple.l * tuple.l / 12.0) / weaponClassDef.InertiaScale; double value = list.Sum<(double, double, double)>(((double m, double d, double l) tuple) => tuple.m * tuple.d) / num5; double num7 = TierDamage[smithingPartDef.Tier - 1]; WeaponStats weaponStats = new WeaponStats { Length = Math.Round(smithingPartDef.Length + (smithingPartDef2?.Length ?? 0.0) + smithingPartDef3.Length + smithingPartDef4.Length), Weight = Math.Round(num5, 2) }; double num8 = Clamp(125.0 - 58.0 * Math.Pow(num6, 0.38) + (double)(weaponClassDef.TwoHanded ? 8 : 0), 40.0, 120.0); double num9 = Clamp(112.0 - 28.0 * Math.Pow(num5, 0.6) + (double)(weaponClassDef.TwoHanded ? 6 : 0), 40.0, 120.0); double a = Clamp(0.75 * num8 + 15.0 + (smithingPartDef2?.Handling ?? 0.0) + smithingPartDef3.Handling - 15.0 * Math.Abs(value), 30.0, 120.0); weaponStats.Handling = Math.Round(a); if (weaponClassDef.Thrown) { weaponStats.MissileKind = weaponClassDef.Missile; double num10 = ((weaponClassDef.Missile == DamageKind.Cut) ? smithingPartDef.Cut : smithingPartDef.Pierce); weaponStats.MissileSpeed = Math.Round(Clamp(31.0 - 4.5 * num5, 16.0, 32.0), 1); weaponStats.MissileDamage = Math.Round((14.0 + 26.0 * Math.Pow(num5, 0.7)) * num10 * num7, 1); weaponStats.Accuracy = Math.Round(Clamp(68.0 + (smithingPartDef2?.Handling ?? 0.0) + smithingPartDef3.Handling + smithingPartDef4.Handling - 6.0 * num5, 50.0, 100.0)); return weaponStats; } double num11 = num8 * 0.1; double x = 0.5 * num6 * num11 * num11; if (weaponClassDef.Swing != DamageKind.None) { double num12 = ((weaponClassDef.Swing == DamageKind.Blunt) ? smithingPartDef.Blunt : smithingPartDef.Cut); weaponStats.SwingKind = weaponClassDef.Swing; weaponStats.SwingSpeed = Math.Round(num8); weaponStats.SwingDamage = Math.Round((6.0 + 9.0 * Math.Pow(x, 0.6)) * num12 * num7, 1); } if (weaponClassDef.Thrust != DamageKind.None && smithingPartDef.Pierce > 0.0) { weaponStats.ThrustKind = weaponClassDef.Thrust; weaponStats.ThrustSpeed = Math.Round(num9); weaponStats.ThrustDamage = Math.Round((5.0 + 14.0 * Math.Sqrt(num5) * num9 / 80.0) * smithingPartDef.Pierce * num7, 1); } return weaponStats; } private static double Clamp(double v, double lo, double hi) { return Math.Max(lo, Math.Min(hi, v)); } public static double AveragePartTier(IList partIds) { double num = 0.0; double num2 = 0.0; foreach (SmithingPartDef item in DesignParts(partIds)) { num += (double)item.Tier * SlotDifficultyWeight[(int)item.Slot]; num2 += SlotDifficultyWeight[(int)item.Slot]; } if (!(num2 <= 0.0)) { return num / num2; } return 1.0; } public static int Difficulty(IList partIds) { return (int)Math.Round(50.0 * AveragePartTier(partIds)); } public static double AttackScore(WeaponStats s) { if (!(s.HitPoints > 0.0)) { if (!(s.DrawSpeed > 0.0)) { if (s.MissileKind == DamageKind.None || !(s.MissileSpeed <= 0.0)) { if (s.MissileKind == DamageKind.None) { return Math.Max(s.SwingDamage * s.SwingSpeed, s.ThrustDamage * s.ThrustSpeed) / 100.0; } return s.MissileDamage * s.MissileSpeed / 30.0; } return AmmoScore(s); } return LauncherScore(s); } return ShieldScore(s); } private static Dictionary BuildAttackRanges() { Dictionary dictionary = new Dictionary(); foreach (WeaponClassDef def in Classes) { double num = double.MaxValue; double num2 = 0.0; int[] array = new int[2] { 1, 5 }; foreach (int tier in array) { foreach (SmithingPartDef item in Parts.Where((SmithingPartDef p) => p.Class == def.Class && p.Slot == PartSlot.Blade && p.Tier == tier)) { string[] array2 = new string[4] { item.Id, null, null, null }; foreach (PartSlot slot in def.Slots.Where((PartSlot x) => x != PartSlot.Blade)) { array2[(int)slot] = Parts.First((SmithingPartDef p) => p.Class == def.Class && p.Slot == slot && p.Tier == tier).Id; } for (int num3 = 0; num3 < 4; num3++) { if (array2[num3] == null) { array2[num3] = ""; } } double val = AttackScore(Stats(def.Class, array2)); num = Math.Min(num, val); num2 = Math.Max(num2, val); } } dictionary[def.Class] = (num, Math.Max(num + 1E-06, num2)); } return dictionary; } public static double TierScore(WeaponClass c, WeaponStats s, IList partIds) { (double, double) tuple = AttackRange[c]; double num = 1.0 + 5.0 * Clamp((AttackScore(s) - tuple.Item1) / (tuple.Item2 - tuple.Item1), 0.0, 1.0); double num2 = 1.0 + (AveragePartTier(partIds) - 1.0) * 1.25; return Clamp(0.6 * num + 0.4 * num2, 1.0, 6.0); } public static int WeaponTier(double tierScore) { return (int)Clamp(Math.Round(tierScore), 1.0, 6.0); } public static long Value(WeaponClass c, double tierScore, WeaponQuality quality) { return Math.Max(1L, (long)Math.Round(ClassDef(c).BaseValue * Math.Pow(2.75, tierScore - 1.0) * QualityPrice(quality))); } public static SortedDictionary CraftingCost(IList partIds) { SortedDictionary sortedDictionary = new SortedDictionary { [SmithingMaterial.Charcoal] = 1 }; foreach (SmithingPartDef item in DesignParts(partIds)) { foreach (KeyValuePair material in item.Materials) { sortedDictionary[material.Key] = (sortedDictionary.TryGetValue(material.Key, out var value) ? value : 0) + material.Value; } } return sortedDictionary; } public static SortedDictionary SmeltingYield(IList partIds) { SortedDictionary sortedDictionary = new SortedDictionary(); foreach (SmithingPartDef item in DesignParts(partIds)) { foreach (KeyValuePair material in item.Materials) { sortedDictionary[material.Key] = (sortedDictionary.TryGetValue(material.Key, out var value) ? value : 0) + material.Value; } } Downgrade(sortedDictionary); return sortedDictionary; } private static void Downgrade(SortedDictionary yield) { for (SmithingMaterial smithingMaterial = SmithingMaterial.Thamaskene; smithingMaterial > SmithingMaterial.CrudeIron; smithingMaterial--) { if (yield.TryGetValue(smithingMaterial, out var value) && value > 0) { if (value == 1) { yield.Remove(smithingMaterial); } else { yield[smithingMaterial] = value - 1; } yield[smithingMaterial - 1] = (yield.TryGetValue(smithingMaterial - 1, out var value2) ? value2 : 0) + 1; break; } } } public static bool KitSmelting(string kitId, out WeaponClass taught, out SortedDictionary yield) { yield = new SortedDictionary(); taught = WeaponClass.OneHandedSword; switch (kitId) { case "eq.weapon.club": taught = WeaponClass.Mace; yield[SmithingMaterial.Hardwood] = 2; yield[SmithingMaterial.CrudeIron] = 1; return true; case "eq.weapon.sword": taught = WeaponClass.OneHandedSword; yield[SmithingMaterial.WroughtIron] = 2; yield[SmithingMaterial.CrudeIron] = 1; return true; case "eq.weapon.bow": taught = WeaponClass.Bow; yield[SmithingMaterial.Hardwood] = 2; yield[SmithingMaterial.Flax] = 1; return true; case "eq.weapon.javelin": taught = WeaponClass.Javelin; yield[SmithingMaterial.Hardwood] = 1; yield[SmithingMaterial.WroughtIron] = 1; return true; case "eq.weapon.axe_shield": taught = WeaponClass.OneHandedAxe; yield[SmithingMaterial.WroughtIron] = 2; yield[SmithingMaterial.Hardwood] = 1; yield[SmithingMaterial.CrudeIron] = 1; return true; case "eq.weapon.knight_kit": taught = WeaponClass.OneHandedSword; yield[SmithingMaterial.Iron] = 2; yield[SmithingMaterial.WroughtIron] = 2; yield[SmithingMaterial.CrudeIron] = 1; return true; case "eq.weapon.knight_sword": taught = WeaponClass.OneHandedSword; yield[SmithingMaterial.Iron] = 1; yield[SmithingMaterial.WroughtIron] = 1; yield[SmithingMaterial.CrudeIron] = 1; return true; case "eq.weapon.bearded_axe": taught = WeaponClass.OneHandedAxe; yield[SmithingMaterial.WroughtIron] = 1; yield[SmithingMaterial.Hardwood] = 1; yield[SmithingMaterial.CrudeIron] = 1; return true; case "eq.shield.knight": taught = WeaponClass.Shield; yield[SmithingMaterial.Hardwood] = 1; yield[SmithingMaterial.Iron] = 1; yield[SmithingMaterial.WroughtIron] = 1; return true; case "eq.shield.round": taught = WeaponClass.Shield; yield[SmithingMaterial.Hardwood] = 2; yield[SmithingMaterial.CrudeIron] = 1; return true; default: return false; } } public static double MaximumStamina(int skill) { return 100.0 + Math.Round(0.5 * (double)Math.Max(0, skill)); } public static double StaminaPerHour(int skill) { return 5.0 + Math.Round(0.025 * (double)Math.Max(0, skill)); } public static double ForgingStamina(int weaponTier, bool practicalSmith) { return (double)(10 + 5 * (Math.Max(1, weaponTier) - 1)) * (practicalSmith ? 0.5 : 1.0); } public static double RefineStamina(bool practicalRefiner) { return 6.0 * (practicalRefiner ? 0.5 : 1.0); } public static double SmeltStamina(bool practicalSmelter) { return 10.0 * (practicalSmelter ? 0.5 : 1.0); } public static double ForgingXp(long value) { return 0.2 * (double)value; } public static double SmeltingXp(long value) { return 0.2 * (double)value; } public static double OrderXp(long craftedValue, long orderValue, bool success) { return ((double)craftedValue + 0.25 * (double)orderValue) * (success ? 1.0 : 0.5); } public static int ForgingResearch(long value, bool curiousSmith, bool freeBuild) { return 1 + (int)Math.Floor(0.5 * (double)value * ((double)(1 + (curiousSmith ? 1 : 0)) + (freeBuild ? 0.1 : 0.0))); } public static int SmeltingResearch(long value, bool curiousSmelter) { return (1 + (int)Math.Round(0.1 * (double)value)) * ((!curiousSmelter) ? 1 : 2); } public static int ResearchForNextPart(int totalParts, int learnedParts) { return (int)Math.Ceiling(Math.Sqrt(100.0 / (double)Math.Max(1, totalParts)) * (double)(learnedParts * 9 + 10)); } public static double QualityPrice(WeaponQuality q) { return QualityPriceFactor[(int)q]; } public static double QualityDamage(WeaponQuality q) { return QualityDamageFactor[(int)q]; } public static void CombatRatings(UnitDef basis, WeaponClass c, double tierScore, WeaponQuality quality, out double attack, out double defense, out double ranged) { WeaponClassDef weaponClassDef = ClassDef(c); double num = Clamp(double.IsNaN(tierScore) ? 1.0 : tierScore, 1.0, 6.0); double num2 = basis?.Attack ?? 1.0; double num3 = basis?.Defense ?? 1.0; double num4 = basis?.Ranged ?? 0.0; if (weaponClassDef.Launcher) { attack = num2; defense = num3; ranged = Math.Round(((weaponClassDef.Family == WeaponFamily.Crossbow) ? (0.7 + 0.15 * (num - 1.0)) : (0.6 + 0.14 * (num - 1.0))) * QualityDamage(quality), 4); } else if (weaponClassDef.Thrown) { attack = num2; defense = num3; ranged = Math.Round((0.5 + 0.12 * (num - 1.0)) * QualityDamage(quality), 4); } else { attack = Math.Round((1.2 + 1.1 * (num - 1.0)) * QualityDamage(quality) * (weaponClassDef.TwoHanded ? 1.1 : 1.0), 4); defense = Math.Round(num3 * (weaponClassDef.TwoHanded ? 0.85 : 1.0), 4); ranged = num4; } } public static void OffhandRatings(CraftedWeaponState shield, CraftedWeaponState ammo, ref double defense, ref double ranged) { if (shield != null && ClassDef(shield.Class).Family == WeaponFamily.Shield) { defense = Math.Round(defense * (1.0 + (0.1 + 0.04 * (Clamp(shield.TierScore, 1.0, 6.0) - 1.0)) * QualityDamage(shield.Quality)), 4); } if (ammo != null && ClassDef(ammo.Class).Family == WeaponFamily.Ammo && ranged > 0.0) { ranged = Math.Round(ranged * (1.0 + 0.04 * Clamp(ammo.TierScore, 1.0, 6.0) * QualityDamage(ammo.Quality)), 4); } } public static string QualityName(WeaponQuality q) { if (q != WeaponQuality.Common) { return q.ToString(); } return ""; } public static WeaponStats Finished(WeaponStats common, WeaponQuality quality, bool sharpenedEdge, bool sharpenedTip) { WeaponStats weaponStats = common.Copy(); double num = QualityDamageFactor[(int)quality]; double num2 = QualitySpeedFactor[(int)quality]; weaponStats.SwingDamage = Math.Round(weaponStats.SwingDamage * num * (sharpenedEdge ? 1.02 : 1.0), 1); weaponStats.ThrustDamage = Math.Round(weaponStats.ThrustDamage * num * (sharpenedTip ? 1.02 : 1.0), 1); weaponStats.MissileDamage = Math.Round(weaponStats.MissileDamage * num * (sharpenedTip ? 1.02 : 1.0), 1); weaponStats.SwingSpeed = Math.Round(Math.Min(120.0, weaponStats.SwingSpeed * num2)); weaponStats.ThrustSpeed = Math.Round(Math.Min(120.0, weaponStats.ThrustSpeed * num2)); weaponStats.Handling = Math.Round(Math.Min(120.0, weaponStats.Handling * num2)); weaponStats.MissileSpeed = Math.Round(Math.Min((weaponStats.DrawSpeed > 0.0) ? 100 : 40, weaponStats.MissileSpeed * num2), 1); weaponStats.HitPoints = Math.Round(weaponStats.HitPoints * num); weaponStats.DrawSpeed = Math.Round(Math.Min(120.0, weaponStats.DrawSpeed * num2)); return weaponStats; } public static double[] OrderStatValues(WeaponClassDef def, WeaponStats s) { if (def.Family < WeaponFamily.Shield) { if (def.Thrown) { return new double[3] { s.MissileDamage, s.MissileSpeed, s.Accuracy }; } return new double[6] { s.SwingDamage, s.SwingSpeed, s.ThrustDamage, s.ThrustSpeed, s.Handling, s.Length }; } return ArmsOrderValues(def, s); } public static string[] OrderStatNames(WeaponClassDef def) { if (def.Family < WeaponFamily.Shield) { if (def.Thrown) { return new string[3] { "Thrown damage", "Missile speed", "Accuracy" }; } return new string[6] { "Swing damage", "Swing speed", "Thrust damage", "Thrust speed", "Handling", "Length" }; } return ArmsOrderNames(def); } public static string DefaultName(WeaponClass c, IList partIds) { SmithingPartDef smithingPartDef = Part((partIds != null && partIds.Count > 0) ? partIds[0] : null); if (ClassDef(c).Family >= WeaponFamily.Shield) { return ArmsDefaultName(c, smithingPartDef); } SmithingMaterial smithingMaterial = DesignParts(partIds).SelectMany((SmithingPartDef p) => p.Materials.Keys).Where(IsMetal).DefaultIfEmpty(SmithingMaterial.WroughtIron) .Max(); string text = ((smithingMaterial >= SmithingMaterial.Thamaskene) ? "Thamaskene" : ((smithingMaterial >= SmithingMaterial.FineSteel) ? "Fine Steel" : ((smithingMaterial >= SmithingMaterial.Steel) ? "Steel" : ((smithingMaterial >= SmithingMaterial.Iron) ? "Iron" : "Wrought")))); string name = ClassDef(c).Name; name = char.ToUpperInvariant(name[0]) + name.Substring(1); return (text + " " + smithingPartDef?.Shape + " " + name).Replace(" ", " ").Trim(); } private static WeaponClassDef Arms(WeaponClass c, string name, WeaponFamily family, string[] slotNames, double baseValue) { WeaponClassDef weaponClassDef = new WeaponClassDef(); weaponClassDef.Class = c; weaponClassDef.Name = name; weaponClassDef.Family = family; weaponClassDef.TwoHanded = family == WeaponFamily.Bow || family == WeaponFamily.Crossbow; weaponClassDef.Slots = new PartSlot[4] { PartSlot.Blade, PartSlot.Guard, PartSlot.Handle, PartSlot.Pommel }; weaponClassDef.SlotNames = slotNames; weaponClassDef.Swing = ((family == WeaponFamily.Shield) ? DamageKind.Blunt : DamageKind.None); weaponClassDef.Missile = ((family == WeaponFamily.Bow || family == WeaponFamily.Crossbow) ? DamageKind.Pierce : DamageKind.None); weaponClassDef.Grip = 0.5; weaponClassDef.InertiaScale = 1.0; weaponClassDef.BaseValue = baseValue; return weaponClassDef; } public static bool IsArms(WeaponClass c) { return ClassDef(c).Family >= WeaponFamily.Shield; } private static Shape A(string name, double length, double weight, double toughness = 0.0, double handling = 0.0, double breadth = 0.0, double draw = 0.0, double accuracy = 0.0, double cap = 0.0, double cut = 0.0, double pierce = 0.0, double blunt = 0.0, double width = 1.0, params SmithingMaterial[] made) { return new Shape { Name = name, Length = length, Weight = weight, Toughness = toughness, Handling = handling, Breadth = breadth, Draw = draw, Accuracy = accuracy, Cap = cap, Cut = cut, Pierce = pierce, Blunt = blunt, Width = width, Made = ((made == NoMaterials) ? NoMaterials : ((made == null || made.Length == 0) ? null : made)) }; } private static IEnumerable> ArmsShapes() { yield return new KeyValuePair(WeaponClass.Shield, new Shape[4][] { new Shape[8] { A("Round", 80.0, 4.0, 120.0, 0.0, 80.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.785), A("Heater", 85.0, 4.2, 140.0, 2.0, 60.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.8), A("Kite", 115.0, 5.5, 160.0, -4.0, 60.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.7), A("Tower", 120.0, 8.0, 210.0, -10.0, 70.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.95), A("Buckler", 38.0, 1.4, 90.0, 12.0, 38.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.785, SmithingMaterial.Iron), A("Oval", 100.0, 5.0, 150.0, -2.0, 65.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.78), A("Targe", 60.0, 2.6, 110.0, 6.0, 60.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.785), A("Pavise", 130.0, 9.5, 240.0, -14.0, 75.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.95) }, new Shape[5] { A("Rawhide", 3.0, 0.3, 15.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Hides), A("Laced", 3.0, 0.2, 10.0, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Hides), A("Banded", 4.0, 0.8, 30.0, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0), A("Studded", 4.0, 0.6, 25.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0), A("Riveted", 5.0, 1.0, 35.0, -2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0) }, new Shape[5] { A("Painted Linen", 1.0, 0.2, 10.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Flax), A("Leather", 1.0, 0.5, 25.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Hides), A("Felt", 1.0, 0.4, 15.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Wool), A("Rawhide", 2.0, 0.9, 35.0, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Hides, SmithingMaterial.Hides), A("Quilted", 2.0, 0.6, 20.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Wool, SmithingMaterial.Wool) }, new Shape[5] { A("Dome", 14.0, 0.5, 10.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0), A("Spiked", 16.0, 0.6, 5.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.35, 1.0), A("Conical", 15.0, 0.55, 8.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.2, 1.0), A("Flat", 13.0, 0.45, 12.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.9, 1.0), A("Wooden", 12.0, 0.25, 4.0, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.8, 1.0, default(SmithingMaterial)) } }); yield return new KeyValuePair(WeaponClass.Bow, new Shape[4][] { new Shape[12] { A("Self", 150.0, 0.7, 0.0, 6.0, 0.0, 50.0, 2.0, 0.0, 0.0, 0.0, 0.0, 1.0, default(SmithingMaterial), default(SmithingMaterial)), A("Longbow", 185.0, 0.9, 0.0, 0.0, 0.0, 75.0, 4.0, 0.0, 0.0, 0.0, 0.0, 1.0, default(SmithingMaterial), default(SmithingMaterial), default(SmithingMaterial)), A("Flat", 160.0, 0.75, 0.0, 5.0, 0.0, 55.0, 3.0, 0.0, 0.0, 0.0, 0.0, 1.0, default(SmithingMaterial), default(SmithingMaterial)), A("Recurve", 130.0, 0.7, 0.0, 8.0, 0.0, 62.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Hardwood, SmithingMaterial.Hides), A("Composite", 120.0, 0.75, 0.0, 7.0, 0.0, 72.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Hardwood, SmithingMaterial.Hides, SmithingMaterial.Hides), A("Horn", 115.0, 0.8, 0.0, 6.0, 0.0, 80.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Hardwood, SmithingMaterial.Hides, SmithingMaterial.Hides), A("Hunting", 140.0, 0.55, 0.0, 12.0, 0.0, 42.0, 4.0, 0.0, 0.0, 0.0, 0.0, 1.0, default(SmithingMaterial)), A("War", 178.0, 1.0, 0.0, -6.0, 0.0, 92.0, 2.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Hardwood, SmithingMaterial.Hardwood, SmithingMaterial.Hardwood, SmithingMaterial.Hides), A("Yumi", 220.0, 0.95, 0.0, -2.0, 0.0, 70.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Hardwood, SmithingMaterial.Hardwood, SmithingMaterial.Flax), A("Scythian", 110.0, 0.6, 0.0, 10.0, 0.0, 64.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Hardwood, SmithingMaterial.Hides, SmithingMaterial.Hides), A("Mongol", 125.0, 0.85, 0.0, 5.0, 0.0, 86.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Hardwood, SmithingMaterial.Hides, SmithingMaterial.Hides, SmithingMaterial.Hides), A("Short", 100.0, 0.45, 0.0, 14.0, 0.0, 40.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, default(SmithingMaterial)) }, new Shape[8] { A("Wrapped", 12.0, 0.05, 0.0, 3.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Flax), A("Leather", 12.0, 0.06, 0.0, 4.0, 0.0, 0.0, 3.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Hides), A("Corded", 12.0, 0.05, 0.0, 2.0, 0.0, 0.0, 4.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Flax), A("Felted", 12.0, 0.05, 0.0, 5.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Wool), A("Riser", 16.0, 0.15, 0.0, 0.0, 0.0, 0.0, 7.0, 0.0, 0.0, 0.0, 0.0, 1.0, default(SmithingMaterial)), A("Arrow Shelf", 17.0, 0.14, 0.0, 1.0, 0.0, 0.0, 6.0, 0.0, 0.0, 0.0, 0.0, 1.0, default(SmithingMaterial)), A("Bone Plate", 13.0, 0.1, 0.0, 2.0, 0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Hides), A("Fur", 13.0, 0.08, 0.0, 6.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Wool) }, new Shape[8] { A("Linen", 1.0, 0.02, 0.0, 2.0, 0.0, 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Flax), A("Hemp", 1.0, 0.02, 0.0, 5.0, 0.0, 97.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Flax), A("Sinew", 1.0, 0.03, 0.0, 0.0, 0.0, 105.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Hides), A("Silk", 1.0, 0.02, 0.0, 3.0, 0.0, 108.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Flax, SmithingMaterial.Flax), A("Waxed", 1.0, 0.02, 0.0, 2.0, 0.0, 103.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Flax, SmithingMaterial.Wool), A("Flemish", 1.0, 0.03, 0.0, 3.0, 0.0, 104.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Flax, SmithingMaterial.Flax), A("Endless Loop", 1.0, 0.03, 0.0, 4.0, 0.0, 102.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Flax, SmithingMaterial.Flax), A("Rawhide", 1.0, 0.03, 0.0, 1.0, 0.0, 99.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Hides) }, new Shape[8] { A("Self", 3.0, 0.01, 0.0, 0.0, 0.0, 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, NoMaterials), A("Horn", 4.0, 0.02, 0.0, 0.0, 0.0, 101.0, 2.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Hides), A("Bone", 4.0, 0.02, 0.0, 0.0, 0.0, 100.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Hides), A("Iron-Capped", 4.0, 0.05, 0.0, 0.0, 0.0, 99.0, 3.0, 0.0, 0.0, 0.0, 0.0, 1.0), A("Siyah", 12.0, 0.08, 0.0, 0.0, 0.0, 106.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Hardwood, SmithingMaterial.Hides), A("Bone Ears", 7.0, 0.04, 0.0, 0.0, 0.0, 103.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Hides), A("Carved Knobs", 4.0, 0.04, 0.0, 0.0, 0.0, 100.0, 2.0, 0.0, 0.0, 0.0, 0.0, 1.0, default(SmithingMaterial)), A("Horn Ears", 11.0, 0.06, 0.0, 0.0, 0.0, 105.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Hides, SmithingMaterial.Hides) } }); yield return new KeyValuePair(WeaponClass.Crossbow, new Shape[4][] { new Shape[8] { A("Wooden", 70.0, 1.2, 0.0, 0.0, 0.0, 160.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, default(SmithingMaterial), default(SmithingMaterial)), A("Yew", 75.0, 1.1, 0.0, 0.0, 0.0, 190.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, default(SmithingMaterial), default(SmithingMaterial)), A("Composite", 65.0, 1.4, 0.0, 0.0, 0.0, 260.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Hardwood, SmithingMaterial.Hides, SmithingMaterial.Hides), A("Horn", 60.0, 1.5, 0.0, 0.0, 0.0, 240.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Hardwood, SmithingMaterial.Hides, SmithingMaterial.Hides), A("Iron", 70.0, 2.4, 0.0, 0.0, 0.0, 320.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0), A("Steel", 72.0, 2.2, 0.0, 0.0, 0.0, 420.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0), A("Recurved", 66.0, 1.8, 0.0, 0.0, 0.0, 290.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0), A("Great Steel", 85.0, 3.2, 0.0, 0.0, 0.0, 520.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0) }, new Shape[5] { A("Hand", 8.0, 0.1, 0.0, 25.0, 0.0, 0.0, 0.0, 200.0, 0.0, 0.0, 0.0, 1.0), A("Belt Hook", 10.0, 0.3, 0.0, 14.0, 0.0, 0.0, 0.0, 280.0, 0.0, 0.0, 0.0, 1.0), A("Stirrup", 14.0, 0.4, 0.0, 6.0, 0.0, 0.0, 0.0, 340.0, 0.0, 0.0, 0.0, 1.0), A("Goat's Foot", 18.0, 0.9, 0.0, -4.0, 0.0, 0.0, 0.0, 420.0, 0.0, 0.0, 0.0, 1.0), A("Windlass", 20.0, 1.6, 0.0, -22.0, 0.0, 0.0, 0.0, 600.0, 0.0, 0.0, 0.0, 1.0) }, new Shape[5] { A("Plain", 80.0, 1.5, 0.0, 2.0, 0.0, 0.0, 4.0, 0.0, 0.0, 0.0, 0.0, 1.0), A("Long", 95.0, 1.9, 0.0, -2.0, 0.0, 0.0, 7.0, 0.0, 0.0, 0.0, 0.0, 1.0), A("Carved", 82.0, 1.6, 0.0, 1.0, 0.0, 0.0, 6.0, 0.0, 0.0, 0.0, 0.0, 1.0), A("Bound", 85.0, 2.0, 0.0, 0.0, 0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0), A("Arbalest", 100.0, 2.6, 0.0, -5.0, 0.0, 0.0, 9.0, 0.0, 0.0, 0.0, 0.0, 1.0) }, new Shape[5] { A("Linen", 1.0, 0.03, 0.0, 2.0, 0.0, 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Flax), A("Hemp", 1.0, 0.03, 0.0, 4.0, 0.0, 97.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Flax), A("Sinew", 1.0, 0.04, 0.0, 0.0, 0.0, 105.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Hides), A("Cord", 1.0, 0.04, 0.0, 1.0, 0.0, 102.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Flax, SmithingMaterial.Flax), A("Waxed", 1.0, 0.03, 0.0, 2.0, 0.0, 103.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Flax, SmithingMaterial.Wool) } }); yield return new KeyValuePair(WeaponClass.Arrows, new Shape[4][] { new Shape[8] { A("Bodkin", 6.0, 0.3, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 7.0, 0.0, 1.0), A("Broadhead", 7.0, 0.35, 0.0, 0.0, 0.0, 0.0, -2.0, 0.0, 9.0, 0.0, 0.0, 1.0), A("Leaf", 6.0, 0.3, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 6.0, 0.0, 1.0), A("Barbed", 7.0, 0.35, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, 0.0, 8.0, 0.0, 1.0), A("Needle", 8.0, 0.25, 0.0, 0.0, 0.0, 0.0, 3.0, 0.0, 0.0, 6.0, 0.0, 1.0), A("Blunt", 4.0, 0.4, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 7.0, 1.0), A("Swallowtail", 8.0, 0.35, 0.0, 0.0, 0.0, 0.0, -3.0, 0.0, 10.0, 0.0, 0.0, 1.0), A("Crescent", 7.0, 0.35, 0.0, 0.0, 0.0, 0.0, -4.0, 0.0, 8.0, 0.0, 0.0, 1.0) }, new Shape[5] { A("Goose", 14.0, 0.05, 0.0, 0.0, 0.0, 0.0, 4.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Flax), A("Swan", 15.0, 0.05, 0.0, 0.0, 0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Flax), A("Short", 9.0, 0.03, 0.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Flax), A("Long", 18.0, 0.06, 0.0, 0.0, 0.0, 0.0, 6.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Flax), A("Spiral", 15.0, 0.06, 0.0, 0.0, 0.0, 0.0, 7.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Flax, SmithingMaterial.Flax) }, new Shape[5] { A("Ash", 75.0, 0.6, 0.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 0.0, 1.0, default(SmithingMaterial)), A("Birch", 76.0, 0.55, 0.0, 0.0, 0.0, 0.0, 3.0, 0.0, 0.0, 0.0, 0.0, 1.0, default(SmithingMaterial)), A("Pine", 74.0, 0.5, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, default(SmithingMaterial)), A("Cane", 78.0, 0.45, 0.0, 0.0, 0.0, 0.0, 4.0, 0.0, 0.0, 0.0, 0.0, 1.0, default(SmithingMaterial)), A("Footed", 77.0, 0.65, 0.0, 0.0, 0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, default(SmithingMaterial), default(SmithingMaterial)) }, new Shape[5] { A("Self", 2.0, 0.02, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, NoMaterials), A("Horn", 2.0, 0.03, 0.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Hides), A("Bone", 2.0, 0.03, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Hides), A("Reinforced", 2.0, 0.05, 0.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 0.0, 1.0), A("Inlaid", 2.0, 0.05, 0.0, 0.0, 0.0, 0.0, 3.0, 0.0, 0.0, 0.0, 0.0, 1.0) } }); yield return new KeyValuePair(WeaponClass.Bolts, new Shape[4][] { new Shape[8] { A("Bodkin", 5.0, 0.4, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 8.0, 0.0, 1.0), A("Square", 5.0, 0.45, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, 0.0, 9.0, 0.0, 1.0), A("Broad", 6.0, 0.45, 0.0, 0.0, 0.0, 0.0, -2.0, 0.0, 10.0, 0.0, 0.0, 1.0), A("Barbed", 6.0, 0.45, 0.0, 0.0, 0.0, 0.0, -2.0, 0.0, 0.0, 9.0, 0.0, 1.0), A("Needle", 7.0, 0.35, 0.0, 0.0, 0.0, 0.0, 3.0, 0.0, 0.0, 7.0, 0.0, 1.0), A("Blunt", 4.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 8.0, 1.0), A("Fork", 6.0, 0.45, 0.0, 0.0, 0.0, 0.0, -4.0, 0.0, 11.0, 0.0, 0.0, 1.0), A("Heavy", 6.0, 0.6, 0.0, 0.0, 0.0, 0.0, -3.0, 0.0, 0.0, 11.0, 0.0, 1.0) }, new Shape[5] { A("Wooden", 8.0, 0.04, 0.0, 0.0, 0.0, 0.0, 3.0, 0.0, 0.0, 0.0, 0.0, 1.0, default(SmithingMaterial)), A("Leather", 8.0, 0.04, 0.0, 0.0, 0.0, 0.0, 4.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Hides), A("Feathered", 9.0, 0.03, 0.0, 0.0, 0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Flax), A("Paper", 8.0, 0.02, 0.0, 0.0, 0.0, 0.0, 4.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Flax), A("Spiral", 9.0, 0.05, 0.0, 0.0, 0.0, 0.0, 6.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Flax, SmithingMaterial.Hides) }, new Shape[5] { A("Ash", 38.0, 0.5, 0.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 0.0, 1.0, default(SmithingMaterial)), A("Oak", 36.0, 0.6, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, default(SmithingMaterial)), A("Birch", 38.0, 0.45, 0.0, 0.0, 0.0, 0.0, 3.0, 0.0, 0.0, 0.0, 0.0, 1.0, default(SmithingMaterial)), A("Thick", 34.0, 0.7, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, default(SmithingMaterial), default(SmithingMaterial)), A("Footed", 40.0, 0.55, 0.0, 0.0, 0.0, 0.0, 4.0, 0.0, 0.0, 0.0, 0.0, 1.0, default(SmithingMaterial), default(SmithingMaterial)) }, new Shape[5] { A("Self", 2.0, 0.02, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, NoMaterials), A("Horn", 2.0, 0.03, 0.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Hides), A("Bone", 2.0, 0.03, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, SmithingMaterial.Hides), A("Capped", 2.0, 0.05, 0.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 0.0, 1.0), A("Inlaid", 2.0, 0.05, 0.0, 0.0, 0.0, 0.0, 3.0, 0.0, 0.0, 0.0, 0.0, 1.0) } }); } private static string[] ArmsTierWords(WeaponClassDef def, PartSlot slot, Shape shape) { SmithingMaterial[] array = shape.Made ?? new SmithingMaterial[0]; if (shape.Made == null && ((def.Family == WeaponFamily.Shield && slot == PartSlot.Blade) || (def.Family == WeaponFamily.Crossbow && slot == PartSlot.Handle))) { return WoodTierWords; } if (shape.Made != null && array.Length == 0) { if (def.Family != WeaponFamily.Bow && def.Family != WeaponFamily.Crossbow) { return WoodTierWords; } return BowTierWords; } if (shape.Made == null || array.Any(IsMetal)) { if (slot != PartSlot.Blade) { return FittingTierWords; } return MetalTierWords; } if (array.All((SmithingMaterial m) => m == SmithingMaterial.Hides)) { return HideTierWords; } if (array.All((SmithingMaterial m) => m == SmithingMaterial.Flax || m == SmithingMaterial.Wool)) { return ClothTierWords; } if (def.Family != WeaponFamily.Bow && def.Family != WeaponFamily.Crossbow) { return WoodTierWords; } return BowTierWords; } private static void AddArmsMaterials(SmithingPartDef part, WeaponClassDef def, Shape shape) { int tier = part.Tier; if (shape.Made != null && !shape.Made.Any(IsMetal)) { SmithingMaterial[] made = shape.Made; for (int i = 0; i < made.Length; i++) { Add(made[i], 1); } if (tier >= 4 && shape.Made.Length != 0) { Add(shape.Made[0], 1); } if (((def.Family == WeaponFamily.Shield && part.Slot == PartSlot.Blade) || (def.Family == WeaponFamily.Crossbow && part.Slot == PartSlot.Handle)) && tier >= 3) { Add(FittingMetal[tier - 2], 1); } return; } SmithingMaterial smithingMaterial = FittingMetal[tier - 1]; switch (def.Family) { case WeaponFamily.Shield: if (part.Slot == PartSlot.Blade) { if (shape.Made != null) { Add(BladeGrade(tier, high: true), 1); Add(smithingMaterial, 1); break; } double num = part.Length * part.Breadth; Add(SmithingMaterial.Hardwood, (num < 3600.0) ? 1 : ((num < 7000.0) ? 2 : 3)); if (tier >= 3) { Add(FittingMetal[tier - 2], 1); } } else { Add(smithingMaterial, 1); } break; case WeaponFamily.Crossbow: if (part.Slot == PartSlot.Blade) { Add(BladeGrade(tier, high: false), 1); Add(BladeGrade(tier, high: true), (!(shape.Name == "Great Steel")) ? 1 : 2); if (shape.Name == "Recurved") { Add(SmithingMaterial.Hardwood, 1); Add(SmithingMaterial.Hides, 1); } } else if (part.Slot == PartSlot.Handle) { Add(SmithingMaterial.Hardwood, (!(part.Length >= 95.0)) ? 1 : 2); if (tier >= 2) { Add(FittingMetal[tier - 2], 1); } } else { Add(smithingMaterial, (part.Slot != PartSlot.Guard || !(part.Cap >= 420.0)) ? 1 : 2); } break; case WeaponFamily.Ammo: Add((part.Slot == PartSlot.Blade) ? BladeGrade(tier, high: true) : smithingMaterial, 1); break; default: Add(smithingMaterial, 1); break; } void Add(SmithingMaterial m, int n) { if (n > 0) { part.Materials[m] = (part.Materials.TryGetValue(m, out var value) ? value : 0) + n; } } } private static SmithingMaterial BladeGrade(int tier, bool high) { switch (tier) { case 1: return SmithingMaterial.WroughtIron; case 2: return SmithingMaterial.Iron; case 3: if (!high) { return SmithingMaterial.Iron; } return SmithingMaterial.Steel; case 4: if (!high) { return SmithingMaterial.Steel; } return SmithingMaterial.FineSteel; default: if (!high) { return SmithingMaterial.FineSteel; } return SmithingMaterial.Thamaskene; } } private static double TierFactor(SmithingPartDef p) { if (p != null) { return TierDamage[Math.Max(1, Math.Min(5, p.Tier)) - 1]; } return 1.0; } private static WeaponStats ArmsStats(WeaponClassDef def, IList partIds) { SmithingPartDef smithingPartDef = Part(partIds[0]); SmithingPartDef smithingPartDef2 = Part(partIds[1]); SmithingPartDef smithingPartDef3 = Part(partIds[2]); SmithingPartDef smithingPartDef4 = Part(partIds[3]); SmithingPartDef[] source = new SmithingPartDef[4] { smithingPartDef, smithingPartDef2, smithingPartDef3, smithingPartDef4 }; double num = source.Sum((SmithingPartDef p) => p.Weight); WeaponStats weaponStats = new WeaponStats { Weight = Math.Round(num, 2) }; switch (def.Family) { case WeaponFamily.Shield: { double num4 = smithingPartDef.Length * smithingPartDef.Breadth * smithingPartDef.Width; weaponStats.Length = smithingPartDef.Length; weaponStats.Breadth = smithingPartDef.Breadth; weaponStats.HitPoints = Math.Round(source.Sum((SmithingPartDef p) => p.Toughness * TierFactor(p))); weaponStats.Handling = Math.Round(Clamp(110.0 - 7.0 * Math.Pow(num, 0.85) - num4 / 250.0 + source.Sum((SmithingPartDef p) => p.Handling), 30.0, 120.0)); weaponStats.SwingKind = DamageKind.Blunt; weaponStats.SwingSpeed = weaponStats.Handling; weaponStats.SwingDamage = Math.Round((8.0 + 4.0 * Math.Sqrt(num)) * smithingPartDef4.Blunt * TierFactor(smithingPartDef4), 1); break; } case WeaponFamily.Bow: { double num3 = smithingPartDef.Draw * TierFactor(smithingPartDef) * smithingPartDef3.Draw / 100.0 * smithingPartDef4.Draw / 100.0; weaponStats.Length = smithingPartDef.Length; weaponStats.MissileKind = DamageKind.Pierce; weaponStats.MissileDamage = Math.Round(10.0 + 0.55 * num3, 1); weaponStats.MissileSpeed = Math.Round(Clamp(40.0 + 0.3 * num3 - 6.0 * num, 40.0, 90.0), 1); weaponStats.Accuracy = Math.Round(Clamp(72.0 + source.Sum((SmithingPartDef p) => p.Accuracy) - num3 / 12.0, 40.0, 100.0)); weaponStats.DrawSpeed = Math.Round(Clamp(100.0 - 0.45 * num3 + source.Sum((SmithingPartDef p) => p.Handling) - 4.0 * num, 30.0, 120.0)); weaponStats.Handling = weaponStats.DrawSpeed; weaponStats.Range = Math.Round(55.0 + 0.9 * num3); break; } case WeaponFamily.Crossbow: { double num5 = Math.Min(smithingPartDef.Draw * TierFactor(smithingPartDef) * smithingPartDef4.Draw / 100.0, smithingPartDef2.Cap * TierFactor(smithingPartDef2)); weaponStats.Length = smithingPartDef3.Length; weaponStats.MissileKind = DamageKind.Pierce; weaponStats.MissileDamage = Math.Round(18.0 + 0.17 * num5, 1); weaponStats.MissileSpeed = Math.Round(Clamp(50.0 + 0.06 * num5, 50.0, 95.0), 1); weaponStats.Accuracy = Math.Round(Clamp(78.0 + source.Sum((SmithingPartDef p) => p.Accuracy) - 0.02 * num5, 45.0, 100.0)); weaponStats.DrawSpeed = Math.Round(Clamp(85.0 - 0.09 * num5 + source.Sum((SmithingPartDef p) => p.Handling) - 2.0 * num, 20.0, 110.0)); weaponStats.Handling = weaponStats.DrawSpeed; weaponStats.Range = Math.Round(70.0 + 0.16 * num5); break; } default: { double cut = smithingPartDef.Cut; double pierce = smithingPartDef.Pierce; double blunt = smithingPartDef.Blunt; weaponStats.MissileKind = ((pierce >= cut && pierce >= blunt) ? DamageKind.Pierce : ((cut >= blunt) ? DamageKind.Cut : DamageKind.Blunt)); double num2 = Math.Max(cut, Math.Max(pierce, blunt)); weaponStats.Length = smithingPartDef3.Length; weaponStats.MissileDamage = Math.Round(num2 * TierFactor(smithingPartDef) + 5.0 * (TierFactor(smithingPartDef3) - 1.0), 1); weaponStats.Accuracy = Math.Round(Math.Max(0.0, source.Sum((SmithingPartDef p) => p.Accuracy) + 10.0 * (TierFactor(smithingPartDef2) - 1.0))); break; } } return weaponStats; } private static double ShieldScore(WeaponStats s) { return s.HitPoints * (s.Handling / 80.0) * Math.Pow(Math.Max(1.0, s.Breadth) / 60.0, 0.3) / 10.0; } private static double LauncherScore(WeaponStats s) { return s.MissileDamage * s.MissileSpeed / 30.0 * Math.Pow(s.DrawSpeed / 80.0, 0.4) * Math.Pow(Math.Max(1.0, s.Accuracy) / 80.0, 0.5); } private static double AmmoScore(WeaponStats s) { return (s.MissileDamage + 5.0) * (s.Accuracy + 20.0) / 20.0; } private static double[] ArmsOrderValues(WeaponClassDef def, WeaponStats s) { return def.Family switch { WeaponFamily.Shield => new double[3] { s.HitPoints, s.Handling, s.Breadth }, WeaponFamily.Ammo => new double[2] { s.MissileDamage, s.Accuracy }, _ => new double[4] { s.MissileDamage, s.MissileSpeed, s.Accuracy, s.DrawSpeed }, }; } private static string[] ArmsOrderNames(WeaponClassDef def) { return def.Family switch { WeaponFamily.Shield => new string[3] { "Hit points", "Speed", "Width" }, WeaponFamily.Ammo => new string[2] { "Damage bonus", "Accuracy bonus" }, WeaponFamily.Crossbow => new string[4] { "Damage", "Missile speed", "Accuracy", "Reload speed" }, _ => new string[4] { "Damage", "Missile speed", "Accuracy", "Draw speed" }, }; } private static string ArmsDefaultName(WeaponClass c, SmithingPartDef main) { string name = ClassDef(c).Name; if (main == null) { return name; } string obj = main.Name.Split(new char[1] { ' ' })[0]; string shape = main.Shape; string text = (shape.EndsWith("bow", StringComparison.OrdinalIgnoreCase) ? "" : (" " + name)); return (obj + " " + shape + text).Trim(); } public static ForgingSetup Setup(int skill, int difficulty, double averagePartTier, Func hasPerk) { hasPerk = hasPerk ?? ((Func)((string _) => false)); int num = (int)Clamp(skill - difficulty, -250.0, 300.0); bool flag = num >= 0; double num2 = (hasPerk("perk.smith.master") ? 1.2 : 1.0) * (hasPerk("perk.smith.legendary") ? (1.0 + (double)(Math.Max(0, skill - 275) / 5) * 0.01) : 1.0); ForgingSetup forgingSetup = new ForgingSetup { Margin = num, Strikes = 6 + (int)Math.Ceiling(Clamp(averagePartTier, 1.0, 5.0)), Window = Math.Round(Clamp(0.1 + 0.0008 * (double)num, 0.03, 0.22) * num2, 4), Speed = Math.Round(Clamp(1.25 - 0.0025 * (double)num, 0.75, 2.2), 4), Cooling = Math.Round(Clamp(0.5 - 0.001 * (double)num, 0.3, 0.8), 4), HeatSeconds = 6.0, QuenchCentre = 0.62, QuenchWindow = Math.Round(Clamp(0.09 + 0.0006 * (double)num, 0.04, 0.18), 4), QuenchSpeed = Math.Round(Clamp(0.8 - 0.0012 * (double)num, 0.5, 1.2), 4), Bonus = ((flag && hasPerk("perk.smith.experienced")) ? 0.05 : 0.0) }; forgingSetup.Perfect = Math.Round(forgingSetup.Window * 0.25, 4); double num3 = Clamp(0.14 + 0.0006 * (double)num, 0.07, 0.24); forgingSetup.HeatLow = Math.Round(0.7 - num3 / 2.0, 4); forgingSetup.HeatHigh = Math.Round(0.7 + num3 / 2.0, 4); WeaponQuality weaponQuality = ((num < -50) ? WeaponQuality.Inferior : ((num < 0) ? WeaponQuality.Common : ((num < 25) ? WeaponQuality.Fine : ((num < (hasPerk("perk.smith.legendary") ? 35 : 60)) ? WeaponQuality.Masterwork : WeaponQuality.Legendary)))); if (averagePartTier < 3.5 && weaponQuality > WeaponQuality.Fine) { weaponQuality = WeaponQuality.Fine; } else if (averagePartTier < 4.5 && weaponQuality > WeaponQuality.Masterwork) { weaponQuality = WeaponQuality.Masterwork; } forgingSetup.Ceiling = weaponQuality; forgingSetup.AutoScore = Math.Round(Math.Min(0.69, Clamp(0.5 + 0.002 * (double)num, 0.1, 0.69) + forgingSetup.Bonus), 4); forgingSetup.AutoQuality = QualityFor(forgingSetup.AutoScore, (weaponQuality < WeaponQuality.Common) ? weaponQuality : WeaponQuality.Common); return forgingSetup; } public static double HitAccuracy(double offset, double window, double perfect) { double num = Math.Abs(double.IsNaN(offset) ? 1.0 : offset); if (num <= perfect / 2.0) { return 1.0; } if (num > window / 2.0) { return 0.0; } return 1.0 - 0.7 * (num - perfect / 2.0) / Math.Max(1E-06, window / 2.0 - perfect / 2.0); } public static string WorkReason(ForgingWork work, ForgingSetup setup) { if (work == null) { return ""; } if (double.IsNaN(work.Heat) || work.Heat < 0.0 || work.Heat > 1.0) { return "The heating was not measured."; } if (work.StrikeOffsets == null || work.StrikeOffsets.Count != setup.Strikes) { return "Finish every hammer blow (" + setup.Strikes + ")."; } if (work.StrikeOffsets.Any((double o) => double.IsNaN(o) || double.IsInfinity(o) || o < 0.0)) { return "A hammer blow was not measured."; } if (double.IsNaN(work.QuenchOffset) || double.IsInfinity(work.QuenchOffset) || work.QuenchOffset < 0.0) { return "The quench was not measured."; } return ""; } public static double WorkScore(ForgingWork work, ForgingSetup setup) { if (work == null) { return setup.AutoScore; } double num = ((work.StrikeOffsets.Count == 0) ? 0.0 : work.StrikeOffsets.Average((double o) => HitAccuracy(o, setup.Window, setup.Perfect))); double num2 = HitAccuracy(work.QuenchOffset, setup.QuenchWindow, setup.QuenchWindow * 0.4); return Math.Round(Clamp(0.2 * Clamp(work.Heat, 0.0, 1.0) + 0.65 * num + 0.15 * num2 + setup.Bonus, 0.0, 1.0), 4); } public static WeaponQuality QualityFor(double score, WeaponQuality ceiling) { WeaponQuality weaponQuality = WeaponQuality.Poor; for (int i = 0; i < QualityThresholds.Length; i++) { if (score + 1E-09 >= QualityThresholds[i]) { weaponQuality = (WeaponQuality)(i + 1); } } if (weaponQuality <= ceiling) { return weaponQuality; } return ceiling; } } public sealed class ForgingWork { public double Heat; public List StrikeOffsets = new List(); public double QuenchOffset = 1.0; } public sealed class ForgingSetup { public int Margin; public int Strikes; public double Window; public double Perfect; public double Speed; public double HeatLow; public double HeatHigh; public double Cooling; public double HeatSeconds; public double QuenchCentre; public double QuenchWindow; public double QuenchSpeed; public double Bonus; public WeaponQuality Ceiling; public double AutoScore; public WeaponQuality AutoQuality; } public static class Tournaments { public const int Fighters = 16; public static readonly int[] TeamSize = new int[4] { 2, 2, 2, 1 }; public static readonly string[] RoundNames = new string[4] { "First round", "Second round", "Semi-final", "Final" }; public const double DailyStartChance = 0.025; public const int DurationDays = 14; public const double InitialShare = 0.25; public const long MaximumBet = 150L; public const double MinimumOdds = 1.1; public const double MaximumOdds = 4.0; public const double WinRenown = 3.0; public const int MaximumActiveAbilities = 5; public const string AbilityPrefix = "ability."; public const int MaximumLocalTier = 4; private static readonly string[] Given = new string[30] { "Bram", "Tilda", "Osk", "Merry", "Gorm", "Pip", "Ulla", "Rolf", "Wren", "Dag", "Hilde", "Tam", "Nessa", "Brock", "Ida", "Fenn", "Odo", "Runa", "Cob", "Signe", "Basil", "Greta", "Hux", "Lotte", "Mags", "Ned", "Petra", "Quill", "Sten", "Vala" }; private static readonly string[] SurnameStart = new string[15] { "Iron", "Mud", "Oak", "Bram", "Stone", "Thistle", "Copper", "Barrel", "Quick", "Grim", "Kettle", "Hay", "Wolf", "Ash", "Turnip" }; private static readonly string[] SurnameEnd = new string[15] { "knee", "boot", "fist", "shank", "brow", "helm", "beard", "jaw", "back", "toe", "hand", "belly", "nose", "chin", "heel" }; public static int Rounds => TeamSize.Length; public static bool IsAbilityId(string id) { if (id != null && id.StartsWith("ability.", StringComparison.Ordinal)) { return id.Length > "ability.".Length; } return false; } public static bool CanFight(UnitDef unit) { if (unit != null && unit.Slots == 1 && !unit.Mounted && !string.IsNullOrEmpty(unit.TabsUnitId) && (unit.Role == TroopRole.Infantry || unit.Role == TroopRole.Ranged || unit.Role == TroopRole.Support)) { return unit.Workload <= 2.0; } return false; } public static double LocalTierWeight(int tier) { return (tier <= 1) ? 2 : (tier switch { 3 => 3, 2 => 3, _ => (tier == 4) ? 1 : 0, }); } public static double WinChance(double strengthA, double strengthB) { if (strengthA <= 0.0 && strengthB <= 0.0) { return 0.5; } return Math.Max(0.0, strengthA) / (Math.Max(0.0, strengthA) + Math.Max(0.0, strengthB)); } public static double Odds(double chance) { double val = ((chance <= 0.0) ? 4.0 : (0.9 / chance)); return Math.Round(Math.Max(1.1, Math.Min(4.0, val)), 1); } public static string LocalName(RandomStream rng) { return Given[rng.Range(0, Given.Length)] + " " + SurnameStart[rng.Range(0, SurnameStart.Length)] + SurnameEnd[rng.Range(0, SurnameEnd.Length)]; } } public enum GoodCategory { Food, Raw, Processed } public sealed class TradeGoodDef { public string Id = ""; public string Name = ""; public long BasePrice; public double Weight; public GoodCategory Category = GoodCategory.Raw; public int TownDemand; } public static class TradeGoods { public const string Timber = "good.timber"; public const string Ore = "good.ore"; public const string Wool = "good.wool"; public const string Tools = "good.tools"; public const string Cloth = "good.cloth"; public const string Grain = "good.grain"; public const string Fish = "good.fish"; public const string Meat = "good.meat"; public const string Olives = "good.olives"; public const string Grapes = "good.grapes"; public const string Dates = "good.dates"; public const string Hides = "good.hides"; public const string Flax = "good.flax"; public const string Cotton = "good.cotton"; public const string Clay = "good.clay"; public const string Silver = "good.silver"; public const string Salt = "good.salt"; public const string Horses = "good.horses"; public const string Fur = "good.fur"; public const string Beer = "good.beer"; public const string Wine = "good.wine"; public const string Oil = "good.oil"; public const string Linen = "good.linen"; public const string Velvet = "good.velvet"; public const string Leather = "good.leather"; public const string Pottery = "good.pottery"; public const string Jewelry = "good.jewelry"; public static readonly string[] Original = new string[5] { "good.timber", "good.ore", "good.wool", "good.tools", "good.cloth" }; public static readonly List All = new List { Good("good.timber", "Hardwood", 14L, 3.0, GoodCategory.Raw), Good("good.ore", "Iron Ore", 22L, 3.0, GoodCategory.Raw), Good("good.wool", "Wool", 18L, 2.0, GoodCategory.Raw), Good("good.tools", "Tools", 100L, 2.0, GoodCategory.Processed, 1), Good("good.cloth", "Cloth", 72L, 1.0, GoodCategory.Processed, 1), Good("good.grain", "Grain", 10L, 1.0, GoodCategory.Food), Good("good.fish", "Fish", 18L, 1.0, GoodCategory.Food), Good("good.meat", "Meat", 24L, 1.0, GoodCategory.Food), Good("good.olives", "Olives", 20L, 1.0, GoodCategory.Food), Good("good.grapes", "Grapes", 18L, 1.0, GoodCategory.Food), Good("good.dates", "Dates", 22L, 1.0, GoodCategory.Food), Good("good.hides", "Hides", 30L, 2.0, GoodCategory.Raw), Good("good.flax", "Flax", 22L, 1.0, GoodCategory.Raw), Good("good.cotton", "Cotton", 26L, 1.0, GoodCategory.Raw), Good("good.clay", "Clay", 10L, 2.0, GoodCategory.Raw), Good("good.silver", "Silver Ore", 80L, 2.0, GoodCategory.Raw), Good("good.salt", "Salt", 40L, 1.0, GoodCategory.Raw, 1), Good("good.horses", "Horses", 200L, 2.0, GoodCategory.Raw), Good("good.fur", "Fur", 60L, 1.0, GoodCategory.Raw, 1), Good("good.beer", "Beer", 40L, 1.0, GoodCategory.Processed, 1), Good("good.wine", "Wine", 70L, 1.0, GoodCategory.Processed, 1), Good("good.oil", "Oil", 80L, 1.0, GoodCategory.Processed, 1), Good("good.linen", "Linen", 80L, 1.0, GoodCategory.Processed, 1), Good("good.velvet", "Velvet", 160L, 1.0, GoodCategory.Processed, 1), Good("good.leather", "Leather", 90L, 1.0, GoodCategory.Processed, 1), Good("good.pottery", "Pottery", 50L, 2.0, GoodCategory.Processed, 1), Good("good.jewelry", "Jewelry", 300L, 0.5, GoodCategory.Processed, 1) }; public static TradeGoodDef Get(string id) { return All.FirstOrDefault((TradeGoodDef g) => g.Id == id); } public static bool IsOriginal(string id) { return Original.Contains(id); } private static TradeGoodDef Good(string id, string name, long price, double weight, GoodCategory category, int demand = 0) { return new TradeGoodDef { Id = id, Name = name, BasePrice = price, Weight = weight, Category = category, TownDemand = demand }; } } public sealed class VillageProductDef { public string GoodId = ""; public string Name = ""; public string NameSuffix = ""; public double FoodPerDay; public int GoodsPerDay = 6; public bool FoodVillage; } public static class VillageProducts { public static readonly List All = new List { Kind("good.grain", "Wheat farm", "Fields", 6.0, foodVillage: true), Kind("good.fish", "Fishing village", "Harbour", 5.0, foodVillage: true), Kind("good.meat", "Hog farm", "Sty", 5.0, foodVillage: true), Kind("good.olives", "Olive grove", "Grove", 4.0, foodVillage: true), Kind("good.grapes", "Vineyard", "Vines", 4.0, foodVillage: true), Kind("good.dates", "Date palms", "Oasis", 5.0, foodVillage: true), Kind("good.hides", "Cattle farm", "Pasture", 4.0, foodVillage: true), Kind("good.wool", "Sheep farm", "Downs", 3.0, foodVillage: false), Kind("good.horses", "Horse ranch", "Paddock", 2.0, foodVillage: false), Kind("good.flax", "Flax farm", "Flaxmead", 2.0, foodVillage: false), Kind("good.cotton", "Cotton fields", "Cottonfield", 2.0, foodVillage: false), Kind("good.clay", "Clay pits", "Claypits", 1.0, foodVillage: false), Kind("good.ore", "Iron mine", "Ironworks", 1.0, foodVillage: false), Kind("good.silver", "Silver mine", "Silverdeep", 1.0, foodVillage: false), Kind("good.salt", "Salt pans", "Saltpans", 1.0, foodVillage: false), Kind("good.timber", "Lumber camp", "Timberwood", 1.0, foodVillage: false), Kind("good.fur", "Trappers' camp", "Trappers", 1.0, foodVillage: false) }; public static VillageProductDef Get(string goodId) { return All.FirstOrDefault((VillageProductDef k) => k.GoodId == goodId); } private static VillageProductDef Kind(string good, string name, string suffix, double food, bool foodVillage) { return new VillageProductDef { GoodId = good, Name = name, NameSuffix = suffix, FoodPerDay = food, FoodVillage = foodVillage }; } } public sealed class WandererArchetype { public string Id = ""; public string[] Skills = new string[0]; public TroopRole[] Roles = new TroopRole[0]; public string[] Descriptions = new string[0]; } public static class Wanderers { public const double PerTown = 0.6; public const int MinStayDays = 5; public const int MaxStayDays = 12; public const int MinArrivalDays = 3; public const int MaxArrivalDays = 7; public const int NearestTowns = 5; public const double PaceOfParty = 0.8; public const int BaseRiding = 15; public static readonly WandererArchetype[] Archetypes = new WandererArchetype[10] { new WandererArchetype { Id = "scout", Skills = new string[3] { "scouting", "tactics", "riding" }, Roles = new TroopRole[2] { TroopRole.Ranged, TroopRole.Infantry }, Descriptions = new string[3] { "A {folk} trail guide who reads hoofprints like a ledger and never takes the same road twice.", "Once rode ahead of the {folk} army. Knows every ford, short cut and suspicious hedge for miles.", "A poacher turned pathfinder, happiest on a ridge with the whole valley spread out below." } }, new WandererArchetype { Id = "healer", Skills = new string[3] { "medicine", "stewardship", "leadership" }, Roles = new TroopRole[3] { TroopRole.Support, TroopRole.Ranged, TroopRole.Infantry }, Descriptions = new string[3] { "A {folk} bonesetter with a bag of herbs, a steady hand and strong opinions about running at spears.", "Has stitched more cuts than they can remember. Lost very few.", "A former temple healer who left to see the world and keeps finding it in need of bandages." } }, new WandererArchetype { Id = "quartermaster", Skills = new string[3] { "stewardship", "trade", "leadership" }, Roles = new TroopRole[2] { TroopRole.Infantry, TroopRole.Support }, Descriptions = new string[3] { "A {folk} provisioner who can make a sack of grain last a week and a week's wages last a fortnight.", "Used to cook for a camp. Counts every barrel twice and every soldier's appetite three times.", "A steward who ran a great house until its lord ran out of money, and never forgot why." } }, new WandererArchetype { Id = "merchant", Skills = new string[3] { "trade", "diplomacy", "stewardship" }, Roles = new TroopRole[2] { TroopRole.Infantry, TroopRole.Ranged }, Descriptions = new string[3] { "A {folk} pedlar who knows what every market pays for salt, wool and gossip.", "Their last caravan met some bandits. Now they're after a safer purse to carry.", "A haggler of some fame who once sold a ruined mill for the price of a castle." } }, new WandererArchetype { Id = "engineer", Skills = new string[3] { "engineering", "tactics", "smithing" }, Roles = new TroopRole[2] { TroopRole.Ranged, TroopRole.Infantry }, Descriptions = new string[3] { "A {folk} sapper who has built siege towers out of barns and brought down walls that were meant to stand forever.", "A millwright. Decided catapults are just mills that throw things.", "A former master of works who can tell you a wall's weak spot by tapping it with a spoon." } }, new WandererArchetype { Id = "smith", Skills = new string[3] { "smithing", "engineering", "trade" }, Roles = new TroopRole[2] { TroopRole.Infantry, TroopRole.Support }, Descriptions = new string[3] { "A {folk} blacksmith with scorched eyebrows and a hammer they will not let anyone else carry.", "Walking the land to learn every forge's secrets. Might share a few.", "An armourer whose blades are prized and whose temper is known to be shorter than their daggers." } }, new WandererArchetype { Id = "captain", Skills = new string[3] { "leadership", "tactics", "scouting" }, Roles = new TroopRole[2] { TroopRole.Infantry, TroopRole.Ranged }, Descriptions = new string[3] { "A {folk} sergeant whose voice can turn a rout around and a tavern quiet.", "Their company broke up after one battle too many. Looking for a banner worth following.", "A veteran drillmaster who believes any rabble becomes an army with enough shouting." } }, new WandererArchetype { Id = "tactician", Skills = new string[3] { "tactics", "leadership", "engineering" }, Roles = new TroopRole[2] { TroopRole.Infantry, TroopRole.Ranged }, Descriptions = new string[3] { "A {folk} war-gamer who has fought every famous battle twice on a tavern table with salt cellars.", "Was a herald once. Watched so many battles they started to see why people lost them.", "A cautious strategist who always knows where the high ground is and where the exit is." } }, new WandererArchetype { Id = "rider", Skills = new string[3] { "riding", "scouting", "leadership" }, Roles = new TroopRole[2] { TroopRole.Ranged, TroopRole.Infantry }, Descriptions = new string[3] { "A {folk} horse-breaker who can ride anything with four legs and has tried a few with more.", "Has worn out more horses than boots, and knows every stable on the road.", "A former tournament rider who still bows to the crowd when there is no crowd." } }, new WandererArchetype { Id = "envoy", Skills = new string[3] { "diplomacy", "trade", "leadership" }, Roles = new TroopRole[2] { TroopRole.Support, TroopRole.Infantry }, Descriptions = new string[3] { "A {folk} go-between who has carried messages between lords who would rather have carried swords.", "Could talk a toll-keeper into paying them.", "Their last embassy ended in a war. Not their fault, they insist." } } }; private static readonly Dictionary FirstNames = new Dictionary(StringComparer.Ordinal) { { "medieval", new string[12] { "Alda", "Bertram", "Cedric", "Edda", "Godfrey", "Hilde", "Jory", "Maud", "Osric", "Rowena", "Tamsin", "Wat" } }, { "viking", new string[12] { "Arne", "Brynja", "Dagny", "Egil", "Gunnar", "Halla", "Ivar", "Kari", "Leif", "Runa", "Sten", "Tova" } }, { "tribal", new string[12] { "Ugg", "Mog", "Rokka", "Thud", "Garra", "Nub", "Okka", "Brak", "Zuzu", "Hoot", "Grunna", "Pok" } }, { "farmer", new string[12] { "Barley", "Clem", "Daisy", "Fen", "Hob", "Marigold", "Ned", "Poppy", "Rowan", "Tilly", "Dob", "Hazel" } }, { "ancient", new string[12] { "Aelia", "Castor", "Daphne", "Galen", "Iona", "Leander", "Myra", "Nikos", "Phoebe", "Theron", "Cleon", "Thalia" } }, { "dynasty", new string[12] { "Akio", "Bao", "Hana", "Jin", "Kenta", "Lian", "Mei", "Ren", "Suki", "Tao", "Yuna", "Shen" } }, { "renaissance", new string[12] { "Beatrice", "Carlo", "Dante", "Elena", "Fabio", "Giulia", "Lorenzo", "Marco", "Paola", "Rosa", "Silvio", "Vera" } }, { "pirate", new string[12] { "Anne", "Barnaby", "Calico", "Davy", "Flint", "Grace", "Jonah", "Mags", "Peg", "Silas", "Morgan", "Bess" } }, { "spooky", new string[12] { "Bones", "Clatter", "Ebon", "Grimsby", "Hollis", "Mortimer", "Nell", "Ossie", "Shade", "Wisp", "Rattle", "Mab" } }, { "wildwest", new string[12] { "Abner", "Belle", "Cassidy", "Dusty", "Eli", "Hattie", "Jeb", "Lou", "Rusty", "Wyatt", "Clara", "Zeke" } }, { "fantasygood", new string[12] { "Aurel", "Celestine", "Elara", "Gideon", "Ilys", "Lumen", "Orin", "Seraph", "Talia", "Vesper", "Caelan", "Isolde" } }, { "fantasyevil", new string[12] { "Ash", "Cinder", "Drav", "Ember", "Grisk", "Hex", "Morda", "Nox", "Scorch", "Vile", "Rusk", "Sable" } } }; private static readonly string[] AnyFirstNames = new string[12] { "Ada", "Bram", "Cora", "Dell", "Emry", "Finn", "Gwen", "Hal", "Ines", "Jasper", "Kit", "Lark" }; private static readonly Dictionary SurnameStarts = new Dictionary(StringComparer.Ordinal) { { "medieval", new string[8] { "Candle", "Thistle", "Copper", "Barley", "Pudding", "Saddle", "Button", "Kettle" } }, { "viking", new string[8] { "Frost", "Oar", "Herring", "Rune", "Fjord", "Mead", "Helm", "Snow" } }, { "tribal", new string[8] { "Bone", "Mud", "Stone", "Tusk", "Fern", "Club", "Moss", "Rock" } }, { "farmer", new string[8] { "Turnip", "Hay", "Plough", "Cabbage", "Clover", "Butter", "Apple", "Barn" } }, { "ancient", new string[8] { "Marble", "Olive", "Laurel", "Column", "Amphora", "Scroll", "Bronze", "Myrtle" } }, { "dynasty", new string[8] { "Jade", "Lantern", "Silk", "Bamboo", "Lotus", "Ink", "Tea", "Kite" } }, { "renaissance", new string[8] { "Gilt", "Brush", "Velvet", "Quill", "Canvas", "Ducat", "Lute", "Fresco" } }, { "pirate", new string[8] { "Barrel", "Anchor", "Brine", "Rum", "Tide", "Gull", "Cutlass", "Kraken" } }, { "spooky", new string[8] { "Grave", "Wax", "Moth", "Crypt", "Bell", "Raven", "Coffin", "Fog" } }, { "wildwest", new string[8] { "Dust", "Cactus", "Boot", "Spur", "Canyon", "Lasso", "Wagon", "Mesa" } }, { "fantasygood", new string[8] { "Dawn", "Star", "Halo", "Bright", "Sun", "Silver", "Lark", "Glimmer" } }, { "fantasyevil", new string[8] { "Ember", "Soot", "Gloom", "Brimstone", "Thorn", "Shadow", "Cinder", "Hex" } } }; private static readonly string[] AnySurnameStarts = new string[8] { "Pebble", "Puddle", "Bramble", "Nettle", "Pepper", "Mallow", "Tinder", "Wobble" }; private static readonly string[] SurnameEnds = new string[16] { "foot", "back", "beard", "hand", "nose", "belly", "toe", "knee", "whistle", "wobble", "tumble", "grip", "wick", "bottom", "cap", "boots" }; public static int TargetFor(int towns) { return (int)Math.Round((double)Math.Max(0, towns) * 0.6, MidpointRounding.AwayFromZero); } public static string Name(string cultureId, RandomStream rng, ICollection taken) { if (!FirstNames.TryGetValue(cultureId ?? "", out var value)) { value = AnyFirstNames; } if (!SurnameStarts.TryGetValue(cultureId ?? "", out var value2)) { value2 = AnySurnameStarts; } for (int i = 0; i < 40; i++) { string text = rng.Pick(value); string text2 = rng.Pick(value2); if (!string.Equals(text, text2, StringComparison.OrdinalIgnoreCase)) { string text3 = text + " " + text2 + rng.Pick(SurnameEnds); if (!taken.Contains(text3)) { return text3; } } } int num = 2; string text4; while (true) { text4 = rng.Pick(value) + " " + rng.Pick(value2) + rng.Pick(SurnameEnds) + " " + num.ToString(CultureInfo.InvariantCulture); if (!taken.Contains(text4)) { break; } num++; } return text4; } public static string Surname(string cultureId, ulong hash) { if (!SurnameStarts.TryGetValue(cultureId ?? "", out var value)) { value = AnySurnameStarts; } return value[(uint)(hash % (ulong)value.Length)] + SurnameEnds[(uint)(hash / 97 % (ulong)SurnameEnds.Length)]; } public static List Bodies(IEnumerable units, string cultureId) { return (from u in units where u.Culture == cultureId && !u.Mounted && u.Slots == 1 && u.Workload <= 2.0 && !string.IsNullOrEmpty(u.TabsUnitId) && (u.Role == TroopRole.Infantry || u.Role == TroopRole.Ranged || u.Role == TroopRole.Support) && u.Tier >= 2 && u.Tier <= 4 orderby u.Tier select u).ThenBy((UnitDef u) => u.Id, StringComparer.Ordinal).ToList(); } public static string Describe(string template, CultureDef culture) { string text = Folk(culture); string text2 = template.Replace("{folk}", text); if (template.StartsWith("A {folk}", StringComparison.Ordinal) && text.Length > 0 && "AEIOUaeiou".IndexOf(text[0]) >= 0) { text2 = "An" + text2.Substring(1); } return text2; } public static string Folk(CultureDef culture) { string text = culture?.Name ?? "wandering"; int num = text.IndexOf(" (", StringComparison.Ordinal); if (num <= 0) { return text; } return text.Substring(0, num); } public static SortedDictionary Skills(WandererArchetype archetype, RandomStream rng) { SortedDictionary sortedDictionary = new SortedDictionary(StringComparer.Ordinal); int[][] array = new int[3][] { new int[2] { 30, 56 }, new int[2] { 12, 31 }, new int[2] { 5, 16 } }; for (int i = 0; i < archetype.Skills.Length && i < array.Length; i++) { sortedDictionary[archetype.Skills[i]] = rng.Range(array[i][0], array[i][1]); } sortedDictionary["riding"] = (sortedDictionary.TryGetValue("riding", out var value) ? Math.Max(value, 15) : 15); return sortedDictionary; } public static void Price(SortedDictionary skills, out long hireCost, out int dailyWage) { int num = skills.Sum((KeyValuePair s) => (!(s.Key == "riding")) ? s.Value : Math.Max(0, s.Value - 15)); hireCost = (long)Math.Round((100.0 + 3.0 * (double)num) / 10.0, MidpointRounding.AwayFromZero) * 10; dailyWage = 2 + num / 30; } } public enum ClothingSlot { Head, Neck, Shoulders, Torso, Arms, Wrists, Hands, Waist, Legs, Feet } public sealed class ClothingPieceDef { public string Id = ""; public string Name = ""; public ClothingSlot Slot; public int Tier = 1; public int ColorChannels; public long Price => Wardrobe.PriceFor(Slot, Tier); public double Weight => Wardrobe.WeightFor(Slot, Tier); public ClothingPieceDef Copy() { return new ClothingPieceDef { Id = Id, Name = Name, Slot = Slot, Tier = Tier, ColorChannels = ColorChannels }; } } public sealed class WardrobeCatalogue { public sealed class Piece { public string Id = ""; public string Name = ""; public ClothingSlot Slot; public long WearerCost; public int ColorChannels; } public List Pieces = new List(); public SortedDictionary> UnitPieces = new SortedDictionary>(StringComparer.Ordinal); } public static class Wardrobe { public const string PiecePrefix = "cloth."; public const double MinimumSize = 0.8; public const double MaximumSize = 1.25; public const double SizeStep = 0.01; public const int MaximumColorChannels = 12; public const int MaximumColorIndex = 255; public const int OwnColor = -1; public const int InventoryLimit = 100; public const double LootChancePerTroop = 0.06; public const int MaximumLootPerBattle = 8; public static readonly ClothingSlot[] Slots = (ClothingSlot[])Enum.GetValues(typeof(ClothingSlot)); public const int Layers = 3; private static readonly double[] TierPrice = new double[6] { 0.0, 1.0, 2.0, 3.5, 6.0, 10.0 }; public static bool IsPieceId(string id) { if (id != null && id.StartsWith("cloth.", StringComparison.Ordinal)) { return id.Length > "cloth.".Length; } return false; } public static string NativeId(string pieceId) { if (!IsPieceId(pieceId)) { return ""; } return pieceId.Substring("cloth.".Length); } public static string PieceId(string nativeId) { return "cloth." + nativeId; } public static string SlotKey(ClothingSlot slot) { return slot.ToString().ToLowerInvariant(); } public static bool TryParseSlotKey(string key, out ClothingSlot slot) { ClothingSlot[] slots = Slots; foreach (ClothingSlot clothingSlot in slots) { if (SlotKey(clothingSlot) == key) { slot = clothingSlot; return true; } } slot = ClothingSlot.Head; return false; } public static string LayerKey(ClothingSlot slot, int layer) { if (layer > 1) { return SlotKey(slot) + ":" + layer.ToString(CultureInfo.InvariantCulture); } return SlotKey(slot); } public static bool TryParseLayerKey(string key, out ClothingSlot slot, out int layer) { layer = 1; int num = key?.IndexOf(':') ?? (-1); if (num < 0) { return TryParseSlotKey(key, out slot); } if (!TryParseSlotKey(key.Substring(0, num), out slot)) { return false; } string text = key.Substring(num + 1); if (int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out layer) && layer >= 2 && layer <= 3) { return text == layer.ToString(CultureInfo.InvariantCulture); } return false; } public static string SlotName(ClothingSlot slot) { return slot.ToString(); } public static int TierForCost(long wearerCost) { if (wearerCost > 0) { if (wearerCost > 100) { if (wearerCost > 250) { if (wearerCost > 500) { if (wearerCost > 1000) { return 5; } return 4; } return 3; } return 2; } return 1; } return 2; } private static double SlotPriceBase(ClothingSlot slot) { return slot switch { ClothingSlot.Torso => 30.0, ClothingSlot.Head => 24.0, ClothingSlot.Legs => 18.0, ClothingSlot.Shoulders => 14.0, ClothingSlot.Arms => 12.0, ClothingSlot.Feet => 10.0, ClothingSlot.Hands => 9.0, ClothingSlot.Waist => 9.0, _ => 7.0, }; } private static double SlotWeightBase(ClothingSlot slot) { return slot switch { ClothingSlot.Torso => 1.5, ClothingSlot.Legs => 1.0, ClothingSlot.Head => 0.8, ClothingSlot.Shoulders => 0.6, ClothingSlot.Feet => 0.6, ClothingSlot.Arms => 0.5, ClothingSlot.Waist => 0.4, ClothingSlot.Hands => 0.3, _ => 0.2, }; } public static long PriceFor(ClothingSlot slot, int tier) { return (long)Math.Round(SlotPriceBase(slot) * TierPrice[Math.Max(1, Math.Min(5, tier))]); } public static double WeightFor(ClothingSlot slot, int tier) { return Math.Round(SlotWeightBase(slot) * (0.8 + 0.2 * (double)Math.Max(1, Math.Min(5, tier))), 2); } public static string FallbackName(ClothingSlot slot, string nativeId) { return SlotName(slot) + " piece " + nativeId.ToString(CultureInfo.InvariantCulture); } public static List NormalizeColors(IEnumerable colors) { List list = (colors ?? Enumerable.Empty()).ToList(); while (list.Count > 0 && list[list.Count - 1] == -1) { list.RemoveAt(list.Count - 1); } return list; } public static double RoundSize(double size) { return Math.Round(size / 0.01) * 0.01; } public static bool ValidSize(double size) { if (!double.IsNaN(size) && !double.IsInfinity(size) && size >= 0.7999999990000001) { return size <= 1.250000001; } return false; } } public sealed class WeaponSheetLine { public string Label = ""; public string Value = ""; public double Bar = -1.0; public string Tip = ""; } public sealed class WeaponSheet { public string Id = ""; public string Name = ""; public string ClassName = ""; public WeaponClass? Class; public WeaponFamily Family; public string Hands = ""; public string Use = ""; public int Tier; public string Quality = ""; public string Origin = ""; public double Weight; public List Lines = new List(); public string SecondName = ""; public List SecondLines = new List(); public List Notes = new List(); public string Summary { get { IEnumerable source = from l in Lines.Where((WeaponSheetLine l) => l.Bar >= 0.0).Take(3) select l.Label.ToLowerInvariant() + " " + l.Value; return ClassName + ((Hands.Length > 0) ? (" · " + Hands.ToLowerInvariant()) : "") + ((Tier > 0) ? (" · tier " + Tier) : "") + ((Lines.Count > 0) ? (" · " + string.Join(", ", source.ToArray())) : ""); } } } public static class WeaponSheets { private static readonly Dictionary Typical = new Dictionary(StringComparer.Ordinal); public static WeaponStats TypicalStats(WeaponClass c, int tier, string shape = "") { tier = Math.Max(1, Math.Min(5, tier)); string key = c.ToString() + "|" + tier + "|" + shape; lock (Typical) { if (Typical.TryGetValue(key, out var value)) { return value.Copy(); } WeaponClassDef weaponClassDef = Smithing.ClassDef(c); string[] array = new string[4]; for (int i = 0; i < 4; i++) { array[i] = ""; } PartSlot[] slots = weaponClassDef.Slots; foreach (PartSlot partSlot in slots) { List source = Smithing.PartsFor(c, partSlot).ToList(); SmithingPartDef smithingPartDef = null; if (partSlot == PartSlot.Blade && !string.IsNullOrEmpty(shape)) { smithingPartDef = (from p in source where string.Equals(p.Shape, shape, StringComparison.OrdinalIgnoreCase) orderby Math.Abs(p.Tier - tier) select p).FirstOrDefault(); } if (smithingPartDef == null) { smithingPartDef = (from p in source orderby Math.Abs(p.Tier - tier), p.ShapeIndex select p).FirstOrDefault(); } array[(int)partSlot] = smithingPartDef?.Id ?? ""; } WeaponStats weaponStats = Smithing.Stats(c, array); Typical[key] = weaponStats; return weaponStats.Copy(); } } public static string HandsOf(WeaponClassDef def) { switch (def.Family) { case WeaponFamily.Shield: return "Off hand"; case WeaponFamily.Bow: return "Two hands (bow)"; case WeaponFamily.Crossbow: return "Two hands (crossbow)"; case WeaponFamily.Ammo: return "Quiver"; case WeaponFamily.Thrown: return "One hand, thrown"; default: if (!def.TwoHanded) { return "One-handed"; } return "Two-handed"; } } public static string UseOf(WeaponClassDef def) { switch (def.Family) { case WeaponFamily.Shield: return "Blocks blows and arrows; leaves the other hand free for a one-handed or thrown weapon."; case WeaponFamily.Bow: return "Shoots arrows: quick to draw, best at range. Takes both hands, so no shield."; case WeaponFamily.Crossbow: return "Shoots bolts: hard-hitting and accurate, slow to reload. Takes both hands, so no shield."; case WeaponFamily.Ammo: return "Ammunition: adds its damage and accuracy to the launcher it is shot from."; case WeaponFamily.Thrown: return "Thrown at close range; leaves the other hand free for a shield."; default: if (!def.TwoHanded) { return "Quick and handy in one hand: the other hand can carry a shield or a second weapon."; } if (def.Class != WeaponClass.Pike) { return "Heavy blows and long reach, held in both hands, so no shield."; } return "A long thrusting weapon that keeps enemies at bay, cavalry above all. Two hands, so no shield."; } } private static string Kind(DamageKind k) { if (k != DamageKind.None) { return " " + k.ToString().ToLowerInvariant(); } return ""; } private static WeaponSheetLine L(string label, string value, double bar, string tip = "") { return new WeaponSheetLine { Label = label, Value = value, Bar = ((bar < 0.0) ? (-1.0) : Math.Max(0.0, Math.Min(1.0, bar))), Tip = tip }; } public static List StatLines(WeaponClassDef def, WeaponStats s) { List list = new List(); if (s == null) { return list; } switch (def.Family) { case WeaponFamily.Shield: list.Add(L("Hit points", s.HitPoints.ToString("0"), s.HitPoints / 300.0, "How much punishment it takes before it breaks.")); list.Add(L("Speed", s.Handling.ToString("0"), s.Handling / 120.0, "How quickly it is raised to block.")); list.Add(L("Width", s.Breadth.ToString("0") + " cm", s.Breadth / 100.0, "Wider shields cover more.")); if (s.SwingDamage > 0.0) { list.Add(L("Bash", s.SwingDamage.ToString("0.#") + Kind(s.SwingKind), s.SwingDamage / 40.0)); } break; case WeaponFamily.Bow: case WeaponFamily.Crossbow: list.Add(L("Damage", s.MissileDamage.ToString("0.#") + Kind(s.MissileKind), s.MissileDamage / 90.0, "Damage of each shot.")); list.Add(L("Missile speed", s.MissileSpeed.ToString("0"), s.MissileSpeed / 95.0, "Faster missiles are harder to dodge and drop less.")); list.Add(L("Accuracy", s.Accuracy.ToString("0"), s.Accuracy / 100.0)); list.Add(L((def.Family == WeaponFamily.Crossbow) ? "Reload speed" : "Draw speed", s.DrawSpeed.ToString("0"), s.DrawSpeed / 120.0)); list.Add(L("Range", s.Range.ToString("0") + " m", s.Range / 160.0)); break; case WeaponFamily.Ammo: list.Add(L("Extra damage", "+" + s.MissileDamage.ToString("0.#") + Kind(s.MissileKind), s.MissileDamage / 20.0)); list.Add(L("Extra accuracy", "+" + s.Accuracy.ToString("0"), s.Accuracy / 20.0)); break; case WeaponFamily.Thrown: list.Add(L("Damage", s.MissileDamage.ToString("0.#") + Kind(s.MissileKind), s.MissileDamage / 90.0)); list.Add(L("Missile speed", s.MissileSpeed.ToString("0"), s.MissileSpeed / 32.0)); list.Add(L("Accuracy", s.Accuracy.ToString("0"), s.Accuracy / 100.0)); list.Add(L("Handling", s.Handling.ToString("0"), s.Handling / 120.0)); break; default: if (s.SwingDamage > 0.0) { list.Add(L("Swing damage", s.SwingDamage.ToString("0.#") + Kind(s.SwingKind), s.SwingDamage / 120.0, "Damage of a swing at full speed.")); list.Add(L("Swing speed", s.SwingSpeed.ToString("0"), s.SwingSpeed / 120.0)); } if (s.ThrustDamage > 0.0) { list.Add(L("Thrust damage", s.ThrustDamage.ToString("0.#") + Kind(s.ThrustKind), s.ThrustDamage / 90.0, "Damage of a thrust.")); list.Add(L("Thrust speed", s.ThrustSpeed.ToString("0"), s.ThrustSpeed / 120.0)); } list.Add(L("Handling", s.Handling.ToString("0"), s.Handling / 120.0, "How quickly it recovers and changes direction.")); break; } if (s.Length > 0.0 && def.Family != WeaponFamily.Ammo && def.Family != WeaponFamily.Shield) { list.Add(L((def.Family == WeaponFamily.Melee) ? "Reach" : "Length", s.Length.ToString("0") + " cm", s.Length / 300.0)); } list.Add(L("Weight", s.Weight.ToString("0.##") + " kg", -1.0)); return list; } public static WeaponSheet For(EquipmentDef item, Func unitDef = null) { if (item == null) { return null; } WeaponSheet weaponSheet = new WeaponSheet { Id = item.Id, Name = item.Name, Weight = item.Weight, Origin = "Bought" }; UnitDef unitDef2 = unitDef?.Invoke(item.SourceUnitId); if (unitDef2 != null) { weaponSheet.Notes.Add("Carried as the " + unitDef2.Name + " carries it" + ((item.Hand == EquipmentHand.Both && item.SecondClass.HasValue) ? ", both pieces together." : ".")); } if (!item.Class.HasValue) { weaponSheet.ClassName = ((item.Slot == EquipmentSlot.Outfit) ? "Outfit" : "Gear"); weaponSheet.Notes.Add((item.Slot == EquipmentSlot.Outfit) ? "Clothing only: it changes how the hero looks, not how they fight." : ""); return weaponSheet; } WeaponClassDef weaponClassDef = Smithing.ClassDef(item.Class.Value); weaponSheet.Class = item.Class; weaponSheet.Family = weaponClassDef.Family; weaponSheet.ClassName = weaponClassDef.Name; weaponSheet.Tier = item.Tier; weaponSheet.Hands = ((item.Hand == EquipmentHand.Main) ? "One-handed" : ((item.Hand == EquipmentHand.Off) ? "Off hand" : ((item.SecondClass == WeaponClass.Shield) ? "One-handed, with a shield" : ((item.SecondClass == item.Class) ? "One in each hand" : HandsOf(weaponClassDef))))); weaponSheet.Use = UseOf(weaponClassDef); weaponSheet.Lines = StatLines(weaponClassDef, TypicalStats(item.Class.Value, item.Tier, (item.Class == WeaponClass.Shield || weaponClassDef.Family >= WeaponFamily.Shield) ? item.Shape : "")); if (item.SecondClass.HasValue) { WeaponClassDef weaponClassDef2 = Smithing.ClassDef(item.SecondClass.Value); weaponSheet.SecondName = weaponClassDef2.Name; weaponSheet.SecondLines = StatLines(weaponClassDef2, TypicalStats(item.SecondClass.Value, item.Tier, (item.SecondClass == WeaponClass.Shield) ? item.Shape : "")); } if (item.Hand == EquipmentHand.Main) { weaponSheet.Notes.Add("Leaves the off hand to the hero's own gear, a shield or a second one-handed weapon."); } if (item.ShieldDefense > 0.0) { List notes = weaponSheet.Notes; double shieldDefense = item.ShieldDefense; notes.Add("On its own: +" + shieldDefense.ToString("P0") + " defence in campaign battles. Needs a free hand."); } return weaponSheet; } public static WeaponSheet For(CraftedWeaponState w) { if (w == null) { return null; } WeaponClassDef weaponClassDef = Smithing.ClassDef(w.Class); WeaponSheet weaponSheet = new WeaponSheet { Id = w.Id, Name = w.Name, Class = w.Class, Family = weaponClassDef.Family, ClassName = weaponClassDef.Name, Tier = w.Tier, Quality = w.Quality.ToString(), Hands = HandsOf(weaponClassDef), Use = UseOf(weaponClassDef), Origin = "Forged", Weight = (w.Stats?.Weight ?? 0.0), Lines = StatLines(weaponClassDef, w.Stats) }; weaponSheet.Notes.Add("Forged" + ((w.Quality == WeaponQuality.Common) ? "" : (", " + w.Quality.ToString().ToLowerInvariant() + " quality")) + ": worth about " + w.Value.ToString("N0") + " denars."); return weaponSheet; } } public sealed class WorkshopTypeDef { public string Id = ""; public string Name = ""; public string Description = ""; public long Cost = 1500L; public string OutputGoodId = ""; public SortedDictionary Inputs = new SortedDictionary(); public int OperatingCost = 6; } public static class WorkshopTypes { public static readonly WorkshopTypeDef[] All = new WorkshopTypeDef[10] { Type("workshop.smithy", "Smithy", "good.tools", 1500L, 6, ("good.ore", 2), ("good.timber", 1)), Type("workshop.weavery", "Wool weavery", "good.cloth", 1500L, 6, ("good.wool", 2)), Type("workshop.brewery", "Brewery", "good.beer", 1200L, 5, ("good.grain", 3)), Type("workshop.winepress", "Wine press", "good.wine", 1500L, 6, ("good.grapes", 2)), Type("workshop.olivepress", "Olive press", "good.oil", 1500L, 6, ("good.olives", 2)), Type("workshop.linen", "Linen weavery", "good.linen", 1600L, 6, ("good.flax", 2)), Type("workshop.velvet", "Velvet weavery", "good.velvet", 2200L, 8, ("good.cotton", 2)), Type("workshop.tannery", "Tannery", "good.leather", 1600L, 6, ("good.hides", 2)), Type("workshop.pottery", "Pottery shop", "good.pottery", 1200L, 5, ("good.clay", 3)), Type("workshop.silversmith", "Silversmith", "good.jewelry", 2500L, 10, ("good.silver", 2)) }; public static WorkshopTypeDef Get(string id) { return All.FirstOrDefault((WorkshopTypeDef x) => x.Id == id); } private static WorkshopTypeDef Type(string id, string name, string output, long cost, int operating, params (string good, int count)[] inputs) { WorkshopTypeDef workshopTypeDef = new WorkshopTypeDef { Id = id, Name = name, OutputGoodId = output, Cost = cost, OperatingCost = operating }; for (int i = 0; i < inputs.Length; i++) { (string, int) tuple = inputs[i]; workshopTypeDef.Inputs[tuple.Item1] = tuple.Item2; } workshopTypeDef.Description = string.Join(" + ", inputs.Select(((string good, int count) tuple2) => tuple2.count + " " + TradeGoods.Get(tuple2.good).Name.ToLowerInvariant())) + " → 1 " + TradeGoods.Get(output).Name.ToLowerInvariant() + " per day. Operating cost: " + operating + " denars."; return workshopTypeDef; } } } namespace TabsBannerlord.Core.Common { public struct Vec2 : IEquatable { public double X; public double Y; public static readonly Vec2 Zero = new Vec2(0.0, 0.0); public double Length => Math.Sqrt(X * X + Y * Y); public double LengthSquared => X * X + Y * Y; public Vec2 Normalized { get { double length = Length; if (!(length < 1E-12)) { return new Vec2(X / length, Y / length); } return Zero; } } public Vec2(double x, double y) { X = x; Y = y; } public static Vec2 operator +(Vec2 a, Vec2 b) { return new Vec2(a.X + b.X, a.Y + b.Y); } public static Vec2 operator -(Vec2 a, Vec2 b) { return new Vec2(a.X - b.X, a.Y - b.Y); } public static Vec2 operator *(Vec2 a, double s) { return new Vec2(a.X * s, a.Y * s); } public static Vec2 operator /(Vec2 a, double s) { return new Vec2(a.X / s, a.Y / s); } public static double Dot(Vec2 a, Vec2 b) { return a.X * b.X + a.Y * b.Y; } public static double Distance(Vec2 a, Vec2 b) { return (a - b).Length; } public static Vec2 Lerp(Vec2 a, Vec2 b, double t) { return new Vec2(a.X + (b.X - a.X) * t, a.Y + (b.Y - a.Y) * t); } public static Vec2 MoveTowards(Vec2 from, Vec2 to, double maxDistance) { Vec2 vec = to - from; double length = vec.Length; if (length <= maxDistance || length < 1E-12) { return to; } return from + vec / length * maxDistance; } public bool Equals(Vec2 o) { if (X == o.X) { return Y == o.Y; } return false; } public override bool Equals(object obj) { if (obj is Vec2 o) { return Equals(o); } return false; } public override int GetHashCode() { return (X.GetHashCode() * 397) ^ Y.GetHashCode(); } public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "({0:0.##}, {1:0.##})", X, Y); } } public static class StableHash { public static ulong Fnv1a64(string s) { ulong num = 14695981039346656037uL; foreach (char c in s) { num ^= (byte)(c & 0xFF); num *= 1099511628211L; num ^= (byte)((int)c >> 8); num *= 1099511628211L; } return num; } public static ulong Combine(ulong a, ulong b) { return SplitMix(a ^ (ulong)((long)b + -7046029254386353131L + (long)(a << 6) + (long)(a >> 2))); } public static ulong SplitMix(ulong z) { z += 11400714819323198485uL; z = (z ^ (z >> 30)) * 13787848793156543929uL; z = (z ^ (z >> 27)) * 10723151780598845931uL; return z ^ (z >> 31); } } public sealed class RandomStream { public string Name = ""; public ulong S0; public ulong S1; public ulong S2; public ulong S3; public long Draws; public RandomStream() { } public RandomStream(string name, ulong seed) { Name = name; ulong z = StableHash.Combine(seed, StableHash.Fnv1a64(name)); S0 = StableHash.SplitMix(z); S1 = StableHash.SplitMix(S0); S2 = StableHash.SplitMix(S1); S3 = StableHash.SplitMix(S2); if ((S0 | S1 | S2 | S3) == 0L) { S0 = 1uL; } } private static ulong Rotl(ulong x, int k) { return (x << k) | (x >> 64 - k); } public ulong NextULong() { ulong result = Rotl(S1 * 5, 7) * 9; ulong num = S1 << 17; S2 ^= S0; S3 ^= S1; S1 ^= S2; S0 ^= S3; S2 ^= num; S3 = Rotl(S3, 45); Draws++; return result; } public double NextDouble() { return (double)(NextULong() >> 11) * 1.1102230246251565E-16; } public int Range(int min, int maxExclusive) { if (maxExclusive <= min) { return min; } ulong num = (ulong)(maxExclusive - min); return min + (int)(NextULong() % num); } public double Range(double min, double max) { return min + (max - min) * NextDouble(); } public bool Chance(double probability) { if (probability > 0.0) { if (!(probability >= 1.0)) { return NextDouble() < probability; } return true; } return false; } public T Pick(IList items) { if (items.Count != 0) { return items[Range(0, items.Count)]; } return default(T); } public int PickWeighted(IList weights) { double num = 0.0; foreach (double weight in weights) { if (weight > 0.0) { num += weight; } } if (num <= 0.0) { return -1; } double num2 = NextDouble() * num; for (int i = 0; i < weights.Count; i++) { if (!(weights[i] <= 0.0)) { num2 -= weights[i]; if (num2 < 0.0) { return i; } } } for (int num3 = weights.Count - 1; num3 >= 0; num3--) { if (weights[num3] > 0.0) { return num3; } } return -1; } } public sealed class RandomStreams { public const string World = "world"; public const string Movement = "movement"; public const string Ai = "ai"; public const string Recruitment = "recruitment"; public const string Economy = "economy"; public const string Battle = "battle"; public const string AutoResolve = "autoresolve"; public const string Captivity = "captivity"; public const string Names = "names"; public const string Events = "events"; public ulong Seed; public SortedDictionary Streams = new SortedDictionary(StringComparer.Ordinal); public RandomStreams() { } public RandomStreams(ulong seed) { Seed = seed; } public RandomStream Get(string name) { if (!Streams.TryGetValue(name, out var value)) { value = new RandomStream(name, Seed); Streams[name] = value; } return value; } } public interface IEntity { string Id { get; } } public sealed class EntityTable : IEnumerable, IEnumerable, IJsonCustom where T : class, IEntity { private readonly List _items = new List(); private readonly Dictionary _index = new Dictionary(StringComparer.Ordinal); public int Count => _items.Count; public T this[int i] => _items[i]; public T Get(string id) { if (id == null || !_index.TryGetValue(id, out var value)) { return null; } return _items[value]; } public bool Contains(string id) { if (id != null) { return _index.ContainsKey(id); } return false; } public T Require(string id) { T val = Get(id); if (val == null) { throw new KeyNotFoundException("No " + typeof(T).Name + " with id '" + id + "'"); } return val; } public void Add(T item) { if (item == null) { throw new ArgumentNullException("item"); } if (string.IsNullOrEmpty(item.Id)) { throw new ArgumentException(typeof(T).Name + " has no id"); } if (_index.ContainsKey(item.Id)) { throw new InvalidOperationException("Duplicate " + typeof(T).Name + " id '" + item.Id + "'"); } _index[item.Id] = _items.Count; _items.Add(item); } public void Replace(T item) { if (item == null) { throw new ArgumentNullException("item"); } if (string.IsNullOrEmpty(item.Id) || !_index.TryGetValue(item.Id, out var value)) { throw new InvalidOperationException("No " + typeof(T).Name + " id '" + item?.Id + "' to replace"); } _items[value] = item; } public bool Remove(string id) { if (id == null || !_index.TryGetValue(id, out var value)) { return false; } _items.RemoveAt(value); _index.Remove(id); for (int i = value; i < _items.Count; i++) { _index[_items[i].Id] = i; } return true; } public List ToList() { return new List(_items); } public IEnumerator GetEnumerator() { return _items.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return _items.GetEnumerator(); } public JsonNode ToJson(JsonSerializer serializer) { JsonArray jsonArray = new JsonArray(); foreach (T item in _items) { jsonArray.Add(serializer.ToNode(item, typeof(T))); } return jsonArray; } public void FromJson(JsonNode node, JsonSerializer serializer) { _items.Clear(); _index.Clear(); foreach (JsonNode item in node.AsArray.Items) { Add((T)serializer.FromNode(item, typeof(T))); } } } public sealed class IdAllocator { public SortedDictionary Next = new SortedDictionary(StringComparer.Ordinal); public string Allocate(string prefix) { Next.TryGetValue(prefix, out var value); value++; Next[prefix] = value; return prefix + "." + value.ToString("000000", CultureInfo.InvariantCulture); } public long AllocateNumber(string prefix) { Next.TryGetValue(prefix, out var value); value++; Next[prefix] = value; return value; } } } namespace TabsBannerlord.Core.Campaign { internal sealed class AbilitiesSystem { private readonly Campaign C; private CampaignState State => C.State; public IEnumerable KnownAbilities { get { IEnumerable enumerable = State.Abilities?.Known?.Values; return enumerable ?? Enumerable.Empty(); } } internal AbilitiesSystem(Campaign host) { C = host; } public void EnsureAbilityFields() { bool flag = false; if (State.Abilities == null) { State.Abilities = new AbilitiesState(); flag = true; } if (State.Abilities.Known == null) { State.Abilities.Known = new SortedDictionary(StringComparer.Ordinal); flag = true; } foreach (Hero hero in State.Heroes) { if (hero.Abilities == null) { hero.Abilities = new List(); flag = true; } if (hero.Loadout != null && hero.Loadout.Abilities == null) { hero.Loadout.Abilities = new List(); flag = true; } } if (flag) { State.Touch(); } } public AbilityDef Ability(string id) { if (id == null || State.Abilities?.Known == null || !State.Abilities.Known.TryGetValue(id, out var value)) { return null; } return value; } public string AbilityName(string id) { return Ability(id)?.Name ?? "Unknown ability"; } public int ImportAbilities(IEnumerable abilities) { EnsureAbilityFields(); int num = 0; foreach (AbilityDef item in (abilities ?? Enumerable.Empty()).Where((AbilityDef a) => a != null).OrderBy((AbilityDef a) => a.Id, StringComparer.Ordinal)) { if (Tournaments.IsAbilityId(item.Id) && !State.Abilities.Known.ContainsKey(item.Id)) { string name = (string.IsNullOrWhiteSpace(item.Name) ? item.Id.Substring("ability.".Length) : item.Name.Trim()); State.Abilities.Known[item.Id] = new AbilityDef { Id = item.Id, Name = name }; num++; } } if (num > 0) { State.Touch(); } C.EnsureTournaments(); return num; } public bool HeroKnowsAbility(Hero hero, string abilityId) { if (hero?.Abilities != null) { return hero.Abilities.Contains(abilityId); } return false; } public bool AbilityActive(Hero hero, string abilityId) { if (hero?.Loadout?.Abilities != null) { return hero.Loadout.Abilities.Contains(abilityId); } return false; } public int ActiveAbilityCount(Hero hero) { return (hero?.Loadout?.Abilities?.Count).GetValueOrDefault(); } public void LearnAbility(Hero hero, string abilityId) { if (hero == null || Ability(abilityId) == null) { return; } if (hero.Abilities == null) { hero.Abilities = new List(); } if (hero.Abilities.Contains(abilityId)) { return; } hero.Abilities.Add(abilityId); if (Campaign.SupportsWardrobe(C.UnitDef(hero.UnitId)) && ActiveAbilityCount(hero) < 5) { if (hero.Loadout == null) { hero.Loadout = new HeroEquipmentState(); } if (hero.Loadout.Abilities == null) { hero.Loadout.Abilities = new List(); } hero.Loadout.Abilities.Add(abilityId); } State.Touch(); } public string AbilityHeroReason(string heroId) { Hero hero = State.Heroes.Get(heroId ?? ""); if (hero == null || hero.ClanId != State.PlayerClanId || (hero.Id != State.PlayerHeroId && !C.IsOwnedCompanion(hero))) { return "Pick yourself or a companion."; } if (!string.IsNullOrEmpty(State.Player.PendingEncounterId) || State.Player.Activity == PlayerActivity.InBattle) { return "Deal with the encounter first."; } if (hero.State != HeroState.Active || !Campaign.IsPresentPartyHero(State.PlayerParty, hero)) { return "They have to be in your party for that."; } if (!Campaign.SupportsWardrobe(C.UnitDef(hero.UnitId))) { return "This archetype can't use special abilities."; } return ""; } public string AbilityToggleReason(string heroId, string abilityId, bool on) { string text = AbilityHeroReason(heroId); if (text.Length > 0) { return text; } Hero hero = State.Heroes.Require(heroId); if (Ability(abilityId) == null) { return "Unknown ability."; } if (!HeroKnowsAbility(hero, abilityId)) { return hero.Name + " has not learned " + AbilityName(abilityId) + "."; } bool flag = AbilityActive(hero, abilityId); if (on && flag) { return AbilityName(abilityId) + " is already on."; } if (!on && !flag) { return AbilityName(abilityId) + " is already off."; } if (on && ActiveAbilityCount(hero) >= 5) { return "A hero can use at most " + 5 + " abilities at once. Switch one off first."; } return ""; } public CommandResult SetAbilityActive(string heroId, string abilityId, bool on) { string text = AbilityToggleReason(heroId, abilityId, on); if (text.Length > 0) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Require(heroId); if (hero.Loadout == null) { hero.Loadout = new HeroEquipmentState(); } if (hero.Loadout.Abilities == null) { hero.Loadout.Abilities = new List(); } if (on) { hero.Loadout.Abilities.Add(abilityId); } else { hero.Loadout.Abilities.Remove(abilityId); } string text2 = hero.Name + (on ? " will use " : " will no longer use ") + AbilityName(abilityId) + " in battle."; State.AddLog(LogCategory.Info, text2, hero.Id); State.Touch(); return CommandResult.Success(text2); } } internal sealed class AiArmiesSystem { private readonly Campaign C; private CampaignRules Rules => C.Rules; private CampaignState State => C.State; public List AiArmies => State.KingdomArmies?.Armies ?? new List(); public AiArmy PlayerAiArmy => AiArmies.FirstOrDefault((AiArmy a) => a.PlayerJoined); internal AiArmiesSystem(Campaign host) { C = host; } public void EnsureKingdomArmyFields() { bool flag = false; if (State.KingdomArmies == null) { State.KingdomArmies = new KingdomArmiesState(); flag = true; } KingdomArmiesState kingdomArmies = State.KingdomArmies; if (kingdomArmies.Armies == null) { kingdomArmies.Armies = new List(); flag = true; } if (kingdomArmies.AttachedTo == null) { kingdomArmies.AttachedTo = new SortedDictionary(StringComparer.Ordinal); flag = true; } if (!kingdomArmies.Initialized) { kingdomArmies.Initialized = true; kingdomArmies.LastDay = State.Clock.Day; flag = true; } if (flag) { State.Touch(); } } public AiArmy AiArmyOf(Party p) { if (p != null) { return AiArmies.FirstOrDefault((AiArmy a) => a.LeaderPartyId == p.Id || a.MemberPartyIds.Contains(p.Id) || (a.PlayerJoined && p.Id == State.PlayerPartyId)); } return null; } internal bool MarchesWithAiArmy(Party p, Party leader) { AiArmy aiArmy = AiArmies.FirstOrDefault((AiArmy a) => a.LeaderPartyId == leader?.Id); if (aiArmy != null && p != null) { if (!aiArmy.MemberPartyIds.Contains(p.Id)) { if (aiArmy.PlayerJoined) { return p.Id == State.PlayerPartyId; } return false; } return true; } return false; } internal bool PlayerMarchesWith(Party p) { AiArmy playerAiArmy = PlayerAiArmy; if (playerAiArmy != null && p != null) { if (!(p.Id == playerAiArmy.LeaderPartyId)) { return playerAiArmy.MemberPartyIds.Contains(p.Id); } return true; } return false; } internal bool LiveLordParty(Party p) { if (p != null && p.Kind == PartyKind.Lord && p.State != PartyState.Destroyed) { return p.State != PartyState.Disbanded; } return false; } internal bool FreeForArmy(Party p, string kingdomId, int minimum) { if (!LiveLordParty(p) || p.Id == State.PlayerPartyId || p.ClanId == State.PlayerClanId || p.AiFrozen) { return false; } Clan clan = State.Clans.Get(p.ClanId); Hero hero = State.Heroes.Get(p.LeaderHeroId); if (clan != null && !clan.IsEliminated && clan.KingdomId == kingdomId && hero != null && hero.CanFight && hero.ClanId == clan.Id && (p.State == PartyState.Active || p.State == PartyState.InSettlement) && string.IsNullOrEmpty(p.EncounterId) && C.MilitaryPartyFor(p) == null && !C.ClanArmyContains(p.Id) && AiArmyOf(p) == null && C.PartyCombatants(p) >= minimum && !State.Sieges.Any((SiegeState s) => s.Stage != SiegeStage.Ended && s.BesiegerPartyId == p.Id)) { return p.ActiveRaid == null; } return false; } internal bool KingdomAtWar(string kingdomId) { return State.Stances.Any((StanceRecord s) => s.Stance == Stance.War && ((s.A == kingdomId && C.KnownDiplomacyFaction(s.B)) || (s.B == kingdomId && C.KnownDiplomacyFaction(s.A)))); } public double AiArmyStrength(AiArmy army) { Party leader = State.Parties.Get(army?.LeaderPartyId ?? ""); if (leader == null) { return 0.0; } double radius = Rules.JoinBattleRadius * 3.0; return C.PartyStrength(leader) + (from id in army.MemberPartyIds select State.Parties.Get(id) into p where LiveLordParty(p) && Vec2.Distance(p.Position, leader.Position) <= radius select p).Sum((Func)C.PartyStrength) + ((army.PlayerJoined && State.PlayerParty != null && Vec2.Distance(State.PlayerParty.Position, leader.Position) <= radius) ? C.PartyStrength(State.PlayerParty) : 0.0); } internal bool AiArmyGathered(AiArmy army, Party leader) { if (State.Clock.Day - army.FormedDay < 2) { return army.MemberPartyIds.Select((string id) => State.Parties.Get(id)).Where(LiveLordParty).All((Party p) => Vec2.Distance(p.Position, leader.Position) <= Rules.JoinBattleRadius * 2.0); } return true; } internal void DailyKingdomArmies() { KingdomArmiesState kingdomArmies = State.KingdomArmies; if (kingdomArmies == null || !kingdomArmies.Initialized || kingdomArmies.LastDay >= State.Clock.Day) { return; } kingdomArmies.LastDay = State.Clock.Day; State.Touch(); foreach (AiArmy army in kingdomArmies.Armies.ToList()) { Party party = State.Parties.Get(army.LeaderPartyId); army.MemberPartyIds.RemoveAll(delegate(string id) { Party party2 = State.Parties.Get(id); return !LiveLordParty(party2) || State.Clans.Get(party2.ClanId)?.KingdomId != army.KingdomId; }); army.Cohesion = Math.Max(0.0, army.Cohesion - 4.0); if (army.PlayerJoined && State.PlayerClan?.KingdomId == army.KingdomId) { C.AddPoliticalInfluence(State.PlayerClan, 0.5); } object obj; if (LiveLordParty(party)) { Hero hero = State.Heroes.Get(army.LeaderHeroId); if (hero != null && hero.CanFight && !(party.LeaderHeroId != army.LeaderHeroId)) { obj = ((!KingdomAtWar(army.KingdomId)) ? "the war is over" : ((army.Cohesion <= 0.0) ? "its cohesion is spent" : ((army.MemberPartyIds.Count == 0 && !army.PlayerJoined) ? "its lords have gone" : ""))); goto IL_01f6; } } obj = "its marshal has fallen"; goto IL_01f6; IL_01f6: string text = (string)obj; if (text.Length > 0) { DisbandAiArmy(army, text); } } if (State.Clock.Day % 3 == 0L) { FormAiArmies(force: false); } } internal int FormAiArmies(bool force) { KingdomArmiesState kingdomArmies = State.KingdomArmies; int num = 0; foreach (Kingdom kingdom in State.Kingdoms.Where((Kingdom k) => !k.IsEliminated && KingdomAtWar(k.Id)).OrderBy((Kingdom k) => k.Id, StringComparer.Ordinal).ToList()) { if (kingdomArmies.Armies.Any((AiArmy a) => a.KingdomId == kingdom.Id)) { continue; } List source = State.Parties.Where((Party p) => FreeForArmy(p, kingdom.Id, force ? 5 : 20) && (force || (State.Clans.Get(p.ClanId)?.Influence ?? 0.0) >= 20.0)).ToList(); Clan ruler = C.ServiceRuler(kingdom.Id); Party marshal = source.OrderByDescending((Party p) => (ruler != null && p.ClanId == ruler.Id && State.Clans.Get(p.ClanId)?.LeaderHeroId == p.LeaderHeroId) ? 1 : 0).ThenByDescending(C.PartyStrength).ThenBy((Party p) => p.Id, StringComparer.Ordinal) .FirstOrDefault(); if (marshal == null) { continue; } List list = (from p in State.Parties where p.Id != marshal.Id && FreeForArmy(p, kingdom.Id, force ? 3 : 10) && Vec2.Distance(p.Position, marshal.Position) <= C.StrategicRange(force ? 60 : 18) orderby Vec2.Distance(p.Position, marshal.Position) select p).ThenBy((Party p) => p.Id, StringComparer.Ordinal).Take(5).ToList(); if (list.Count == 0) { continue; } Clan clan = State.Clans.Require(marshal.ClanId); if (!force) { clan.Influence -= 20.0; } num++; AiArmy item = new AiArmy { Id = State.Ids.Allocate("army"), KingdomId = kingdom.Id, LeaderPartyId = marshal.Id, LeaderHeroId = marshal.LeaderHeroId, MemberPartyIds = list.Select((Party p) => p.Id).ToList(), FormedDay = State.Clock.Day, Cohesion = 100.0 }; kingdomArmies.Armies.Add(item); foreach (Party item2 in list) { item2.NextThinkMinute = 0L; } marshal.NextThinkMinute = 0L; Hero hero = State.Heroes.Get(marshal.LeaderHeroId); string text = hero?.Name + " of " + clan.Name + " gathers an army of " + kingdom.Name + ": " + string.Join(", ", list.Select((Party m) => State.Heroes.Get(m.LeaderHeroId)?.Name ?? m.Name)) + "."; State.AddLog(LogCategory.Politics, text, marshal.Id, kingdom.Id); Party playerParty = State.PlayerParty; if (State.PlayerClan?.KingdomId == kingdom.Id && playerParty != null && playerParty.State != PartyState.Destroyed && Vec2.Distance(playerParty.Position, marshal.Position) <= C.StrategicRange(18.0)) { C.Raise(CampaignEventKind.Info, text + " Ride to them and march with the army from Realm → Army.", false, marshal.Id); } } return num; } internal void DisbandAiArmy(AiArmy army, string why) { State.KingdomArmies.Armies.Remove(army); foreach (Party item in army.MemberPartyIds.Select((string id) => State.Parties.Get(id)).Where(LiveLordParty)) { if (item.Order.Kind == OrderKind.Follow && item.Order.TargetId == army.LeaderPartyId) { C.ClearOrder(item); } item.NextThinkMinute = 0L; } State.Parties.Get(army.LeaderPartyId); string text = State.Heroes.Get(army.LeaderHeroId)?.Name ?? "the marshal"; State.AddLog(LogCategory.Politics, "The army of " + text + " has broken up: " + why + ".", army.LeaderPartyId); if (army.PlayerJoined) { Party playerParty = State.PlayerParty; if (playerParty != null && playerParty.Order.Kind == OrderKind.Follow && playerParty.Order.TargetId == army.LeaderPartyId) { C.ClearOrder(playerParty); } C.Raise(CampaignEventKind.Info, "The army of " + text + " has broken up (" + why + "). Your warband is your own again.", false, army.LeaderPartyId); } State.Touch(); } internal bool AiArmyOptions(Party p, double strength, List options) { AiArmy aiArmy = AiArmyOf(p); if (aiArmy == null || p.Id == State.PlayerPartyId) { return false; } Party leader = State.Parties.Get(aiArmy.LeaderPartyId); if (leader == null) { return false; } if (p.Id != leader.Id) { if (leader.State == PartyState.InSettlement) { options.Add(new Campaign.AiOption { Task = "Wait for the army", Score = 2.9, Detail = "outside " + State.Settlements.Get(leader.CurrentSettlementId)?.Name, Apply = delegate { C.ClearOrder(p); } }); } else { options.Add(new Campaign.AiOption { Task = "March with the army", Score = 2.9, Detail = "following " + (State.Heroes.Get(leader.LeaderHeroId)?.Name ?? leader.Name), Apply = delegate { if (p.Order.Kind != OrderKind.Follow || p.Order.TargetId != leader.Id) { C.SetMoveOrder(p, OrderKind.Follow, leader.Position, leader.Id, "army"); } } }); } return true; } if (State.Sieges.Any((SiegeState s) => s.Stage != SiegeStage.Ended && s.BesiegerPartyId == p.Id)) { return false; } if (!AiArmyGathered(aiArmy, p)) { options.Add(new Campaign.AiOption { Task = "Gather the army", Score = 2.4, Detail = aiArmy.MemberPartyIds.Count + " lords on their way", Apply = delegate { C.ClearOrder(p); } }); return false; } if (p.Food < C.DailyFoodNeed(p) * 5.0) { Settlement market = (from s in State.Settlements where s.Type != SettlementType.Hideout && C.CanEnter(p, s) && C.SettlementFood(s) > 0.0 orderby Vec2.Distance(s.Position, p.Position) select s).ThenBy((Settlement s) => s.Id, StringComparer.Ordinal).FirstOrDefault(); if (market != null) { options.Add(new Campaign.AiOption { Task = "Supply the army at " + market.Name, Score = 2.5, Detail = $"food {p.Food:0.0}", Apply = delegate { C.AiSystem.GoToSettlementAi(p, market); } }); } return false; } double force = AiArmyStrength(aiArmy); Settlement target = (from s in State.Settlements where (s.Type == SettlementType.Town || s.Type == SettlementType.Castle) && Vec2.Distance(s.Position, p.Position) <= C.StrategicRange(30.0) && force >= C.SiegeDefenderStrength(s) * 1.25 && C.SiegeOrderReason(p, s).Length == 0 orderby Vec2.Distance(s.Position, p.Position) select s).ThenBy((Settlement s) => s.Id, StringComparer.Ordinal).FirstOrDefault(); if (target != null) { aiArmy.TargetSettlementId = target.Id; options.Add(new Campaign.AiOption { Task = "Lead the army against " + target.Name, Score = 3.2, Detail = "army strength " + force.ToString("0"), Apply = delegate { C.OrderSiege(p, target); } }); } return false; } public string JoinAiArmyReason(string armyId) { AiArmy aiArmy = AiArmies.FirstOrDefault((AiArmy a) => a.Id == armyId); if (aiArmy == null) { return "That army has broken up."; } CommandResult commandResult = C.RequireFree(); if (!commandResult.Ok) { return commandResult.Message; } Clan playerClan = State.PlayerClan; ClanServiceState clanService = State.ClanService; if (playerClan?.KingdomId != aiArmy.KingdomId || clanService == null || clanService.Kind == ClanServiceKind.Independent) { return "Only vassals and mercenaries of " + (State.Kingdoms.Get(aiArmy.KingdomId)?.Name ?? "its realm") + " may march with this army."; } Hero playerHero = State.PlayerHero; if (playerHero == null || !playerHero.CanFight) { return "You're not fit to lead right now."; } ClanArmyState clanArmy = State.ClanArmy; if (clanArmy != null && clanArmy.Active) { return "Disband your own army first."; } if (PlayerAiArmy != null) { return "You're already marching with an army."; } Party party = State.Parties.Get(aiArmy.LeaderPartyId); Party playerParty = State.PlayerParty; if (party == null || playerParty == null || Vec2.Distance(playerParty.Position, party.Position) > Rules.JoinBattleRadius * 2.0) { return "Ride to " + (State.Heroes.Get(aiArmy.LeaderHeroId)?.Name ?? "the marshal") + "'s army first."; } return ""; } public CommandResult JoinAiArmy(string armyId) { string text = JoinAiArmyReason(armyId); if (text.Length > 0) { return CommandResult.Fail(text); } AiArmy aiArmy = AiArmies.First((AiArmy a) => a.Id == armyId); aiArmy.PlayerJoined = true; aiArmy.PlayerJoinedDay = State.Clock.Day; aiArmy.Cohesion = Math.Min(100.0, aiArmy.Cohesion + 10.0); MaintainPlayerArmyFollow(); State.Touch(); return CommandResult.Success("You march with the army of " + (State.Heroes.Get(aiArmy.LeaderHeroId)?.Name ?? "the marshal") + ". Your warband follows the marshal and joins the army's battles; leave from Realm → Army."); } public CommandResult LeaveAiArmy() { AiArmy playerAiArmy = PlayerAiArmy; if (playerAiArmy == null) { return CommandResult.Fail("You're not marching with an army."); } playerAiArmy.PlayerJoined = false; playerAiArmy.PlayerJoinedDay = -1L; Party playerParty = State.PlayerParty; if (playerParty != null && playerParty.Order.Kind == OrderKind.Follow && playerParty.Order.TargetId == playerAiArmy.LeaderPartyId) { C.ClearOrder(playerParty); } State.Touch(); return CommandResult.Success("You leave the army."); } internal void MaintainPlayerArmyFollow() { AiArmy playerAiArmy = PlayerAiArmy; Party playerParty = State.PlayerParty; if (playerAiArmy == null || playerParty == null) { return; } Party party = State.Parties.Get(playerAiArmy.LeaderPartyId); if (!LiveLordParty(party)) { DisbandAiArmy(playerAiArmy, "its marshal has fallen"); } else if (State.Player.Activity == PlayerActivity.Captive || playerParty.State == PartyState.Destroyed || playerParty.State == PartyState.Disbanded) { playerAiArmy.PlayerJoined = false; playerAiArmy.PlayerJoinedDay = -1L; State.Touch(); } else { if (playerParty.State != PartyState.Active || !string.IsNullOrEmpty(playerParty.EncounterId)) { return; } if (party.State == PartyState.InSettlement || party.State == PartyState.Engaged) { if (playerParty.Order.Kind == OrderKind.Follow && playerParty.Order.TargetId == party.Id) { C.ClearOrder(playerParty); } } else if (playerParty.Order.Kind != OrderKind.Follow || playerParty.Order.TargetId != party.Id) { C.SetMoveOrder(playerParty, OrderKind.Follow, party.Position, party.Id, "army"); } } } internal string MarchingWithArmyReason() { AiArmy playerAiArmy = PlayerAiArmy; if (playerAiArmy != null) { return "You march with " + (State.Heroes.Get(playerAiArmy.LeaderHeroId)?.Name ?? "the marshal") + "'s army. Leave it first (Realm → Army)."; } return ""; } } internal sealed class AiSystem { private readonly Campaign C; private ContentDatabase Content => C.Content; private NavGrid Nav => C.Nav; private CampaignRules Rules => C.Rules; private CampaignState State => C.State; internal AiSystem(Campaign host) { C = host; } internal void RunAi() { long minute = State.Clock.Minute; foreach (Party item in State.Parties.ToList()) { if (!(item.Id == State.PlayerPartyId) && !item.AiFrozen && item.Kind != PartyKind.SiegeDefender && (!C.IsMergedIntoArmy(item) || C.AiArmyOf(item) == null) && (item.State == PartyState.Active || item.State == PartyState.InSettlement) && (!C.ClanArmyContains(item.Id) || !C.ClanArmyPartyReserved(item.Id)) && ((item.Order.Kind == OrderKind.None && item.State == PartyState.Active) || minute >= item.NextThinkMinute || SightedPlayer(item))) { long num = (long)(Rules.AiThinkIntervalHours * 60.0); long num2 = (long)(StableHash.Fnv1a64(item.Id) % (ulong)Math.Max(1, Rules.StepMinutes * 3)); item.NextThinkMinute = minute + num + num2; Think(item); } } } internal void Think(Party p) { List list = new List(); Clan clan = State.Clans.Get(p.ClanId); double num = Math.Max(0.01, C.MapStrength(C.ArmyHead(p))); List<(Party, double, double)> list2 = new List<(Party, double, double)>(); if (p.State == PartyState.Active) { foreach (Party party in State.Parties) { if (!(party.Id == p.Id) && party.State == PartyState.Active && State.AreHostile(p, party) && C.CanSee(p, party) && (!(party.Id == State.PlayerPartyId) || State.Player.Activity != PlayerActivity.Captive) && !C.IsMergedIntoArmy(party)) { list2.Add((party, C.MapStrength(party), Vec2.Distance(p.Position, party.Position))); } } } if (p.State == PartyState.InSettlement && p.Kind == PartyKind.Lord && C.MilitaryPartyFor(p) == null && DefendsUnderSiege(p, clan, out var fort)) { double num2 = C.DailyFoodNeed(p) - p.Food; if (num2 > 0.0) { p.Food += C.TakeSettlementFood(fort, num2); } Record(p, new List { new Campaign.AiOption { Task = "Defend " + fort.Name, Score = 3.0, Detail = "under siege" } }, 0); return; } if (p.State == PartyState.InSettlement && State.Clock.Minute < p.WaitUntilMinute) { Record(p, new List { new Campaign.AiOption { Task = "Resting", Score = 1.0, Detail = "in " + State.Settlements.Get(p.CurrentSettlementId)?.Name } }, 0); return; } switch (p.Kind) { case PartyKind.Bandit: BanditOptions(p, num, list2, list); break; case PartyKind.Villager: VillagerOptions(p, num, list2, list); break; case PartyKind.Caravan: C.CaravanOptions(p, num, list2, list); break; case PartyKind.Garrison: C.GarrisonsSystem.Options(p, num, list2, list); break; case PartyKind.Lord: if (C.ClanArmyContains(p.Id) && State.ClanArmy.Members.Any((ClanArmyMember member) => member.KingdomCall && member.PartyId == p.Id)) { C.KingdomArmyOptions(p, clan, num, list2, list); } else if (C.MilitaryPartyFor(p) != null) { C.MilitaryOptions(p, clan, num, list2, list); } else { LordOptions(p, clan, num, list2, list); } break; } AttackPlayerOption(p, num, list); if (list.Count == 0) { return; } list = list.OrderByDescending((Campaign.AiOption o) => o.Score).ThenBy((Campaign.AiOption o) => o.Task, StringComparer.Ordinal).ToList(); int num3 = 0; string prev = p.Ai.Task; if (list[0].Task != prev && list.Count > 1 && p.Order.Kind != OrderKind.None && !list[0].AttacksPlayer) { int num4 = list.FindIndex((Campaign.AiOption o) => o.Task == prev); if (num4 > 0 && list[num4].Score >= list[0].Score * 0.85 && !prev.StartsWith("Flee", StringComparison.Ordinal)) { num3 = num4; p.Ai.OscillationCount++; } } list[num3].Apply?.Invoke(); Record(p, list, num3); } private bool DefendsUnderSiege(Party p, Clan clan, out Settlement fort) { fort = State.Settlements.Get(p.CurrentSettlementId); SiegeState siegeState = ((fort == null) ? null : C.SiegeForSettlement(fort.Id)); if (siegeState != null && (siegeState.Stage == SiegeStage.Preparing || siegeState.Stage == SiegeStage.Ready) && clan != null) { return State.FactionOf(clan) == State.FactionOf(State.Clans.Get(fort.OwnerClanId)); } return false; } internal void Record(Party p, List options, int chosen) { AiDecision aiDecision = new AiDecision { Task = options[chosen].Task, Reason = (options[chosen].Detail ?? ""), AtMinute = State.Clock.Minute, PreviousTask = p.Ai.Task, OscillationCount = p.Ai.OscillationCount }; foreach (Campaign.AiOption item in options.Take(4)) { aiDecision.Alternatives.Add(new AiAlternative { Task = item.Task, Score = Math.Round(item.Score, 3), Detail = (item.Detail ?? "") }); } p.Ai = aiDecision; } internal void AddFleeOrFight(Party p, double myStrength, List<(Party party, double strength, double dist)> hostiles, List options, bool canEngage) { foreach (var item4 in hostiles.OrderBy(((Party party, double strength, double dist) x) => x.dist).ThenBy<(Party, double, double), string>(((Party party, double strength, double dist) x) => x.party.Id, StringComparer.Ordinal)) { Party item = item4.Item1; double item2 = item4.Item2; double item3 = item4.Item3; double num = myStrength / Math.Max(0.01, item2); Party target = item; if (num < Rules.FleeStrengthRatio) { double num2 = 1.0 / num * (1.0 + Math.Max(0.0, 6.0 - item3) / 6.0); options.Add(new Campaign.AiOption { Task = "Flee " + target.Name, Score = 1.5 + num2, Detail = $"threat {target.Name} ratio {num:0.00} at {item3:0.0}", Apply = delegate { C.CancelRaid(p, "withdrawing from a threat", notify: false); p.Order = new MovementOrder { Kind = OrderKind.Flee, ThreatId = target.Id, IssuedAtMinute = State.Clock.Minute - 60 }; } }); } else if (canEngage && num >= Rules.EngageStrengthRatio && target.DisengagedUntilMinute <= State.Clock.Minute) { options.Add(new Campaign.AiOption { Task = "Engage " + target.Name, Score = 1.0 + Math.Min(3.0, num) / 2.0 + Math.Max(0.0, 6.0 - item3) / 12.0, Detail = $"prey {target.Name} ratio {num:0.00} at {item3:0.0}", Apply = delegate { C.SetMoveOrder(p, OrderKind.Engage, target.Position, target.Id, "ai"); } }); } } } internal void AttackPlayerOption(Party p, double myStrength, List options) { Party me = State.PlayerParty; if (MayAttackPlayer(p, me) && OutmatchesPlayer(p, myStrength, me) && !options.Any((Campaign.AiOption o) => o.Task.StartsWith("Flee ", StringComparison.Ordinal))) { string task = "Engage " + me.Name; options.RemoveAll((Campaign.AiOption o) => o.Task == task); double num = myStrength / Math.Max(0.01, C.MapStrength(me)); options.Add(new Campaign.AiOption { Task = task, Score = 5.0, AttacksPlayer = true, Detail = $"prey {me.Name} ratio {num:0.00} at {Vec2.Distance(p.Position, me.Position):0.0}", Apply = delegate { C.SetMoveOrder(p, OrderKind.Engage, me.Position, me.Id, "ai"); } }); } } internal bool SightedPlayer(Party p) { Party playerParty = State.PlayerParty; if (!MayAttackPlayer(p, playerParty) || p.Order.Kind == OrderKind.Flee || (p.Order.Kind == OrderKind.Engage && p.Order.TargetId == playerParty.Id)) { return false; } return OutmatchesPlayer(p, Math.Max(0.01, C.MapStrength(C.ArmyHead(p))), playerParty); } private bool MayAttackPlayer(Party p, Party me) { if (me != null && (p.Kind == PartyKind.Bandit || p.Kind == PartyKind.Lord)) { return p.State == PartyState.Active; } return false; } private bool OutmatchesPlayer(Party p, double myStrength, Party me) { if (me.State == PartyState.Active && State.Player.Activity != PlayerActivity.Captive && !C.IsMergedIntoArmy(me) && me.DisengagedUntilMinute <= State.Clock.Minute && State.AreHostile(p, me) && C.CanSee(p, me)) { return myStrength > C.MapStrength(me); } return false; } internal void BanditOptions(Party p, double myStrength, List<(Party party, double strength, double dist)> hostiles, List options) { AddFleeOrFight(p, myStrength, hostiles, options, canEngage: true); Settlement home = State.Settlements.Get(p.HomeSettlementId); if (home != null && Vec2.Distance(p.Position, home.Position) > Rules.PatrolRadius * 1.5) { options.Add(new Campaign.AiOption { Task = "Return to hideout", Score = 0.6, Detail = home.Name, Apply = delegate { C.SetMoveOrder(p, OrderKind.Patrol, home.Position, "", "home"); } }); } if (p.Order.Kind == OrderKind.None || p.Order.Kind == OrderKind.Patrol) { options.Add(new Campaign.AiOption { Task = "Patrol", Score = ((p.Order.Kind == OrderKind.None) ? 0.5 : 0.3), Detail = "around " + (home?.Name ?? "camp"), Apply = delegate { PatrolNear(p, home?.Position ?? p.Position); } }); } } internal void VillagerOptions(Party p, double myStrength, List<(Party party, double strength, double dist)> hostiles, List options) { AddFleeOrFight(p, myStrength, hostiles, options, canEngage: false); Settlement settlement = State.Settlements.Get(p.HomeSettlementId); Settlement settlement2 = State.Settlements.Get(settlement?.BoundTo ?? ""); if (settlement == null) { return; } if (p.State == PartyState.InSettlement) { Settlement dest = ((p.CurrentSettlementId == settlement.Id) ? settlement2 : settlement); if (dest != null) { options.Add(new Campaign.AiOption { Task = "Travel to " + dest.Name, Score = 0.8, Detail = "trade run", Apply = delegate { C.SetMoveOrder(p, OrderKind.GoToSettlement, dest.Position, dest.Id, "trade"); } }); } } else if (p.Order.Kind == OrderKind.None) { Settlement dest2 = settlement2 ?? settlement; options.Add(new Campaign.AiOption { Task = "Travel to " + dest2.Name, Score = 0.7, Detail = "resume trade run", Apply = delegate { C.SetMoveOrder(p, OrderKind.GoToSettlement, dest2.Position, dest2.Id, "trade"); } }); } } internal void LordOptions(Party p, Clan clan, double myStrength, List<(Party party, double strength, double dist)> hostiles, List options) { if (C.AiArmyOptions(p, myStrength, options)) { AddFleeOrFight(p, myStrength, hostiles, options, canEngage: false); return; } bool flag = State.Sieges.Any((SiegeState s) => s.Stage != SiegeStage.Ended && s.BesiegerPartyId == p.Id); AddFleeOrFight(p, myStrength, hostiles, options, !flag && C.PartyCombatants(p) >= Rules.LordRecruitThreshold / 2); int num = C.PartyCombatants(p); List list = (from s in State.Settlements where s.Type != SettlementType.Hideout && C.CanEnter(p, s) orderby Vec2.Distance(s.Position, p.Position) select s).ThenBy((Settlement s) => s.Id, StringComparer.Ordinal).ToList(); List list2 = list.Where((Settlement s) => s.OwnerClanId == p.ClanId).ToList(); int num2 = C.AiLordRecruitTarget(p); bool flag2 = num < Rules.LordRecruitThreshold; if ((flag2 || num < (int)((double)num2 * 0.6)) && list.Count > 0 && (clan?.Gold ?? 0) > 50 && (flag2 ? C.ClanCanAffordUpkeep(clan, 0.0) : C.LordCanGrowParty(p, 0.0))) { Settlement target = list.FirstOrDefault((Settlement s) => s.Recruits.Any((RecruitSlot r) => r.Available && C.RecruitSlotRelationReason(s, r, p.ClanId).Length == 0)) ?? list2.FirstOrDefault((Settlement s) => C.VillageRecruitmentReason(s).Length == 0) ?? list.FirstOrDefault((Settlement s) => C.VillageRecruitmentReason(s).Length == 0); if (target != null) { options.Add(new Campaign.AiOption { Task = "Recruit at " + target.Name, Score = (flag2 ? (1.2 + (double)(Rules.LordRecruitThreshold - num) / (double)Rules.LordRecruitThreshold) : (0.35 + 0.35 * (double)(num2 - num) / Math.Max(1.0, num2))), Detail = $"{num} / {num2} troops", Apply = delegate { GoToSettlementAi(p, target); } }); } } if (p.Food < C.DailyFoodNeed(p) * 1.5 && list.Count > 0) { Settlement target2 = list[0]; options.Add(new Campaign.AiOption { Task = "Resupply at " + target2.Name, Score = 1.1, Detail = $"food {p.Food:0.0}", Apply = delegate { GoToSettlementAi(p, target2); } }); } if (p.State == PartyState.InSettlement || p.Order.Kind == OrderKind.None || p.Order.Kind == OrderKind.Patrol) { Settlement anchor = ((list2.Count > 0) ? list2[C.RandomInt("ai", 0, list2.Count)] : list.FirstOrDefault()); options.Add(new Campaign.AiOption { Task = "Patrol", Score = ((p.Order.Kind == OrderKind.None) ? 0.5 : 0.25), Detail = "near " + (anchor?.Name ?? "here"), Apply = delegate { PatrolNear(p, anchor?.Position ?? p.Position); } }); } C.LordRaidOptions(p, clan, myStrength, hostiles, options); C.LordSiegeOptions(p, clan, myStrength, hostiles, options); } internal void GoToSettlementAi(Party p, Settlement s) { if (p.State == PartyState.InSettlement && p.CurrentSettlementId == s.Id) { OnAiEnteredSettlement(p, s); } else { C.SetMoveOrder(p, OrderKind.GoToSettlement, s.Position, s.Id, "ai"); } } internal void PatrolNear(Party p, Vec2 anchor) { RandomStream randomStream = State.Random.Get("ai"); for (int i = 0; i < 8; i++) { double num = randomStream.Range(0.0, Math.PI * 2.0); double num2 = randomStream.Range(2.0, Rules.PatrolRadius); Vec2 vec = anchor + new Vec2(Math.Cos(num) * num2, Math.Sin(num) * num2); if (Nav.IsPassable(vec) && Nav.SameComponent(p.Position, vec)) { C.SetMoveOrder(p, OrderKind.Patrol, vec, "", "patrol"); break; } } } internal void OnAiEnteredSettlement(Party p, Settlement s) { if (C.IsKingdomArmyParty(p)) { C.KingdomArmySettlementArrival(p, s); return; } if (C.MilitaryPartyFor(p) != null) { C.MilitarySettlementArrival(p, s); return; } Clan clan = State.Clans.Get(p.ClanId); if (p.Kind == PartyKind.Lord && clan != null) { int num = Math.Min(C.PartySizeLimit(p), C.AiLordRecruitTarget(p)) - p.Troops.TotalTroops; foreach (RecruitSlot item in s.Recruits.Where((RecruitSlot r) => r.Available).ToList()) { if (C.RecruitSlotRelationReason(s, item, p.ClanId).Length > 0) { continue; } if (num <= 0) { break; } UnitDef unitDef = C.UnitDef(item.UnitId); if (unitDef != null && clan.Gold >= unitDef.RecruitCost + 100) { double extraDaily = unitDef.DailyWage + Rules.FoodPerTroopPerDay * unitDef.FoodUse * Rules.FoodPrice; if ((C.PartyCombatants(p) < Rules.LordRecruitThreshold) ? (!C.ClanCanAffordUpkeep(clan, extraDaily)) : (!C.LordCanGrowParty(p, extraDaily))) { break; } State.Transact(clan, -unitDef.RecruitCost, LedgerAccount.Recruitment, p.Name + " recruits " + unitDef.Name + " at " + s.Name); p.Troops.Add(unitDef.Id, 1); item.Available = false; num--; } } if (C.PartyCombatants(p) < 3 && s.OwnerClanId == p.ClanId && C.VillageRecruitmentReason(s).Length == 0) { string text = Content.Cultures.Get(s.CultureId)?.BasicTroop; if (text != null) { p.Troops.Add(text, Rules.LordEmergencyLevy); State.AddLog(LogCategory.Recruitment, $"{p.Name} raised an emergency levy of {Rules.LordEmergencyLevy} at {s.Name}.", p.Id, s.Id); } } double num2 = Math.Min(C.SettlementFood(s), C.DailyFoodNeed(p) * 7.0 - p.Food); if (num2 > 0.0) { long num3 = (long)Math.Ceiling(num2 * C.FoodPrice(s)); if (clan.Gold >= num3 + 50) { State.Transact(clan, -num3, LedgerAccount.Food, p.Name + " buys food at " + s.Name); p.Food += C.TakeSettlementFood(s, num2); } } p.WaitUntilMinute = State.Clock.Minute + 60 * C.RandomInt("ai", 2, 7); } else if (p.Kind == PartyKind.Caravan) { C.CaravanTradeArrival(p, s); } else if (p.Kind == PartyKind.Villager) { p.WaitUntilMinute = State.Clock.Minute + 60 * C.RandomInt("ai", 3, 9); C.VillageTradeArrival(p, s); } } } internal sealed class AllegianceSystem { private readonly Campaign C; private CampaignState State => C.State; internal AllegianceSystem(Campaign host) { C = host; } public double ServiceRetainerForecast() { ClanServiceState clanService = State.ClanService; Clan playerClan = State.PlayerClan; if (clanService == null || !clanService.Initialized || clanService.Kind != ClanServiceKind.Mercenary || playerClan == null || playerClan.IsEliminated || playerClan.KingdomId != clanService.KingdomId || State.Clock.Day >= clanService.EndsDay) { return 0.0; } Clan clan = C.ServiceRuler(clanService.KingdomId); if (clan == null || clan.Id == playerClan.Id) { return 0.0; } return Math.Min(50L, Math.Min(Math.Max(0L, clan.Gold), long.MaxValue - playerClan.Gold)); } public void ChangeSettlementOwner(Settlement settlement, string ownerClanId) { Clan clan = State.Clans.Get(ownerClanId); if (settlement == null || State.Settlements.Get(settlement.Id) != settlement || settlement.Type == SettlementType.Hideout || clan == null || clan.IsBandit || clan.IsEliminated) { throw new InvalidOperationException("Invalid settlement ownership transfer."); } if (settlement.OwnerClanId == ownerClanId) { return; } settlement.OwnerClanId = ownerClanId; foreach (Party item in State.Parties.Where((Party p) => p.ActiveRaid?.SettlementId == settlement.Id || (p.Order.Kind == OrderKind.Raid && p.Order.TargetId == settlement.Id)).ToList()) { C.CancelRaid(item, "the village changed hands"); } C.ReleaseSettlementGovernor(settlement, "their holding changed hands"); C.SyncSettlementManagementOwner(settlement); NotableState notableState = C.SettlementNotable(settlement.Id); if (notableState != null) { notableState.OwnerClanId = ownerClanId; } State.Touch(); } public void OnPlayerAllegianceChanged() { C.OnDiplomacyChanged(); } } internal sealed class ArmyMergeSystem { private readonly Campaign C; private NavGrid Nav => C.Nav; private CampaignRules Rules => C.Rules; private CampaignState State => C.State; internal SortedDictionary Attached => State.KingdomArmies?.AttachedTo; internal ArmyMergeSystem(Campaign host) { C = host; } public double ArmyMergeRadius(Party leader) { return Math.Max(Rules.ContactRadius, (leader == null || leader.State != PartyState.Active) ? 0.0 : (C.ComputeUnaccompaniedSpeed(leader).Speed * (double)Rules.StepMinutes / 60.0 * 1.15)); } internal Party ArmyLeaderOf(Party p) { if (p == null) { return null; } ClanArmyState clanArmy = State.ClanArmy; if (clanArmy != null && clanArmy.Active && p.Id != clanArmy.LeaderPartyId && C.ClanArmyContains(p.Id)) { return State.Parties.Get(clanArmy.LeaderPartyId); } if (p.Id == State.PlayerPartyId) { AiArmy playerAiArmy = C.PlayerAiArmy; if (playerAiArmy != null) { return State.Parties.Get(playerAiArmy.LeaderPartyId); } return null; } AiArmy aiArmy = C.AiArmies.FirstOrDefault((AiArmy a) => a.MemberPartyIds.Contains(p.Id)); if (aiArmy != null) { return State.Parties.Get(aiArmy.LeaderPartyId); } return null; } public bool IsMergedIntoArmy(Party p) { if (p != null && Attached != null) { return Attached.ContainsKey(p.Id); } return false; } public Party ArmyHead(Party p) { if (p == null || Attached == null || !Attached.TryGetValue(p.Id, out var value)) { return p; } return State.Parties.Get(value) ?? p; } public IEnumerable MergedMembers(Party leader) { if (Attached != null && leader != null) { return from x in Attached where x.Value == leader.Id select State.Parties.Get(x.Key) into m where m != null && m.State != PartyState.Destroyed && m.State != PartyState.Disbanded select m; } return Enumerable.Empty(); } public bool IsArmyHead(Party p) { if (p != null && Attached != null) { return Attached.ContainsValue(p.Id); } return false; } public double MapStrength(Party p) { if (p != null) { return C.PartyStrength(p) + MergedMembers(p).Sum((Func)C.PartyStrength); } return 0.0; } public int MapCombatants(Party p) { if (p != null) { return C.PartyCombatants(p) + MergedMembers(p).Sum((Func)C.PartyCombatants); } return 0; } public bool HiddenOnMap(Party p) { if (p == null) { return false; } Party playerParty = State.PlayerParty; bool flag = IsMergedIntoArmy(playerParty); if (p.Id == State.PlayerPartyId) { return false; } if (flag && ArmyHead(playerParty)?.Id == p.Id) { return true; } return IsMergedIntoArmy(p); } public int MapPartyCount(Party p) { if (p == null) { return 0; } if (p.Id == State.PlayerPartyId && IsMergedIntoArmy(p)) { return MapCombatants(ArmyHead(p)); } return MapCombatants(p); } public bool ShownAsArmy(Party p) { if (p != null) { if (!IsArmyHead(p)) { if (p.Id == State.PlayerPartyId) { return IsMergedIntoArmy(p); } return false; } return true; } return false; } internal void UpdateArmyMerges() { SortedDictionary attached = Attached; if (attached == null) { return; } bool flag = false; foreach (KeyValuePair item in attached.ToList()) { Party party = State.Parties.Get(item.Key); Party party2 = State.Parties.Get(item.Value); bool flag2 = party == null || party.State == PartyState.Destroyed || party.State == PartyState.Disbanded; bool flag3 = party2 == null || party2.State == PartyState.Destroyed || party2.State == PartyState.Disbanded; if (flag2 || flag3 || ArmyLeaderOf(party)?.Id != party2.Id || !ArmyBoundOrder(party, party2) || (party.Id == State.PlayerPartyId && State.Player.Activity == PlayerActivity.Captive)) { attached.Remove(item.Key); if (!flag2) { Separate(party, party2); } flag = true; } } foreach (Party party7 in State.Parties) { if (!attached.ContainsKey(party7.Id) && party7.State == PartyState.Active && string.IsNullOrEmpty(party7.EncounterId)) { Party party3 = ArmyLeaderOf(party7); if (party3 != null && !(party3.Id == party7.Id) && !attached.ContainsKey(party3.Id) && string.IsNullOrEmpty(party3.EncounterId) && party3.State != PartyState.Destroyed && party3.State != PartyState.Disbanded && !(Vec2.Distance(party7.Position, party3.Position) > ArmyMergeRadius(party3)) && ArmyBoundOrder(party7, party3)) { attached[party7.Id] = party3.Id; flag = true; } } } foreach (KeyValuePair item2 in attached.ToList()) { Party party4 = State.Parties.Get(item2.Key); Party party5 = State.Parties.Get(item2.Value); if (party4 == null || party5 == null || !string.IsNullOrEmpty(party4.EncounterId) || !string.IsNullOrEmpty(party5.EncounterId)) { continue; } if (party5.State == PartyState.InSettlement) { Settlement settlement = State.Settlements.Get(party5.CurrentSettlementId); if (party4.State == PartyState.Active && settlement != null && party4.CurrentSettlementId != settlement.Id) { if (party4.Id != State.PlayerPartyId) { C.ClearOrder(party4); } party4.Position = settlement.Position; C.TryEnterSettlement(party4, settlement); flag = true; } } else if (party5.State == PartyState.Active) { if (party4.State == PartyState.InSettlement) { C.LeaveSettlementInternal(party4); party4.Position = party5.Position; flag = true; } else if (party4.State == PartyState.Active && (party4.Position.X != party5.Position.X || party4.Position.Y != party5.Position.Y)) { party4.Position = party5.Position; flag = true; } } } foreach (string item3 in attached.Values.Distinct().ToList()) { Party party6 = State.Parties.Get(item3); if (party6 != null && string.IsNullOrEmpty(party6.EncounterId)) { List list = new List { party6 }; list.AddRange(from m in MergedMembers(party6) where string.IsNullOrEmpty(m.EncounterId) select m); if (list.Count > 1 && list.Any((Party m) => C.FoodSupply(m) < C.DailyFoodNeed(m) * 2.0)) { C.ShareArmyFood(list, 3.0, 2.0); } } } if (flag) { State.Touch(); } } internal bool ArmyBoundOrder(Party member, Party leader) { if (member.Id == State.PlayerPartyId) { return true; } MovementOrder order = member.Order; if (order.Kind != OrderKind.None && (order.Kind != OrderKind.Follow || !(order.TargetId == leader.Id))) { if (order.Kind == OrderKind.GoToSettlement && leader.State == PartyState.InSettlement) { return order.TargetId == leader.CurrentSettlementId; } return false; } return true; } internal void Separate(Party member, Party leader) { if (member.State == PartyState.Active && leader != null) { double num = (double)(StableHash.Fnv1a64("separate|" + member.Id) % 360) * Math.PI / 180.0; Vec2 vec = leader.Position + new Vec2(Math.Cos(num) * Rules.ContactRadius * 1.5, Math.Sin(num) * Rules.ContactRadius * 1.5); if (Nav.IsPassable(vec) && Nav.SameComponent(leader.Position, vec)) { member.Position = vec; } member.NextThinkMinute = 0L; } } } public sealed class Campaign { internal sealed class AiOption { public string Task; public double Score; public string Detail; public Action Apply; public bool AttacksPlayer; } public struct Personality { public int Honor; public int Mercy; public int Valor; public int Generosity; public int Calculating; } internal struct ContactCandidate { public double T; public string Initiator; public string Target; public Vec2 InitiatorPos; public Vec2 TargetPos; } internal sealed class WarRecord { public string Other = ""; public long SinceMinute; } internal sealed class LegendQuest : QuestTemplate { private readonly LegendDef _l; public override string Id => "legend." + _l.Unit; public override QuestSource Source { get { if (!(_l.QuestGiver == "lord")) { if (!(_l.QuestGiver == "tavern")) { return QuestSource.Notable; } return QuestSource.Chain; } return QuestSource.Lord; } } public override string[] GiverKinds => new string[1] { _l.QuestGiver }; public override int Days { get { if (!(_l.QuestTask == "hunt")) { return 16; } return 12; } } private bool Deliver => _l.QuestTask == "deliver"; public LegendQuest(LegendDef l) { _l = l; } public override QuestState TryOffer(Campaign c, QuestGiver giver, RandomStream rng) { long num = c.State.Clock.Day / 7; if ((double)(StableHash.Fnv1a64(Id + "|" + giver.Id + "|" + num.ToString(CultureInfo.InvariantCulture) + "|" + c.State.Random.Seed.ToString(CultureInfo.InvariantCulture)) % 10000) / 10000.0 >= 0.2) { return null; } if (c.UnitDef(_l.Unit) == null || giver.Settlement == null) { return null; } if (!Deliver && c.NearestHideout(giver.Settlement.Position) == null) { return null; } QuestState questState = new QuestState { Title = _l.QuestTitle, UnitId = _l.Unit, TargetSettlementId = giver.Settlement.Id, Quantity = _l.QuestJoin, Note = _l.Story }; if (Deliver) { TradeGoodDef tradeGoodDef = TabsBannerlord.Core.Content.TradeGoods.Get(_l.QuestGood); if (tradeGoodDef == null) { return null; } questState.GoodId = tradeGoodDef.Id; questState.Needed = ((tradeGoodDef.Id == "good.horses") ? (4 + rng.Range(0, 3)) : (6 + rng.Range(0, 5))); } else { questState.Needed = 7 + rng.Range(0, 5); } return questState; } private long PayCost(QuestState q) { return Round10((double)((TabsBannerlord.Core.Content.TradeGoods.Get(q.GoodId)?.BasePrice ?? 50) * q.Needed) * 1.6); } public override List OfferLines(Campaign c, QuestState q) { UnitDef unitDef = c.UnitDef(q.UnitId); List list = new List { _l.Story }; list.Add(Deliver ? ("Bring " + q.Needed + " " + QuestTemplate.GoodName(q.GoodId).ToLowerInvariant() + " and " + q.Quantity + " " + unitDef?.Name + ((q.Quantity == 1) ? "" : "s") + " will join you.") : ("Beat about " + q.Needed + " bandits nearby and " + q.Quantity + " " + unitDef?.Name + ((q.Quantity == 1) ? "" : "s") + " will join you.")); return list; } public override List OfferOptions(Campaign c, QuestState q, QuestContext ctx) { List list = new List(); if (Deliver) { list.Add(QuestTemplate.Option("deliver", "I'll bring the " + QuestTemplate.GoodName(q.GoodId).ToLowerInvariant() + ".", "", "Bring " + q.Needed + " to " + c.State.Settlements.Get(q.TargetSettlementId)?.Name + ((q.Source == QuestSource.Lord) ? (" (or wherever " + q.GiverName + " is)") : "") + ".")); long num = PayCost(q); list.Add(QuestTemplate.Option("pay", "Pay for them instead. (" + num.ToString("N0") + " denars)", (c.State.PlayerClan.Gold < num) ? ("You cannot spare " + num.ToString("N0") + " denars.") : "", "Settled at once: the troops join you now.")); } else { list.Add(QuestTemplate.Option("hunt", "I'll deal with the bandits.", "", "Beat them, then come back.")); } return list; } public override CommandResult Accept(Campaign c, QuestState q, string approach, QuestContext ctx) { if (approach == "pay") { long amount = PayCost(q); Settlement settlement = c.State.Settlements.Get(q.TargetSettlementId); if (settlement?.Market == null) { return CommandResult.Fail("There is nobody to pay here."); } if (!c.PlayerPaysMarket(settlement, amount, "Paid for " + q.Title)) { return CommandResult.Fail("You cannot spare " + amount.ToString("N0") + " denars."); } string text = Grant(c, q); c.EndQuest(q, QuestStatus.Succeeded, text); return CommandResult.Success(text); } if (approach == "hunt") { Settlement settlement2 = c.State.Settlements.Require(q.TargetSettlementId); string[] array = new string[4] { "Thieves", "Wreckers", "Bandits", "Cutthroats" }; RandomStream randomStream = c.State.Random.Get("quests"); Party party = c.SpawnQuestBand(settlement2.Position, array[randomStream.Range(0, array.Length)] + " near " + settlement2.Name, q.Needed, null, randomStream); if (party == null) { return CommandResult.Fail("There are no bandits to be found."); } q.TargetPartyId = party.Id; q.TargetName = party.Name; q.Stage = "hunt"; return CommandResult.Success(party.Name + " were last seen near " + settlement2.Name + "."); } q.Stage = "gather"; return CommandResult.Success(); } private static string Grant(Campaign c, QuestState q) { UnitDef unitDef = c.UnitDef(q.UnitId); c.State.PlayerParty.Troops.Add(q.UnitId, q.Quantity); if (!string.IsNullOrEmpty(q.GiverNotableId)) { c.AdjustNotableRelation(q.GiverNotableId, 5, "you helped them"); } else if (!string.IsNullOrEmpty(q.GiverHeroId)) { c.AdjustClanRelation(c.State.PlayerClanId, q.GiverClanId, 5); } c.State.PlayerClan.Renown += 2.0; string text = q.Quantity + " " + unitDef?.Name + ((q.Quantity == 1) ? "" : "s") + " joined your party."; c.State.AddLog(LogCategory.Recruitment, q.Title + ": " + text, q.TargetSettlementId); return text; } public override string OnVictory(Campaign c, QuestState q, HashSet beaten) { if (q.Stage != "hunt" || !beaten.Contains(q.TargetPartyId)) { return ""; } q.Stage = "beaten"; return "The bandits are beaten: go back to " + q.GiverName + "."; } public override string Invalid(Campaign c, QuestState q) { if (!(q.Stage == "hunt") || !PartyGone(c.State.Parties.Get(q.TargetPartyId))) { return ""; } return "Somebody else dealt with the bandits first."; } private bool AtGiver(QuestState q, QuestContext ctx) { if (q.Source != QuestSource.Lord) { return QuestTemplate.At(ctx, q.TargetSettlementId); } if (ctx?.TalkingTo != null) { return ctx.TalkingTo.Id == q.GiverHeroId; } return false; } public override StoryPrompt Stage(Campaign c, QuestState q, QuestContext ctx) { if (!AtGiver(q, ctx)) { return null; } if (q.Stage == "gather") { int num = c.CargoCount(c.State.PlayerParty, q.GoodId); StoryPrompt storyPrompt = QuestTemplate.Prompt(q, q.GiverName, "", "Have you brought the " + QuestTemplate.GoodName(q.GoodId).ToLowerInvariant() + "?"); storyPrompt.Options.Add(QuestTemplate.Option("hand", "Hand over " + q.Needed + " " + QuestTemplate.GoodName(q.GoodId).ToLowerInvariant() + ".", (num < q.Needed) ? ("You carry " + num + " of " + q.Needed + ".") : "")); storyPrompt.Options.Add(QuestTemplate.Option("close", "Not yet.")); storyPrompt.Optional = num < q.Needed; return storyPrompt; } if (q.Stage == "beaten") { StoryPrompt storyPrompt2 = QuestTemplate.Prompt(q, q.GiverName, "", "You did it! As we promised."); storyPrompt2.Options.Add(QuestTemplate.Option("collect", "Welcome them to your party.")); return storyPrompt2; } return null; } public override CommandResult Choose(Campaign c, QuestState q, string option, QuestContext ctx) { if (option == "close") { return CommandResult.Success(); } if (option == "hand") { Party playerParty = c.State.PlayerParty; int num = c.CargoCount(playerParty, q.GoodId) - q.Needed; if (num < 0) { return CommandResult.Fail("You do not carry enough."); } if (num == 0) { playerParty.Cargo.Remove(q.GoodId); } else { playerParty.Cargo[q.GoodId] = num; } } string text = Grant(c, q); c.EndQuest(q, QuestStatus.Succeeded, text); return CommandResult.Success(text); } public override List Objectives(Campaign c, QuestState q) { if (Deliver) { List list = new List(); list.Add(QuestTemplate.Goal("Carry " + q.Needed + " " + QuestTemplate.GoodName(q.GoodId).ToLowerInvariant() + " (" + Math.Min(q.Needed, c.CargoCount(c.State.PlayerParty, q.GoodId)) + " aboard)", c.CargoCount(c.State.PlayerParty, q.GoodId) >= q.Needed)); list.Add(QuestTemplate.Goal("Bring them to " + ((q.Source == QuestSource.Lord) ? q.GiverName : c.State.Settlements.Get(q.TargetSettlementId)?.Name), done: false)); return list; } return new List { QuestTemplate.Goal("Beat the bandits" + c.KnownPartyWhereabouts(q.TargetPartyId), q.Stage == "beaten"), QuestTemplate.Goal("Go back to " + q.GiverName, done: false) }; } public override string Summary(Campaign c, QuestState q) { return q.Note; } public override IEnumerable Places(Campaign c, QuestState q) { if (q.Stage == "hunt" && c.State.PlayerSightings.ContainsKey(q.TargetPartyId)) { yield return q.TargetPartyId; } yield return q.TargetSettlementId; } } private sealed class HeirloomStory : QuestTemplate { public override string Id => "story.heirloom"; public override QuestSource Source => QuestSource.Chain; public override string[] GiverKinds => new string[1] { "tavern" }; public override int Days => 30; public override QuestState TryOffer(Campaign c, QuestGiver giver, RandomStream rng) { Settlement settlement = giver.Settlement; if (c.NearestHideout(settlement.Position) == null) { return null; } string[] array = new string[5] { "Wobblefang", "Old Grumbler", "the Turnip Splitter", "Lady Pointy", "Grandfather's Regret" }; return new QuestState { Title = "The Heirloom Blade", TargetSettlementId = settlement.Id, TargetName = array[rng.Range(0, array.Length)], Quantity = rng.Range(10, 15) }; } public override List OfferLines(Campaign c, QuestState q) { List list = new List(); list.Add("Buy an old soldier a drink? ... Thank you. My grandfather's sword, " + q.TargetName + ", was buried with him in a barrow outside " + c.State.Settlements.Get(q.TargetSettlementId)?.Name + "."); list.Add("Last week I went to pay my respects and the stones were pulled aside. Grave robbers. I'm too old to chase them. Will you find it? Bring it home?"); return list; } public override List OfferOptions(Campaign c, QuestState q, QuestContext ctx) { return new List { QuestTemplate.Option("seek", "I'll find your grandfather's sword.", "", "Visit the barrow; follow where it leads.") }; } public override CommandResult Accept(Campaign c, QuestState q, string approach, QuestContext ctx) { Settlement settlement = c.State.Settlements.Require(q.TargetSettlementId); DiscoverySite discoverySite = c.NewQuestSite(q, SiteKind.Barrow, "The barrow of " + q.GiverName.Split(new char[1] { ' ' }).Last() + "'s grandfather", settlement.Position, c.StrategicRange(3.0), c.StrategicRange(7.0), c.State.Random.Get("quests")); q.TargetSiteId = discoverySite.Id; q.Stage = "barrow"; return CommandResult.Success("The barrow lies outside " + settlement.Name + "; it is marked on your map."); } public override StoryPrompt Stage(Campaign c, QuestState q, QuestContext ctx) { if (q.Stage == "barrow" && ctx.Site != null && ctx.Site.Id == q.TargetSiteId) { StoryPrompt storyPrompt = QuestTemplate.Prompt(q, "", "", "The barrow's capstones have been levered aside. Boot prints in the mud; a broken spade."); storyPrompt.Title = ctx.Site.Name; storyPrompt.Options.Add(QuestTemplate.Option("search", "Search the barrow carefully. (6 hours)", "", "Your party waits here while you search.")); storyPrompt.Options.Add(QuestTemplate.Option("dig", "Set the men digging. (2 hours, needs 10 troops)", (c.State.PlayerParty.Troops.TotalHealthy < 10) ? "You need 10 healthy troops to dig." : "")); storyPrompt.Options.Add(QuestTemplate.Option("close", "Come back later.")); return storyPrompt; } if (q.Stage != "blade") { return null; } Settlement settlement = c.State.Settlements.Get(q.TargetSettlementId); if (ctx.Here != null && ctx.Here.Id == q.TargetSettlementId) { StoryPrompt storyPrompt2 = QuestTemplate.Prompt(q, q.GiverName, "in the tavern of " + settlement?.Name, "Is that... " + q.TargetName + "! You found it!"); storyPrompt2.Options.Add(QuestTemplate.Option("return", "It's yours. Your grandfather's sword, home again.", "", "Renown, and the old soldier's grandson asks to ride with you.")); storyPrompt2.Options.Add(QuestTemplate.Option("keep", "I think I'll keep it.", "", q.TargetName + " goes in your bag. The town will hear of it.")); return storyPrompt2; } NotableState notableState = ((ctx.Here == null || ctx.Here.Type != SettlementType.Town) ? null : c.SettlementNotable(ctx.Here.Id)); StoryPrompt storyPrompt3 = QuestTemplate.Prompt(q, notableState?.Name ?? "", (notableState == null) ? "" : (notableState.Occupation + " of " + ctx.Here.Name), (notableState == null) ? ("You carry " + q.TargetName + ", the old soldier's sword.") : "That is a fine old blade. I would pay well for it."); if (notableState != null) { long num = 700L; storyPrompt3.Options.Add(QuestTemplate.Option("sell", "Sell it to " + notableState.Name + ". (" + num + " denars)", (ctx.Here.Market.Gold < num) ? (notableState.Name + " cannot pay that much just now.") : "")); } storyPrompt3.Options.Add(QuestTemplate.Option("keep", "Keep it for yourself.", "", q.TargetName + " goes in your bag.")); storyPrompt3.Options.Add(QuestTemplate.Option("close", "Not now.")); storyPrompt3.Title = q.Title; storyPrompt3.Optional = true; return storyPrompt3; } public override CommandResult Choose(Campaign c, QuestState q, string option, QuestContext ctx) { if (option == "close") { return CommandResult.Success(); } RandomStream rng = c.State.Random.Get("quests"); Settlement settlement = c.State.Settlements.Require(q.TargetSettlementId); if (q.Stage == "barrow") { DiscoverySite discoverySite = c.State.Quests.Sites.FirstOrDefault((DiscoverySite s) => s.Id == q.TargetSiteId); if (discoverySite == null) { return CommandResult.Fail("The barrow is gone."); } CommandResult commandResult = c.Wait((option == "dig") ? 2 : 6); if (!commandResult.Ok) { return commandResult; } discoverySite.Explored = true; discoverySite.ExploredMinute = c.State.Clock.Minute; discoverySite.Outcome = "The grave was robbed by Gerrold the Grabby."; Party party = c.SpawnQuestBand(discoverySite.Position, "Gerrold the Grabby's Band", q.Quantity, null, rng); if (party == null) { c.EndQuest(q, QuestStatus.Cancelled, "The robbers' trail goes cold."); return CommandResult.Success("The trail goes cold."); } q.TargetPartyId = party.Id; q.Stage = "thief"; QuestLog(c, q, "The grave is empty but for a scabbard and a note: \"Thanks for the sword. — G.\" Gerrold the Grabby's band is camped nearby."); c.GrantSkillExperience(c.State.PlayerHero, "scouting", 30.0); return CommandResult.Success("Gerrold the Grabby took it. His band is camped nearby."); } if (option == "return") { c.State.PlayerClan.Renown += 8.0; c.GrantSkillExperience(c.State.PlayerHero, "leadership", 60.0); c.AdjustNotableRelation(c.SettlementNotable(settlement.Id)?.Id, 5, "you brought home an old soldier's sword"); UnitDef unitDef = c.CultureSoldier(settlement.CultureId, 4, rare: false); int num = ((unitDef != null) ? c.JoinPlayer(unitDef.Id, 1) : 0); c.EndQuest(q, QuestStatus.Succeeded, "You brought " + q.TargetName + " home to " + q.GiverName + "." + ((num > 0) ? (" Their grandson, a " + unitDef.Name + ", rides with you now.") : "")); return CommandResult.Success("The old soldier weeps with joy."); } if (option == "sell") { long num2 = 700L; Settlement here = ctx.Here; if (here?.Market == null || here.Market.Gold < num2) { return CommandResult.Fail("They cannot pay."); } here.Market.Gold -= num2; c.State.Transact(c.State.PlayerClan, num2, LedgerAccount.Quest, q.TargetName + ", sold at " + here.Name); c.AdjustNotableRelation(c.SettlementNotable(settlement.Id)?.Id, -3, "you sold an old soldier's sword"); c.EndQuest(q, QuestStatus.Succeeded, "You sold " + q.TargetName + " in " + here.Name + " for " + num2 + " denars."); return CommandResult.Success("Sold for " + num2 + " denars."); } string text = c.GiveRelicWeapon(q.TargetName, rng); c.AdjustNotableRelation(c.SettlementNotable(settlement.Id)?.Id, -3, "you kept an old soldier's sword"); c.EndQuest(q, QuestStatus.Succeeded, "You kept " + q.TargetName + " for yourself."); return CommandResult.Success(text + " is in your bag."); } public override string OnVictory(Campaign c, QuestState q, HashSet beaten) { if (q.Stage != "thief" || !beaten.Contains(q.TargetPartyId)) { return ""; } q.Stage = "blade"; return "You took back " + q.TargetName + " from Gerrold the Grabby. Return it to " + q.GiverName + " in " + c.State.Settlements.Get(q.TargetSettlementId)?.Name + ", or not."; } public override string Invalid(Campaign c, QuestState q) { if (!(q.Stage == "thief") || !PartyGone(c.State.Parties.Get(q.TargetPartyId))) { return ""; } return "Somebody else caught Gerrold the Grabby, and the sword vanished."; } public override List Objectives(Campaign c, QuestState q) { string text = c.State.Settlements.Get(q.TargetSettlementId)?.Name; List list = new List(); list.Add(QuestTemplate.Goal("Visit the robbed barrow outside " + text, q.Stage != "barrow")); list.Add(QuestTemplate.Goal("Catch the grave robbers" + ((q.Stage == "thief") ? c.KnownPartyWhereabouts(q.TargetPartyId) : ""), q.Stage == "blade")); list.Add(QuestTemplate.Goal("Bring " + q.TargetName + " home to " + q.GiverName + " in " + text + " (or keep it, or sell it)", done: false)); return list; } public override string Summary(Campaign c, QuestState q) { return "An old soldier's family sword, " + q.TargetName + ", was stolen from a barrow."; } public override IEnumerable Places(Campaign c, QuestState q) { if (q.Stage == "barrow") { yield return "site:" + q.TargetSiteId; } if (q.Stage == "thief" && c.State.PlayerSightings.ContainsKey(q.TargetPartyId)) { yield return q.TargetPartyId; } yield return q.TargetSettlementId; } } private sealed class FeudStory : QuestTemplate { private const long Fine = 200L; private const int FeastGrain = 3; public override string Id => "story.feud"; public override QuestSource Source => QuestSource.Chain; public override string[] GiverKinds => new string[1] { "village" }; public override int Days => 20; public override QuestState TryOffer(Campaign c, QuestGiver giver, RandomStream rng) { Settlement a = giver.Settlement; Settlement settlement = (from s in c.State.Settlements where s.Type == SettlementType.Village && s.Id != a.Id && c.SettlementNotable(s.Id) != null && c.ContractFriendlySettlement(s) where Vec2.Distance(s.Position, a.Position) <= c.StrategicRange(20.0) orderby Vec2.Distance(s.Position, a.Position) select s).ThenBy((Settlement s) => s.Id, StringComparer.Ordinal).FirstOrDefault(); if (settlement == null) { return null; } string[] array = new string[4] { settlement.Name + "'s goat ate our prize cabbages. All of them. Then it ate the fence", "someone moved the boundary stones in the night, and the tracks lead to " + settlement.Name, "they stole Lady Honkington, our prize goose, and now she lays for " + settlement.Name, settlement.Name + "'s bell-ringer starts at dawn on purpose, and points the bell at us" }; return new QuestState { Title = "Bad blood between " + a.Name + " and " + settlement.Name, TargetSettlementId = a.Id, OtherSettlementId = settlement.Id, TargetName = c.SettlementNotable(settlement.Id).Name, Note = array[rng.Range(0, array.Length)], GoodId = "good.grain", Quantity = 3 }; } public override List OfferLines(Campaign c, QuestState q) { List list = new List(); list.Add("You'll have heard about " + c.State.Settlements.Get(q.OtherSettlementId)?.Name + ". No? Well. " + Capital(q.Note) + "."); list.Add("We want justice! Or at least an apology. And the goose back, if it comes to that."); return list; } private static string Capital(string s) { if (!string.IsNullOrEmpty(s)) { return char.ToUpperInvariant(s[0]) + s.Substring(1); } return s; } public override List OfferOptions(Campaign c, QuestState q, QuestContext ctx) { return new List { QuestTemplate.Option("side", "You are in the right. I'll make " + c.State.Settlements.Get(q.OtherSettlementId)?.Name + " pay.", "", "Go to " + c.State.Settlements.Get(q.OtherSettlementId)?.Name + " and demand amends."), QuestTemplate.Option("mediate", "Let me hear both sides first.", "", "Go to " + c.State.Settlements.Get(q.OtherSettlementId)?.Name + " and listen; perhaps the feud can end.") }; } public override CommandResult Accept(Campaign c, QuestState q, string approach, QuestContext ctx) { q.Stage = ((approach == "side") ? "demand" : "listen"); return CommandResult.Success("Go to " + c.State.Settlements.Get(q.OtherSettlementId)?.Name + "."); } private double Persuade(Campaign c) { return Math.Max(0.15, Math.Min(0.85, 0.3 + (double)c.Skill("diplomacy") / 200.0)); } public override string Invalid(Campaign c, QuestState q) { if (c.SettlementNotable(q.OtherSettlementId) != null) { return ""; } return "There is nobody left in " + c.State.Settlements.Get(q.OtherSettlementId)?.Name + " to quarrel with."; } public override StoryPrompt Stage(Campaign c, QuestState q, QuestContext ctx) { Settlement settlement = c.State.Settlements.Get(q.TargetSettlementId); Settlement settlement2 = c.State.Settlements.Get(q.OtherSettlementId); NotableState notableState = c.SettlementNotable(q.OtherSettlementId); if (QuestTemplate.At(ctx, q.OtherSettlementId) && (q.Stage == "demand" || q.Stage == "listen")) { if (q.Stage == "demand") { StoryPrompt storyPrompt = QuestTemplate.Prompt(q, notableState?.Name ?? q.TargetName, "Village elder of " + settlement2?.Name, "From " + settlement?.Name + ", are you? We never touched anything. Well. Hardly anything."); storyPrompt.Options.Add(QuestTemplate.Option("fine", "Pay " + settlement?.Name + " for the trouble. (" + 200L + " from " + settlement2?.Name + "'s purse)", ((settlement2?.Market?.Gold).GetValueOrDefault() < 200) ? (settlement2?.Name + " cannot pay just now.") : "", settlement2?.Name + " pays; its elder will not like you (relation −10).")); storyPrompt.Options.Add(QuestTemplate.Option("threaten", "Pay up, or I'll make you sorry.", "", "They pay in fear: " + settlement2?.Name + " suffers (relation −15) and it is a crime in its realm.")); storyPrompt.Options.Add(QuestTemplate.Option("close", "I'll be back.")); return storyPrompt; } StoryPrompt storyPrompt2 = QuestTemplate.Prompt(q, notableState?.Name ?? q.TargetName, "Village elder of " + settlement2?.Name, "Their side of it, is it? Here is ours: they started it. Their goose ate our cabbages first!", "We would make peace, if they would. But they won't."); storyPrompt2.Options.Add(QuestTemplate.Option("persuade", "Come and share a feast with them, and end this. (" + (int)Math.Round(Persuade(c) * 100.0) + "% chance)", "", "Diplomacy decides it.")); storyPrompt2.Options.Add(QuestTemplate.Option("sideb", "You are in the right. I'll tell " + settlement?.Name + " to apologise.", "", settlement2?.Name + " loves you for it (+10); " + settlement?.Name + " does not (−10).")); storyPrompt2.Options.Add(QuestTemplate.Option("close", "I'll be back.")); return storyPrompt2; } if (QuestTemplate.At(ctx, q.TargetSettlementId) && q.Stage == "report") { StoryPrompt storyPrompt3 = QuestTemplate.Prompt(q, q.GiverName, "", "Ha! That'll teach them. You have our thanks."); storyPrompt3.Options.Add(QuestTemplate.Option("collect", "Glad to help.")); return storyPrompt3; } if (QuestTemplate.At(ctx, q.TargetSettlementId) && q.Stage == "feast") { StoryPrompt storyPrompt4 = QuestTemplate.Prompt(q, q.GiverName, "", "A feast? With them? ... Well, if they're coming, we can't look mean. Did you bring the grain?"); storyPrompt4.Options.Add(QuestTemplate.Option("feast", "Lay out the feast. (" + 3 + " grain)", (c.CargoCount(c.State.PlayerParty, "good.grain") < 3) ? ("You need " + 3 + " grain in your cargo.") : "", "Both villages make peace: they grow, and you are remembered.")); storyPrompt4.Options.Add(QuestTemplate.Option("close", "Not yet.")); return storyPrompt4; } return null; } public override CommandResult Choose(Campaign c, QuestState q, string option, QuestContext ctx) { if (option == "close") { return CommandResult.Success(); } Settlement settlement = c.State.Settlements.Require(q.TargetSettlementId); Settlement settlement2 = c.State.Settlements.Require(q.OtherSettlementId); string notableId = c.SettlementNotable(settlement2.Id)?.Id; switch (option) { case "fine": if (settlement2.Market.Gold < 200) { return CommandResult.Fail(settlement2.Name + " cannot pay."); } c.MoveMarketGold(settlement2, settlement, 200L); c.AdjustNotableRelation(notableId, -10, "you made them pay " + settlement.Name); q.Stage = "report"; QuestLog(c, q, settlement2.Name + " paid " + 200L + " denars to " + settlement.Name + "."); return CommandResult.Success(settlement2.Name + " pays. Tell " + settlement.Name + "."); case "threaten": c.AdjustNotableRelation(notableId, -15, "you threatened them"); settlement2.Prosperity = Math.Max(0.0, settlement2.Prosperity - 10.0); c.AddCrime(c.CrimeFactionOf(settlement2), 8.0, "threatening the villagers of " + settlement2.Name, settlement2.Id); q.Stage = "report"; QuestLog(c, q, "You frightened " + settlement2.Name + " into an apology."); return CommandResult.Success(settlement2.Name + " apologises, trembling. Tell " + settlement.Name + "."); case "sideb": c.AdjustNotableRelation(notableId, 10, "you took their side"); c.AdjustNotableRelation(q.GiverNotableId, -10, "you took the other village's side"); c.EndQuest(q, QuestStatus.Succeeded, "You took " + settlement2.Name + "'s side in the feud with " + settlement.Name + "."); return CommandResult.Success(settlement2.Name + " is delighted. " + settlement.Name + " is not."); case "persuade": c.GrantSkillExperience(c.State.PlayerHero, "diplomacy", 40.0); if (c.State.Random.Get("quests").Chance(Persuade(c))) { c.AdjustNotableRelation(notableId, 5, "you talked of peace"); q.Stage = "feast"; QuestLog(c, q, settlement2.Name + " agrees to a feast of reconciliation in " + settlement.Name + "."); return CommandResult.Success("They agree to a feast. Bring " + 3 + " grain to " + settlement.Name + "."); } c.AdjustNotableRelation(notableId, -3, "you meddled"); c.AdjustNotableRelation(q.GiverNotableId, -3, "you meddled"); c.EndQuest(q, QuestStatus.Failed, "Neither " + settlement.Name + " nor " + settlement2.Name + " would hear of peace. The feud goes on."); return CommandResult.Success("They will not hear of it."); case "collect": c.AdjustNotableRelation(q.GiverNotableId, 10, "you stood up for them"); c.State.PlayerClan.Renown += 1.0; c.EndQuest(q, QuestStatus.Succeeded, "You made " + settlement2.Name + " pay " + settlement.Name + " for the trouble."); return CommandResult.Success(settlement.Name + " is satisfied."); case "feast": { if (c.CargoCount(c.State.PlayerParty, "good.grain") < 3) { return CommandResult.Fail("You need " + 3 + " grain."); } int num = c.CargoCount(c.State.PlayerParty, "good.grain") - 3; if (num == 0) { c.State.PlayerParty.Cargo.Remove("good.grain"); } else { c.State.PlayerParty.Cargo["good.grain"] = num; } c.AdjustNotableRelation(q.GiverNotableId, 10, "you made peace"); c.AdjustNotableRelation(notableId, 10, "you made peace"); settlement.Prosperity += 10.0; settlement2.Prosperity += 10.0; c.State.PlayerClan.Renown += 3.0; c.GrantSkillExperience(c.State.PlayerHero, "diplomacy", 60.0); c.EndQuest(q, QuestStatus.Succeeded, "The feud between " + settlement.Name + " and " + settlement2.Name + " ended over a feast you laid out."); return CommandResult.Success("Peace, and pie."); } default: return CommandResult.Fail("That choice is not open."); } } public override List Objectives(Campaign c, QuestState q) { string text = c.State.Settlements.Get(q.TargetSettlementId)?.Name; string text2 = c.State.Settlements.Get(q.OtherSettlementId)?.Name; List list = new List { QuestTemplate.Goal((q.Approach == "side") ? ("Demand amends from " + text2) : ("Hear " + text2 + "'s side"), q.Stage == "report" || q.Stage == "feast") }; if (q.Stage == "feast") { list.Add(QuestTemplate.Goal("Bring " + 3 + " grain to " + text + " for a feast of peace (" + Math.Min(3, c.CargoCount(c.State.PlayerParty, "good.grain")) + " aboard)", done: false)); } else { list.Add(QuestTemplate.Goal("Return to " + text, done: false)); } return list; } public override string Summary(Campaign c, QuestState q) { return c.State.Settlements.Get(q.TargetSettlementId)?.Name + " says " + q.Note + "."; } public override IEnumerable Places(Campaign c, QuestState q) { yield return (q.Stage == "demand" || q.Stage == "listen") ? q.OtherSettlementId : q.TargetSettlementId; } } private sealed class LegionStory : QuestTemplate { private const long PayChest = 800L; private const int Kneel = 4; public override string Id => "story.legion"; public override QuestSource Source => QuestSource.Chain; public override string[] GiverKinds => new string[1] { "tavern" }; public override int Days => 40; public override QuestState TryOffer(Campaign c, QuestGiver giver, RandomStream rng) { Settlement settlement = giver.Settlement; if (c.NearestHideout(settlement.Position) == null || LegionUnits(c, settlement.CultureId).Count == 0) { return null; } return new QuestState { Title = "The Lost Legion", TargetSettlementId = settlement.Id, Quantity = rng.Range(10, 15) }; } private static List LegionUnits(Campaign c, string regionCulture) { Func> func = (string culture) => (from u in (from u in c.Content.Units where u.Culture == culture && u.Tier >= 2 && !u.Mounted && u.Slots <= 1 && u.Workload <= 2.0 orderby u.Tier descending select u).ThenBy((UnitDef u) => u.Id, StringComparer.Ordinal).Take(3) select u.Id).ToList(); List list = func("ancient"); if (list.Count <= 0) { return func(regionCulture); } return list; } public override List OfferLines(Campaign c, QuestState q) { return new List { "A hundred years ago a legion marched into the hills past " + c.State.Settlements.Get(q.TargetSettlementId)?.Name + ". They never marched out.", "Their standard is still out there, they say. And their pay chest. And... them. Every soldier in this tavern has a story. Mine is true." }; } public override List OfferOptions(Campaign c, QuestState q, QuestContext ctx) { return new List { QuestTemplate.Option("seek", "I'll find the Lost Legion.", "", "Start at the legion's old camp; it is marked on your map.") }; } public override CommandResult Accept(Campaign c, QuestState q, string approach, QuestContext ctx) { Settlement settlement = c.State.Settlements.Require(q.TargetSettlementId); DiscoverySite discoverySite = c.NewQuestSite(q, SiteKind.Camp, "The Legion's last camp", settlement.Position, c.StrategicRange(4.0), c.StrategicRange(9.0), c.State.Random.Get("quests")); q.TargetSiteId = discoverySite.Id; q.Stage = "camp"; return CommandResult.Success("The legion's old camp is marked on your map."); } private double Rest(Campaign c) { return Math.Max(0.1, Math.Min(0.8, 0.25 + (double)c.Skill("leadership") / 200.0)); } public override StoryPrompt Stage(Campaign c, QuestState q, QuestContext ctx) { if (ctx.Site == null) { return null; } if (q.Stage == "camp" && ctx.Site.Id == q.TargetSiteId) { StoryPrompt storyPrompt = QuestTemplate.Prompt(q, "", "", "Ditches and a rampart, grown over with thistles. Tent pegs of bronze. The camp was left in a hurry."); storyPrompt.Title = ctx.Site.Name; storyPrompt.Options.Add(QuestTemplate.Option("search", "Search the camp. (4 hours)", "", "Your party waits here while you search.")); storyPrompt.Options.Add(QuestTemplate.Option("close", "Come back later.")); return storyPrompt; } if (q.Stage == "stand" && ctx.Site.Id == q.OtherSiteId) { StoryPrompt storyPrompt2 = QuestTemplate.Prompt(q, "", "", "Mist on the hillside. Rusted shields lie in rows, as if the men who held them simply lay down.", "Then the rows stand up."); storyPrompt2.Title = ctx.Site.Name; storyPrompt2.Options.Add(QuestTemplate.Option("standard", "Raise their standard and call them to rest. (" + (int)Math.Round(Rest(c) * 100.0) + "% chance)", "", "Leadership decides it. If they kneel, some may follow you; if not, they attack.")); storyPrompt2.Options.Add(QuestTemplate.Option("fight", "Draw swords!", "", "Fight the legion. Their pay chest is the prize.")); storyPrompt2.Options.Add(QuestTemplate.Option("leave", "Back away slowly and leave them to their rest.", "", "The story ends here.")); return storyPrompt2; } return null; } public override CommandResult Choose(Campaign c, QuestState q, string option, QuestContext ctx) { if (option == "close") { return CommandResult.Success(); } RandomStream randomStream = c.State.Random.Get("quests"); Settlement settlement = c.State.Settlements.Require(q.TargetSettlementId); if (q.Stage == "camp") { CommandResult commandResult = c.Wait(4.0); if (!commandResult.Ok) { return commandResult; } DiscoverySite discoverySite = c.State.Quests.Sites.FirstOrDefault((DiscoverySite s) => s.Id == q.TargetSiteId); if (discoverySite != null) { discoverySite.Explored = true; discoverySite.ExploredMinute = c.State.Clock.Minute; discoverySite.Outcome = "A map scratched on a shield."; } DiscoverySite discoverySite2 = c.NewQuestSite(q, SiteKind.Battlefield, "The Legion's last stand", discoverySite?.Position ?? settlement.Position, c.StrategicRange(8.0), c.StrategicRange(15.0), randomStream); q.OtherSiteId = discoverySite2.Id; q.Stage = "stand"; c.GrantSkillExperience(c.State.PlayerHero, "scouting", 40.0); QuestLog(c, q, "On the inside of a shield, a map: the way the legion marched. The place where it ends is marked with a skull."); return CommandResult.Success("A map on a shield shows where the legion made its last stand."); } DiscoverySite discoverySite3 = c.State.Quests.Sites.FirstOrDefault((DiscoverySite s) => s.Id == q.OtherSiteId); Settlement settlement2 = c.State.Settlements.Get(discoverySite3?.RegionSettlementId ?? "") ?? settlement; List list = LegionUnits(c, settlement2.CultureId); if (option == "leave") { if (discoverySite3 != null) { discoverySite3.Explored = true; discoverySite3.ExploredMinute = c.State.Clock.Minute; discoverySite3.Outcome = "You left the legion to rest."; } c.State.PlayerClan.Renown += 2.0; c.EndQuest(q, QuestStatus.Succeeded, "You found the Lost Legion and left them to their rest."); return CommandResult.Success("You leave the dead in peace."); } if (option == "standard") { c.GrantSkillExperience(c.State.PlayerHero, "leadership", 60.0); if (randomStream.Chance(Rest(c))) { if (discoverySite3 != null) { discoverySite3.Explored = true; discoverySite3.ExploredMinute = c.State.Clock.Minute; discoverySite3.Outcome = "The legion knelt to its standard."; } int num = ((list.Count != 0) ? c.JoinPlayer(list[0], 4) : 0); c.State.PlayerClan.Renown += 10.0; c.EndQuest(q, QuestStatus.Succeeded, "The Lost Legion knelt to its standard." + ((num > 0) ? (" " + num + " of them, " + c.UnitDef(list[0])?.Name + ", follow you now.") : " They faded into the mist.")); return CommandResult.Success("They kneel."); } QuestLog(c, q, "The legion does not kneel."); } Party party = c.SpawnQuestBand(discoverySite3?.Position ?? c.State.PlayerParty.Position, "The Lost Legion", q.Quantity, list, randomStream); if (party == null) { c.EndQuest(q, QuestStatus.Cancelled, "The mist rolls in, and the legion is gone."); return CommandResult.Success("The legion is gone."); } party.Position = c.QuestSpotNear(c.State.PlayerParty.Position, 0.6, 1.2, randomStream); party.NextThinkMinute = c.State.Clock.Minute; q.TargetPartyId = party.Id; q.Stage = "battle"; return CommandResult.Success((option == "standard") ? "They do not kneel. The legion attacks!" : "The legion marches on you!"); } public override string OnVictory(Campaign c, QuestState q, HashSet beaten) { if (q.Stage != "battle" || !beaten.Contains(q.TargetPartyId)) { return ""; } RandomStream rng = c.State.Random.Get("quests"); c.State.Transact(c.State.PlayerClan, 800L, LedgerAccount.Discovery, "The Lost Legion's pay chest"); string text = c.GiveRelicWeapon("The Legate's Blade", rng); c.State.PlayerClan.Renown += 15.0; DiscoverySite discoverySite = c.State.Quests.Sites.FirstOrDefault((DiscoverySite s) => s.Id == q.OtherSiteId); if (discoverySite != null) { discoverySite.Explored = true; discoverySite.ExploredMinute = c.State.Clock.Minute; discoverySite.Outcome = "You defeated the Lost Legion."; } c.EndQuest(q, QuestStatus.Succeeded, "You defeated the Lost Legion and took its pay chest (" + 800L + " denars) and " + text + "."); return "The Lost Legion falls. Their pay chest holds " + 800L + " denars, and " + text + "."; } public override string Invalid(Campaign c, QuestState q) { if (!(q.Stage == "battle") || !PartyGone(c.State.Parties.Get(q.TargetPartyId))) { return ""; } return "The legion melted back into the mist."; } public override List Objectives(Campaign c, QuestState q) { return new List { QuestTemplate.Goal("Search the legion's old camp", q.Stage != "camp"), QuestTemplate.Goal("Find the legion's last stand", q.Stage == "battle"), QuestTemplate.Goal((q.Stage == "battle") ? ("Defeat the Lost Legion" + c.KnownPartyWhereabouts(q.TargetPartyId)) : "Lay the legion to rest, one way or another", done: false) }; } public override string Summary(Campaign c, QuestState q) { return "A legion marched into the hills a hundred years ago and never came out."; } public override IEnumerable Places(Campaign c, QuestState q) { if (q.Stage == "camp") { yield return "site:" + q.TargetSiteId; } if (q.Stage == "stand") { yield return "site:" + q.OtherSiteId; } if (q.Stage == "battle" && c.State.PlayerSightings.ContainsKey(q.TargetPartyId)) { yield return q.TargetPartyId; } } } internal sealed class QuestGiver { public string Id = ""; public string Kind = ""; public Hero Hero; public NotableState Notable; public Settlement Settlement; public string Name = ""; } internal sealed class QuestContext { public Hero TalkingTo; public Settlement Here; public DiscoverySite Site; } internal abstract class QuestTemplate { public abstract string Id { get; } public abstract QuestSource Source { get; } public abstract string[] GiverKinds { get; } public abstract int Days { get; } public virtual string DelegateSkill => null; public virtual int DelegateTroops => 0; public virtual int DelegateDays => 5; public virtual double DelegateDifficulty => 60.0; public abstract QuestState TryOffer(Campaign c, QuestGiver giver, RandomStream rng); public abstract List OfferLines(Campaign c, QuestState q); public abstract List OfferOptions(Campaign c, QuestState q, QuestContext ctx); public abstract CommandResult Accept(Campaign c, QuestState q, string approach, QuestContext ctx); public virtual StoryPrompt Stage(Campaign c, QuestState q, QuestContext ctx) { return null; } public virtual CommandResult Choose(Campaign c, QuestState q, string option, QuestContext ctx) { return CommandResult.Fail("Nothing to decide here."); } public abstract List Objectives(Campaign c, QuestState q); public virtual string Summary(Campaign c, QuestState q) { return q.Note; } public virtual IEnumerable Places(Campaign c, QuestState q) { yield return q.GiverSettlementId; } public virtual void Daily(Campaign c, QuestState q) { } public virtual void Hourly(Campaign c, QuestState q) { } public virtual string OnVictory(Campaign c, QuestState q, HashSet beaten) { return ""; } public virtual string OnDefeat(Campaign c, QuestState q) { return ""; } public virtual void OnRaid(Campaign c, QuestState q, Settlement village) { } public virtual string Invalid(Campaign c, QuestState q) { return ""; } public virtual string DelegateEscrowReason(Campaign c, QuestState q) { if (q.Reward <= 0) { return ""; } if (!string.IsNullOrEmpty(q.GiverHeroId)) { if ((c.State.Clans.Get(q.GiverClanId)?.Gold ?? 0) >= q.Reward) { return ""; } return q.GiverName + " cannot pay just now."; } Settlement settlement = c.State.Settlements.Get(q.GiverSettlementId); if ((settlement?.Market?.Gold).GetValueOrDefault() >= q.Reward) { return ""; } return (settlement?.Name ?? q.GiverName) + " cannot raise the reward just now."; } public virtual bool DelegateEscrow(Campaign c, QuestState q) { if (q.Reward <= 0) { return true; } if (!string.IsNullOrEmpty(q.GiverHeroId)) { return c.HoldQuestEscrow(q, q.Reward, c.State.Clans.Get(q.GiverClanId), null); } return c.HoldQuestEscrow(q, q.Reward, null, c.State.Settlements.Get(q.GiverSettlementId)); } public virtual void DelegatedSuccess(Campaign c, QuestState q, Hero companion) { if (!string.IsNullOrEmpty(q.GiverNotableId)) { c.AdjustNotableRelation(q.GiverNotableId, 5, companion.Name + " saw to their trouble"); } else if (!string.IsNullOrEmpty(q.GiverHeroId)) { c.AdjustClanRelation(c.State.PlayerClanId, q.GiverClanId, 4); } c.State.PlayerClan.Renown += 1.0; } protected static StoryOption Option(string id, string text, string reason = "", string hint = "") { return new StoryOption { Id = id, Text = text, Reason = (reason ?? ""), Hint = (hint ?? "") }; } protected static StoryPrompt Prompt(QuestState q, string speaker, string role, params string[] lines) { StoryPrompt storyPrompt = new StoryPrompt(); storyPrompt.Speaker = speaker; storyPrompt.SpeakerRole = role; storyPrompt.Lines.AddRange(lines.Where((string l) => !string.IsNullOrEmpty(l))); return storyPrompt; } protected static QuestObjective Goal(string text, bool done) { return new QuestObjective { Text = text, Done = done }; } protected static bool At(QuestContext ctx, string settlementId) { if (ctx?.Here != null) { return ctx.Here.Id == settlementId; } return false; } protected static string GoodName(string goodId) { return TabsBannerlord.Core.Content.TradeGoods.Get(goodId)?.Name ?? goodId; } } private sealed class EscortQuest : QuestTemplate { public const string TemplateId = "notable.escort"; private static readonly string[] Loads = new string[6] { "cloth and dyes", "wine and oil", "salt and spices", "iron tools", "fine pottery", "furs and hides" }; public override string Id => "notable.escort"; public override QuestSource Source => QuestSource.Notable; public override string[] GiverKinds => new string[1] { "town" }; public override int Days => 14; public override string DelegateSkill => "tactics"; public override int DelegateTroops => 8; public override int DelegateDays => 6; public override double DelegateDifficulty => 60.0; public override QuestState TryOffer(Campaign c, QuestGiver giver, RandomStream rng) { Settlement town = giver.Settlement; Clan me = c.State.PlayerClan; Clan owner = c.State.Clans.Get(town.OwnerClanId); List list = c.State.Settlements.Where((Settlement s) => s.Type == SettlementType.Town && s.Id != town.Id && !c.IsSettlementBesieged(s) && !c.State.AreHostile(me, c.State.Clans.Get(s.OwnerClanId)) && !c.State.AreHostile(owner, c.State.Clans.Get(s.OwnerClanId)) && Vec2.Distance(town.Position, s.Position) >= c.StrategicRange(12.0) && Vec2.Distance(town.Position, s.Position) <= c.StrategicRange(60.0) && c.Nav.SameComponent(town.Position, s.Position)).OrderBy((Settlement s) => s.Id, StringComparer.Ordinal).ToList(); if (list.Count == 0) { return null; } Settlement settlement = list[rng.Range(0, list.Count)]; double num = Vec2.Distance(town.Position, settlement.Position) / Math.Max(1.0, c.StrategicRange(1.0)); return new QuestState { Title = "Wagons for " + settlement.Name, TargetSettlementId = settlement.Id, OtherSettlementId = town.Id, TargetName = settlement.Name, Quantity = rng.Range(3, 7), Note = Loads[rng.Range(0, Loads.Length)], Reward = Round10(220.0 + num * 9.0 + (double)rng.Range(0, 100)) }; } public override List OfferLines(Campaign c, QuestState q) { List list = new List(); list.Add("I have " + q.Quantity + " wagons of " + q.Note + " that must reach " + q.TargetName + ", and the roads are full of thieves who know it."); list.Add("Ride with them. If they arrive whole, you will be paid well; if raiders come, see them off."); return list; } public override List OfferOptions(Campaign c, QuestState q, QuestContext ctx) { Settlement settlement = c.State.Settlements.Get(q.OtherSettlementId); List list = new List(); list.Add(QuestTemplate.Option("escort", "I'll take your wagons to " + q.TargetName + ".", ((settlement?.Market?.Gold).GetValueOrDefault() < q.Reward) ? "The merchants can't raise the reward just now." : "", "Travel with the wagons (" + 15.000000000000002.ToString("0") + "% slower) and bring them to " + q.TargetName + ". Raiders may come for them on the way. " + q.Reward + " denars.")); return list; } public override string DelegateEscrowReason(Campaign c, QuestState q) { if ((c.State.Settlements.Get(q.OtherSettlementId)?.Market?.Gold).GetValueOrDefault() >= q.Reward) { return ""; } return "The merchants can't raise the reward just now."; } public override bool DelegateEscrow(Campaign c, QuestState q) { return c.HoldQuestEscrow(q, q.Reward, null, c.State.Settlements.Get(q.OtherSettlementId)); } public override CommandResult Accept(Campaign c, QuestState q, string approach, QuestContext ctx) { Settlement market = c.State.Settlements.Require(q.OtherSettlementId); if (!c.HoldQuestEscrow(q, q.Reward, null, market)) { return CommandResult.Fail("The merchants can't raise the reward just now."); } q.Stage = "escort"; q.Progress = 0; return CommandResult.Success("The wagons are with you. Take them to " + q.TargetName + "."); } public override string Invalid(Campaign c, QuestState q) { Settlement settlement = c.State.Settlements.Get(q.TargetSettlementId); if (settlement == null) { return "The place is gone."; } if (c.State.AreHostile(c.State.PlayerClan, c.State.Clans.Get(settlement.OwnerClanId))) { return settlement.Name + " is now an enemy's; the merchants call the wagons back."; } return ""; } public override void Hourly(Campaign c, QuestState q) { if (q.Stage != "escort" || q.Progress != 0) { return; } Party playerParty = c.State.PlayerParty; Settlement settlement = c.State.Settlements.Get(q.OtherSettlementId); Settlement settlement2 = c.State.Settlements.Get(q.TargetSettlementId); if (playerParty == null || settlement == null || settlement2 == null || playerParty.State != PartyState.Active || !string.IsNullOrEmpty(playerParty.EncounterId)) { return; } double num = Math.Max(1E-06, Vec2.Distance(settlement.Position, settlement2.Position)); double num2 = Vec2.Distance(settlement.Position, playerParty.Position) / num; if (!(num2 < 0.3) && !(num2 > 0.85) && !(Vec2.Distance(playerParty.Position, settlement2.Position) < c.StrategicRange(3.0))) { RandomStream rng = c.State.Random.Get("quests"); int size = Math.Max(8, Math.Min(40, (int)Math.Round((double)(playerParty.Troops.TotalHealthy + playerParty.Troops.Heroes.Count) * 0.8))); Party party = c.SpawnQuestBand(playerParty.Position, "Wagon raiders", size, null, rng); q.Progress = 1; if (party != null) { q.TargetPartyId = party.Id; party.Position = c.QuestSpotNear(playerParty.Position, 1.5, 3.0, rng); c.SetMoveOrder(party, OrderKind.Engage, playerParty.Position, playerParty.Id, "ambush"); QuestLog(c, q, "Raiders are after the wagons!"); c.Raise(CampaignEventKind.Warning, "Raiders have come for the wagons you are escorting!", true, party.Id); } } } public override string OnVictory(Campaign c, QuestState q, HashSet beaten) { if (q.Stage != "escort" || string.IsNullOrEmpty(q.TargetPartyId) || !beaten.Contains(q.TargetPartyId)) { return ""; } q.Progress = 2; return "The raiders are beaten off; the wagons roll on to " + q.TargetName + "."; } public override string OnDefeat(Campaign c, QuestState q) { if (q.Stage != "escort") { return ""; } c.EndQuest(q, QuestStatus.Failed, "The wagons were plundered when you were beaten.", 3); return "The merchant's wagons were plundered."; } public override void Daily(Campaign c, QuestState q) { if (q.Stage == "escort" && c.State.Player.Activity == PlayerActivity.Captive) { c.EndQuest(q, QuestStatus.Failed, "The wagons were lost when you were taken.", 3); } } public override StoryPrompt Stage(Campaign c, QuestState q, QuestContext ctx) { if (q.Stage != "escort" || !QuestTemplate.At(ctx, q.TargetSettlementId)) { return null; } StoryPrompt storyPrompt = QuestTemplate.Prompt(q, "The merchants' factor", "in " + q.TargetName, "The wagons from " + c.State.Settlements.Get(q.OtherSettlementId)?.Name + "! Every one of them, too.", "Here is what was promised, and the guild's thanks."); storyPrompt.Options.Add(QuestTemplate.Option("deliver", "Hand over the wagons. (" + q.Reward + " denars)")); return storyPrompt; } public override CommandResult Choose(Campaign c, QuestState q, string option, QuestContext ctx) { c.AdjustNotableRelation(q.GiverNotableId, 6, "you brought their wagons through"); c.GrantSkillExperience(c.State.PlayerHero, "trade", 30.0); c.GrantSkillExperience(c.State.PlayerHero, "tactics", (q.Progress == 2) ? 40 : 15); c.State.PlayerClan.Renown += ((q.Progress != 2) ? 1 : 2); Settlement settlement = c.State.Settlements.Get(q.TargetSettlementId); if (settlement != null) { settlement.Prosperity += 5.0; } c.EndQuest(q, QuestStatus.Succeeded, "You brought " + q.Quantity + " wagons of " + q.Note + " safely to " + q.TargetName + "."); return CommandResult.Success("Delivered. " + q.Reward + " denars."); } public override List Objectives(Campaign c, QuestState q) { return new List { QuestTemplate.Goal("Bring the wagons to " + q.TargetName + ((q.Progress == 1) ? (" (raiders are after them" + c.KnownPartyWhereabouts(q.TargetPartyId) + ")") : ""), done: false) }; } public override string Summary(Campaign c, QuestState q) { return q.Quantity + " wagons of " + q.Note + " from " + c.State.Settlements.Get(q.OtherSettlementId)?.Name + " must reach " + q.TargetName + "."; } public override IEnumerable Places(Campaign c, QuestState q) { if (q.Progress == 1 && c.State.PlayerSightings.ContainsKey(q.TargetPartyId)) { yield return q.TargetPartyId; } yield return q.TargetSettlementId; } } private sealed class LetterQuest : QuestTemplate { private static readonly string[] Contents = new string[6] { "a proposal of marriage between their children, with a dowry of three hundred sheep", "a warning that bandits have been seen near their fiefs", "a long complaint about a borrowed hunting dog that was never returned", "an offer to buy their finest warhorse, and a veiled insult about their second-finest", "a recipe for honey cakes, written with surprising passion", "plans for a joint campaign in the spring" }; public override string Id => "lord.letter"; public override QuestSource Source => QuestSource.Lord; public override string[] GiverKinds => new string[1] { "lord" }; public override int Days => 15; public override string DelegateSkill => "diplomacy"; public override int DelegateDays => 6; public override double DelegateDifficulty => 30.0; public override QuestState TryOffer(Campaign c, QuestGiver giver, RandomStream rng) { Hero h = giver.Hero; string realm = c.State.FactionOf(c.State.Clans.Get(h.ClanId)); List list = c.State.Heroes.Where(delegate(Hero x) { if (x.Id != h.Id && x.State == HeroState.Active && x.Occupation == HeroOccupation.Lord && c.IsGrown(x) && x.ClanId != c.State.PlayerClanId && x.ClanId != h.ClanId) { Clan clan = c.State.Clans.Get(x.ClanId); if (clan != null && !clan.IsBandit && !c.State.AreHostile(c.State.PlayerClan, c.State.Clans.Get(x.ClanId))) { return !c.State.AtWar(realm, c.State.FactionOf(c.State.Clans.Get(x.ClanId))); } } return false; }).OrderBy((Hero x) => x.Id, StringComparer.Ordinal).ToList(); if (list.Count == 0) { return null; } Hero hero = list[rng.Range(0, list.Count)]; return new QuestState { Title = "A letter for " + hero.Name, TargetHeroId = hero.Id, TargetName = hero.Name, TargetClanId = hero.ClanId, Reward = 200 + Round10(rng.Range(0, 160)), Note = Contents[rng.Range(0, Contents.Length)] }; } public override List OfferLines(Campaign c, QuestState q) { List list = new List(); list.Add("I need a letter carried to " + q.TargetName + " of " + c.State.Clans.Get(q.TargetClanId)?.Name + ". In their own hands, mind, not a steward's."); list.Add("And the seal stays unbroken. I will know if it is not."); return list; } public override List OfferOptions(Campaign c, QuestState q, QuestContext ctx) { Clan clan = c.State.Clans.Get(q.GiverClanId); List list = new List(); list.Add(QuestTemplate.Option("carry", "I'll carry it.", ((clan?.Gold ?? 0) < q.Reward) ? (q.GiverName + " cannot pay just now.") : "", "Find " + q.TargetName + " and speak to them. " + q.Reward + " denars.")); return list; } public override CommandResult Accept(Campaign c, QuestState q, string approach, QuestContext ctx) { if (!c.HoldQuestEscrow(q, q.Reward, c.State.Clans.Get(q.GiverClanId), null)) { return CommandResult.Fail(q.GiverName + " cannot pay just now."); } q.Stage = "carry"; return CommandResult.Success("Find " + q.TargetName + "."); } public override string Invalid(Campaign c, QuestState q) { Hero hero = c.State.Heroes.Get(q.TargetHeroId); if (hero == null || hero.State == HeroState.Dead) { return q.TargetName + " is dead; the letter will never reach them."; } if (c.State.AreHostile(c.State.PlayerClan, c.State.Clans.Get(hero.ClanId))) { return "You are at war with " + q.TargetName + "'s realm; the letter can't be delivered."; } return ""; } private double Counsel(Campaign c) { return Math.Max(0.15, Math.Min(0.85, 0.3 + (double)c.Skill("diplomacy") / 200.0)); } public override StoryPrompt Stage(Campaign c, QuestState q, QuestContext ctx) { if (q.Stage != "carry") { return null; } if (ctx.TalkingTo != null && ctx.TalkingTo.Id == q.TargetHeroId) { StoryPrompt storyPrompt = QuestTemplate.Prompt(q, q.TargetName, "", "A letter? From " + q.GiverName + "? Give it here."); storyPrompt.Options.Add(QuestTemplate.Option("deliver", "Hand over the letter.", "", q.Reward + " denars from " + q.GiverName + ".")); if (q.Progress == 1) { storyPrompt.Options.Add(QuestTemplate.Option("counsel", "Hand it over, and say what you make of it. (" + (int)Math.Round(Counsel(c) * 100.0) + "% chance)", "", "You read it, so you can speak to it (Diplomacy): " + q.TargetName + " may think better of you, or worse.")); } return storyPrompt; } if (ctx.TalkingTo == null && q.Progress == 0) { StoryPrompt storyPrompt2 = QuestTemplate.Prompt(q, "", "", "The letter for " + q.TargetName + " sits in your saddlebag, sealed with " + q.GiverName + "'s wax."); storyPrompt2.Title = q.Title; storyPrompt2.Optional = true; storyPrompt2.Options.Add(QuestTemplate.Option("read", "Break the seal and read it.", "", "You will know what it says. " + q.GiverName + " may notice.")); storyPrompt2.Options.Add(QuestTemplate.Option("close", "Leave it sealed.")); return storyPrompt2; } return null; } public override CommandResult Choose(Campaign c, QuestState q, string option, QuestContext ctx) { if (option == "close") { return CommandResult.Success(); } if (option == "read") { q.Progress = 1; q.Needed = (c.State.Random.Get("quests").Chance(0.35) ? 1 : 0); c.GrantSkillExperience(c.State.PlayerHero, "scouting", 20.0); QuestLog(c, q, "You broke the seal. The letter is " + q.Note + "."); return CommandResult.Success("The letter is " + q.Note + "."); } Clan clan = c.State.Clans.Get(q.TargetClanId); int num = 3; string text = ""; if (option == "counsel") { c.GrantSkillExperience(c.State.PlayerHero, "diplomacy", 30.0); if (c.State.Random.Get("quests").Chance(Counsel(c))) { num += 6; text = " Your counsel was welcome."; } else { num -= 6; text = " " + q.TargetName + " did not care for your opinion."; } } if (clan != null) { c.AdjustClanRelation(c.State.PlayerClanId, clan.Id, num); } bool flag = q.Progress == 1 && q.Needed == 1; c.AdjustClanRelation(c.State.PlayerClanId, q.GiverClanId, flag ? (-5) : 5); c.GrantSkillExperience(c.State.PlayerHero, "diplomacy", 20.0); c.EndQuest(q, QuestStatus.Succeeded, "You delivered " + q.GiverName + "'s letter to " + q.TargetName + "." + text + (flag ? (" " + q.GiverName + " heard that the seal was broken.") : "")); return CommandResult.Success("Delivered. " + q.Reward + " denars."); } public override List Objectives(Campaign c, QuestState q) { string mapTarget; string text = c.HeroWhereaboutsForTalk(c.State.Heroes.Get(q.TargetHeroId), out mapTarget); List list = new List(); list.Add(QuestTemplate.Goal("Deliver the letter to " + q.TargetName + " in person (they are " + text + ")", done: false)); List list2 = list; if (q.Progress == 1) { list2.Insert(0, QuestTemplate.Goal("You read it: " + q.Note, done: true)); } return list2; } public override string Summary(Campaign c, QuestState q) { return q.GiverName + " asked you to carry a sealed letter to " + q.TargetName + "."; } public override IEnumerable Places(Campaign c, QuestState q) { c.HeroWhereaboutsForTalk(c.State.Heroes.Get(q.TargetHeroId), out var mapTarget); yield return mapTarget; } } private sealed class RaidOrderQuest : QuestTemplate { public override string Id => "lord.raid"; public override QuestSource Source => QuestSource.Lord; public override string[] GiverKinds => new string[1] { "lord" }; public override int Days => 12; public override QuestState TryOffer(Campaign c, QuestGiver giver, RandomStream rng) { Hero hero = giver.Hero; Clan clan = c.State.Clans.Get(hero.ClanId); string realm = c.State.FactionOf(clan); List homes = c.State.Settlements.Where((Settlement s) => c.State.FactionOf(c.State.Clans.Get(s.OwnerClanId)) == realm).ToList(); if (homes.Count == 0) { return null; } List list = (from s in c.State.Settlements where s.Type == SettlementType.Village && !c.IsVillageBeingRaided(s) && c.State.AtWar(realm, c.State.FactionOf(c.State.Clans.Get(s.OwnerClanId))) && c.State.AreHostile(c.State.PlayerClan, c.State.Clans.Get(s.OwnerClanId)) orderby homes.Min((Settlement x) => Vec2.Distance(x.Position, s.Position)) select s).ThenBy((Settlement s) => s.Id, StringComparer.Ordinal).Take(3).ToList(); if (list.Count == 0) { return null; } Settlement settlement = list[rng.Range(0, list.Count)]; return new QuestState { Title = "Burn the fields of " + settlement.Name, TargetSettlementId = settlement.Id, TargetClanId = settlement.OwnerClanId, TargetName = settlement.Name, Reward = 450 + Round10(rng.Range(0, 200)) }; } public override List OfferLines(Campaign c, QuestState q) { return new List { q.TargetName + " feeds our enemies' garrisons. Every sack of grain from there is an arrow pointed at us.", "Raid it. Take what you like; I only want it empty." }; } public override List OfferOptions(Campaign c, QuestState q, QuestContext ctx) { Clan clan = c.State.Clans.Get(q.GiverClanId); List list = new List(); list.Add(QuestTemplate.Option("raid", "Consider it burned.", ((clan?.Gold ?? 0) < q.Reward) ? (q.GiverName + " cannot pay just now.") : "", "Raid " + q.TargetName + ". " + q.Reward + " denars, paid the moment it is done (raiding is a crime in its realm).")); return list; } public override CommandResult Accept(Campaign c, QuestState q, string approach, QuestContext ctx) { if (!c.HoldQuestEscrow(q, q.Reward, c.State.Clans.Get(q.GiverClanId), null)) { return CommandResult.Fail(q.GiverName + " cannot pay just now."); } q.Stage = "raid"; return CommandResult.Success("Raid " + q.TargetName + "."); } public override void OnRaid(Campaign c, QuestState q, Settlement village) { if (!(q.Stage != "raid") && !(village.Id != q.TargetSettlementId)) { c.AdjustClanRelation(c.State.PlayerClanId, q.GiverClanId, 6); c.State.PlayerClan.Renown += 2.0; c.EndQuest(q, QuestStatus.Succeeded, "You raided " + q.TargetName + " for " + q.GiverName + "."); } } public override string Invalid(Campaign c, QuestState q) { Settlement settlement = c.State.Settlements.Get(q.TargetSettlementId); if (settlement == null) { return "The village is gone."; } if (!c.State.AreHostile(c.State.PlayerClan, c.State.Clans.Get(settlement.OwnerClanId))) { return q.TargetName + " isn't held by your enemies any more; the raid's off."; } Clan clan = c.State.Clans.Get(q.GiverClanId); if (!c.State.AtWar(c.State.FactionOf(clan), c.State.FactionOf(c.State.Clans.Get(settlement.OwnerClanId)))) { return "The war is over; " + q.GiverName + " no longer wants it raided."; } return ""; } public override List Objectives(Campaign c, QuestState q) { return new List { QuestTemplate.Goal("Raid " + q.TargetName, done: false) }; } public override string Summary(Campaign c, QuestState q) { return q.GiverName + " wants " + q.TargetName + " raided."; } public override IEnumerable Places(Campaign c, QuestState q) { yield return q.TargetSettlementId; } } private sealed class PrisonerOrderQuest : QuestTemplate { public override string Id => "lord.prisoner"; public override QuestSource Source => QuestSource.Lord; public override string[] GiverKinds => new string[1] { "lord" }; public override int Days => 20; private static List EnemyRealms(Campaign c, string clanId) { string realm = c.State.FactionOf(c.State.Clans.Get(clanId)); return (from s in c.State.Stances where s.Stance == Stance.War && (s.A == realm || s.B == realm) select (!(s.A == realm)) ? s.A : s.B).Where(delegate(string f) { if (!c.State.Kingdoms.Contains(f)) { Clan clan = c.State.Clans.Get(f); if (clan == null) { return false; } return !clan.IsBandit; } return true; }).Distinct().OrderBy((string f) => f, StringComparer.Ordinal) .ToList(); } public override QuestState TryOffer(Campaign c, QuestGiver giver, RandomStream rng) { List list = (from f in EnemyRealms(c, giver.Hero.ClanId) where c.State.AreHostile(c.State.PlayerClan, c.State.Clans.Get(c.State.Kingdoms.Get(f)?.RulerClanId ?? f)) select f).ToList(); if (list.Count == 0) { return null; } return new QuestState { Title = "A prisoner for " + giver.Hero.Name, Reward = 700 + Round10(rng.Range(0, 300)), Note = string.Join(",", list) }; } public override List OfferLines(Campaign c, QuestState q) { List list = new List(); list.Add("Our enemies have lords who would fetch a fine price, and tell us much besides. Bring me one, alive."); list.Add("Any lord or lady of " + string.Join(" or ", from f in q.Note.Split(new char[1] { ',' }) select c.DiplomacyFactionName(f)) + " will do."); return list; } public override List OfferOptions(Campaign c, QuestState q, QuestContext ctx) { Clan clan = c.State.Clans.Get(q.GiverClanId); List list = new List(); list.Add(QuestTemplate.Option("hunt", "I'll bring you one.", ((clan?.Gold ?? 0) < q.Reward) ? (q.GiverName + " cannot pay just now.") : "", "Capture an enemy lord or lady in battle and hand them to " + q.GiverName + " where they hold a dungeon. " + q.Reward + " denars.")); return list; } public override CommandResult Accept(Campaign c, QuestState q, string approach, QuestContext ctx) { if (!c.HoldQuestEscrow(q, q.Reward, c.State.Clans.Get(q.GiverClanId), null)) { return CommandResult.Fail(q.GiverName + " cannot pay just now."); } q.Stage = "hunt"; return CommandResult.Success("Capture an enemy lord or lady."); } private List Candidates(Campaign c, QuestState q) { HashSet enemies = new HashSet(EnemyRealms(c, q.GiverClanId), StringComparer.Ordinal); return (from id in c.State.PlayerParty?.Prisoners.Heroes ?? new List() select c.State.Heroes.Get(id) into h where h != null && h.State == HeroState.Captive && h.Occupation == HeroOccupation.Lord && h.CaptorPartyId == c.State.PlayerPartyId && enemies.Contains(c.State.FactionOf(c.State.Clans.Get(h.ClanId))) && c.NamedCustodyIntegrityReason(h.Id).Length == 0 select h).OrderBy((Hero h) => h.Name, StringComparer.Ordinal).ThenBy((Hero h) => h.Id, StringComparer.Ordinal).Take(4) .ToList(); } private Settlement Dungeon(Campaign c, QuestState q, QuestContext ctx) { Settlement here = ctx.Here; string text = c.State.FactionOf(c.State.Clans.Get(q.GiverClanId)); if (here == null || (here.Type != SettlementType.Town && here.Type != SettlementType.Castle) || !(c.State.FactionOf(c.State.Clans.Get(here.OwnerClanId)) == text)) { return null; } return here; } public override StoryPrompt Stage(Campaign c, QuestState q, QuestContext ctx) { if (q.Stage != "hunt" || ctx.TalkingTo == null || ctx.TalkingTo.Id != q.GiverHeroId) { return null; } List list = Candidates(c, q); if (list.Count == 0) { return null; } Settlement settlement = Dungeon(c, q, ctx); StoryPrompt storyPrompt = QuestTemplate.Prompt(q, q.GiverName, "", "You have brought me someone, I see."); foreach (Hero item in list) { storyPrompt.Options.Add(QuestTemplate.Option("hand:" + item.Id, "Hand over " + item.Name + " of " + c.State.Clans.Get(item.ClanId)?.Name + ".", (settlement == null) ? ("Meet " + q.GiverName + " in a town or castle of their realm, where there is a dungeon.") : (c.NamedCustodyPartyReserved(c.State.PlayerPartyId) ? "Finish your encounter first." : ""), "They go to " + settlement?.Name + "'s dungeon. " + q.Reward + " denars.")); } storyPrompt.Options.Add(QuestTemplate.Option("close", "Not yet.")); return storyPrompt; } public override CommandResult Choose(Campaign c, QuestState q, string option, QuestContext ctx) { if (option == "close") { return CommandResult.Success(); } string heroId = (option.StartsWith("hand:", StringComparison.Ordinal) ? option.Substring(5) : ""); Hero hero = Candidates(c, q).FirstOrDefault((Hero h) => h.Id == heroId); Settlement settlement = Dungeon(c, q, ctx); if (hero == null || settlement == null) { return CommandResult.Fail("You can't hand that prisoner over here."); } c.State.PlayerParty.Prisoners.Heroes.Remove(hero.Id); settlement.Prisoners.Heroes.Add(hero.Id); hero.CaptorPartyId = ""; hero.CaptorSettlementId = settlement.Id; c.State.AddLog(LogCategory.Captivity, hero.Name + " was handed over to " + q.GiverName + " and taken to " + settlement.Name + "'s dungeon.", hero.Id, settlement.Id); c.AdjustClanRelation(c.State.PlayerClanId, q.GiverClanId, 10); c.AdjustClanRelation(c.State.PlayerClanId, hero.ClanId, -10); c.State.PlayerClan.Renown += 3.0; c.EndQuest(q, QuestStatus.Succeeded, "You handed " + hero.Name + " over to " + q.GiverName + "."); return CommandResult.Success(hero.Name + " is handed over. " + q.Reward + " denars."); } public override string Invalid(Campaign c, QuestState q) { if (EnemyRealms(c, q.GiverClanId).Count != 0) { return ""; } return q.GiverName + "'s realm is at peace; they don't want a prisoner now."; } public override List Objectives(Campaign c, QuestState q) { bool done = Candidates(c, q).Count > 0; string mapTarget; string text = c.HeroWhereaboutsForTalk(c.State.Heroes.Get(q.GiverHeroId), out mapTarget); List list = new List(); list.Add(QuestTemplate.Goal("Capture a lord or lady of " + string.Join(" or ", from f in EnemyRealms(c, q.GiverClanId) select c.DiplomacyFactionName(f)), done)); list.Add(QuestTemplate.Goal("Hand them to " + q.GiverName + " in a town or castle of their realm (they are " + text + ")", done: false)); return list; } public override string Summary(Campaign c, QuestState q) { return q.GiverName + " wants an enemy lord or lady brought to them as a prisoner."; } public override IEnumerable Places(Campaign c, QuestState q) { c.HeroWhereaboutsForTalk(c.State.Heroes.Get(q.GiverHeroId), out var mapTarget); yield return mapTarget; } } private sealed class RecruitsOrderQuest : QuestTemplate { public override string Id => "lord.recruits"; public override QuestSource Source => QuestSource.Lord; public override string[] GiverKinds => new string[1] { "lord" }; public override int Days => 12; public override QuestState TryOffer(Campaign c, QuestGiver giver, RandomStream rng) { if (string.IsNullOrEmpty(giver.Hero.PartyId)) { return null; } int num = rng.Range(6, 11); return new QuestState { Title = "Men for " + giver.Hero.Name + "'s retinue", Needed = num, Reward = Round10(num * 60) }; } public override List OfferLines(Campaign c, QuestState q) { return new List { "My retinue is thin, and good men are hard to find. I need " + q.Needed + " of them: trained, not farmers with pitchforks.", "Bring them to me and I will pay what they are worth, and a little more." }; } public override List OfferOptions(Campaign c, QuestState q, QuestContext ctx) { Clan clan = c.State.Clans.Get(q.GiverClanId); List list = new List(); list.Add(QuestTemplate.Option("raise", "I'll find you " + q.Needed + " good men.", ((clan?.Gold ?? 0) < q.Reward) ? (q.GiverName + " cannot pay just now.") : "", "Bring " + q.Needed + " troops of tier 2 or better and hand them over in person. " + q.Reward + " denars.")); return list; } public override CommandResult Accept(Campaign c, QuestState q, string approach, QuestContext ctx) { if (!c.HoldQuestEscrow(q, q.Reward, c.State.Clans.Get(q.GiverClanId), null)) { return CommandResult.Fail(q.GiverName + " cannot pay just now."); } q.Stage = "raise"; return CommandResult.Success("Raise " + q.Needed + " troops of tier 2 or better."); } private Party GiverParty(Campaign c, QuestState q, QuestContext ctx) { Hero hero = c.State.Heroes.Get(q.GiverHeroId); Party party = c.State.Parties.Get(hero?.PartyId ?? ""); if (party == null || party.State != PartyState.InSettlement || ctx.Here == null || !(party.CurrentSettlementId == ctx.Here.Id) || !string.IsNullOrEmpty(party.EncounterId)) { return null; } return party; } public override StoryPrompt Stage(Campaign c, QuestState q, QuestContext ctx) { if (q.Stage != "raise" || ctx.TalkingTo == null || ctx.TalkingTo.Id != q.GiverHeroId) { return null; } Party party = GiverParty(c, q, ctx); int num = c.HandableTroops(2); StoryPrompt storyPrompt = QuestTemplate.Prompt(q, q.GiverName, "", "Have you found my men?"); storyPrompt.Options.Add(QuestTemplate.Option("hand", "Hand over " + q.Needed + " troops (tier 2 or better).", (num < q.Needed) ? ("You have " + num + " troops of tier 2 or better; " + q.Needed + " are needed.") : ((party == null) ? (q.GiverName + "'s party is not here to take them.") : ""), "Your lowest-tier troops of tier 2 or better go first. " + q.Reward + " denars.")); storyPrompt.Options.Add(QuestTemplate.Option("close", "Not yet.")); return storyPrompt; } public override CommandResult Choose(Campaign c, QuestState q, string option, QuestContext ctx) { if (option == "close") { return CommandResult.Success(); } Party party = GiverParty(c, q, ctx); if (party == null || c.HandableTroops(2) < q.Needed) { return CommandResult.Fail("You can't hand them over here."); } c.TakeTroops(q.Needed, 2, party.Troops); c.AdjustClanRelation(c.State.PlayerClanId, q.GiverClanId, 6); c.GrantSkillExperience(c.State.PlayerHero, "leadership", 40.0); c.EndQuest(q, QuestStatus.Succeeded, "You brought " + q.Needed + " troops for " + q.GiverName + "'s retinue."); return CommandResult.Success("Handed over. " + q.Reward + " denars."); } public override List Objectives(Campaign c, QuestState q) { string mapTarget; string text = c.HeroWhereaboutsForTalk(c.State.Heroes.Get(q.GiverHeroId), out mapTarget); int num = c.HandableTroops(2); List list = new List(); list.Add(QuestTemplate.Goal("Have " + q.Needed + " troops of tier 2 or better (" + Math.Min(num, q.Needed) + " with you)", num >= q.Needed)); list.Add(QuestTemplate.Goal("Hand them to " + q.GiverName + " in person (they are " + text + ")", done: false)); return list; } public override string Summary(Campaign c, QuestState q) { return q.GiverName + " needs " + q.Needed + " trained troops."; } public override IEnumerable Places(Campaign c, QuestState q) { c.HeroWhereaboutsForTalk(c.State.Heroes.Get(q.GiverHeroId), out var mapTarget); yield return mapTarget; } } private sealed class RoadsQuest : QuestTemplate { private const int Bands = 3; public override string Id => "lord.roads"; public override QuestSource Source => QuestSource.Lord; public override string[] GiverKinds => new string[1] { "lord" }; public override int Days => 20; public override string DelegateSkill => "tactics"; public override int DelegateTroops => 12; public override int DelegateDays => 8; public override double DelegateDifficulty => 80.0; public override QuestState TryOffer(Campaign c, QuestGiver giver, RandomStream rng) { if (!c.State.Settlements.Any((Settlement s) => s.OwnerClanId == giver.Hero.ClanId)) { return null; } return new QuestState { Title = "Clear the roads of " + c.State.Clans.Get(giver.Hero.ClanId)?.Name, Needed = 3, Reward = 550 + Round10(rng.Range(0, 150)) }; } public override List OfferLines(Campaign c, QuestState q) { return new List { "Bandits on every road. My merchants won't travel, my villagers won't sell, and my bailiff hides under his bed.", "Break " + 3 + " of their bands in my lands and I will pay you handsomely." }; } public override List OfferOptions(Campaign c, QuestState q, QuestContext ctx) { Clan clan = c.State.Clans.Get(q.GiverClanId); List list = new List(); list.Add(QuestTemplate.Option("hunt", "I'll clear your roads.", ((clan?.Gold ?? 0) < q.Reward) ? (q.GiverName + " cannot pay just now.") : "", "Defeat " + 3 + " bandit parties near " + q.GiverName + "'s clan's fiefs. " + q.Reward + " denars, paid when the last one falls.")); return list; } public override CommandResult Accept(Campaign c, QuestState q, string approach, QuestContext ctx) { if (!c.HoldQuestEscrow(q, q.Reward, c.State.Clans.Get(q.GiverClanId), null)) { return CommandResult.Fail(q.GiverName + " cannot pay just now."); } q.Stage = "hunt"; return CommandResult.Success("Defeat " + 3 + " bandit parties in " + c.State.Clans.Get(q.GiverClanId)?.Name + "'s lands."); } private bool InLands(Campaign c, QuestState q, Party p) { if (p != null) { return c.State.Settlements.Any((Settlement s) => s.OwnerClanId == q.GiverClanId && Vec2.Distance(s.Position, p.Position) <= c.StrategicRange(30.0)); } return false; } public override string OnVictory(Campaign c, QuestState q, HashSet beaten) { if (q.Stage != "hunt") { return ""; } int num = beaten.Select((string id) => c.State.Parties.Get(id)).Count((Party p) => p != null && p.Kind == PartyKind.Bandit && InLands(c, q, p)); if (num == 0) { return ""; } q.Progress = Math.Min(q.Needed, q.Progress + num); if (q.Progress < q.Needed) { return "Bandits broken in " + c.State.Clans.Get(q.GiverClanId)?.Name + "'s lands: " + q.Progress + " of " + q.Needed + "."; } c.AdjustClanRelation(c.State.PlayerClanId, q.GiverClanId, 8); c.State.PlayerClan.Renown += 3.0; c.GrantSkillExperience(c.State.PlayerHero, "tactics", 40.0); c.EndQuest(q, QuestStatus.Succeeded, "You cleared the roads of " + c.State.Clans.Get(q.GiverClanId)?.Name + "'s lands."); return "The roads are clear: " + q.GiverName + " pays " + q.Reward + " denars."; } public override List Objectives(Campaign c, QuestState q) { List list = new List(); list.Add(QuestTemplate.Goal("Defeat bandit parties near the fiefs of " + c.State.Clans.Get(q.GiverClanId)?.Name + " (" + q.Progress + " / " + q.Needed + ")", q.Progress >= q.Needed)); return list; } public override string Summary(Campaign c, QuestState q) { return q.GiverName + " wants the bandits on their roads broken."; } public override IEnumerable Places(Campaign c, QuestState q) { return (from s in (from s in c.State.Settlements where s.OwnerClanId == q.GiverClanId orderby s.Type select s).ThenBy((Settlement s) => s.Id, StringComparer.Ordinal) select s.Id).Take(1); } } private sealed class RustlersQuest : QuestTemplate { private const long HerdCost = 300L; private const int Guards = 5; public override string Id => "notable.rustlers"; public override QuestSource Source => QuestSource.Notable; public override string[] GiverKinds => new string[1] { "village" }; public override int Days => 10; public override string DelegateSkill => "tactics"; public override int DelegateTroops => 6; public override int DelegateDays => 4; public override double DelegateDifficulty => 50.0; private static string Herd(Campaign c, Settlement v) { switch (c.PrimaryVillageGood(v)) { default: return "goats"; case "good.horses": return "horses"; case "good.hides": case "good.meat": return "cattle"; case "good.wool": return "sheep"; } } public override QuestState TryOffer(Campaign c, QuestGiver giver, RandomStream rng) { Settlement settlement = giver.Settlement; if (c.NearestHideout(settlement.Position) == null) { return null; } return new QuestState { Title = "Rustlers at " + settlement.Name, TargetSettlementId = settlement.Id, Reward = 250 + Round10(rng.Range(0, 120)), Quantity = rng.Range(6, 11), Note = Herd(c, settlement) }; } public override List OfferLines(Campaign c, QuestState q) { Settlement settlement = c.State.Settlements.Get(q.TargetSettlementId); return new List { "Rustlers! They come by night and drive off our " + q.Note + ". Three nights running now.", "We are farmers, not fighters. They camp somewhere near " + settlement?.Name + ", bold as you like. Will you help us?" }; } public override List OfferOptions(Campaign c, QuestState q, QuestContext ctx) { Settlement settlement = c.State.Settlements.Get(q.TargetSettlementId); List list = new List(); list.Add(QuestTemplate.Option("hunt", "I'll hunt the rustlers down.", ((settlement?.Market?.Gold).GetValueOrDefault() < q.Reward) ? (settlement?.Name + " cannot raise the reward just now.") : "", "Defeat about " + q.Quantity + " rustlers nearby, then come back. " + q.Reward + " denars from the village purse.")); list.Add(QuestTemplate.Option("pay", "Here: buy yourselves a new herd. (" + 300L + " denars)", (c.State.PlayerClan.Gold < 300) ? ("You cannot spare " + 300L + " denars.") : "", "Settled at once. The village grows; the elder is grateful.")); list.Add(QuestTemplate.Option("guard", "I'll leave " + 5 + " of my men to guard the herds.", (c.HandableTroops(1) < 5) ? ("You need " + 5 + " healthy troops to spare.") : "", "Settled at once. Your weakest " + 5 + " troops join the village militia.")); return list; } public override CommandResult Accept(Campaign c, QuestState q, string approach, QuestContext ctx) { Settlement settlement = c.State.Settlements.Require(q.TargetSettlementId); if (approach == "pay") { if (!c.PlayerPaysMarket(settlement, 300L, "A new herd for " + settlement.Name)) { return CommandResult.Fail("You cannot spare " + 300L + " denars."); } settlement.Prosperity += 15.0; c.AdjustNotableRelation(q.GiverNotableId, 6, "you paid for a new herd"); c.GrantSkillExperience(c.State.PlayerHero, "stewardship", 20.0); q.Reward = 0L; c.EndQuest(q, QuestStatus.Succeeded, "You paid for a new herd; " + settlement.Name + " will not forget it."); return CommandResult.Success("You paid " + 300L + " denars for a new herd."); } if (approach == "guard") { if (c.HandableTroops(1) < 5) { return CommandResult.Fail("You need " + 5 + " healthy troops to spare."); } c.TakeTroops(5, 1, null); settlement.Militia += 5; c.AdjustNotableRelation(q.GiverNotableId, 6, "you left men to guard the herds"); c.GrantSkillExperience(c.State.PlayerHero, "leadership", 20.0); q.Reward = 0L; c.EndQuest(q, QuestStatus.Succeeded, 5 + " of your men now stand guard over the " + q.Note + " of " + settlement.Name + "."); return CommandResult.Success(5 + " troops joined " + settlement.Name + "'s militia."); } if (!c.HoldQuestEscrow(q, q.Reward, null, settlement)) { return CommandResult.Fail(settlement.Name + " cannot raise the reward just now."); } Party party = c.SpawnQuestBand(settlement.Position, "Rustlers of " + settlement.Name, q.Quantity, null, c.State.Random.Get("quests")); if (party == null) { c.RefundQuestEscrow(q); return CommandResult.Fail("No rustlers to be found."); } q.TargetPartyId = party.Id; q.TargetName = party.Name; q.Stage = "hunt"; return CommandResult.Success("The rustlers were last seen near " + settlement.Name + "."); } public override string OnVictory(Campaign c, QuestState q, HashSet beaten) { if (q.Stage != "hunt" || !beaten.Contains(q.TargetPartyId)) { return ""; } q.Stage = "beaten"; return "The rustlers are beaten: return to " + c.State.Settlements.Get(q.TargetSettlementId)?.Name + " for your reward."; } public override string Invalid(Campaign c, QuestState q) { if (!(q.Stage == "hunt") || !PartyGone(c.State.Parties.Get(q.TargetPartyId))) { return ""; } return "Somebody else dealt with the rustlers first."; } public override StoryPrompt Stage(Campaign c, QuestState q, QuestContext ctx) { if (q.Stage != "beaten" || !QuestTemplate.At(ctx, q.TargetSettlementId)) { return null; } StoryPrompt storyPrompt = QuestTemplate.Prompt(q, q.GiverName, "", "You did it! The " + q.Note + " are home and the rustlers will think twice.", "Here, as we promised. It is not much, but it is honestly given."); storyPrompt.Options.Add(QuestTemplate.Option("collect", "Take the reward. (" + q.Reward + " denars)")); return storyPrompt; } public override CommandResult Choose(Campaign c, QuestState q, string option, QuestContext ctx) { Settlement settlement = c.State.Settlements.Require(q.TargetSettlementId); c.AdjustNotableRelation(q.GiverNotableId, 8, "you saw off the rustlers"); settlement.Prosperity += 5.0; c.State.PlayerClan.Renown += 2.0; c.GrantSkillExperience(c.State.PlayerHero, "leadership", 30.0); c.EndQuest(q, QuestStatus.Succeeded, "You saw off the rustlers of " + settlement.Name + "."); return CommandResult.Success("Reward: " + q.Reward + " denars."); } public override List Objectives(Campaign c, QuestState q) { return new List { QuestTemplate.Goal("Defeat the rustlers" + c.KnownPartyWhereabouts(q.TargetPartyId), q.Stage == "beaten"), QuestTemplate.Goal("Return to " + c.State.Settlements.Get(q.TargetSettlementId)?.Name, done: false) }; } public override string Summary(Campaign c, QuestState q) { return "Rustlers are driving off the " + q.Note + " of " + c.State.Settlements.Get(q.TargetSettlementId)?.Name + "."; } public override IEnumerable Places(Campaign c, QuestState q) { if (q.Stage == "hunt" && c.State.PlayerSightings.ContainsKey(q.TargetPartyId)) { yield return q.TargetPartyId; } yield return q.TargetSettlementId; } } private sealed class VillageLevyQuest : QuestTemplate { public override string Id => "notable.levy"; public override QuestSource Source => QuestSource.Notable; public override string[] GiverKinds => new string[1] { "village" }; public override int Days => 14; public override QuestState TryOffer(Campaign c, QuestGiver giver, RandomStream rng) { Settlement settlement = giver.Settlement; Clan clan = c.State.Clans.Get(settlement.OwnerClanId); if (clan == null || clan.IsBandit || clan.IsEliminated || clan.Id == c.State.PlayerClanId) { return null; } Hero hero = c.State.Heroes.Get(clan.LeaderHeroId); if (hero == null || hero.State == HeroState.Dead) { return null; } return new QuestState { Title = "The levy at " + settlement.Name, TargetSettlementId = settlement.Id, TargetClanId = clan.Id, TargetHeroId = hero.Id, TargetName = hero.Name, Quantity = (int)Round10(180 + rng.Range(0, 140)) }; } public override List OfferLines(Campaign c, QuestState q) { List list = new List(); list.Add("The bailiff of " + c.State.Clans.Get(q.TargetClanId)?.Name + " came again. Another " + q.Quantity + " denars' worth of grain, he says, on top of what we already gave."); list.Add("If we pay it, we go hungry this winter. If we don't, he'll be back with soldiers. What are we to do?"); return list; } public override List OfferOptions(Campaign c, QuestState q, QuestContext ctx) { return new List { QuestTemplate.Option("pay", "I'll pay the extra levy for you. (" + q.Quantity + " denars)", (c.State.PlayerClan.Gold < q.Quantity) ? ("You cannot spare " + q.Quantity + " denars.") : "", "Settled at once. The money goes to " + c.State.Clans.Get(q.TargetClanId)?.Name + "; the village is grateful."), QuestTemplate.Option("plead", "I'll speak to " + q.TargetName + " on your behalf.", "", "Find " + q.TargetName + " and argue the village's case (Diplomacy) or soften it with a gift."), QuestTemplate.Option("frighten", "Leave the bailiff to me. He won't be back.", "", "Settled at once. The village is delighted; " + c.State.Clans.Get(q.TargetClanId)?.Name + " is not (relation −8, and a crime against its realm).") }; } public override CommandResult Accept(Campaign c, QuestState q, string approach, QuestContext ctx) { Settlement settlement = c.State.Settlements.Require(q.TargetSettlementId); Clan clan = c.State.Clans.Get(q.TargetClanId); if (approach == "pay") { if (c.State.PlayerClan.Gold < q.Quantity || clan == null) { return CommandResult.Fail("You cannot spare " + q.Quantity + " denars."); } c.State.Transact(c.State.PlayerClan, -q.Quantity, LedgerAccount.Quest, "The levy of " + settlement.Name); c.State.Transact(clan, q.Quantity, LedgerAccount.Taxes, "The levy of " + settlement.Name + " (paid by " + c.State.PlayerClan.Name + ")"); c.AdjustNotableRelation(q.GiverNotableId, 8, "you paid the levy"); settlement.Loyalty = Clamp100(settlement.Loyalty + 5.0); settlement.Prosperity += 5.0; c.EndQuest(q, QuestStatus.Succeeded, "You paid " + settlement.Name + "'s extra levy."); return CommandResult.Success("You paid the levy."); } if (approach == "frighten") { c.AdjustNotableRelation(q.GiverNotableId, 12, "you saw off the bailiff"); if (clan != null && !clan.IsEliminated) { c.AdjustClanRelation(c.State.PlayerClanId, clan.Id, -8); } c.AddCrime(c.CrimeFactionOf(settlement), 8.0, "threatening a bailiff at " + settlement.Name, settlement.Id); c.EndQuest(q, QuestStatus.Succeeded, "The bailiff fled from " + settlement.Name + " and has not been back."); return CommandResult.Success("The bailiff will not be back in a hurry."); } q.Stage = "plead"; return CommandResult.Success("Find " + q.TargetName + " and speak for " + settlement.Name + "."); } public override string Invalid(Campaign c, QuestState q) { if (q.Stage != "plead") { return ""; } Settlement settlement = c.State.Settlements.Get(q.TargetSettlementId); if (settlement == null || settlement.OwnerClanId != q.TargetClanId) { return "The village has a new lord; the old levy is forgotten."; } Hero hero = c.State.Heroes.Get(q.TargetHeroId); if (hero != null && hero.State != HeroState.Dead) { return ""; } return q.TargetName + " is dead; the levy is forgotten in the confusion."; } private double Chance(Campaign c, QuestState q) { return Math.Max(0.1, Math.Min(0.9, 0.35 + (double)c.Skill("diplomacy") / 250.0 + (double)c.ClanRelation(c.State.PlayerClanId, q.TargetClanId) / 150.0)); } private long Gift(QuestState q) { return Round10((double)q.Quantity * 1.2); } public override StoryPrompt Stage(Campaign c, QuestState q, QuestContext ctx) { if (q.Stage != "plead" || ctx.TalkingTo == null || ctx.TalkingTo.Id != q.TargetHeroId) { return null; } Settlement settlement = c.State.Settlements.Get(q.TargetSettlementId); StoryPrompt storyPrompt = QuestTemplate.Prompt(q, q.TargetName, "", "The levy at " + settlement?.Name + "? My bailiff knows his business. Why should I care what the villagers say?"); storyPrompt.Options.Add(QuestTemplate.Option("argue", "Hungry villagers grow nothing. Ease the levy and they will repay you. (" + (int)Math.Round(Chance(c, q) * 100.0) + "% chance)", "", "Diplomacy and your clans' relation decide it.")); storyPrompt.Options.Add(QuestTemplate.Option("gift", "Let me make up the difference myself. (" + Gift(q) + " denars)", (c.State.PlayerClan.Gold < Gift(q)) ? ("You cannot spare " + Gift(q) + " denars.") : "", "A sure way: the money goes to " + c.State.Clans.Get(q.TargetClanId)?.Name + ".")); storyPrompt.Options.Add(QuestTemplate.Option("close", "I will think on it.")); return storyPrompt; } public override CommandResult Choose(Campaign c, QuestState q, string option, QuestContext ctx) { if (option == "close") { return CommandResult.Success(); } Settlement settlement = c.State.Settlements.Require(q.TargetSettlementId); Clan clan = c.State.Clans.Get(q.TargetClanId); if (option == "gift") { long num = Gift(q); if (c.State.PlayerClan.Gold < num) { return CommandResult.Fail("You cannot spare " + num + " denars."); } c.State.Transact(c.State.PlayerClan, -num, LedgerAccount.Quest, "A gift to ease the levy of " + settlement.Name); c.State.Transact(clan, num, LedgerAccount.Quest, "A gift from " + c.State.PlayerClan.Name); c.AdjustClanRelation(c.State.PlayerClanId, clan.Id, 1); c.AdjustNotableRelation(q.GiverNotableId, 10, "you had the levy eased"); settlement.Prosperity += 10.0; c.EndQuest(q, QuestStatus.Succeeded, q.TargetName + " eased the levy of " + settlement.Name + " (you made up the difference)."); return CommandResult.Success("The levy is eased."); } c.GrantSkillExperience(c.State.PlayerHero, "diplomacy", 40.0); if (c.State.Random.Get("quests").Chance(Chance(c, q))) { c.AdjustNotableRelation(q.GiverNotableId, 10, "you had the levy eased"); settlement.Prosperity += 10.0; c.EndQuest(q, QuestStatus.Succeeded, "You talked " + q.TargetName + " into easing the levy of " + settlement.Name + "."); return CommandResult.Success(q.TargetName + " agrees to ease the levy."); } c.AdjustNotableRelation(q.GiverNotableId, 2, "you tried"); c.AdjustClanRelation(c.State.PlayerClanId, clan.Id, -3); c.EndQuest(q, QuestStatus.Failed, q.TargetName + " would not hear of it; the levy stands."); return CommandResult.Success(q.TargetName + " will not change their mind."); } public override List Objectives(Campaign c, QuestState q) { string mapTarget; string text = c.HeroWhereaboutsForTalk(c.State.Heroes.Get(q.TargetHeroId), out mapTarget); List list = new List(); list.Add(QuestTemplate.Goal("Speak to " + q.TargetName + " for " + c.State.Settlements.Get(q.TargetSettlementId)?.Name + " (they are " + text + ")", done: false)); return list; } public override string Summary(Campaign c, QuestState q) { return "The bailiff of " + c.State.Clans.Get(q.TargetClanId)?.Name + " demands another " + q.Quantity + " denars of grain."; } public override IEnumerable Places(Campaign c, QuestState q) { c.HeroWhereaboutsForTalk(c.State.Heroes.Get(q.TargetHeroId), out var mapTarget); if (!string.IsNullOrEmpty(mapTarget)) { yield return mapTarget; } yield return q.TargetSettlementId; } } private sealed class StolenLedgerQuest : QuestTemplate { public override string Id => "notable.ledger"; public override QuestSource Source => QuestSource.Notable; public override string[] GiverKinds => new string[1] { "town" }; public override int Days => 10; public override string DelegateSkill => "scouting"; public override int DelegateTroops => 8; public override int DelegateDays => 5; public override double DelegateDifficulty => 70.0; public override QuestState TryOffer(Campaign c, QuestGiver giver, RandomStream rng) { Settlement town = giver.Settlement; Party party = (from x in c.State.ActiveParties where x.Kind == PartyKind.Bandit && string.IsNullOrEmpty(x.HideoutGuardOf) && c.State.AreHostile(c.State.PlayerClan, c.State.Clans.Get(x.ClanId)) where Vec2.Distance(town.Position, x.Position) <= c.StrategicRange(45.0) orderby Vec2.Distance(town.Position, x.Position) select x).ThenBy((Party x) => x.Id, StringComparer.Ordinal).FirstOrDefault(); if (party == null) { return null; } return new QuestState { Title = "The stolen ledger", TargetSettlementId = town.Id, TargetPartyId = party.Id, TargetName = party.Name, Reward = 300 + Round10(rng.Range(0, 120)) }; } public override List OfferLines(Campaign c, QuestState q) { return new List { "A thief broke into the guild hall and made off with our ledger. Every debt, every deal, every... irregularity. All in one book.", "He ran to " + q.TargetName + ". Get it back, unopened if you please, and the guild will pay you well." }; } public override List OfferOptions(Campaign c, QuestState q, QuestContext ctx) { Settlement settlement = c.State.Settlements.Get(q.TargetSettlementId); List list = new List(); list.Add(QuestTemplate.Option("recover", "I'll get your ledger back.", ((settlement?.Market?.Gold).GetValueOrDefault() < q.Reward) ? "The guild can't raise the reward just now." : "", "Defeat " + q.TargetName + " and bring the ledger back. " + q.Reward + " denars from the guild.")); return list; } public override CommandResult Accept(Campaign c, QuestState q, string approach, QuestContext ctx) { Settlement settlement = c.State.Settlements.Require(q.TargetSettlementId); Party party = c.State.Parties.Get(q.TargetPartyId); if (PartyGone(party)) { return CommandResult.Fail("The thieves are already gone."); } if (!c.HoldQuestEscrow(q, q.Reward, null, settlement)) { return CommandResult.Fail("The guild can't raise the reward just now."); } c.State.PlayerSightings[party.Id] = new Sighting { PartyId = party.Id, Position = party.Position, SeenAtMinute = c.State.Clock.Minute, EstimatedStrength = EstimateCount(c.PartyCombatants(party)) }; q.Stage = "recover"; return CommandResult.Success(q.TargetName + " was last seen near " + settlement.Name + "."); } public override string OnVictory(Campaign c, QuestState q, HashSet beaten) { if (q.Stage != "recover" || !beaten.Contains(q.TargetPartyId)) { return ""; } q.Stage = "holding"; return "Among the thieves' loot: the guild's ledger. Take it back to " + c.State.Settlements.Get(q.TargetSettlementId)?.Name + "."; } public override string Invalid(Campaign c, QuestState q) { if (!(q.Stage == "recover") || !PartyGone(c.State.Parties.Get(q.TargetPartyId))) { return ""; } return "Somebody else destroyed the thieves, and the ledger was lost with them."; } public override StoryPrompt Stage(Campaign c, QuestState q, QuestContext ctx) { if (q.Stage != "holding" || ctx.Here == null || ctx.Here.Type != SettlementType.Town) { return null; } if (ctx.Here.Id == q.TargetSettlementId) { Settlement here = ctx.Here; StoryPrompt storyPrompt = QuestTemplate.Prompt(q, q.GiverName, "", "My ledger! And the seal... unbroken? Wonderful. Wonderful."); storyPrompt.Options.Add(QuestTemplate.Option("return", "Here it is. (" + q.Reward + " denars)", "", "The steward is grateful.")); storyPrompt.Options.Add(QuestTemplate.Option("double", "It was hard won. Double the reward, or it goes in the river. (" + q.Reward * 2 + " denars)", (here.Market.Gold < q.Reward) ? "The guild cannot pay more." : "", "You get double; the steward will not forget it (relation −10).")); return storyPrompt; } NotableState notableState = c.SettlementNotable(ctx.Here.Id); if (notableState == null) { return null; } long num = Round10((double)q.Reward * 1.5); StoryPrompt storyPrompt2 = QuestTemplate.Prompt(q, notableState.Name, notableState.Occupation + " of " + ctx.Here.Name, "I hear you have a certain book. The guild of " + c.State.Settlements.Get(q.TargetSettlementId)?.Name + "'s book. I would pay to read it."); storyPrompt2.Options.Add(QuestTemplate.Option("sell", "Sell it to " + notableState.Name + ". (" + num + " denars)", (ctx.Here.Market.Gold < num) ? (notableState.Name + " cannot pay that much just now.") : "", "You get " + num + "; the steward who sent you will be furious (relation −15).")); storyPrompt2.Options.Add(QuestTemplate.Option("close", "It is not for sale.")); return storyPrompt2; } public override CommandResult Choose(Campaign c, QuestState q, string option, QuestContext ctx) { if (option == "close") { return CommandResult.Success(); } Settlement settlement = c.State.Settlements.Require(q.TargetSettlementId); if (option == "sell") { Settlement here = ctx.Here; NotableState notableState = c.SettlementNotable(here.Id); long num = Round10((double)q.Reward * 1.5); if (here.Market.Gold < num) { return CommandResult.Fail("They cannot pay that much."); } here.Market.Gold -= num; c.State.Transact(c.State.PlayerClan, num, LedgerAccount.Quest, "The guild ledger, sold at " + here.Name); c.AdjustNotableRelation(notableState?.Id, 8, "you sold them the ledger"); c.AdjustNotableRelation(q.GiverNotableId, -15, "you sold the ledger"); c.EndQuest(q, QuestStatus.Failed, "You sold the guild's ledger to " + notableState?.Name + " of " + here.Name + " for " + num + " denars."); return CommandResult.Success("Sold for " + num + " denars."); } if (option == "double") { long num2 = Math.Min(q.Reward, settlement.Market.Gold); settlement.Market.Gold -= num2; q.Escrow += num2; c.AdjustNotableRelation(q.GiverNotableId, -10, "you demanded double"); c.GrantSkillExperience(c.State.PlayerHero, "trade", 30.0); c.EndQuest(q, QuestStatus.Succeeded, "You returned the ledger to " + settlement.Name + " for double the reward."); return CommandResult.Success("Paid double."); } c.AdjustNotableRelation(q.GiverNotableId, 8, "you returned the ledger"); c.State.PlayerClan.Renown += 1.0; c.GrantSkillExperience(c.State.PlayerHero, "leadership", 20.0); c.EndQuest(q, QuestStatus.Succeeded, "You returned the guild's ledger to " + settlement.Name + ", seal unbroken."); return CommandResult.Success("Reward: " + q.Reward + " denars."); } public override List Objectives(Campaign c, QuestState q) { return new List { QuestTemplate.Goal("Defeat " + q.TargetName + c.KnownPartyWhereabouts(q.TargetPartyId), q.Stage == "holding"), QuestTemplate.Goal("Bring the ledger back to " + c.State.Settlements.Get(q.TargetSettlementId)?.Name + " (or sell it to another town's steward)", done: false) }; } public override string Summary(Campaign c, QuestState q) { return "A thief stole the guild ledger of " + c.State.Settlements.Get(q.TargetSettlementId)?.Name + "."; } public override IEnumerable Places(Campaign c, QuestState q) { if (q.Stage == "recover" && c.State.PlayerSightings.ContainsKey(q.TargetPartyId)) { yield return q.TargetPartyId; } yield return q.TargetSettlementId; } } private sealed class DebtQuest : QuestTemplate { public override string Id => "notable.debt"; public override QuestSource Source => QuestSource.Notable; public override string[] GiverKinds => new string[1] { "town" }; public override int Days => 14; public override QuestState TryOffer(Campaign c, QuestGiver giver, RandomStream rng) { Settlement town = giver.Settlement; Settlement settlement = (from s in c.State.Settlements where s.Type == SettlementType.Town && s.Id != town.Id && c.ContractFriendlySettlement(s) && c.SettlementNotable(s.Id) != null where Vec2.Distance(s.Position, town.Position) <= c.StrategicRange(40.0) orderby Vec2.Distance(s.Position, town.Position) select s).ThenBy((Settlement s) => s.Id, StringComparer.Ordinal).Skip(rng.Range(0, 2)).FirstOrDefault(); if (settlement == null) { return null; } NotableState notableState = c.SettlementNotable(settlement.Id); long num = Round10(300 + rng.Range(0, 300)); return new QuestState { Title = "An old debt in " + settlement.Name, TargetSettlementId = settlement.Id, OtherSettlementId = town.Id, TargetName = notableState.Name, Needed = (int)num, Reward = Math.Max(60L, Round10((double)num / 4.0)) }; } public override List OfferLines(Campaign c, QuestState q) { List list = new List(); list.Add(q.TargetName + " of " + c.State.Settlements.Get(q.TargetSettlementId)?.Name + " owes the guild " + q.Needed + " denars. Owes it since the spring, and every letter comes back with excuses."); list.Add("Go and collect it. Bring it here and a quarter is yours."); return list; } public override List OfferOptions(Campaign c, QuestState q, QuestContext ctx) { Settlement settlement = c.State.Settlements.Get(q.OtherSettlementId); List list = new List(); list.Add(QuestTemplate.Option("collect", "I'll collect it.", ((settlement?.Market?.Gold).GetValueOrDefault() < q.Reward) ? "The guild can't set aside your fee just now." : "", "Go to " + c.State.Settlements.Get(q.TargetSettlementId)?.Name + ", get the money (or goods) and bring it back. Your fee: " + q.Reward + " denars.")); return list; } public override CommandResult Accept(Campaign c, QuestState q, string approach, QuestContext ctx) { if (!c.HoldQuestEscrow(q, q.Reward, null, c.State.Settlements.Require(q.OtherSettlementId))) { return CommandResult.Fail("The guild can't set aside your fee just now."); } q.Stage = "collect"; return CommandResult.Success("Go to " + c.State.Settlements.Get(q.TargetSettlementId)?.Name + "."); } private static string BestGood(Campaign c, Settlement s) { return (from kv in (from kv in s.Market?.Stock?.Where((KeyValuePair kv) => kv.Value > 0 && TabsBannerlord.Core.Content.TradeGoods.Get(kv.Key) != null) orderby kv.Value * TabsBannerlord.Core.Content.TradeGoods.Get(kv.Key).BasePrice descending select kv).ThenBy, string>((KeyValuePair kv) => kv.Key, StringComparer.Ordinal) select kv.Key).FirstOrDefault() ?? ""; } private static int GoodsFor(Campaign c, Settlement s, string good, long debt) { if (good.Length != 0) { return Math.Max(1, Math.Min(c.MarketStock(s, good), (int)Math.Ceiling((double)debt / (double)Math.Max(1L, TabsBannerlord.Core.Content.TradeGoods.Get(good).BasePrice)))); } return 0; } public override void Daily(Campaign c, QuestState q) { if (q.Stage == "carry" && q.Approach != "paid" && q.DeadlineMinute <= c.State.Clock.Minute) { c.AdjustNotableRelation(q.GiverNotableId, -12, "you kept the guild's money"); } } public override string Invalid(Campaign c, QuestState q) { if (!(q.Stage == "collect") || !(c.SettlementNotable(q.TargetSettlementId)?.Name != q.TargetName)) { return ""; } return q.TargetName + " is gone, and the debt with them."; } public override StoryPrompt Stage(Campaign c, QuestState q, QuestContext ctx) { if (q.Stage == "collect" && QuestTemplate.At(ctx, q.TargetSettlementId)) { Settlement here = ctx.Here; string text = BestGood(c, here); int num = GoodsFor(c, here, text, q.Needed); int num2 = (int)Math.Floor((c.CargoCapacity(c.State.PlayerParty) - c.CargoWeight(c.State.PlayerParty)) / Math.Max(0.1, TabsBannerlord.Core.Content.TradeGoods.Get(text)?.Weight ?? 1.0)); StoryPrompt storyPrompt = QuestTemplate.Prompt(q, q.TargetName, "", "Ah. The guild. Yes. About that money...", "Times are hard, you understand. Very hard."); storyPrompt.Options.Add(QuestTemplate.Option("demand", "Pay what you owe. All " + q.Needed + " denars.", (here.Market.Gold < q.Needed) ? (q.TargetName + " truly cannot pay just now.") : "", "You carry the money back to the guild. " + q.TargetName + " will resent it (relation −8).")); storyPrompt.Options.Add(QuestTemplate.Option("goods", "Pay in goods, then: " + num + " " + QuestTemplate.GoodName(text) + ".", (text.Length == 0) ? "They have nothing worth taking." : ((num2 < num) ? ("You have no room for " + num + " " + QuestTemplate.GoodName(text) + ".") : ""), "Carry the goods back; the guild will take them.")); storyPrompt.Options.Add(QuestTemplate.Option("forgive", "Keep it. I'll settle the debt with the guild myself.", "", q.TargetName + " will be grateful (relation +12); you pay " + q.Needed + " denars when you hand it over.")); storyPrompt.Options.Add(QuestTemplate.Option("close", "I'll come back.")); return storyPrompt; } if (q.Stage == "carry" && QuestTemplate.At(ctx, q.OtherSettlementId)) { bool num3 = q.Approach == "goods"; bool flag = q.Approach == "paid"; string text2 = (num3 ? (q.Quantity + " " + QuestTemplate.GoodName(q.GoodId)) : (q.Needed + " denars")); string reason = ((!num3) ? ((c.State.PlayerClan.Gold < q.Needed) ? ("You no longer have the " + q.Needed + " denars.") : "") : ((c.CargoCount(c.State.PlayerParty, q.GoodId) < q.Quantity) ? ("You no longer carry the " + QuestTemplate.GoodName(q.GoodId) + ".") : "")); StoryPrompt storyPrompt2 = QuestTemplate.Prompt(q, q.GiverName, "", "Well? Did " + q.TargetName + " pay?"); storyPrompt2.Options.Add(QuestTemplate.Option("hand", "Hand over the " + text2 + "." + (flag ? " (your own money)" : ""), reason, "Your fee: " + q.Reward + " denars.")); return storyPrompt2; } return null; } public override CommandResult Choose(Campaign c, QuestState q, string option, QuestContext ctx) { if (option == "close") { return CommandResult.Success(); } Settlement settlement = c.State.Settlements.Require(q.TargetSettlementId); Settlement settlement2 = c.State.Settlements.Require(q.OtherSettlementId); string notableId = c.SettlementNotable(settlement.Id)?.Id; if (q.Stage == "collect") { if (option == "demand") { if (settlement.Market.Gold < q.Needed) { return CommandResult.Fail(q.TargetName + " cannot pay just now."); } settlement.Market.Gold -= q.Needed; c.State.Transact(c.State.PlayerClan, q.Needed, LedgerAccount.Quest, "The guild's debt, collected at " + settlement.Name + " (to hand over)"); c.AdjustNotableRelation(notableId, -8, "you collected the guild's debt"); q.Approach = "coin"; QuestLog(c, q, "You collected " + q.Needed + " denars from " + q.TargetName + "."); } else if (option == "goods") { string text = BestGood(c, settlement); int num = GoodsFor(c, settlement, text, q.Needed); if (text.Length == 0) { return CommandResult.Fail("They have nothing worth taking."); } settlement.Market.Stock[text] = c.MarketStock(settlement, text) - num; c.State.PlayerParty.Cargo[text] = c.CargoCount(c.State.PlayerParty, text) + num; c.AdjustNotableRelation(notableId, -2, "you took goods for the guild's debt"); q.Approach = "goods"; q.GoodId = text; q.Quantity = num; QuestLog(c, q, "You took " + num + " " + QuestTemplate.GoodName(text) + " from " + q.TargetName + " in place of the debt."); } else { c.AdjustNotableRelation(notableId, 12, "you settled their debt"); q.Approach = "paid"; QuestLog(c, q, "You forgave " + q.TargetName + "'s debt and will settle it yourself."); } q.Stage = "carry"; q.StageMinute = c.State.Clock.Minute; return CommandResult.Success("Take it back to " + settlement2.Name + "."); } if (q.Approach == "goods") { if (c.CargoCount(c.State.PlayerParty, q.GoodId) < q.Quantity) { return CommandResult.Fail("You've lost the goods."); } int num2 = c.CargoCount(c.State.PlayerParty, q.GoodId) - q.Quantity; if (num2 == 0) { c.State.PlayerParty.Cargo.Remove(q.GoodId); } else { c.State.PlayerParty.Cargo[q.GoodId] = num2; } int num3 = c.MarketStock(settlement2, q.GoodId); settlement2.Market.Stock[q.GoodId] = Math.Min(500, num3 + q.Quantity); } else { if (c.State.PlayerClan.Gold < q.Needed) { return CommandResult.Fail("You haven't got the money any more."); } c.State.Transact(c.State.PlayerClan, -q.Needed, LedgerAccount.Quest, "The guild's debt, handed over at " + settlement2.Name); settlement2.Market.Gold += q.Needed; } c.AdjustNotableRelation(q.GiverNotableId, (q.Approach == "paid") ? 10 : 6, "you settled the guild's debt"); if (q.Approach == "paid") { c.State.PlayerClan.Renown += 1.0; } c.GrantSkillExperience(c.State.PlayerHero, "trade", 30.0); c.EndQuest(q, QuestStatus.Succeeded, (q.Approach == "paid") ? ("You paid " + q.TargetName + "'s debt to the guild yourself.") : ((q.Approach == "goods") ? ("You brought the guild goods in place of " + q.TargetName + "'s debt.") : ("You collected " + q.TargetName + "'s debt for the guild."))); return CommandResult.Success("Your fee: " + q.Reward + " denars."); } public override List Objectives(Campaign c, QuestState q) { return new List { QuestTemplate.Goal("Collect the debt from " + q.TargetName + " in " + c.State.Settlements.Get(q.TargetSettlementId)?.Name, q.Stage == "carry"), QuestTemplate.Goal("Hand it over in " + c.State.Settlements.Get(q.OtherSettlementId)?.Name, done: false) }; } public override string Summary(Campaign c, QuestState q) { return q.TargetName + " owes the guild " + q.Needed + " denars."; } public override IEnumerable Places(Campaign c, QuestState q) { yield return (q.Stage == "carry") ? q.OtherSettlementId : q.TargetSettlementId; } } private sealed class DrillQuest : QuestTemplate { private const int Troops = 6; private const int DrillHours = 48; private const long DrillMaster = 250L; public override string Id => "notable.drill"; public override QuestSource Source => QuestSource.Notable; public override string[] GiverKinds => new string[1] { "castle" }; public override int Days => 7; public override string DelegateSkill => "leadership"; public override int DelegateDays => 4; public override double DelegateDifficulty => 40.0; public override string DelegateEscrowReason(Campaign c, QuestState q) { if ((c.State.Clans.Get(q.TargetClanId)?.Gold ?? 0) >= q.Reward) { return ""; } return c.State.Clans.Get(q.TargetClanId)?.Name + " cannot pay just now."; } public override bool DelegateEscrow(Campaign c, QuestState q) { return c.HoldQuestEscrow(q, q.Reward, c.State.Clans.Get(q.TargetClanId), null); } public override void DelegatedSuccess(Campaign c, QuestState q, Hero companion) { base.DelegatedSuccess(c, q, companion); Settlement settlement = c.State.Settlements.Get(q.TargetSettlementId); if (settlement != null) { settlement.Militia += 8; } } public override QuestState TryOffer(Campaign c, QuestGiver giver, RandomStream rng) { Settlement settlement = giver.Settlement; Clan clan = c.State.Clans.Get(settlement.OwnerClanId); if (clan == null || clan.IsBandit || clan.IsEliminated || clan.Id == c.State.PlayerClanId || clan.Gold < 400) { return null; } return new QuestState { Title = "Drill the levy of " + settlement.Name, TargetSettlementId = settlement.Id, TargetClanId = clan.Id, Reward = 200L, Needed = 48 }; } public override List OfferLines(Campaign c, QuestState q) { return new List { "Look at them. The levy of " + c.State.Settlements.Get(q.TargetSettlementId)?.Name + ". Half of them hold the spear by the pointy end.", "If anyone comes over that hill, we are done for. I need real soldiers, or someone who can make soldiers of these." }; } public override List OfferOptions(Campaign c, QuestState q, QuestContext ctx) { Clan clan = c.State.Clans.Get(q.TargetClanId); List list = new List(); list.Add(QuestTemplate.Option("troops", "Take " + 6 + " of my seasoned troops (tier 2 or better).", (c.HandableTroops(2) < 6) ? ("You need " + 6 + " healthy troops of tier 2 or better to spare.") : "", "Settled at once. They join the garrison; " + clan?.Name + " pays for them.")); list.Add(QuestTemplate.Option("drill", "I'll drill them myself, for two days.", ((clan?.Gold ?? 0) < q.Reward) ? (clan?.Name + " cannot pay just now.") : "", "Stay (wait) in the castle for " + 48 + " hours. The militia grows; " + q.Reward + " denars from " + clan?.Name + ".")); list.Add(QuestTemplate.Option("pay", "Hire them a proper drill master. (" + 250L + " denars)", (c.State.PlayerClan.Gold < 250) ? ("You cannot spare " + 250L + " denars.") : "", "Settled at once. The militia grows a little.")); return list; } private long Price(Campaign c, List units) { return Round10((double)units.Sum((string u) => c.UnitDef(u)?.RecruitCost ?? 20) * 1.5); } public override CommandResult Accept(Campaign c, QuestState q, string approach, QuestContext ctx) { Settlement settlement = c.State.Settlements.Require(q.TargetSettlementId); Clan clan = c.State.Clans.Get(q.TargetClanId); if (approach == "troops") { if (c.HandableTroops(2) < 6) { return CommandResult.Fail("You need " + 6 + " healthy troops of tier 2 or better to spare."); } List units = (from s in c.State.PlayerParty.Troops.Stacks where (c.UnitDef(s.UnitId)?.Tier ?? 1) >= 2 orderby c.UnitDef(s.UnitId)?.Tier ?? 1 select s).ThenBy((TroopStack s) => s.UnitId, StringComparer.Ordinal).SelectMany((TroopStack s) => Enumerable.Repeat(s.UnitId, s.Healthy)).Take(6) .ToList(); long num = Math.Min(Price(c, units), clan?.Gold ?? 0); List list = c.TakeTroops(6, 2, settlement.Garrison); if (num > 0) { c.State.Transact(clan, -num, LedgerAccount.Recruitment, "Troops for " + settlement.Name); c.State.Transact(c.State.PlayerClan, num, LedgerAccount.Quest, "Troops for " + settlement.Name); } c.AdjustNotableRelation(q.GiverNotableId, 8, "you gave the castle real soldiers"); q.Reward = num; c.EndQuest(q, QuestStatus.Succeeded, list.Count + " of your troops joined the garrison of " + settlement.Name + " for " + num + " denars."); return CommandResult.Success(list.Count + " troops joined the garrison."); } if (approach == "pay") { if (!c.PlayerPaysMarket(settlement, 250L, "A drill master for " + settlement.Name)) { return CommandResult.Fail("You cannot spare " + 250L + " denars."); } settlement.Militia += 8; c.AdjustNotableRelation(q.GiverNotableId, 5, "you hired a drill master"); q.Reward = 0L; c.EndQuest(q, QuestStatus.Succeeded, "A drill master you paid for is licking the levy of " + settlement.Name + " into shape."); return CommandResult.Success("A drill master is hired."); } if (!c.HoldQuestEscrow(q, q.Reward, clan, null)) { return CommandResult.Fail(clan?.Name + " cannot pay just now."); } q.Stage = "drill"; return CommandResult.Success("Wait in " + settlement.Name + " for two days to drill the levy."); } public override void Hourly(Campaign c, QuestState q) { if (q.Stage != "drill") { return; } Party playerParty = c.State.PlayerParty; if (playerParty != null && playerParty.State == PartyState.InSettlement && !(playerParty.CurrentSettlementId != q.TargetSettlementId)) { q.Hours++; if (q.Hours >= q.Needed) { q.Stage = "drilled"; QuestLog(c, q, "Two days of drill: the levy can now hold a spear the right way round."); } } } public override StoryPrompt Stage(Campaign c, QuestState q, QuestContext ctx) { if (q.Stage != "drilled" || !QuestTemplate.At(ctx, q.TargetSettlementId)) { return null; } StoryPrompt storyPrompt = QuestTemplate.Prompt(q, q.GiverName, "", "I watched them this morning. They marched in step! Mostly. Thank you, " + c.PlayerFirstName + "."); storyPrompt.Options.Add(QuestTemplate.Option("collect", "Glad to help. (" + q.Reward + " denars)")); return storyPrompt; } public override CommandResult Choose(Campaign c, QuestState q, string option, QuestContext ctx) { Settlement settlement = c.State.Settlements.Require(q.TargetSettlementId); settlement.Militia += 12; c.GrantSkillExperience(c.State.PlayerHero, "leadership", 80.0); c.AdjustNotableRelation(q.GiverNotableId, 10, "you drilled the levy"); c.EndQuest(q, QuestStatus.Succeeded, "You drilled the levy of " + settlement.Name + "."); return CommandResult.Success("Reward: " + q.Reward + " denars."); } public override List Objectives(Campaign c, QuestState q) { List list = new List(); list.Add(QuestTemplate.Goal("Drill the levy: stay in " + c.State.Settlements.Get(q.TargetSettlementId)?.Name + " (" + Math.Min(q.Hours, q.Needed) + " / " + q.Needed + " hours)", q.Stage == "drilled")); list.Add(QuestTemplate.Goal("Report to " + q.GiverName, done: false)); return list; } public override string Summary(Campaign c, QuestState q) { return "The levy of " + c.State.Settlements.Get(q.TargetSettlementId)?.Name + " needs drilling."; } public override IEnumerable Places(Campaign c, QuestState q) { yield return q.TargetSettlementId; } } private sealed class MortarQuest : QuestTemplate { private const int Timber = 4; private const int Clay = 4; private const int EngineerHours = 24; private const int EngineerSkill = 40; private const long Masons = 450L; public override string Id => "notable.mortar"; public override QuestSource Source => QuestSource.Notable; public override string[] GiverKinds => new string[1] { "castle" }; public override int Days => 12; public override QuestState TryOffer(Campaign c, QuestGiver giver, RandomStream rng) { Settlement settlement = giver.Settlement; Clan clan = c.State.Clans.Get(settlement.OwnerClanId); if (clan == null || clan.IsBandit || clan.IsEliminated || clan.Id == c.State.PlayerClanId || clan.Gold < 400) { return null; } return new QuestState { Title = "Mortar and stone for " + settlement.Name, TargetSettlementId = settlement.Id, TargetClanId = clan.Id, Reward = 300L, Needed = 24 }; } public override List OfferLines(Campaign c, QuestState q) { return new List { "The east wall has a crack you could post a goat through. Somebody already did, last week. Twice.", "I need timber and clay for the masons, or the masons' wages, or someone who knows one end of a trowel from the other." }; } private Hero Engineer(Campaign c) { return (from id in c.State.PlayerParty?.Troops.Heroes select c.State.Heroes.Get(id) into h where h != null && h.State == HeroState.Active && h.Skill("engineering") >= 40 orderby h.Skill("engineering") descending select h).ThenBy((Hero h) => h.Id, StringComparer.Ordinal).FirstOrDefault(); } public override List OfferOptions(Campaign c, QuestState q, QuestContext ctx) { Clan clan = c.State.Clans.Get(q.TargetClanId); Hero hero = Engineer(c); string text = (((clan?.Gold ?? 0) < q.Reward) ? (clan?.Name + " cannot pay just now.") : ""); List list = new List(); list.Add(QuestTemplate.Option("bring", "I'll bring you " + 4 + " timber and " + 4 + " clay.", text, "Buy or bring them here. " + q.Reward + " denars from " + clan?.Name + ".")); list.Add(QuestTemplate.Option("masons", "Pay the masons yourselves; here's the money. (" + 450L + " denars)", (c.State.PlayerClan.Gold < 450) ? ("You cannot spare " + 450L + " denars.") : "", "Settled at once. The walls are safer.")); list.Add(QuestTemplate.Option("engineer", (hero == null) ? "Lend an engineer for a day." : ("Lend " + hero.Name + " to supervise the repairs for a day."), (hero == null) ? ("Nobody in your party has " + 40 + " Engineering.") : text, "Stay (wait) in the castle for " + 24 + " hours. Engineering training; " + Round10((double)(q.Reward * 2) / 3.0) + " denars.")); return list; } public override CommandResult Accept(Campaign c, QuestState q, string approach, QuestContext ctx) { Settlement settlement = c.State.Settlements.Require(q.TargetSettlementId); Clan clan = c.State.Clans.Get(q.TargetClanId); if (approach == "masons") { if (!c.PlayerPaysMarket(settlement, 450L, "Masons for " + settlement.Name)) { return CommandResult.Fail("You cannot spare " + 450L + " denars."); } settlement.Security = Clamp100(settlement.Security + 5.0); c.AdjustNotableRelation(q.GiverNotableId, 6, "you paid the masons"); q.Reward = 0L; c.EndQuest(q, QuestStatus.Succeeded, "The masons of " + settlement.Name + " are at work, paid by you."); return CommandResult.Success("The masons are paid."); } if (approach == "engineer") { Hero hero = Engineer(c); if (hero == null) { return CommandResult.Fail("Nobody in your party has " + 40 + " Engineering."); } if (!c.HoldQuestEscrow(q, Round10((double)(q.Reward * 2) / 3.0), clan, null)) { return CommandResult.Fail(clan?.Name + " cannot pay just now."); } q.TargetHeroId = hero.Id; q.TargetName = hero.Name; q.Stage = "supervise"; return CommandResult.Success("Wait in " + settlement.Name + " for a day while " + hero.Name + " supervises."); } if (!c.HoldQuestEscrow(q, q.Reward, clan, null)) { return CommandResult.Fail(clan?.Name + " cannot pay just now."); } q.Stage = "bring"; return CommandResult.Success("Bring " + 4 + " timber and " + 4 + " clay to " + settlement.Name + "."); } public override void Hourly(Campaign c, QuestState q) { if (q.Stage != "supervise") { return; } Party playerParty = c.State.PlayerParty; if (playerParty == null || playerParty.State != PartyState.InSettlement || playerParty.CurrentSettlementId != q.TargetSettlementId) { return; } Hero hero = c.State.Heroes.Get(q.TargetHeroId); if (hero != null && !(hero.PartyId != playerParty.Id) && hero.State == HeroState.Active) { q.Hours++; if (q.Hours >= q.Needed) { q.Stage = "mended"; QuestLog(c, q, hero.Name + " finished supervising the repairs."); } } } public override StoryPrompt Stage(Campaign c, QuestState q, QuestContext ctx) { if (!QuestTemplate.At(ctx, q.TargetSettlementId)) { return null; } if (q.Stage == "bring") { Party playerParty = c.State.PlayerParty; bool flag = c.CargoCount(playerParty, "good.timber") >= 4 && c.CargoCount(playerParty, "good.clay") >= 4; StoryPrompt storyPrompt = QuestTemplate.Prompt(q, q.GiverName, "", "Did you bring the timber and the clay?"); storyPrompt.Options.Add(QuestTemplate.Option("deliver", "Unload " + 4 + " timber and " + 4 + " clay.", flag ? "" : ("You carry " + c.CargoCount(playerParty, "good.timber") + " timber and " + c.CargoCount(playerParty, "good.clay") + " clay."), "Reward: " + q.Reward + " denars.")); storyPrompt.Options.Add(QuestTemplate.Option("close", "Not yet.")); return storyPrompt; } if (q.Stage == "mended") { StoryPrompt storyPrompt2 = QuestTemplate.Prompt(q, q.GiverName, "", "Not a goat-sized crack left in it. " + q.TargetName + " knows their trade."); storyPrompt2.Options.Add(QuestTemplate.Option("collect", "Good. (" + q.Escrow + " denars)")); return storyPrompt2; } return null; } public override CommandResult Choose(Campaign c, QuestState q, string option, QuestContext ctx) { if (option == "close") { return CommandResult.Success(); } Settlement settlement = c.State.Settlements.Require(q.TargetSettlementId); if (q.Stage == "bring") { Party playerParty = c.State.PlayerParty; if (c.CargoCount(playerParty, "good.timber") < 4 || c.CargoCount(playerParty, "good.clay") < 4) { return CommandResult.Fail("You do not carry enough."); } string[] array = new string[2] { "good.timber", "good.clay" }; foreach (string text in array) { int num = ((text == "good.timber") ? 4 : 4); int num2 = c.CargoCount(playerParty, text) - num; if (num2 == 0) { playerParty.Cargo.Remove(text); } else { playerParty.Cargo[text] = num2; } } settlement.Security = Clamp100(settlement.Security + 5.0); settlement.Prosperity += 20.0; c.AdjustNotableRelation(q.GiverNotableId, 8, "you brought building materials"); c.EndQuest(q, QuestStatus.Succeeded, "You brought timber and clay to mend the walls of " + settlement.Name + "."); return CommandResult.Success("Reward: " + q.Reward + " denars."); } Hero hero = c.State.Heroes.Get(q.TargetHeroId); if (hero != null) { c.GrantSkillExperience(hero, "engineering", 80.0); } settlement.Security = Clamp100(settlement.Security + 8.0); c.AdjustNotableRelation(q.GiverNotableId, 10, "your engineer mended the walls"); c.EndQuest(q, QuestStatus.Succeeded, q.TargetName + " supervised the repairs of " + settlement.Name + "."); return CommandResult.Success("Reward: " + q.Reward + " denars."); } public override List Objectives(Campaign c, QuestState q) { string text = c.State.Settlements.Get(q.TargetSettlementId)?.Name; List list; if (q.Stage == "supervise" || q.Stage == "mended") { list = new List(); list.Add(QuestTemplate.Goal(q.TargetName + " supervises the repairs: stay in " + text + " (" + Math.Min(q.Hours, q.Needed) + " / " + q.Needed + " hours)", q.Stage == "mended")); list.Add(QuestTemplate.Goal("Report to " + q.GiverName, done: false)); return list; } Party playerParty = c.State.PlayerParty; list = new List(); list.Add(QuestTemplate.Goal("Carry " + 4 + " timber (" + Math.Min(4, c.CargoCount(playerParty, "good.timber")) + " aboard) and " + 4 + " clay (" + Math.Min(4, c.CargoCount(playerParty, "good.clay")) + " aboard)", c.CargoCount(playerParty, "good.timber") >= 4 && c.CargoCount(playerParty, "good.clay") >= 4)); list.Add(QuestTemplate.Goal("Deliver them to " + text, done: false)); return list; } public override string Summary(Campaign c, QuestState q) { return "The walls of " + c.State.Settlements.Get(q.TargetSettlementId)?.Name + " need mending."; } public override IEnumerable Places(Campaign c, QuestState q) { yield return q.TargetSettlementId; } } internal sealed class StoryEventDefinition { public string Id = ""; public string Context = ""; public string Title = ""; public Func Prepare = (Campaign c, PendingEventState p, RandomStream r) => true; public Func> Lines; public Func> Options; public Func Resolve; } public const int AiArmyInfluence = 20; public const int AiArmyMembers = 5; public const double AiArmyCohesionPerDay = 4.0; public const int AiArmyGatherDays = 2; public const int AiArmyFormIntervalDays = 3; public const double AiArmyJoinInfluencePerDay = 0.5; public const long TownFiefWorth = 14000L; public const long CastleFiefWorth = 9000L; public const int BarterPassageHours = 8; private BarterSystem _barterSystem; public const long CaravanLaunchCapital = 1000L; public const int CaravanEscortSize = 5; public const int CaravanLimit = 2; public const double CaravanTradeXpPerDenar = 0.1; public const double CaravanTradeXpDailyLimit = 100.0; public const int ClanRecruitmentInfluence = 20; public const int ClanAllegianceCooldownDays = 7; public const int ClanDefectionIntervalDays = 7; public const int ClanDefectionRelation = -40; public const double ClanArmyMinimumCohesion = 20.0; public const double ArmyGatherRadius = 1.25; public const int ClanCaravanSize = 16; public const long ClanCaravanCapital = 1500L; public const long ClanCaravanReserve = 5000L; public const long ClanCaravanRichGold = 30000L; public const int ClanCaravanIntervalDays = 10; public const int ClanCaravanLossDays = 20; public const string ClanCaravanStream = "clancaravans"; private ClanCaravansSystem _clanCaravansSystem; internal const string ExpiredContractReason = "This contract expired."; public const string ConversationStream = "conversations"; public const int SmallTalkRelation = 1; public const double SmallTalkDiplomacyXp = 4.0; public const int CouncilProposalCost = 10; public const long CouncilDurationMinutes = 2880L; public const int CouncilHistoryLimit = 24; internal bool _processingCouncil; public const double WantedCrime = 30.0; public const double OutlawCrime = 60.0; public const double HuntedCrime = 90.0; public const double MaxCrime = 150.0; public const double CrimeDecayPerDay = 0.6; public const string CrimeStream = "crime"; public const double CrimeRaid = 18.0; public const double CrimeAttackCivilians = 8.0; public const double CrimePrisonBreak = 25.0; public const double CrimePrisonAlarm = 12.0; public const double CrimeGuardDowned = 3.0; public const double CrimeCaughtSneaking = 6.0; public const double CrimeExecution = 40.0; private AbilitiesSystem _abilitiesSystem; private AiSystem _aiSystem; private AiArmiesSystem _aiArmiesSystem; private AllegianceSystem _allegianceSystem; private ArmyMergeSystem _armyMergeSystem; private CaravansSystem _caravansSystem; private CargoConsequencesSystem _cargoConsequencesSystem; private ClanAllegianceSystem _clanAllegianceSystem; private ClanArmySystem _clanArmySystem; private ClanArmyDynamicsSystem _clanArmyDynamicsSystem; private CompanionRecoverySystem _companionRecoverySystem; private CompanionsSystem _companionsSystem; private ContractsSystem _contractsSystem; private ConversationsSystem _conversationsSystem; private CouncilSystem _councilSystem; private CouncilDiplomacySystem _councilDiplomacySystem; private CourtshipSystem _courtshipSystem; private CreationLooksSystem _creationLooksSystem; private CrimeSystem _crimeSystem; private DailySystem _dailySystem; private DeveloperSystem _developerSystem; private DeveloperDiplomacySystem _developerDiplomacySystem; private DiplomacySystem _diplomacySystem; private DiplomacyConsequencesSystem _diplomacyConsequencesSystem; private DiscoveriesSystem _discoveriesSystem; private EconomySystem _economySystem; private ElectionsSystem _electionsSystem; private EncountersSystem _encountersSystem; private EncyclopediaSystem _encyclopediaSystem; private EnterprisesSystem _enterprisesSystem; private EquipmentSystem _equipmentSystem; private EquipmentBattlesSystem _equipmentBattlesSystem; private FamiliesSystem _familiesSystem; private GovernanceSystem _governanceSystem; private GovernorsSystem _governorsSystem; private HeroBondsSystem _heroBondsSystem; private HeroDevelopmentSystem _heroDevelopmentSystem; private HideoutsSystem _hideoutsSystem; private HorseLifeSystem _horseLifeSystem; private HorseMarketsSystem _horseMarketsSystem; private HorsesSystem _horsesSystem; private KeepSystem _keepSystem; private KingdomArmySystem _kingdomArmySystem; private KingdomArmyAiSystem _kingdomArmyAiSystem; private KingdomsSystem _kingdomsSystem; private LegendsSystem _legendsSystem; private MerchantCaravansSystem _merchantCaravansSystem; private MilitaryAiSystem _militaryAiSystem; private MilitaryBudgetsSystem _militaryBudgetsSystem; private MilitaryPartiesSystem _militaryPartiesSystem; private MilitaryRecoverySystem _militaryRecoverySystem; private MilitaryTransfersSystem _militaryTransfersSystem; private MovementSystem _movementSystem; private NamedCustodySystem _namedCustodySystem; private NotablesSystem _notablesSystem; private PactsSystem _pactsSystem; private PartyFoodSystem _partyFoodSystem; private PartySizesSystem _partySizesSystem; private PlayerSystem _playerSystem; private PoliciesSystem _policiesSystem; private PoliticsSystem _politicsSystem; private PrisonerRansomsSystem _prisonerRansomsSystem; private PrisonersSystem _prisonersSystem; private ProgressionSystem _progressionSystem; private QuestChainsSystem _questChainsSystem; private QuestsSystem _questsSystem; private QuestsLordSystem _questsLordSystem; private RaidAiSystem _raidAiSystem; private RaidsSystem _raidsSystem; private RebellionsSystem _rebellionsSystem; private RescuedTroopsSystem _rescuedTroopsSystem; private ServiceSystem _serviceSystem; private SettlementFoodSystem _settlementFoodSystem; private SettlementStatsSystem _settlementStatsSystem; private SiegeAiSystem _siegeAiSystem; private SiegeBattlesSystem _siegeBattlesSystem; private SiegeCaptureSystem _siegeCaptureSystem; private SiegeWorksSystem _siegeWorksSystem; private SiegesSystem _siegesSystem; private SkillTrainingSystem _skillTrainingSystem; private SmithingSystem _smithingSystem; private SmithingDeveloperSystem _smithingDeveloperSystem; private StoryEventsSystem _storyEventsSystem; private SuccessionSystem _successionSystem; private TutorialSystem _tutorialSystem; private TournamentsSystem _tournamentsSystem; private ScoutingSystem _scoutingSystem; private TownVisitSystem _townVisitSystem; private UnderworldSystem _underworldSystem; private VillageRecoverySystem _villageRecoverySystem; private WanderersSystem _wanderersSystem; private WardrobeSystem _wardrobeSystem; public readonly ContentDatabase Content; public readonly CampaignRules Rules; public readonly NavGrid Nav; public readonly WorldDef World; private readonly List _events = new List(); public const long DeveloperGoldLimit = 1000000000L; public const int DeveloperTroopLimit = 1000; public const double DeveloperFoodLimit = 100000.0; public const double DeveloperRenownLimit = 100000.0; public const int DeveloperSkipLimitHours = 2016; public const string DeveloperToolsOffReason = "Developer tools were not enabled when this campaign was created."; public const int DiplomacyTruceDays = 7; public const long PeacePayment = 1000L; public const int DiplomacyAiIntervalDays = 7; public const int DiplomacyMinWarDays = 21; public const int DiplomacyMinPeaceDays = 14; public const string DiscoveryStream = "discoveries"; public const double SiteReach = 1.6; internal static readonly string[][] SiteNames = new string[8][] { new string[5] { "the Tumbled Tower", "the Roofless Hall", "the Old Watch", "the Broken Arches", "the Mossy Keep" }, new string[5] { "the Field of Broken Pikes", "the Rusted Meadow", "the Hill of Lost Helmets", "the Muddy Rout", "the Long Ditch" }, new string[5] { "the Shrine of the Spoon", "the Weeping Stone", "the Chapel of Saint Grumble", "the Standing Stones", "the Goose Altar" }, new string[5] { "the Wreck of the Soggy Biscuit", "the Wreck of the Leaky Duchess", "the Beached Barge", "the Upside-Down Galley", "the Wreck of the Lucky Herring" }, new string[5] { "the Grumbling Cave", "the Bat Hole", "the Echoing Hollow", "the Dragon's Burp", "the Damp Grotto" }, new string[5] { "an abandoned bandit camp", "a deserted war camp", "a burned-out camp", "a smugglers' hideaway", "an empty siege camp" }, new string[5] { "the Barrow of the Unknown King", "the Green Mound", "the Sleeping Chief's Barrow", "the Three Mounds", "the Barrow of the Bent Sword" }, new string[5] { "the Wizard's Leaning Tower", "the Signal Tower", "the Tower of Too Many Stairs", "the Hermit's Tower", "the Crooked Spire" } }; internal static readonly string[] SiteSights = new string[8] { "Fallen stones, ivy, and a doorway that leads down into the dark.", "Bones and rusted iron, half sunk in the turf. The crows know this place.", "A ring of old stones, a bowl of rainwater, and offerings nobody has touched in years.", "Ribs of a hull on the shingle, barnacled and gull-spattered. Something rattles inside.", "A cold breath from the cave mouth, and a sound like a giant clearing its throat.", "Firepits gone cold, a broken cart, a tent flapping on its last peg.", "A grassy mound with a stone door, half dug out by someone who gave up.", "A tower leaning at an alarming angle. A bird's nest on the top. A light, once, in the window." }; public const int MarketStockLimit = 500; public const long MarketGoldLimit = 5000L; public const double BaseBuyMarkup = 1.1; public const double BaseSellMarkdown = 0.8; public const double TradeBuyReduction = 0.08; public const double TradeSellIncrease = 0.12; public const double MarketTradeXpPerDenar = 0.1; public const double MarketTradeXpDailyLimit = 100.0; public const int MaxEncyclopediaBookmarks = 60; internal static readonly CultureInfo Inv = CultureInfo.InvariantCulture; public static readonly IReadOnlyList EncyclopediaCategories = (EncyclopediaCategory[])Enum.GetValues(typeof(EncyclopediaCategory)); public const long WorkshopRecharterFee = 250L; public const string FamilyStream = "families"; private FamilyLawSystem _familyLawSystem; public const int GarrisonTrainingXp = 5; public const int GarrisonRecruitPartyMin = 5; public const int GarrisonGuardPartyLimit = 2; public const int GarrisonGuardMin = 5; public const double GarrisonPrisonerSlowness = 2.0; public const double GarrisonFieldPay = 1.5; public static readonly int[] GarrisonTargetSteps = new int[12] { 0, 20, 40, 60, 80, 100, 150, 200, 250, 300, 400, 500 }; public static readonly int[] GarrisonGuardSizes = new int[3] { 10, 25, 50 }; private GarrisonsSystem _garrisonsSystem; public const string GranaryProject = "project.granary"; public const string WatchtowerProject = "project.watchtower"; public const string WallsProject = "project.walls"; public const int WallsProjectDays = 10; public const int SettlementProjectDays = 3; public const int SettlementProjectMaxLevel = 3; public const double GovernorTaxBonus = 0.1; public const double GovernorDailyLoyaltyBonus = 0.5; public const string HeroBondsStream = "herobonds"; public const int MemoryLimit = 6; public const int GiftCooldownDays = 14; public const int FavourCooldownDays = 20; public const int LessonCooldownDays = 10; public const int FavourRelation = 15; public const int LessonRelation = 10; public const int LessonXp = 60; public const int CompanionGiftCost = 100; public const int RequestDays = 60; public const int ApprovalWarn = -60; public const int ApprovalLeave = -80; internal static readonly Dictionary DeedRemarks = new Dictionary(StringComparer.Ordinal) { ["victory"] = new string[2][] { new string[3] { "That is how it's done!", "A good day's work, captain.", "They'll think twice before crossing us again." }, new string[2] { "We won, but at what cost?", "A victory. I hope it was worth the blood." } }, ["defeat"] = new string[2][] { new string[2] { "We live to fight another day.", "No shame in falling back from a fight like that." }, new string[2] { "We should have stood our ground.", "Running again. I did not sign up to run." } }, ["raid"] = new string[2][] { new string[2] { "Their loss is our gain.", "Peasants or soldiers, they all pay." }, new string[2] { "Burning farms is no work for honest soldiers.", "Those were ordinary folk, captain. I don't like this." } }, ["execute"] = new string[2][] { new string[2] { "One less enemy to worry about.", "A hard lesson for their kin." }, new string[2] { "Killing a prisoner. That is not who I thought you were.", "That was murder, captain, whatever the law says." } }, ["release"] = new string[2][] { new string[2] { "Mercy suits you, captain.", "An honourable thing to do." }, new string[2] { "We could have had a fat ransom for that one.", "Letting them go? They'll be back with an army." } }, ["hardship"] = new string[2][] { new string[1] { "Tighten our belts and carry on." }, new string[2] { "The men are hungry and unpaid. So am I.", "How long do you expect us to go on like this?" } } }; public const int MaximumSkillFocus = 5; public const long HeroRetrainingCost = 500L; public const int MaximumBonusFocus = 100; public const double HideoutReach = 2.0; public const int HideoutGangMin = 12; public const int HideoutGangMax = 22; public const int HideoutResettleMinDays = 28; public const int HideoutResettleMaxDays = 42; public const double LegendChiefChance = 0.55; internal static readonly string[] OutlawChiefNames = new string[12] { "Gristle Mag", "Ol' Two-Teeth", "Black Bertil", "Mad Ulla", "Grim Wendel", "Lady Knuckles", "Snaggle Tom", "Big Hilde", "One-Boot Jory", "Mother Crow", "the Pudding Duke", "Ratface Ansel" }; public const int KingdomArmyGuestLimit = 3; public const int ClanArmyMemberLimit = 5; public const int KingdomArmyCallInfluence = 20; public const int KingdomArmyDailyInfluence = 2; public const int KingdomArmyServiceDays = 7; public const int ArmyRallyInfluence = 10; public const int ArmyRallyCohesion = 20; public const long KingdomFoundingCost = 1000L; public const int KingdomFoundingRenown = 200; public const int EnclaveRestockDays = 14; public const int EnclaveStockMax = 3; public const double LegendQuestChance = 0.2; public const int LordRemountDays = 14; public const double LordHorseRetireAge = 18.0; public const string LordHorsesStream = "lordhorses"; private LordHorsesSystem _lordHorsesSystem; public const int MerchantCaravanSize = 30; public const long MerchantCaravanCapital = 2000L; public const int MerchantCaravanReplacementDays = 14; public const int MerchantCaravanBatch = 20; public const int MilitaryRecruitDailyLimit = 3; public const int MilitaryRecruitTargetLimit = 1000; public const int MilitaryPartyLimit = 2; public const int MilitaryEscortSize = 10; public const double MilitaryLaunchFood = 2.0; public const string ModSceneHostMap = "00_simulation_day"; public static Func BattleSceneAvailable; public const int AllianceDays = 84; public const int TradeAgreementDays = 84; public const int TributeDays = 28; public const int MaxAlliances = 2; public const int CallToWarAnswerDays = 5; public const int CallToWarRepeatDays = 14; public const int TributeMissedLimit = 3; public const double TradeAgreementProsperity = 0.2; public const int PactAiIntervalDays = 7; public static readonly int[] ClanTierRenown = new int[7] { 0, 50, 150, 350, 900, 2350, 6150 }; public const int AiLordBaseSize = 20; public const int AiLordSizePerTier = 15; public const int AiClanLeaderBonus = 10; public const int AiRulerBonus = 25; public const int AiSizePerFief = 5; public const int AiMaximumFiefBonus = 4; public const double AiPeaceRecruitShare = 0.6; private PerksSystem _perksSystem; public const double WeaponSkillDamageBonus = 0.15; internal const string PerkRandomStream = "perks"; public const int PersuasionRecruitBarDays = 10; public const int PersuasionFreeBarDays = 7; public const int RecruitPersuadedDays = 3; public const double PersuasionSkillXp = 6.0; private PersuasionSystem _persuasionSystem; public const double MeetingRange = 1.0; public const string IronmanMustFightReason = "Ironman: you've started this battle, so it has to be settled — fight, auto-resolve or surrender."; public const int LawFirstProposalDays = 10; public const int LawProposalIntervalDays = 7; public const double LawProposalInterest = 1.5; public const int TrialByJuryInfluence = 30; public const double DebasementGoldPerFief = 20.0; public const double ForeignRuleLoyalty = -0.75; public const double PoliticalInfluenceLimit = 1000.0; public const long NamedHeroRansomPrice = 300L; public const int MaximumHeroLevel = 50; public const int MaximumHeroSkill = 300; public const double HeroHealthPerLevel = 0.02; private QuestDelegationSystem _questDelegationSystem; public const int MaxActiveQuests = 4; public const int QuestHistoryKept = 40; public const string QuestStream = "quests"; public const int QuestFailureRelation = 3; internal static readonly QuestTemplate[] AllQuestTemplates = new QuestTemplate[15] { new RustlersQuest(), new VillageLevyQuest(), new StolenLedgerQuest(), new DebtQuest(), new DrillQuest(), new MortarQuest(), new LetterQuest(), new RaidOrderQuest(), new PrisonerOrderQuest(), new RecruitsOrderQuest(), new RoadsQuest(), new HeirloomStory(), new FeudStory(), new LegionStory(), new EscortQuest() }.Concat(LegendQuestTemplates()).ToArray(); public const double EscortSpeedFactor = 0.85; public const int RaidBaseMinutes = 360; public const int RaidMinimumCombatants = 5; public const double RebellionLoyalty = 25.0; public const double UnrestToRise = 7.0; public const double UnrestCap = 30.0; public const double RebellionChancePerDay = 0.35; public const int RebelsJoinKingdomDays = 30; public const int RebelsRecognisedDays = 60; public const string RebellionStream = "rebellions"; public const double ScoutSpeed = 7.0; public const long MercenaryRetainer = 50L; public const int MercenaryTermDays = 7; public const int VassalRenown = 100; public const int MaxQueuedProjects = 3; public const int GarrisonRecruitsPerDay = 4; public const double GovernorFoodDays = 10.0; public const double ReliefDenarsPerHardship = 4.0; public const double HardshipStrained = 25.0; public const double HardshipSuffering = 50.0; public const double HardshipDesperate = 75.0; public const double HardshipRisePerDay = 5.0; public const double HardshipEasePerDay = 3.0; public const double RiotLoyalty = 50.0; public const double RiotChancePerDay = 0.2; public const int RiotIntervalDays = 7; public const string HardshipStream = "hardship"; private SettlementBudgetsSystem _settlementBudgetsSystem; public const double TownOpeningFood = 450.0; public const double CastleOpeningFood = 200.0; public const double VillageOpeningFood = 120.0; public const double VillageFoodCapacity = 200.0; public const double VillageSubsistenceFood = 6.0; public static readonly string[] FoodGoods = (from g in TabsBannerlord.Core.Content.TradeGoods.All where g.Category == GoodCategory.Food select g.Id).OrderBy((string id) => id, StringComparer.Ordinal).ToArray(); public const double TownFieldFood = 4.0; public const double CastleFieldFood = 2.0; public const double TownFoodCapacity = 600.0; public const double GranaryFoodCapacity = 120.0; public const double CastleFoodCapacity = 300.0; public const double TownCivilianFood = 3.0; public const double TownCivilianProsperity = 900.0; public const double CastleCivilianFood = 1.0; public const double StarvationProsperityLoss = 10.0; public const double BesiegedProsperityLoss = 2.0; public const double RaidedVillageProsperityLoss = 2.0; public const double VillageTradeProsperity = 0.25; public const double ProsperityFloor = 100.0; public const double ProsperityCeiling = 10000.0; public const double HearthFloor = 100.0; public const double HearthCeiling = 2000.0; public const double TownProsperityPerMilitia = 10.0; public const double CastleProsperityPerMilitia = 9.0; public const double VillageHearthsPerMilitia = 40.0; public const int MinimumWallLevel = 1; public const int MaximumWallLevel = 3; public const double AiSiegeFoodDays = 5.0; public const double AiSiegeAdvantage = 1.35; public const double AiArmySiegeAdvantage = 1.25; public const int SiegePreparationMinutes = 360; public const int SiegeMinimumCombatants = 5; private SiegeSortiesSystem _siegeSortiesSystem; public const double AthleticsXpPerDistance = 3.0; public const double AthleticsDailyLimit = 60.0; public const double WeaponXpPerBattle = 10.0; public const double WeaponXpPerEnemyTier = 2.0; public const double WeaponXpBattleCap = 60.0; public const double AthleticsXpPerBattle = 8.0; public const double AthleticsXpPerEnemyTier = 1.0; public const double AthleticsXpBattleCap = 40.0; public const double WeaponXpPerKillTier = 12.0; public const double WeaponXpPerDamage = 0.05; public const double CreditXpBattleCap = 400.0; public const double RogueryXpSneak = 20.0; public const double RogueryXpPrisonBreak = 60.0; public const double RogueryXpMission = 40.0; public const double RogueryXpRaid = 40.0; public const double RogueryXpPerPrisonerSold = 2.0; public const double RogueryXpSaleCap = 60.0; public const double CharmXpPerRelation = 6.0; public const double CharmDailyLimit = 80.0; public const double EngineeringXpPerBuildHour = 5.0; public const double EngineeringXpPerEngine = 40.0; public const double DiplomacyXpProposal = 50.0; public const double DiplomacyXpBallot = 20.0; public const double DiplomacyXpPerBallotInfluence = 0.5; public const double DiplomacyXpWar = 60.0; public const double DiplomacyXpPeace = 80.0; public const double DiplomacyXpService = 40.0; public const double DiplomacyXpKingdom = 100.0; public const double DiplomacyXpHeroRansom = 40.0; public const double DiplomacyXpPerRansomedTroop = 2.0; public const double DiplomacyXpRansomCap = 40.0; public const int DeveloperMaterialBatch = 10; public const string StoryEventStream = "events.story"; public const int EventGapMinDays = 10; public const int EventGapMaxDays = 18; public const int EventCooldownDays = 120; public const int EventHistoryKept = 40; public const int AftermathMinutes = 360; internal static readonly List StoryEvents = new List { new StoryEventDefinition { Id = "camp.chicken", Context = "Camp", Title = "General Cluck", Lines = (Campaign c, PendingEventState p) => L("A chicken wandered into camp at dusk and will not leave. It has inspected the sentries, eaten a bootlace and settled on your saddle.", "The men have named it General Cluck. Some of them salute it."), Options = (Campaign c, PendingEventState p) => new List { Opt("adopt", "Adopt the General. Every army needs a mascot.", "", "Morale +5."), Opt("cook", "General Cluck makes a fine supper.", "", "Morale +2, and the cook is happy."), Opt("shoo", "Shoo it away.") }, Resolve = delegate(Campaign c, PendingEventState p, string o, RandomStream r) { if (o == "adopt") { c.AddMorale(5.0); return "General Cluck now rides at the head of the column. Morale +5."; } if (o == "cook") { c.AddMorale(2.0); return "Delicious. Some of the men pretend to be sad. Morale +2."; } return "The General departs with great dignity."; } }, new StoryEventDefinition { Id = "camp.halberd", Context = "Camp", Title = "The whispering halberd", Prepare = (Campaign c, PendingEventState p, RandomStream r) => c.State.PlayerParty.Troops.TotalHealthy >= 8, Lines = (Campaign c, PendingEventState p) => L("One of your soldiers swears his halberd whispers to him at night. The men near him have started sleeping with one eye open.", "He is quite calm about it. That is what worries them."), Options = (Campaign c, PendingEventState p) => new List { Opt("bless", "Pay a priest to bless it. (30 denars)", c.CantAfford(30L), "Morale +4."), Opt("listen", "Listen to it yourself.", "", "Scouting experience."), Opt("swap", "Take it off him and give him a spear.", "", "He sulks: morale −2.") }, Resolve = delegate(Campaign c, PendingEventState p, string o, RandomStream r) { if (o == "bless") { c.PayPlace(c.NearestPlace(null, c.StrategicRange(20.0)), 30L, "A priest's blessing for a halberd"); c.AddMorale(4.0); return "The priest sprinkles it twice to be safe. The whispering stops. Morale +4."; } if (o == "listen") { c.GrantSkillExperience(c.State.PlayerHero, "scouting", 25.0); return "You listen half the night. It whispers \"more cabbage\". You learn a great deal about patience."; } c.AddMorale(-2.0); return "He takes the spear. He keeps glancing back at the halberd. Morale −2."; } }, new StoryEventDefinition { Id = "camp.stew", Context = "Camp", Title = "The cook's experiment", Lines = (Campaign c, PendingEventState p) => L("The cook has made a new stew. It is purple. It is bubbling even though it is off the fire.", "\"Trust me,\" says the cook. Nobody trusts the cook."), Options = (Campaign c, PendingEventState p) => new List { Opt("eat", "Eat up, everyone!", "", "Either a feast or a disaster."), Opt("taste", "The cook eats first.", "", "Morale +2."), Opt("bin", "Throw it out.", (c.FoodSupply(c.State.PlayerParty) < 1.0) ? "You cannot spare the food." : "", "One day's ration for one man, lost.") }, Resolve = delegate(Campaign c, PendingEventState p, string o, RandomStream r) { if (o == "taste") { c.AddMorale(2.0); return "The cook eats a bowl, turns briefly green, then declares it perfect. Everyone has bread instead. Morale +2."; } if (o == "bin") { c.TakeFood(c.State.PlayerParty, 1.0); return "The stew is buried. Something in the ground complains."; } if (r.Chance(0.5)) { c.AddMorale(6.0); return "Astonishingly good. The men ask for seconds. Morale +6."; } c.AddMorale(-6.0); string text = c.WoundOne(r); return "A long night for everyone. Morale −6" + ((text.Length > 0) ? ("; a " + text + " is laid up") : "") + "."; } }, new StoryEventDefinition { Id = "camp.skeleton", Context = "Camp", Title = "A guest at the fire", Prepare = (Campaign c, PendingEventState p, RandomStream r) => c.State.Clock.HourOfDay >= 20 || c.State.Clock.HourOfDay < 5, Lines = (Campaign c, PendingEventState p) => L("A skeleton has sat down at your campfire. Nobody saw it arrive. It is warming its hands, which do not need warming.", "It nods politely at you."), Options = (Campaign c, PendingEventState p) => new List { Opt("share", "Let it share the fire.", "", "Morale +4, probably."), Opt("ask", "Ask it where it is going.", "", "Scouting experience."), Opt("chase", "Chase it off with a torch.", "", "Morale +1.") }, Resolve = delegate(Campaign c, PendingEventState p, string o, RandomStream r) { if (o == "share") { c.AddMorale(4.0); return "It tells jokes until dawn. Bone-dry, all of them. The men love it. Morale +4."; } if (o == "ask") { c.GrantSkillExperience(c.State.PlayerHero, "scouting", 20.0); return "It points north, then south, then at your boots. You learn the roads it walked, a century ago."; } c.AddMorale(1.0); return "It leaves, looking hurt. Can a skull look hurt? This one manages. Morale +1."; } }, new StoryEventDefinition { Id = "camp.pay", Context = "Camp", Title = "Grumbling in the ranks", Prepare = (Campaign c, PendingEventState p, RandomStream r) => c.State.PlayerParty.Troops.TotalHealthy >= 5 && (c.State.PlayerParty.UnpaidDays > 0 || c.State.PlayerParty.Morale < 45.0), Lines = (Campaign c, PendingEventState p) => L("Voices round the fire, low and sour. The pay is late, the food is dull and the boots leak. A delegation is coming to see you."), Options = delegate(Campaign c, PendingEventState p) { long n = 2L * (long)c.State.PlayerParty.Troops.TotalTroops; return new List { Opt("bonus", "Pay everyone a bonus. (" + c.Gold(n) + ")", c.CantAfford(n), "Morale +10."), Opt("speech", "Make a speech. (" + Pct(c.Chance(0.3, "leadership", 200.0)) + " chance)", "", "Leadership decides it: morale +6, or −4."), Opt("ignore", "Ignore them.", "", "Morale −5.") }; }, Resolve = delegate(Campaign c, PendingEventState p, string o, RandomStream r) { if (o == "bonus") { long num = 2L * (long)c.State.PlayerParty.Troops.TotalTroops; c.State.Transact(c.State.PlayerClan, -num, LedgerAccount.Wages, "A bonus for the troops"); c.AddMorale(10.0); return "Coins are counted out by firelight. The grumbling becomes singing. Morale +10."; } if (o == "speech") { c.GrantSkillExperience(c.State.PlayerHero, "leadership", 25.0); if (r.Chance(c.Chance(0.3, "leadership", 200.0))) { c.AddMorale(6.0); return "You speak of glory, loot and dry boots. They cheer. Morale +6."; } c.AddMorale(-4.0); return "Halfway through, someone throws a turnip. Morale −4."; } c.AddMorale(-5.0); return "The delegation goes away. The grumbling does not. Morale −5."; } }, new StoryEventDefinition { Id = "road.recruit", Context = "Road", Title = "A wobbly volunteer", Prepare = delegate(Campaign c, PendingEventState p, RandomStream r) { Settlement settlement = c.NearestPlace(SettlementType.Village, c.StrategicRange(12.0)); RecruitSlot recruitSlot = settlement?.Recruits?.FirstOrDefault((RecruitSlot s) => s.Available && c.UnitDef(s.UnitId) != null && c.UnitDef(s.UnitId).Tier <= 2); if (settlement == null || recruitSlot == null) { return false; } p.SettlementId = settlement.Id; p.UnitId = recruitSlot.UnitId; return true; }, Lines = (Campaign c, PendingEventState p) => L("Someone is jogging after your column, waving a pitchfork and shouting. They are from " + c.EventPlace(p)?.Name + ", they say, and they want to join you.", "They trip over the pitchfork twice while saying so."), Options = delegate(Campaign c, PendingEventState p) { UnitDef unitDef = c.UnitDef(p.UnitId); Party playerParty = c.State.PlayerParty; string text = ((playerParty.Troops.TotalTroops + playerParty.Troops.Heroes.Count >= c.PartySizeLimit(playerParty)) ? "Your party is full." : ""); return new List { Opt("take", "Welcome aboard. (" + c.Gold(unitDef?.RecruitCost ?? 0) + ")", (text.Length > 0) ? text : c.CantAfford(unitDef?.RecruitCost ?? 0), "A " + unitDef?.Name + " joins you, like any recruit from " + c.EventPlace(p)?.Name + "."), Opt("coin", "Give them coin for the road home. (20 denars)", c.CantAfford(20L), "The village hears of it."), Opt("home", "Send them home.") }; }, Resolve = delegate(Campaign c, PendingEventState p, string o, RandomStream r) { Settlement settlement = c.EventPlace(p); NotableState notableState = ((settlement == null) ? null : c.SettlementNotable(settlement.Id)); if (o == "take") { RecruitSlot recruitSlot = settlement?.Recruits?.FirstOrDefault((RecruitSlot s) => s.Available && s.UnitId == p.UnitId); UnitDef unitDef = c.UnitDef(p.UnitId); if (recruitSlot == null || unitDef == null) { return "By the time you turn round, they have gone home after all."; } c.State.Transact(c.State.PlayerClan, -unitDef.RecruitCost, LedgerAccount.Recruitment, "Recruited a " + unitDef.Name + " from " + settlement.Name + " on the road"); c.State.PlayerParty.Troops.Add(unitDef.Id, 1); recruitSlot.Available = false; return "A " + unitDef.Name + " from " + settlement.Name + " joins your party, pitchfork and all."; } if (o == "coin") { c.PayPlace(settlement, 20L, "Coin for a volunteer from " + settlement?.Name); c.AdjustNotableRelation(notableState?.Id, 3, "you were kind to one of theirs"); return "They go home richer and happier. " + settlement?.Name + " hears of your kindness."; } c.AdjustNotableRelation(notableState?.Id, 1, "you sent one of theirs home safe"); return "They trudge home. Their mother will be relieved."; } }, new StoryEventDefinition { Id = "road.toll", Context = "Road", Title = "The bucket toll", Lines = (Campaign c, PendingEventState p) => L("A man with a bucket on his head blocks the bridge. \"Toll!\" he booms, from inside the bucket. \"Twenty-five denars, or face the wrath of the Bucket Knight!\"", "Behind him, a goat chews his cloak."), Options = (Campaign c, PendingEventState p) => new List { Opt("pay", "Pay the Bucket Knight. (25 denars)", c.CantAfford(25L), "Fair's fair."), Opt("scare", "Step aside, or else. (" + Pct(c.Chance(0.4, "leadership", 250.0)) + " chance)", "", "Leadership: he flees (morale +3), or he doesn't."), Opt("round", "Go round by the ford.", "", "Wet boots: morale −2.") }, Resolve = delegate(Campaign c, PendingEventState p, string o, RandomStream r) { if (o == "pay") { c.PayPlace(c.NearestPlace(SettlementType.Village, c.StrategicRange(20.0)), 25L, "The Bucket Knight's toll"); return "He bows so low the bucket falls off. It was the miller all along."; } if (o == "scare") { if (r.Chance(c.Chance(0.4, "leadership", 250.0))) { c.AddMorale(3.0); return "The Bucket Knight flees, clanging. The goat stays and joins the baggage train. Morale +3."; } c.AddMorale(-2.0); return "He will not budge. You end up going round by the ford anyway, with the Bucket Knight jeering. Morale −2."; } c.AddMorale(-2.0); return "Wet boots for everyone. Morale −2."; } }, new StoryEventDefinition { Id = "road.cart", Context = "Road", Title = "A wheel short", Prepare = delegate(Campaign c, PendingEventState p, RandomStream r) { Settlement settlement = c.NearestPlace(SettlementType.Town, c.StrategicRange(25.0)); if (settlement == null) { return false; } p.SettlementId = settlement.Id; return true; }, Lines = (Campaign c, PendingEventState p) => L("A merchant's cart sits in the ditch, one wheel off and the merchant sitting on it, weeping into his hat. He is bound for " + c.EventPlace(p)?.Name + "."), Options = (Campaign c, PendingEventState p) => new List { Opt("help", "Put your men to work and get him moving.", "", "Trade experience and a friend in " + c.EventPlace(p)?.Name + "."), Opt("pass", "Ride on.") }, Resolve = delegate(Campaign c, PendingEventState p, string o, RandomStream r) { if (o == "help") { c.GrantSkillExperience(c.State.PlayerHero, "trade", 30.0); c.AddMorale(2.0); c.AdjustNotableRelation(c.SettlementNotable(p.SettlementId)?.Id, 3, "you helped one of their merchants"); return "With much heaving the wheel is back on. The merchant tells you all his prices on the way. Morale +2."; } return "His wails follow you for a mile."; } }, new StoryEventDefinition { Id = "road.statue", Context = "Road", Title = "The pointing statue", Prepare = delegate(Campaign c, PendingEventState p, RandomStream r) { Party party = c.State.PlayerParty; DiscoverySite discoverySite = (from s in c.State.Quests?.Sites?.Where((DiscoverySite s) => !s.Found && string.IsNullOrEmpty(s.QuestId) && Vec2.Distance(s.Position, party.Position) <= c.StrategicRange(30.0)) orderby Vec2.Distance(s.Position, party.Position) select s).ThenBy((DiscoverySite s) => s.Id, StringComparer.Ordinal).FirstOrDefault(); if (discoverySite == null) { return false; } p.SiteId = discoverySite.Id; return true; }, Lines = (Campaign c, PendingEventState p) => L("By the roadside stands an old statue of a man in a toga, pointing dramatically into the distance. Someone has hung a sign on his finger: \"THIS WAY\".", "This way to what, it does not say."), Options = (Campaign c, PendingEventState p) => new List { Opt("follow", "Look where he points.", "", "Something might be out there."), Opt("pass", "Ride on.") }, Resolve = delegate(Campaign c, PendingEventState p, string o, RandomStream r) { DiscoverySite discoverySite = c.Site(p.SiteId); if (o != "follow" || discoverySite == null) { return "The statue keeps pointing, to nobody in particular."; } discoverySite.Found = true; discoverySite.FoundMinute = c.State.Clock.Minute; c.GrantSkillExperience(c.State.PlayerHero, "scouting", 15.0); return "Far off, where the finger points: " + discoverySite.Name + ". It is marked on your map."; } }, new StoryEventDefinition { Id = "road.wolves", Context = "Road", Title = "Wolves", Lines = (Campaign c, PendingEventState p) => L("Wolves have been trailing the column since noon: grey shapes at the edge of the trees, keeping pace. The horses are nervous."), Options = (Campaign c, PendingEventState p) => new List { Opt("hunt", "Hunt them down.", "", "Scouting experience and morale +3; someone may be bitten."), Opt("torches", "Light torches and keep together.", "", "Morale +1."), Opt("press", "Press on.") }, Resolve = delegate(Campaign c, PendingEventState p, string o, RandomStream r) { if (o == "hunt") { c.GrantSkillExperience(c.State.PlayerHero, "scouting", 25.0); c.AddMorale(3.0); string text = (r.Chance(0.3) ? c.WoundOne(r) : ""); return "The pack scatters. Morale +3." + ((text.Length > 0) ? (" A " + text + " was bitten and is laid up.") : ""); } if (o == "torches") { c.AddMorale(1.0); return "The wolves lose interest by nightfall. Morale +1."; } return "The wolves follow for a while, then lose interest."; } }, new StoryEventDefinition { Id = "town.brawl", Context = "Settlement", Title = "A brawl at the tavern", Prepare = delegate(Campaign c, PendingEventState p, RandomStream r) { Settlement settlement = c.State.Settlements.Get(c.State.PlayerParty.CurrentSettlementId); if (settlement == null || settlement.Type != SettlementType.Town || c.State.PlayerParty.Troops.TotalHealthy < 10) { return false; } p.SettlementId = settlement.Id; return true; }, Lines = (Campaign c, PendingEventState p) => L("Your soldiers and the town's dockhands have started a brawl at the tavern over who has the best helmet. Tables are already airborne.", "The landlord is looking at you."), Options = delegate(Campaign c, PendingEventState p) { long n = Math.Max(20L, 3L * (long)c.State.PlayerParty.Troops.TotalTroops); return new List { Opt("pay", "Stop it and pay the damages. (" + c.Gold(n) + ")", c.CantAfford(n), "The town thinks better of you."), Opt("join", "Roll up your sleeves and join in.", "", "Morale +8; you will feel it in the morning."), Opt("leave", "Slip out quietly.", "", "Morale −3.") }; }, Resolve = delegate(Campaign c, PendingEventState p, string o, RandomStream r) { Settlement settlement = c.EventPlace(p); if (o == "pay") { long amount = Math.Max(20L, 3L * (long)c.State.PlayerParty.Troops.TotalTroops); c.PayPlace(settlement, amount, "Damages at the tavern of " + settlement?.Name); c.AdjustNotableRelation(c.SettlementNotable(settlement?.Id ?? "")?.Id, 2, "you paid for the damage"); return "Order is restored. The landlord counts the coins twice and smiles."; } if (o == "join") { Hero playerHero = c.State.PlayerHero; playerHero.Health = Math.Max(0.3, playerHero.Health - 0.1); c.AddMorale(8.0); c.GrantSkillExperience(playerHero, "leadership", 20.0); return "You win the argument about helmets. Your men will tell this story for years. Morale +8; you took a few knocks."; } c.AddMorale(-3.0); return "You leave them to it. They notice. Morale −3."; } }, new StoryEventDefinition { Id = "town.bard", Context = "Settlement", Title = "A song about you", Prepare = delegate(Campaign c, PendingEventState p, RandomStream r) { Settlement settlement = c.State.Settlements.Get(c.State.PlayerParty.CurrentSettlementId); if (settlement == null || settlement.Type != SettlementType.Town) { return false; } p.SettlementId = settlement.Id; return true; }, Lines = (Campaign c, PendingEventState p) => L("A bard in the square is singing a song about you. It is mostly accurate. You did not, however, wrestle a bear. You would remember that."), Options = (Campaign c, PendingEventState p) => new List { Opt("pay", "Pay him to keep singing. (30 denars)", c.CantAfford(30L), "Renown +2."), Opt("correct", "Correct the lyrics.", "", "Diplomacy experience."), Opt("ignore", "Let him sing.") }, Resolve = delegate(Campaign c, PendingEventState p, string o, RandomStream r) { if (o == "pay") { c.PayPlace(c.EventPlace(p), 30L, "A bard's song"); c.State.PlayerClan.Renown += 2.0; return "He adds a second bear. The crowd loves it. Renown +2."; } if (o == "correct") { c.GrantSkillExperience(c.State.PlayerHero, "diplomacy", 15.0); return "You explain about the bear. He changes it to a wolf. A very big wolf."; } return "The song ends. Nobody throws anything. A success, by bardic standards."; } }, new StoryEventDefinition { Id = "village.cabbages", Context = "Settlement", Title = "The cabbage toss", Prepare = delegate(Campaign c, PendingEventState p, RandomStream r) { Settlement settlement = c.State.Settlements.Get(c.State.PlayerParty.CurrentSettlementId); if (settlement == null || settlement.Type != SettlementType.Village) { return false; } p.SettlementId = settlement.Id; return true; }, Lines = (Campaign c, PendingEventState p) => L("It is the day of " + c.EventPlace(p)?.Name + "'s famous cabbage toss. Whoever throws a cabbage furthest is Cabbage Lord for a year.", "The current Cabbage Lord is an enormous woman named Hilde. She has held the title for nine years."), Options = (Campaign c, PendingEventState p) => new List { Opt("enter", "Enter the contest.", "", "Win, and the village will never forget it."), Opt("sponsor", "Put up a prize. (40 denars)", c.CantAfford(40L), "The village is grateful."), Opt("watch", "Watch from a safe distance.", "", "Morale +2.") }, Resolve = delegate(Campaign c, PendingEventState p, string o, RandomStream r) { NotableState notableState = c.SettlementNotable(p.SettlementId); if (o == "enter") { if (r.Chance(0.35)) { c.State.PlayerClan.Renown += 1.0; c.AdjustNotableRelation(notableState?.Id, 4, "you won the cabbage toss"); return "Your cabbage sails over the duck pond. Hilde weeps. You are Cabbage Lord. Renown +1."; } c.AddMorale(2.0); return "Your cabbage lands in the duck pond. Hilde pats you on the head. Your men laugh for a week. Morale +2."; } if (o == "sponsor") { c.PayPlace(c.EventPlace(p), 40L, "A prize for the cabbage toss"); c.AdjustNotableRelation(notableState?.Id, 5, "you put up a prize"); return "Hilde wins again, and your prize. She thanks you with a cabbage."; } c.AddMorale(2.0); return "A cabbage hits a soldier anyway. Everyone else is delighted. Morale +2."; } }, new StoryEventDefinition { Id = "town.pickpocket", Context = "Settlement", Title = "Light fingers", Prepare = delegate(Campaign c, PendingEventState p, RandomStream r) { Settlement settlement = c.State.Settlements.Get(c.State.PlayerParty.CurrentSettlementId); if (settlement == null || settlement.Type != SettlementType.Town || c.State.PlayerClan.Gold < 20) { return false; } p.SettlementId = settlement.Id; p.Number = (r.Chance(c.Chance(0.25, "scouting", 200.0)) ? 1 : 0); return true; }, Lines = (Campaign c, PendingEventState p) => (p.Number != 1) ? L("In the crowd at the market, someone bumps into you. A moment later your purse feels lighter. Much lighter.") : L("In the crowd at the market a hand slides into your purse. You catch the wrist. It belongs to a boy of about twelve, who grins at you hopefully."), Options = (Campaign c, PendingEventState p) => (p.Number != 1) ? new List { Opt("shout", "\"Stop, thief!\"", "", "Probably useless."), Opt("shrug", "Shrug. Easy come, easy go.") } : new List { Opt("guard", "Hand him to the watch.", "", "Security in the town."), Opt("free", "Let him go with a warning, and a coin.", c.CantAfford(5L), "Mercy.") }, Resolve = delegate(Campaign c, PendingEventState p, string o, RandomStream r) { Settlement settlement = c.EventPlace(p); if (p.Number == 1) { if (o == "guard") { if (settlement != null) { settlement.Security = Clamp100(settlement.Security + 1.0); } c.AdjustNotableRelation(c.SettlementNotable(settlement?.Id ?? "")?.Id, 2, "you caught a thief"); return "The watch marches him off. The market applauds."; } c.PayPlace(settlement, 5L, "A coin for a young thief"); return "He bites the coin, bows, and vanishes. You are fairly sure he will be back."; } long num = Math.Min(c.State.PlayerClan.Gold, Math.Max(20L, Math.Min(80L, c.State.PlayerClan.Gold / 50))); c.State.Transact(c.State.PlayerClan, -num, LedgerAccount.Events, "Pickpocketed in " + settlement?.Name); if (settlement?.Market != null) { settlement.Market.Gold += num; } return (!(o == "shout")) ? (c.Gold(num) + " lost to the streets of " + settlement?.Name + ".") : ("Everybody turns to look at you. The thief, too, presumably, from a safe distance. " + c.Gold(num) + " lost."); } }, new StoryEventDefinition { Id = "town.festival", Context = "Settlement", Title = "The Feast of Saint Spoon", Prepare = delegate(Campaign c, PendingEventState p, RandomStream r) { Settlement settlement = c.State.Settlements.Get(c.State.PlayerParty.CurrentSettlementId); if (settlement == null || settlement.Type != SettlementType.Town) { return false; } p.SettlementId = settlement.Id; return true; }, Lines = (Campaign c, PendingEventState p) => L(c.EventPlace(p)?.Name + " is celebrating the Feast of Saint Spoon, who once fed a besieged city with a single, very large spoon.", "The festival committee is passing round a hat."), Options = (Campaign c, PendingEventState p) => new List { Opt("fund", "Fund the feast. (100 denars)", c.CantAfford(100L), "The town grows fond of you; renown +1."), Opt("parade", "March your men in the parade.", "", "Morale +5."), Opt("pass", "Keep your hands in your pockets.") }, Resolve = delegate(Campaign c, PendingEventState p, string o, RandomStream r) { Settlement settlement = c.EventPlace(p); if (o == "fund") { c.PayPlace(settlement, 100L, "The Feast of Saint Spoon in " + settlement?.Name); if (settlement != null) { settlement.Loyalty = Clamp100(settlement.Loyalty + 2.0); } c.AdjustNotableRelation(c.SettlementNotable(settlement?.Id ?? "")?.Id, 6, "you funded the feast"); c.State.PlayerClan.Renown += 1.0; return "A spoon-shaped cake is named after you. Renown +1."; } if (o == "parade") { c.AddMorale(5.0); return "Your men march behind the giant spoon, beaming. Morale +5."; } return "The hat passes you by. The committee notes your name."; } }, new StoryEventDefinition { Id = "after.hat", Context = "Battle", Title = "The fancy hat", Prepare = (Campaign c, PendingEventState p, RandomStream r) => c.State.PlayerParty.Troops.TotalHealthy >= 2, Lines = (Campaign c, PendingEventState p) => L("Two of your soldiers are arguing over a fallen enemy's hat. It has three feathers, a small bell and, somehow, a candle on top.", "They have drawn knives. Over the hat."), Options = (Campaign c, PendingEventState p) => new List { Opt("finder", "Whoever found it keeps it.", "", "Morale +2."), Opt("bravest", "It goes to whoever fought bravest today.", "", "Leadership experience, morale +4."), Opt("mine", "I'll wear it.", "", "Renown +1, morale −1.") }, Resolve = delegate(Campaign c, PendingEventState p, string o, RandomStream r) { if (o == "finder") { c.AddMorale(2.0); return "The finder wears it proudly. The bell rings with every step. Morale +2."; } if (o == "bravest") { c.GrantSkillExperience(c.State.PlayerHero, "leadership", 20.0); c.AddMorale(4.0); return "The bravest turns out to be the cook. Nobody argues. Morale +4."; } c.State.PlayerClan.Renown += 1.0; c.AddMorale(-1.0); return "You look magnificent. The candle keeps going out. Renown +1, morale −1."; } }, new StoryEventDefinition { Id = "after.banner", Context = "Battle", Title = "The enemy's banner", Lines = (Campaign c, PendingEventState p) => L("Your men have taken the enemy's banner. It is muddy, torn and much bigger than it looked from across the field."), Options = delegate(Campaign c, PendingEventState p) { Clan clan = c.FriendlyLordClan(); return new List { Opt("hang", "Hang it in camp.", "", "Morale +5."), Opt("send", (clan == null) ? "Send it to a friendly lord." : ("Send it to " + clan.Name + " as a gift."), (clan == null) ? "No friendly lord to send it to." : "", "Relation +3."), Opt("burn", "Burn it.", "", "Morale +2.") }; }, Resolve = delegate(Campaign c, PendingEventState p, string o, RandomStream r) { if (o == "hang") { c.AddMorale(5.0); return "It flaps over the camp, upside down, to general hilarity. Morale +5."; } if (o == "send") { Clan clan = c.FriendlyLordClan(); if (clan != null) { c.AdjustClanRelation(c.State.PlayerClanId, clan.Id, 3); } if (clan != null) { return clan.Name + " are delighted with the trophy. Relation +3."; } return "Nobody wants a muddy banner."; } c.AddMorale(2.0); return "It burns with a satisfying whoosh. Morale +2."; } }, new StoryEventDefinition { Id = "after.mercy", Context = "Battle", Title = "A plea for mercy", Lines = (Campaign c, PendingEventState p) => L("Among the fallen, a wounded enemy soldier raises a hand. \"Mercy,\" he croaks. \"I have a goat at home. She needs me.\""), Options = (Campaign c, PendingEventState p) => new List { Opt("spare", "Let him go home to his goat.", "", "Renown +1; some of your men grumble (morale −1)."), Opt("bind", "Bind his wounds first.", "", "Medicine experience."), Opt("leave", "Leave him.", "", "Morale +1.") }, Resolve = delegate(Campaign c, PendingEventState p, string o, RandomStream r) { if (o == "spare") { c.State.PlayerClan.Renown += 1.0; c.AddMorale(-1.0); return "He limps away, waving. Word of your mercy spreads. Renown +1, morale −1."; } if (o == "bind") { c.GrantSkillExperience(c.State.PlayerHero, "medicine", 30.0); return "You bind his wounds. He tells you the goat's name, Bertha, several times."; } c.AddMorale(1.0); return "War is war. Morale +1."; } } }; public const int PlayerFighterId = 1; internal const string TournamentStream = "tournaments"; public const int TownVisitNobles = 6; public const int TownVisitCompanions = 3; internal static readonly (string id, int weight)[] TownCivilians = new(string, int)[8] { ("medieval.peasant", 4), ("farmer.farmer", 4), ("renaissance.painter", 2), ("farmer.potionseller", 2), ("medieval.bard", 1), ("wildwest.miner", 1), ("medieval.healer", 1), ("dynasty.monk", 1) }; internal static readonly HashSet OddGuards = new HashSet(StringComparer.Ordinal) { "wildwest.cactus" }; public const int AlleysPerTown = 3; internal static readonly string[] AlleyNames = new string[12] { "Tanners' Row", "Rat's Run", "Cutpurse Lane", "Smoke Alley", "Gallows Yard", "Fishgut Lane", "Crooked Steps", "Candle Alley", "Mudlark Way", "Bonecutter's Close", "Saltpig Lane", "Widow's Turn" }; internal static readonly string[] GangNames = new string[12] { "the Black Hands", "the Red Rats", "the Gutter Kings", "the Lantern Boys", "the Grey Cloaks", "the Copper Fists", "the Night Crows", "the Mud Dogs", "the Quiet Ones", "the Broken Teeth", "the Tallow Gang", "the Sewer Saints" }; internal static readonly string[] GangLeaderNames = new string[12] { "One-Ear Hob", "Mother Grisel", "Ratcatcher Wil", "Tall Ida", "Grim Osk", "Smiling Bren", "Knuckles Marga", "Old Fennick", "Black Jory", "Sly Tamsin", "Fat Ulric", "Needle Sabine" }; internal static readonly string[] ThugUnits = new string[6] { "viking.brawler", "tribal.clubber", "medieval.peasant", "farmer.farmer", "renaissance.fencer", "farmer.halfling" }; internal static readonly string[] GangLeaderUnits = new string[5] { "pirate.captain", "renaissance.fencer", "viking.headbutter", "medieval.squire", "tribal.protector" }; public const int VillageRecoveryPerDay = 20; public const int VillageAidRepair = 25; public const int VillageAidTimber = 3; public const int VillageAidTools = 1; public const int VillageAidTrust = 3; public const int VillageRaidTrustCooldownDays = 7; public const double VillagerReplacementChance = 1.0 / 7.0; public const string WandererStream = "wanderers"; public IEnumerable KnownAbilities => AbilitiesSystem.KnownAbilities; public List AiArmies => AiArmiesSystem.AiArmies; public AiArmy PlayerAiArmy => AiArmiesSystem.PlayerAiArmy; internal BarterSystem BarterSystem => _barterSystem ?? (_barterSystem = new BarterSystem(this)); internal ClanCaravansSystem ClanCaravansSystem => _clanCaravansSystem ?? (_clanCaravansSystem = new ClanCaravansSystem(this)); public bool PlayerSexChoiceNeeded => CourtshipSystem.PlayerSexChoiceNeeded; public bool InDisguise => CrimeSystem.InDisguise; internal AbilitiesSystem AbilitiesSystem => _abilitiesSystem ?? (_abilitiesSystem = new AbilitiesSystem(this)); internal AiSystem AiSystem => _aiSystem ?? (_aiSystem = new AiSystem(this)); internal AiArmiesSystem AiArmiesSystem => _aiArmiesSystem ?? (_aiArmiesSystem = new AiArmiesSystem(this)); internal AllegianceSystem AllegianceSystem => _allegianceSystem ?? (_allegianceSystem = new AllegianceSystem(this)); internal ArmyMergeSystem ArmyMergeSystem => _armyMergeSystem ?? (_armyMergeSystem = new ArmyMergeSystem(this)); internal CaravansSystem CaravansSystem => _caravansSystem ?? (_caravansSystem = new CaravansSystem(this)); internal CargoConsequencesSystem CargoConsequencesSystem => _cargoConsequencesSystem ?? (_cargoConsequencesSystem = new CargoConsequencesSystem(this)); internal ClanAllegianceSystem ClanAllegianceSystem => _clanAllegianceSystem ?? (_clanAllegianceSystem = new ClanAllegianceSystem(this)); internal ClanArmySystem ClanArmySystem => _clanArmySystem ?? (_clanArmySystem = new ClanArmySystem(this)); internal ClanArmyDynamicsSystem ClanArmyDynamicsSystem => _clanArmyDynamicsSystem ?? (_clanArmyDynamicsSystem = new ClanArmyDynamicsSystem(this)); internal CompanionRecoverySystem CompanionRecoverySystem => _companionRecoverySystem ?? (_companionRecoverySystem = new CompanionRecoverySystem(this)); internal CompanionsSystem CompanionsSystem => _companionsSystem ?? (_companionsSystem = new CompanionsSystem(this)); internal ContractsSystem ContractsSystem => _contractsSystem ?? (_contractsSystem = new ContractsSystem(this)); internal ConversationsSystem ConversationsSystem => _conversationsSystem ?? (_conversationsSystem = new ConversationsSystem(this)); internal CouncilSystem CouncilSystem => _councilSystem ?? (_councilSystem = new CouncilSystem(this)); internal CouncilDiplomacySystem CouncilDiplomacySystem => _councilDiplomacySystem ?? (_councilDiplomacySystem = new CouncilDiplomacySystem(this)); internal CourtshipSystem CourtshipSystem => _courtshipSystem ?? (_courtshipSystem = new CourtshipSystem(this)); internal CreationLooksSystem CreationLooksSystem => _creationLooksSystem ?? (_creationLooksSystem = new CreationLooksSystem(this)); internal CrimeSystem CrimeSystem => _crimeSystem ?? (_crimeSystem = new CrimeSystem(this)); internal DailySystem DailySystem => _dailySystem ?? (_dailySystem = new DailySystem(this)); internal DeveloperSystem DeveloperSystem => _developerSystem ?? (_developerSystem = new DeveloperSystem(this)); internal DeveloperDiplomacySystem DeveloperDiplomacySystem => _developerDiplomacySystem ?? (_developerDiplomacySystem = new DeveloperDiplomacySystem(this)); internal DiplomacySystem DiplomacySystem => _diplomacySystem ?? (_diplomacySystem = new DiplomacySystem(this)); internal DiplomacyConsequencesSystem DiplomacyConsequencesSystem => _diplomacyConsequencesSystem ?? (_diplomacyConsequencesSystem = new DiplomacyConsequencesSystem(this)); internal DiscoveriesSystem DiscoveriesSystem => _discoveriesSystem ?? (_discoveriesSystem = new DiscoveriesSystem(this)); internal EconomySystem EconomySystem => _economySystem ?? (_economySystem = new EconomySystem(this)); internal ElectionsSystem ElectionsSystem => _electionsSystem ?? (_electionsSystem = new ElectionsSystem(this)); internal EncountersSystem EncountersSystem => _encountersSystem ?? (_encountersSystem = new EncountersSystem(this)); internal EncyclopediaSystem EncyclopediaSystem => _encyclopediaSystem ?? (_encyclopediaSystem = new EncyclopediaSystem(this)); internal EnterprisesSystem EnterprisesSystem => _enterprisesSystem ?? (_enterprisesSystem = new EnterprisesSystem(this)); internal EquipmentSystem EquipmentSystem => _equipmentSystem ?? (_equipmentSystem = new EquipmentSystem(this)); internal EquipmentBattlesSystem EquipmentBattlesSystem => _equipmentBattlesSystem ?? (_equipmentBattlesSystem = new EquipmentBattlesSystem(this)); internal FamiliesSystem FamiliesSystem => _familiesSystem ?? (_familiesSystem = new FamiliesSystem(this)); internal GovernanceSystem GovernanceSystem => _governanceSystem ?? (_governanceSystem = new GovernanceSystem(this)); internal GovernorsSystem GovernorsSystem => _governorsSystem ?? (_governorsSystem = new GovernorsSystem(this)); internal HeroBondsSystem HeroBondsSystem => _heroBondsSystem ?? (_heroBondsSystem = new HeroBondsSystem(this)); internal HeroDevelopmentSystem HeroDevelopmentSystem => _heroDevelopmentSystem ?? (_heroDevelopmentSystem = new HeroDevelopmentSystem(this)); internal HideoutsSystem HideoutsSystem => _hideoutsSystem ?? (_hideoutsSystem = new HideoutsSystem(this)); internal HorseLifeSystem HorseLifeSystem => _horseLifeSystem ?? (_horseLifeSystem = new HorseLifeSystem(this)); internal HorseMarketsSystem HorseMarketsSystem => _horseMarketsSystem ?? (_horseMarketsSystem = new HorseMarketsSystem(this)); internal HorsesSystem HorsesSystem => _horsesSystem ?? (_horsesSystem = new HorsesSystem(this)); internal KeepSystem KeepSystem => _keepSystem ?? (_keepSystem = new KeepSystem(this)); internal KingdomArmySystem KingdomArmySystem => _kingdomArmySystem ?? (_kingdomArmySystem = new KingdomArmySystem(this)); internal KingdomArmyAiSystem KingdomArmyAiSystem => _kingdomArmyAiSystem ?? (_kingdomArmyAiSystem = new KingdomArmyAiSystem(this)); internal KingdomsSystem KingdomsSystem => _kingdomsSystem ?? (_kingdomsSystem = new KingdomsSystem(this)); internal LegendsSystem LegendsSystem => _legendsSystem ?? (_legendsSystem = new LegendsSystem(this)); internal MerchantCaravansSystem MerchantCaravansSystem => _merchantCaravansSystem ?? (_merchantCaravansSystem = new MerchantCaravansSystem(this)); internal MilitaryAiSystem MilitaryAiSystem => _militaryAiSystem ?? (_militaryAiSystem = new MilitaryAiSystem(this)); internal MilitaryBudgetsSystem MilitaryBudgetsSystem => _militaryBudgetsSystem ?? (_militaryBudgetsSystem = new MilitaryBudgetsSystem(this)); internal MilitaryPartiesSystem MilitaryPartiesSystem => _militaryPartiesSystem ?? (_militaryPartiesSystem = new MilitaryPartiesSystem(this)); internal MilitaryRecoverySystem MilitaryRecoverySystem => _militaryRecoverySystem ?? (_militaryRecoverySystem = new MilitaryRecoverySystem(this)); internal MilitaryTransfersSystem MilitaryTransfersSystem => _militaryTransfersSystem ?? (_militaryTransfersSystem = new MilitaryTransfersSystem(this)); internal MovementSystem MovementSystem => _movementSystem ?? (_movementSystem = new MovementSystem(this)); internal NamedCustodySystem NamedCustodySystem => _namedCustodySystem ?? (_namedCustodySystem = new NamedCustodySystem(this)); internal NotablesSystem NotablesSystem => _notablesSystem ?? (_notablesSystem = new NotablesSystem(this)); internal PactsSystem PactsSystem => _pactsSystem ?? (_pactsSystem = new PactsSystem(this)); internal PartyFoodSystem PartyFoodSystem => _partyFoodSystem ?? (_partyFoodSystem = new PartyFoodSystem(this)); internal PartySizesSystem PartySizesSystem => _partySizesSystem ?? (_partySizesSystem = new PartySizesSystem(this)); internal PlayerSystem PlayerSystem => _playerSystem ?? (_playerSystem = new PlayerSystem(this)); internal PoliciesSystem PoliciesSystem => _policiesSystem ?? (_policiesSystem = new PoliciesSystem(this)); internal PoliticsSystem PoliticsSystem => _politicsSystem ?? (_politicsSystem = new PoliticsSystem(this)); internal PrisonerRansomsSystem PrisonerRansomsSystem => _prisonerRansomsSystem ?? (_prisonerRansomsSystem = new PrisonerRansomsSystem(this)); internal PrisonersSystem PrisonersSystem => _prisonersSystem ?? (_prisonersSystem = new PrisonersSystem(this)); internal ProgressionSystem ProgressionSystem => _progressionSystem ?? (_progressionSystem = new ProgressionSystem(this)); internal QuestChainsSystem QuestChainsSystem => _questChainsSystem ?? (_questChainsSystem = new QuestChainsSystem(this)); internal QuestsSystem QuestsSystem => _questsSystem ?? (_questsSystem = new QuestsSystem(this)); internal QuestsLordSystem QuestsLordSystem => _questsLordSystem ?? (_questsLordSystem = new QuestsLordSystem(this)); internal RaidAiSystem RaidAiSystem => _raidAiSystem ?? (_raidAiSystem = new RaidAiSystem(this)); internal RaidsSystem RaidsSystem => _raidsSystem ?? (_raidsSystem = new RaidsSystem(this)); internal RebellionsSystem RebellionsSystem => _rebellionsSystem ?? (_rebellionsSystem = new RebellionsSystem(this)); internal RescuedTroopsSystem RescuedTroopsSystem => _rescuedTroopsSystem ?? (_rescuedTroopsSystem = new RescuedTroopsSystem(this)); internal ServiceSystem ServiceSystem => _serviceSystem ?? (_serviceSystem = new ServiceSystem(this)); internal SettlementFoodSystem SettlementFoodSystem => _settlementFoodSystem ?? (_settlementFoodSystem = new SettlementFoodSystem(this)); internal SettlementStatsSystem SettlementStatsSystem => _settlementStatsSystem ?? (_settlementStatsSystem = new SettlementStatsSystem(this)); internal SiegeAiSystem SiegeAiSystem => _siegeAiSystem ?? (_siegeAiSystem = new SiegeAiSystem(this)); internal SiegeBattlesSystem SiegeBattlesSystem => _siegeBattlesSystem ?? (_siegeBattlesSystem = new SiegeBattlesSystem(this)); internal SiegeCaptureSystem SiegeCaptureSystem => _siegeCaptureSystem ?? (_siegeCaptureSystem = new SiegeCaptureSystem(this)); internal SiegeWorksSystem SiegeWorksSystem => _siegeWorksSystem ?? (_siegeWorksSystem = new SiegeWorksSystem(this)); internal SiegesSystem SiegesSystem => _siegesSystem ?? (_siegesSystem = new SiegesSystem(this)); internal SkillTrainingSystem SkillTrainingSystem => _skillTrainingSystem ?? (_skillTrainingSystem = new SkillTrainingSystem(this)); internal SmithingSystem SmithingSystem => _smithingSystem ?? (_smithingSystem = new SmithingSystem(this)); internal SmithingDeveloperSystem SmithingDeveloperSystem => _smithingDeveloperSystem ?? (_smithingDeveloperSystem = new SmithingDeveloperSystem(this)); internal StoryEventsSystem StoryEventsSystem => _storyEventsSystem ?? (_storyEventsSystem = new StoryEventsSystem(this)); internal SuccessionSystem SuccessionSystem => _successionSystem ?? (_successionSystem = new SuccessionSystem(this)); internal TutorialSystem TutorialSystem => _tutorialSystem ?? (_tutorialSystem = new TutorialSystem(this)); internal TournamentsSystem TournamentsSystem => _tournamentsSystem ?? (_tournamentsSystem = new TournamentsSystem(this)); internal ScoutingSystem ScoutingSystem => _scoutingSystem ?? (_scoutingSystem = new ScoutingSystem(this)); internal TownVisitSystem TownVisitSystem => _townVisitSystem ?? (_townVisitSystem = new TownVisitSystem(this)); internal UnderworldSystem UnderworldSystem => _underworldSystem ?? (_underworldSystem = new UnderworldSystem(this)); internal VillageRecoverySystem VillageRecoverySystem => _villageRecoverySystem ?? (_villageRecoverySystem = new VillageRecoverySystem(this)); internal WanderersSystem WanderersSystem => _wanderersSystem ?? (_wanderersSystem = new WanderersSystem(this)); internal WardrobeSystem WardrobeSystem => _wardrobeSystem ?? (_wardrobeSystem = new WardrobeSystem(this)); public CampaignState State { get; private set; } public FieldSite FieldSiteOverride { get; set; } public double BacklogMinutes => State.Clock.PendingMinutes; public bool IsBattleFrozen { get { if (State.Player.Activity != PlayerActivity.InBattle) { return State.Player.Activity == PlayerActivity.InEncounter; } return true; } } public bool IsTimeFlowing { get { if (State.Clock.Speed == TimeSpeed.Paused || IsBattleFrozen || AwaitingHeir || LineEnded || EventPending || HideoutChiefPending.Length > 0) { return false; } PlayerActivity activity = State.Player.Activity; if (activity != PlayerActivity.Travelling && activity != PlayerActivity.Waiting && activity != PlayerActivity.Captive && activity != PlayerActivity.Raiding) { return activity == PlayerActivity.Besieging; } return true; } } public string DifficultyPreset => Difficulty.PresetOf(Settings); public string SiteHereId => DiscoveriesSystem.SiteHereId; public Encounter PendingPlayerEncounter => EncountersSystem.PendingPlayerEncounter; public IReadOnlyList EncyclopediaBookmarks => EncyclopediaSystem.EncyclopediaBookmarks; public CampaignSettings Settings => FamiliesSystem.Settings; internal FamilyLawSystem FamilyLawSystem => _familyLawSystem ?? (_familyLawSystem = new FamilyLawSystem(this)); internal GarrisonsSystem GarrisonsSystem => _garrisonsSystem ?? (_garrisonsSystem = new GarrisonsSystem(this)); public string HideoutChiefPending => HideoutsSystem.HideoutChiefPending; internal LordHorsesSystem LordHorsesSystem => _lordHorsesSystem ?? (_lordHorsesSystem = new LordHorsesSystem(this)); internal PerksSystem PerksSystem => _perksSystem ?? (_perksSystem = new PerksSystem(this)); internal PersuasionSystem PersuasionSystem => _persuasionSystem ?? (_persuasionSystem = new PersuasionSystem(this)); public bool WaitingInSettlement { get { if (State.Player.Activity == PlayerActivity.Waiting) { return PlayerSystem.CurrentSettlement() != null; } return false; } } public bool IsIronman => PlayerSystem.IsIronman; internal QuestDelegationSystem QuestDelegationSystem => _questDelegationSystem ?? (_questDelegationSystem = new QuestDelegationSystem(this)); public IEnumerable ActiveQuests => QuestsSystem.ActiveQuests; public static IEnumerable QuestTemplateIds => QuestsSystem.QuestTemplateIds; public QuestState TrackedQuest => QuestsSystem.TrackedQuest; internal string PlayerFirstName => QuestsSystem.PlayerFirstName; public bool RebellionsEnabled => RebellionsSystem.RebellionsEnabled; public IReadOnlyList ScoutMissions => State.Scouting.Missions; internal SettlementBudgetsSystem SettlementBudgetsSystem => _settlementBudgetsSystem ?? (_settlementBudgetsSystem = new SettlementBudgetsSystem(this)); public static long[] GarrisonWageLimitSteps => SettlementBudgetsSystem.WageLimitSteps; public static long[] GovernorBudgetSteps => SettlementBudgetsSystem.GovernorBudgetSteps; public SiegeState PlayerSiege => SiegesSystem.PlayerSiege; internal SiegeSortiesSystem SiegeSortiesSystem => _siegeSortiesSystem ?? (_siegeSortiesSystem = new SiegeSortiesSystem(this)); public bool RandomEventsEnabled => StoryEventsSystem.RandomEventsEnabled; public bool EventPending => StoryEventsSystem.EventPending; public static IEnumerable StoryEventIds => StoryEventsSystem.StoryEventIds; public bool AwaitingHeir => SuccessionSystem.AwaitingHeir; public bool LineEnded => SuccessionSystem.LineEnded; public Hero DeceasedPlayer => SuccessionSystem.DeceasedPlayer; public IEnumerable ActiveTournaments => TournamentsSystem.ActiveTournaments; public IEnumerable HeardTournaments => TournamentsSystem.HeardTournaments; public TournamentState PlayerTournament => TournamentsSystem.PlayerTournament; public static IReadOnlyList TutorialChapters => TutorialSystem.Chapters; public bool TutorialActive => State.Tutorial?.Active ?? false; public IEnumerable WanderingHeroes => WanderersSystem.WanderingHeroes; public int WandererTarget => WanderersSystem.WandererTarget; public IEnumerable ClothingPieces => WardrobeSystem.ClothingPieces; public event Action HourPassed; public event Action DayPassed; public event Action EventRaised; public void EnsureAbilityFields() { AbilitiesSystem.EnsureAbilityFields(); } public AbilityDef Ability(string id) { return AbilitiesSystem.Ability(id); } public string AbilityName(string id) { return AbilitiesSystem.AbilityName(id); } public int ImportAbilities(IEnumerable abilities) { return AbilitiesSystem.ImportAbilities(abilities); } public bool HeroKnowsAbility(Hero hero, string abilityId) { return AbilitiesSystem.HeroKnowsAbility(hero, abilityId); } public bool AbilityActive(Hero hero, string abilityId) { return AbilitiesSystem.AbilityActive(hero, abilityId); } public int ActiveAbilityCount(Hero hero) { return AbilitiesSystem.ActiveAbilityCount(hero); } public void LearnAbility(Hero hero, string abilityId) { AbilitiesSystem.LearnAbility(hero, abilityId); } public string AbilityHeroReason(string heroId) { return AbilitiesSystem.AbilityHeroReason(heroId); } public string AbilityToggleReason(string heroId, string abilityId, bool on) { return AbilitiesSystem.AbilityToggleReason(heroId, abilityId, on); } public CommandResult SetAbilityActive(string heroId, string abilityId, bool on) { return AbilitiesSystem.SetAbilityActive(heroId, abilityId, on); } internal void RunAi() { AiSystem.RunAi(); } internal void AddFleeOrFight(Party p, double myStrength, List<(Party party, double strength, double dist)> hostiles, List options, bool canEngage) { AiSystem.AddFleeOrFight(p, myStrength, hostiles, options, canEngage); } internal void PatrolNear(Party p, Vec2 anchor) { AiSystem.PatrolNear(p, anchor); } internal void OnAiEnteredSettlement(Party p, Settlement s) { AiSystem.OnAiEnteredSettlement(p, s); } public void EnsureKingdomArmyFields() { AiArmiesSystem.EnsureKingdomArmyFields(); } public AiArmy AiArmyOf(Party p) { return AiArmiesSystem.AiArmyOf(p); } internal bool MarchesWithAiArmy(Party p, Party leader) { return AiArmiesSystem.MarchesWithAiArmy(p, leader); } internal bool PlayerMarchesWith(Party p) { return AiArmiesSystem.PlayerMarchesWith(p); } public double AiArmyStrength(AiArmy army) { return AiArmiesSystem.AiArmyStrength(army); } internal void DailyKingdomArmies() { AiArmiesSystem.DailyKingdomArmies(); } internal int FormAiArmies(bool force) { return AiArmiesSystem.FormAiArmies(force); } internal bool AiArmyOptions(Party p, double strength, List options) { return AiArmiesSystem.AiArmyOptions(p, strength, options); } public string JoinAiArmyReason(string armyId) { return AiArmiesSystem.JoinAiArmyReason(armyId); } public CommandResult JoinAiArmy(string armyId) { return AiArmiesSystem.JoinAiArmy(armyId); } public CommandResult LeaveAiArmy() { return AiArmiesSystem.LeaveAiArmy(); } internal void MaintainPlayerArmyFollow() { AiArmiesSystem.MaintainPlayerArmyFollow(); } internal string MarchingWithArmyReason() { return AiArmiesSystem.MarchingWithArmyReason(); } public double ServiceRetainerForecast() { return AllegianceSystem.ServiceRetainerForecast(); } public void ChangeSettlementOwner(Settlement settlement, string ownerClanId) { AllegianceSystem.ChangeSettlementOwner(settlement, ownerClanId); } public void OnPlayerAllegianceChanged() { AllegianceSystem.OnPlayerAllegianceChanged(); } public bool IsMergedIntoArmy(Party p) { return ArmyMergeSystem.IsMergedIntoArmy(p); } public Party ArmyHead(Party p) { return ArmyMergeSystem.ArmyHead(p); } public IEnumerable MergedMembers(Party leader) { return ArmyMergeSystem.MergedMembers(leader); } public double MapStrength(Party p) { return ArmyMergeSystem.MapStrength(p); } public int MapCombatants(Party p) { return ArmyMergeSystem.MapCombatants(p); } public bool HiddenOnMap(Party p) { return ArmyMergeSystem.HiddenOnMap(p); } public int MapPartyCount(Party p) { return ArmyMergeSystem.MapPartyCount(p); } public bool ShownAsArmy(Party p) { return ArmyMergeSystem.ShownAsArmy(p); } internal void UpdateArmyMerges() { ArmyMergeSystem.UpdateArmyMerges(); } public string BarterReason(BarterKind kind, string heroId, string partyId = "") { return BarterSystem.Reason(kind, heroId, partyId); } public BarterSession StartBarter(BarterKind kind, string heroId, string partyId = "") { return BarterSystem.Start(kind, heroId, partyId); } public List BarterStock(BarterSession s, bool playerSide) { return BarterSystem.Stock(s, playerSide); } public CommandResult SetBarterCount(BarterSession s, BarterItemKind kind, string id, bool fromPlayer, int count) { return BarterSystem.SetCount(s, kind, id, fromPlayer, count); } public BarterEvaluation EvaluateBarter(BarterSession s) { return BarterSystem.Evaluate(s); } public long BarterItemValue(BarterSession s, BarterItem item) { return BarterSystem.ItemValue(s, item, item.Count); } public CommandResult BalanceBarter(BarterSession s) { return BarterSystem.Balance(s); } public CommandResult OfferBarter(BarterSession s) { return BarterSystem.Offer(s); } public long HeroWorth(Hero hero) { return BarterSystem.HeroWorth(hero); } public Conversation StartRansomTalk() { return BarterSystem.StartRansomTalk(); } public void EnsureCaravanFields() { CaravansSystem.EnsureCaravanFields(); } public int CaravanTradeSkill(Party p) { return CaravansSystem.CaravanTradeSkill(p); } public string LaunchCaravanReason(string companionId, string unitId) { return CaravansSystem.LaunchCaravanReason(companionId, unitId); } public CommandResult LaunchCaravan(string companionId, string unitId) { return CaravansSystem.LaunchCaravan(companionId, unitId); } public string CaravanActionReason(string id, string action, long amount = 0L) { return CaravansSystem.CaravanActionReason(id, action, amount); } public CommandResult RecallCaravan(string id) { return CaravansSystem.RecallCaravan(id); } public CommandResult FundCaravan(string id, long amount) { return CaravansSystem.FundCaravan(id, amount); } public CommandResult WithdrawCaravan(string id, long amount) { return CaravansSystem.WithdrawCaravan(id, amount); } public CommandResult DisbandCaravan(string id) { return CaravansSystem.DisbandCaravan(id); } public (int guards, int prisoners) CaravanDisbandLosses(string id) { return CaravansSystem.CaravanDisbandLosses(id); } internal void CaravanOptions(Party p, double strength, List<(Party party, double strength, double dist)> hostiles, List options) { CaravansSystem.CaravanOptions(p, strength, hostiles, options); } public void CaravanTradeArrival(Party p, Settlement s) { CaravansSystem.CaravanTradeArrival(p, s); } internal void ResupplyCaravan(Party p, Settlement s) { CaravansSystem.ResupplyCaravan(p, s); } public void DailyCaravans() { CaravansSystem.DailyCaravans(); } public void ReconcileCaravans() { CaravansSystem.ReconcileCaravans(); } public string SeizeCargo(Party source, Party captor) { return CargoConsequencesSystem.SeizeCargo(source, captor); } public void EnsureClanAllegianceFields() { ClanAllegianceSystem.EnsureClanAllegianceFields(); } public long ClanAllegianceCooldown(string clanId) { return ClanAllegianceSystem.ClanAllegianceCooldown(clanId); } public ClanRecruitmentQuote QuoteClanRecruitment(string targetClanId) { return ClanAllegianceSystem.QuoteClanRecruitment(targetClanId); } public CommandResult RecruitClan(string targetClanId, ClanRecruitmentQuote expectedQuote = null) { return ClanAllegianceSystem.RecruitClan(targetClanId, expectedQuote); } internal void ClearClanIndependentDiplomacy(string clanId) { ClanAllegianceSystem.ClearClanIndependentDiplomacy(clanId); } internal void RecordClanAllegiance(Clan clan, string former, string sponsor, ClanAllegianceChange kind, long payment = 0L) { ClanAllegianceSystem.RecordClanAllegiance(clan, former, sponsor, kind, payment); } public string ClanExpulsionStaleReason(string targetClanId, string kingdomId) { return ClanAllegianceSystem.ClanExpulsionStaleReason(targetClanId, kingdomId); } public string CouncilExpulsionReason(string targetClanId, string kingdomId) { return ClanAllegianceSystem.CouncilExpulsionReason(targetClanId, kingdomId); } public CommandResult ApplyCouncilExpulsion(KingdomDecision decision) { return ClanAllegianceSystem.ApplyCouncilExpulsion(decision); } public string ClanDefectionReason(string clanId) { return ClanAllegianceSystem.ClanDefectionReason(clanId); } public void DailyClanAllegiance() { ClanAllegianceSystem.DailyClanAllegiance(); } public void EnsureClanArmyFields() { ClanArmySystem.EnsureClanArmyFields(); } public bool ClanArmyContains(string partyId) { return ClanArmySystem.ClanArmyContains(partyId); } public IEnumerable ClanArmyParties() { return ClanArmySystem.ClanArmyParties(); } internal static bool ClanArmyLiveParty(Party party, string clanId) { return ClanArmySystem.ClanArmyLiveParty(party, clanId); } internal bool ClanArmyPartyReserved(string partyId) { return ClanArmySystem.ClanArmyPartyReserved(partyId); } internal bool ClanArmyBattleReserved() { return ClanArmySystem.ClanArmyBattleReserved(); } internal bool ClanArmyPlayerAvailable() { return ClanArmySystem.ClanArmyPlayerAvailable(); } public string ClanArmyActionReason(string militaryId, string action) { return ClanArmySystem.ClanArmyActionReason(militaryId, action); } internal void WakeClanArmyParty(Party party) { ClanArmySystem.WakeClanArmyParty(party); } public CommandResult FormClanArmy(string militaryId) { return ClanArmySystem.FormClanArmy(militaryId); } public CommandResult AddClanArmyParty(string militaryId) { return ClanArmySystem.AddClanArmyParty(militaryId); } internal void RestoreClanArmyMember(ClanArmyMember member) { ClanArmySystem.RestoreClanArmyMember(member); } public CommandResult ReleaseClanArmyParty(string militaryId) { return ClanArmySystem.ReleaseClanArmyParty(militaryId); } public CommandResult DisbandClanArmy() { return ClanArmySystem.DisbandClanArmy(); } public void EndClanArmy(string reason, bool notify = true) { ClanArmySystem.EndClanArmy(reason, notify); } public void ReconcileClanArmy() { ClanArmySystem.ReconcileClanArmy(); } public bool ArmyPartyGathered(Party party) { return ClanArmyDynamicsSystem.ArmyPartyGathered(party); } public IEnumerable AssembledArmyParties() { return ClanArmyDynamicsSystem.AssembledArmyParties(); } internal void ShareArmyFood(List assembled, double targetDays, double keepDays) { ClanArmyDynamicsSystem.ShareArmyFood(assembled, targetDays, keepDays); } public void DailyClanArmy() { ClanArmyDynamicsSystem.DailyClanArmy(); } internal CaravanState CaravanFor(Party p) { return CaravansSystem.CaravanFor(p); } public void EnsureClanCaravanFields() { ClanCaravansSystem.EnsureClanCaravanFields(); } public bool IsClanCaravan(Party p) { return ClanCaravansSystem.IsClanCaravan(p); } public IEnumerable ClanCaravans(string clanId) { return ClanCaravansSystem.ClanCaravans(clanId); } public int ClanCaravanLimit(Clan clan) { return ClanCaravansSystem.ClanCaravanLimit(clan); } public Settlement ClanCaravanHome(Clan clan) { return ClanCaravansSystem.ClanCaravanHome(clan); } public string ClanCaravanReason(Clan clan) { return ClanCaravansSystem.ClanCaravanReason(clan); } internal Party FormClanCaravan(Clan clan) { return ClanCaravansSystem.FormClanCaravan(clan); } internal bool ClanCaravanShouldGoHome(Party p) { return ClanCaravansSystem.ClanCaravanShouldGoHome(p); } internal void SettleClanCaravan(Party p, CaravanState c, Settlement home) { ClanCaravansSystem.SettleClanCaravan(p, c, home); } internal bool ReconcileClanCaravan(CaravanState c) { return ClanCaravansSystem.ReconcileClanCaravan(c); } internal void DailyClanCaravans() { ClanCaravansSystem.DailyClanCaravans(); } public void RecoverSeparatedCompanions() { CompanionRecoverySystem.RecoverSeparatedCompanions(); } internal void ShelterCompanion(Hero hero, Vec2 from, string reason) { CompanionRecoverySystem.ShelterCompanion(hero, from, reason); } public void EnsureCompanions() { CompanionsSystem.EnsureCompanions(); } public int CompanionCount() { return CompanionsSystem.CompanionCount(); } public int CompanionLimit() { return CompanionsSystem.CompanionLimit(); } public IEnumerable AvailableCompanions() { return CompanionsSystem.AvailableCompanions(); } public string CompanionRecruitmentReason(string heroId) { return CompanionsSystem.CompanionRecruitmentReason(heroId); } public CommandResult RecruitCompanion(string heroId) { return CompanionsSystem.RecruitCompanion(heroId); } public string CompanionDismissalReason(string heroId) { return CompanionsSystem.CompanionDismissalReason(heroId); } public CommandResult DismissCompanion(string heroId) { return CompanionsSystem.DismissCompanion(heroId); } public string CompanionRejoinReason(string heroId) { return CompanionsSystem.CompanionRejoinReason(heroId); } public CommandResult RejoinCompanion(string heroId) { return CompanionsSystem.RejoinCompanion(heroId); } public string PartyRoleAssignmentReason(PartyRole role, string heroId) { return CompanionsSystem.PartyRoleAssignmentReason(role, heroId); } public CommandResult AssignPartyRole(PartyRole role, string heroId) { return CompanionsSystem.AssignPartyRole(role, heroId); } public Hero RoleHolder(Party party, PartyRole role) { return CompanionsSystem.RoleHolder(party, role); } public int RoleSkill(Party party, PartyRole role) { return CompanionsSystem.RoleSkill(party, role); } public void ClearHeroRoleAssignments(string heroId) { CompanionsSystem.ClearHeroRoleAssignments(heroId); } internal string CompanionCommandReason() { return CompanionsSystem.CompanionCommandReason(); } internal Settlement CompanionMeetingSettlement(bool townOnly) { return CompanionsSystem.CompanionMeetingSettlement(townOnly); } internal bool IsOwnedCompanion(Hero hero) { return CompanionsSystem.IsOwnedCompanion(hero); } internal static bool IsPresentPartyHero(Party party, Hero hero) { return CompanionsSystem.IsPresentPartyHero(party, hero); } internal void JoinCompanionToPlayerParty(Hero hero) { CompanionsSystem.JoinCompanionToPlayerParty(hero); } public void EnsureContractFields() { ContractsSystem.EnsureContractFields(); } public void RefreshContractOffers() { ContractsSystem.RefreshContractOffers(); } public IEnumerable CurrentContractOffers() { return ContractsSystem.CurrentContractOffers(); } internal bool ContractFriendlySettlement(Settlement settlement) { return ContractsSystem.ContractFriendlySettlement(settlement); } public static bool IsCargoContract(ContractState contract) { return ContractsSystem.IsCargoContract(contract); } public string ContractAcceptReason(string id) { return ContractsSystem.ContractAcceptReason(id); } public CommandResult AcceptContract(string id) { return ContractsSystem.AcceptContract(id); } public string ContractCompleteReason(string id) { return ContractsSystem.ContractCompleteReason(id); } public CommandResult CompleteContract(string id) { return ContractsSystem.CompleteContract(id); } public string ContractAbandonReason(string id) { return ContractsSystem.ContractAbandonReason(id); } public CommandResult AbandonContract(string id) { return ContractsSystem.AbandonContract(id); } public void DailyContracts() { ContractsSystem.DailyContracts(); } public void RecordContractBattle(Encounter encounter, BattleResult result, BattleReport report) { ContractsSystem.RecordContractBattle(encounter, result, report); } public static Personality PersonalityOf(Hero h) { return ConversationsSystem.PersonalityOf(h); } public static string DescribePersonality(Hero h) { return ConversationsSystem.DescribePersonality(h); } public string TalkReason(string heroId) { return ConversationsSystem.TalkReason(heroId); } public Conversation StartConversation(string heroId) { return ConversationsSystem.StartConversation(heroId); } public Conversation StartTownConversation(string role, int person) { return ConversationsSystem.StartTownConversation(role, person); } public void ChooseConversationOption(Conversation c, string optionId) { ConversationsSystem.ChooseConversationOption(c, optionId); } public string EncounterTalkReason() { return ConversationsSystem.EncounterTalkReason(); } public Conversation StartEncounterTalk() { return ConversationsSystem.StartEncounterTalk(); } public void CloseBarter(Conversation c) { ConversationsSystem.CloseBarter(c); } internal static string First(Hero h) { return ConversationsSystem.First(h); } internal int HeroRelation(Hero h) { return ConversationsSystem.HeroRelation(h); } internal bool HeroIsEnemy(Hero h) { return ConversationsSystem.HeroIsEnemy(h); } internal static T Pick(Random r, params T[] options) { return ConversationsSystem.Pick(r, options); } internal static int StableSeed(string key) { return ConversationsSystem.StableSeed(key); } internal Random TalkRandom(Conversation c, string topic) { return ConversationsSystem.TalkRandom(c, topic); } internal static string Cap(string s) { return ConversationsSystem.Cap(s); } internal string HeroWhereaboutsForTalk(Hero other, out string mapTarget) { return ConversationsSystem.HeroWhereaboutsForTalk(other, out mapTarget); } internal static string SkillWord(string id) { return ConversationsSystem.SkillWord(id); } public static string TownRoleName(string role, Settlement s) { return ConversationsSystem.TownRoleName(role, s); } internal static bool CouncilIsLive(KingdomDecision decision) { return CouncilSystem.CouncilIsLive(decision); } internal bool CouncilMember(string kingdomId, string clanId) { return CouncilSystem.CouncilMember(kingdomId, clanId); } internal string NewCouncilProposalReason() { return CouncilSystem.NewCouncilProposalReason(); } public string ProposePolicyReason(RealmPolicy policy) { return CouncilSystem.ProposePolicyReason(policy); } public CommandResult ProposeRealmPolicy(RealmPolicy policy) { return CouncilSystem.ProposeRealmPolicy(policy); } public string ProposeFiefGrantReason(string settlementId, string recipientClanId) { return CouncilSystem.ProposeFiefGrantReason(settlementId, recipientClanId); } public CommandResult ProposeFiefGrant(string settlementId, string recipientClanId) { return CouncilSystem.ProposeFiefGrant(settlementId, recipientClanId); } public string ProposeClanExpulsionReason(string targetClanId) { return CouncilSystem.ProposeClanExpulsionReason(targetClanId); } public CommandResult ProposeClanExpulsion(string targetClanId) { return CouncilSystem.ProposeClanExpulsion(targetClanId); } internal KingdomDecision NewCouncilDecision(string kingdomId, string proposer, KingdomDecisionKind kind) { return CouncilSystem.NewCouncilDecision(kingdomId, proposer, kind); } internal void OpenCouncilDecision(KingdomDecision decision) { CouncilSystem.OpenCouncilDecision(decision); } public string CouncilVoteReason(string decisionId, bool support, int influence) { return CouncilSystem.CouncilVoteReason(decisionId, support, influence); } public CommandResult VoteCouncil(string decisionId, bool support, int influence) { return CouncilSystem.VoteCouncil(decisionId, support, influence); } public int CouncilSupportWeight(KingdomDecision decision, bool support) { return CouncilSystem.CouncilSupportWeight(decision, support); } public bool CouncilPreference(KingdomDecision decision, Clan clan) { return CouncilSystem.CouncilPreference(decision, clan); } public string CouncilPreferenceReason(KingdomDecision decision, Clan clan) { return CouncilSystem.CouncilPreferenceReason(decision, clan); } public void QueueCapturedFiefCouncil(SiegeState siege, Clan captor, Settlement settlement) { CouncilSystem.QueueCapturedFiefCouncil(siege, captor, settlement); } internal string CouncilStaleReason(KingdomDecision decision) { return CouncilSystem.CouncilStaleReason(decision); } public void ReconcileCouncil() { CouncilSystem.ReconcileCouncil(); } public void DailyCouncil() { CouncilSystem.DailyCouncil(); } internal static bool CouncilDiplomacyDecision(KingdomDecision decision) { return CouncilDiplomacySystem.CouncilDiplomacyDecision(decision); } internal bool CouncilDiplomacyReserved(KingdomDecision decision) { return CouncilDiplomacySystem.CouncilDiplomacyReserved(decision); } internal bool CouncilDiplomacyPending(string a, string b) { return CouncilDiplomacySystem.CouncilDiplomacyPending(a, b); } public string ProposeKingdomWarReason(string targetKingdomId) { return CouncilDiplomacySystem.ProposeKingdomWarReason(targetKingdomId); } public string ProposeKingdomPeaceReason(string targetKingdomId) { return CouncilDiplomacySystem.ProposeKingdomPeaceReason(targetKingdomId); } public CommandResult ProposeKingdomWar(string targetKingdomId) { return CouncilDiplomacySystem.ProposeKingdomWar(targetKingdomId); } public CommandResult ProposeKingdomPeace(string targetKingdomId) { return CouncilDiplomacySystem.ProposeKingdomPeace(targetKingdomId); } internal string CouncilDiplomacyStaleReason(KingdomDecision decision) { return CouncilDiplomacySystem.CouncilDiplomacyStaleReason(decision); } public CommandResult ApplyCouncilDiplomacy(KingdomDecision decision) { return CouncilDiplomacySystem.ApplyCouncilDiplomacy(decision); } internal bool CouncilDiplomacyPreference(KingdomDecision decision, Clan clan, out string reason) { return CouncilDiplomacySystem.CouncilDiplomacyPreference(decision, clan, out reason); } public Settlement MeetingPlace() { return CourtshipSystem.MeetingPlace(); } public List NoblesHere() { return CourtshipSystem.NoblesHere(); } public CourtshipState CourtshipOf(string heroId) { return CourtshipSystem.CourtshipOf(heroId); } public List PlayerCourtships() { return CourtshipSystem.PlayerCourtships(); } public long MarriageGiftFor(Hero noble) { return CourtshipSystem.MarriageGiftFor(noble); } public string CourtReason(string heroId) { return CourtshipSystem.CourtReason(heroId); } public CommandResult Court(string heroId) { return CourtshipSystem.Court(heroId); } public string ProposeReason(string heroId) { return CourtshipSystem.ProposeReason(heroId); } public CommandResult Propose(string heroId) { return CourtshipSystem.Propose(heroId); } public List MarriageableFamily() { return CourtshipSystem.MarriageableFamily(); } public string ArrangeReason(string memberId, string nobleId) { return CourtshipSystem.ArrangeReason(memberId, nobleId); } public CommandResult ArrangeMarriage(string memberId, string nobleId) { return CourtshipSystem.ArrangeMarriage(memberId, nobleId); } public CommandResult SetPlayerSex(HeroSex sex) { return CourtshipSystem.SetPlayerSex(sex); } public CommandResult SetFamilyRule(string rule, bool on) { return CourtshipSystem.SetFamilyRule(rule, on); } public SortedSet CreationClothing(string cultureId) { return CreationLooksSystem.CreationClothing(cultureId); } public CommandResult ApplyCreationLooks(HeroEquipmentState looks) { return CreationLooksSystem.ApplyCreationLooks(looks); } public void EnsureCrimeFields() { CrimeSystem.EnsureCrimeFields(); } public double CrimeRating(string faction) { return CrimeSystem.CrimeRating(faction); } public static CrimeTier CrimeTierOf(double rating) { return CrimeSystem.CrimeTierOf(rating); } public static string CrimeTierName(CrimeTier tier) { return CrimeSystem.CrimeTierName(tier); } public static string CrimeTierEffect(CrimeTier tier) { return CrimeSystem.CrimeTierEffect(tier); } public string CrimeFactionOf(Settlement s) { return CrimeSystem.CrimeFactionOf(s); } public string CrimeFactionName(string faction) { return CrimeSystem.CrimeFactionName(faction); } public CrimeTier CrimeTierWith(Settlement s) { return CrimeSystem.CrimeTierWith(s); } public List> CrimeRecords() { return CrimeSystem.CrimeRecords(); } internal void AddCrime(string faction, double amount, string what, params string[] links) { CrimeSystem.AddCrime(faction, amount, what, links); } internal void DailyCrime() { CrimeSystem.DailyCrime(); } public long CrimeFine(string faction, bool inDisguise) { return CrimeSystem.CrimeFine(faction, inDisguise); } public string PayCrimeFineReason(Settlement s) { return CrimeSystem.PayCrimeFineReason(s); } public CommandResult PayCrimeFine(Settlement s) { return CrimeSystem.PayCrimeFine(s); } internal bool StopAtGate(Party p, Settlement s) { return CrimeSystem.StopAtGate(p, s); } internal void StopPlayerAtGate(Party p, Settlement s) { CrimeSystem.StopPlayerAtGate(p, s); } public Settlement CrimeGate() { return CrimeSystem.CrimeGate(); } public CommandResult LeaveGate() { return CrimeSystem.LeaveGate(); } public string DisguiseBlockReason() { return CrimeSystem.DisguiseBlockReason(); } public double SneakChance(Settlement s) { return CrimeSystem.SneakChance(s); } public string SneakInReason() { return CrimeSystem.SneakInReason(); } public CommandResult SneakIn() { return CrimeSystem.SneakIn(); } public string ExecuteReason(string heroId, bool inDungeon) { return CrimeSystem.ExecuteReason(heroId, inDungeon); } public CommandResult ExecutePrisoner(string heroId, bool inDungeon) { return CrimeSystem.ExecutePrisoner(heroId, inDungeon); } internal double StrategicRange(double authoredRange) { if (!(World.Id == "world.continent")) { return authoredRange; } return authoredRange * 3.0; } public Campaign(ContentDatabase content, CampaignState state) { Content = content ?? throw new ArgumentNullException("content"); State = state ?? throw new ArgumentNullException("state"); CustomFactions.Register(content, state.CustomContent, replace: true); Rules = content.Rules; World = ProceduralWorld.Resolve(content, state); Nav = new NavGrid(World); EnsureCompanions(); EnsureHeroProgressionFields(); HeroDevelopmentSystem.EnsureHeroAttributes(); EnsureEconomyFields(); EnsureEquipmentFields(); EnsureWardrobeFields(); EnsureEnterpriseFields(); EnsureContractFields(); EnsureCaravanFields(); EnsureNotableFields(); EnsureSmithingFields(); EnsureHorseFields(); EnsureGovernanceFields(); EnsureBudgetFields(); EnsureServiceFields(); EnsureDiplomacyFields(); EnsureDeveloperChoice(); EnsureSiegeFields(); EnsurePoliticsFields(); EnsureClanAllegianceFields(); EnsureVillageRecoveryFields(); EnsureMilitaryPartyFields(); EnsureClanArmyFields(); EnsureOutlawPartySizes(); EnsureLordUnitVariety(); EnsureMerchantCaravans(); EnsureClanCaravanFields(); EnsureAbilityFields(); EnsureTournamentFields(); EnsureWandererFields(); EnsureFamilyFields(); EnsureCrimeFields(); Difficulty.Normalise(Settings); EnsureRebellionFields(); EnsureKingdomArmyFields(); EnsureQuestFields(); EnsureStoryEventFields(); EnsureHideoutFields(); EnsureLegendFields(); EnsureScoutingFields(); EnsureLordHorsesOnLoad(); TutorialSystem.EnsureTutorialFields(); GarrisonsSystem.EnsureGarrisonFields(); ReconcileMilitaryParties(); } public void Raise(CampaignEventKind kind, string text, bool forcePause, params string[] links) { CampaignEvent campaignEvent = new CampaignEvent { Kind = kind, Text = text, ForcesPause = forcePause }; campaignEvent.Links.AddRange(links.Where((string l) => !string.IsNullOrEmpty(l))); _events.Add(campaignEvent); if (forcePause) { ForcePause(text); } this.EventRaised?.Invoke(this, campaignEvent); } public List DrainEvents() { List result = new List(_events); _events.Clear(); return result; } public void SetSpeed(TimeSpeed speed) { if (speed == TimeSpeed.Rapid && State.Player.Activity != PlayerActivity.Captive) { speed = TimeSpeed.Fast; } State.Clock.Speed = speed; if (speed != TimeSpeed.Paused) { State.Clock.LastRunningSpeed = speed; State.Clock.PauseReason = ""; } } public void ForcePause(string reason) { State.Clock.Speed = TimeSpeed.Paused; State.Clock.PauseReason = reason ?? ""; } internal void ResumeIfPaused() { if (State.Clock.Speed == TimeSpeed.Paused) { SetSpeed((State.Clock.LastRunningSpeed == TimeSpeed.Paused) ? TimeSpeed.Normal : State.Clock.LastRunningSpeed); } } public int Tick(double realSeconds, bool modalUiOpen = false) { if (State.Clock.Speed == TimeSpeed.Rapid && State.Player.Activity != PlayerActivity.Captive) { SetSpeed(TimeSpeed.Fast); } if (modalUiOpen || !IsTimeFlowing || realSeconds <= 0.0) { return 0; } double num = ((State.Clock.Speed == TimeSpeed.Rapid) ? Rules.CaptiveHoursPerSecond : ((State.Clock.Speed == TimeSpeed.Fast) ? Rules.FastHoursPerSecond : Rules.NormalHoursPerSecond)); State.Clock.PendingMinutes += realSeconds * num * 60.0; double num2 = Math.Max(Rules.MaxBacklogHours, (State.Clock.Speed == TimeSpeed.Rapid) ? Rules.CaptiveHoursPerSecond : 0.0) * 60.0; if (State.Clock.PendingMinutes > num2) { State.Clock.PendingMinutes = num2; } int num3 = 0; while (State.Clock.PendingMinutes >= (double)Rules.StepMinutes && num3 < Rules.MaxStepsPerFrame && IsTimeFlowing) { State.Clock.PendingMinutes -= Rules.StepMinutes; Step(); num3++; } if (!IsTimeFlowing) { State.Clock.PendingMinutes = 0.0; } return num3; } public void RunSteps(int steps) { for (int i = 0; i < steps; i++) { Step(); } } public void Step() { ClockState clock = State.Clock; if (!AwaitingHeir && !LineEnded) { TournamentsState tournaments = State.Tournaments; if (tournaments == null || !tournaments.Started) { EnsureTournaments(); } clock.Minute += Rules.StepMinutes; double hours = (double)Rules.StepMinutes / 60.0; if (clock.Minute >= clock.NextDayMinute) { DailyService(); DailyDiplomacy(); DailyClanAllegiance(); DailyPoliticalInfluence(); } DailyCouncil(); ReconcileMilitaryParties(); if (clock.Minute >= clock.NextDayMinute) { DailyClanArmy(); } UpdatePlayerTimeStates(); UpdateSieges(advanceProgress: false); List moves = MoveParties(hours); UpdateArmyMerges(); DetectEncounters(moves); UpdateSieges(); UpdateRaids(); UpdateVisibility(); RunAi(); MaintainPlayerArmyFollow(); UpdateArmyMerges(); while (clock.Minute >= clock.NextHourMinute) { HourlyTick(); clock.NextHourMinute += 60L; } while (clock.Minute >= clock.NextDayMinute) { DailyTick(); clock.NextDayMinute += 1440L; } State.Touch(); } } private void HourlyTick() { ExpireSightings(); HourlySmithing(); HourlyHorses(); HourlyWanderers(); HourlyQuests(); HourlyHideouts(); HourlyStoryEvents(); HourlyScouting(); this.HourPassed?.Invoke(this); } private void DailyTick() { DailyClanArmy(); DailyLogistics(); DailyHorses(); DailyLordHorses(); DailyPrisonerCare(); DailyGovernors(); DailyGovernance(); DailyVillageRecovery(); DailySettlements(); DailySettlementStats(); DailyRebellions(); DailySieges(); DailyMarkets(); DailyCaravans(); DailyMilitaryParties(); DailyGarrisonParties(); DailyKingdomArmies(); DailyEnterprises(); DailyContracts(); DailyQuests(); DailySmithingOrders(); DailyCaptivity(); DailyBanditSpawns(); DailyHideouts(); DailyLegendSites(); DailyTournaments(); DailyWanderers(); DailyFamilies(); DailyCrime(); DailyHeroBonds(); this.DayPassed?.Invoke(this); } public UnitDef UnitDef(string id) { return Content.Units.Get(id); } public string FormatTime(long minute) { long num = minute / 1440 + 1; int num2 = (int)(minute % 1440 / 60); int num3 = (int)(minute % 60); return $"Day {num}, {num2:00}:{num3:00}"; } public double UnitPower(string unitId) { UnitDef unitDef = UnitDef(unitId); if (unitDef == null) { return 1.0; } return (unitDef.Attack * 0.6 + unitDef.Defense * 0.4) * unitDef.Health; } public double HeroPower(Hero h) { if (h == null || !h.CanFight) { return 0.0; } EquipmentCombatStats equipmentCombatStats = HeroEquipmentStats(h); return (equipmentCombatStats.Attack * 0.6 + equipmentCombatStats.Defense * 0.4) * equipmentCombatStats.Health * 1.5 * h.Health; } public double PartyStrength(Party p) { double num = 0.0; foreach (TroopStack stack in p.Troops.Stacks) { num += (double)stack.Healthy * UnitPower(stack.UnitId); } foreach (string hero in p.Troops.Heroes) { num += HeroPower(State.Heroes.Get(hero)); } return num; } public int PartyCombatants(Party p) { return p.Troops.TotalHealthy + p.Troops.Heroes.Count((string h) => State.Heroes.Get(h)?.CanFight ?? false); } public int PartySizeLimit(Party p) { double num = LawPartySizeFactor(p); int num2 = (int)Math.Round(PartyPerk(p, PerkEffect.PartySize)); if (IsAiLordParty(p)) { return (int)Math.Round((double)AiLordPartySizeLimit(p) * num) + num2; } Clan clan = State.Clans.Get(p.ClanId); Hero hero = State.Heroes.Get(p.LeaderHeroId); int num3 = Rules.PartyBaseSize + (int)((clan?.Renown ?? 0.0) / 100.0 * (double)Rules.PartySizePerRenown100); if (hero != null) { num3 += hero.Skill("leadership") / 5; } return (int)Math.Round((double)num3 * num) + num2; } public int PrisonerLimit(Party p) { Hero hero = State.Heroes.Get(p.LeaderHeroId); return Rules.PrisonerBaseLimit + (hero?.Skill("leadership") ?? 0) / 4 + p.Troops.TotalTroops / 4 + (int)Math.Round(PartyPerk(p, PerkEffect.PrisonerLimit)); } public double DailyFoodNeed(Party p) { double num = 0.0; foreach (TroopStack stack in p.Troops.Stacks) { num += (double)stack.Total * (UnitDef(stack.UnitId)?.FoodUse ?? 1.0); } num += (double)p.Troops.Heroes.Count; num += (double)p.Prisoners.TotalTroops * Rules.PrisonerFoodFactor; double num2 = RoleSkill(p, PartyRole.Quartermaster); return num * Rules.FoodPerTroopPerDay * (1.0 - Math.Min(0.25, num2 / 1000.0)) * (HasRolePerk(p, PartyRole.Quartermaster, "perk.quartermaster.frugal") ? 0.9 : 1.0) * PerkReduction(p, PerkEffect.FoodUse) * LawFoodFactor(p); } public double DailyWages(Party p) { double num = 0.0; foreach (TroopStack stack in p.Troops.Stacks) { num += (double)stack.Total * (UnitDef(stack.UnitId)?.DailyWage ?? 0.0); } foreach (string item in p.Troops.Heroes.Distinct()) { Hero hero = State.Heroes.Get(item); if (hero != null && hero.Occupation == HeroOccupation.Companion && hero.State == HeroState.Active && hero.PartyId == p.Id && hero.ClanId == p.ClanId) { num += (double)Math.Max(0, hero.DailyWage); } } return num * (HasRolePerk(p, PartyRole.Quartermaster, "perk.quartermaster.paymaster") ? 0.9 : 1.0) * PerkReduction(p, PerkEffect.Wages); } public long RecruitPrice(Party p, UnitDef unit) { if (unit != null) { return Math.Max(0L, (long)Math.Round((double)Math.Max(0, unit.RecruitCost) * PerkReduction(p, PerkEffect.RecruitCost))); } return 0L; } public long UpgradePrice(Party p, int gold) { return Math.Max(0L, (long)Math.Round((double)Math.Max(0, gold) * PerkReduction(p, PerkEffect.UpgradeCost))); } internal double PerkReduction(Party p, PerkEffect effect) { return 1.0 - Math.Max(0.0, Math.Min(0.5, PartyPerk(p, effect))); } public int RandomInt(string stream, int min, int maxExclusive) { return State.Random.Get(stream).Range(min, maxExclusive); } internal bool UsesLogistics(Party p) { return DailySystem.UsesLogistics(p); } public double SettlementDailyTax(Settlement s) { return DailySystem.SettlementDailyTax(s); } public double GarrisonDailyWages(Settlement s) { return DailySystem.GarrisonDailyWages(s); } public double DailyIncome(string clanId) { return DailySystem.DailyIncome(clanId); } public double DailyExpenses(string clanId) { return DailySystem.DailyExpenses(clanId); } public bool ClanCanAffordUpkeep(Clan clan, double extraDaily) { return DailySystem.ClanCanAffordUpkeep(clan, extraDaily); } internal void DailyLogistics() { DailySystem.DailyLogistics(); } internal void DailySettlements() { DailySystem.DailySettlements(); } internal void DailyBanditSpawns() { DailySystem.DailyBanditSpawns(); } public void EnsureOutlawPartySizes() { DailySystem.EnsureOutlawPartySizes(); } internal Party SpawnBanditParty(Settlement hideout, Clan clan, RandomStream rng) { return DailySystem.SpawnBanditParty(hideout, clan, rng); } internal Party CreateLordParty(Hero h, Settlement home) { return DailySystem.CreateLordParty(h, home); } internal void DailyCaptivity() { DailySystem.DailyCaptivity(); } internal void OnPlayerReleased(string reason) { DailySystem.OnPlayerReleased(reason); } internal void OnHeroDied(Hero hero) { DailySystem.OnHeroDied(hero); } internal void EnsureDeveloperChoice() { DeveloperSystem.EnsureDeveloperChoice(); } public string DeveloperCampaignReason() { return DeveloperSystem.DeveloperCampaignReason(); } internal string DeveloperFreeReason() { return DeveloperSystem.DeveloperFreeReason(); } public List DeveloperHeroes() { return DeveloperSystem.DeveloperHeroes(); } public CommandResult DeveloperAddYears(string heroId, int years) { return DeveloperSystem.DeveloperAddYears(heroId, years); } public CommandResult DeveloperAddGold(long amount) { return DeveloperSystem.DeveloperAddGold(amount); } public CommandResult DeveloperSetSkill(string heroId, string skill, int level) { return DeveloperSystem.DeveloperSetSkill(heroId, skill, level); } public CommandResult DeveloperSetAllSkills(string heroId, int level) { return DeveloperSystem.DeveloperSetAllSkills(heroId, level); } public static string SkillName(string skill) { return DeveloperSystem.SkillName(skill); } public CommandResult DeveloperSetHeroLevel(string heroId, int level) { return DeveloperSystem.DeveloperSetHeroLevel(heroId, level); } public CommandResult DeveloperAddFocus(string heroId, int points) { return DeveloperSystem.DeveloperAddFocus(heroId, points); } public CommandResult DeveloperClearFocus(string heroId) { return DeveloperSystem.DeveloperClearFocus(heroId); } public CommandResult DeveloperClearPerks(string heroId) { return DeveloperSystem.DeveloperClearPerks(heroId); } public CommandResult DeveloperAddRenown(double amount) { return DeveloperSystem.DeveloperAddRenown(amount); } public double DeveloperRenownToNextTier() { return DeveloperSystem.DeveloperRenownToNextTier(); } public CommandResult DeveloperAddInfluence(double amount) { return DeveloperSystem.DeveloperAddInfluence(amount); } public CommandResult DeveloperHealParty() { return DeveloperSystem.DeveloperHealParty(); } public CommandResult DeveloperAddFood(double amount) { return DeveloperSystem.DeveloperAddFood(amount); } public CommandResult DeveloperAddHorse(string breedId) { return DeveloperSystem.DeveloperAddHorse(breedId); } public CommandResult DeveloperRestoreHorse(string horseId) { return DeveloperSystem.DeveloperRestoreHorse(horseId); } public CommandResult DeveloperTrainHorse(string horseId) { return DeveloperSystem.DeveloperTrainHorse(horseId); } public List DeveloperUnits() { return DeveloperSystem.DeveloperUnits(); } public CommandResult DeveloperAddTroops(string unitId, int count) { return DeveloperSystem.DeveloperAddTroops(unitId, count); } public CommandResult DeveloperClearTroops() { return DeveloperSystem.DeveloperClearTroops(); } public string DeveloperTimeReason() { return DeveloperSystem.DeveloperTimeReason(); } public DeveloperSkipResult DeveloperSkipTime(int minutes, int maxSteps) { return DeveloperSystem.DeveloperSkipTime(minutes, maxSteps); } public void DeveloperSkipFinished(int minutes, string stopped) { DeveloperSystem.DeveloperSkipFinished(minutes, stopped); } public static string FormatDuration(int minutes) { return DeveloperSystem.FormatDuration(minutes); } public CommandResult DeveloperTeleport(string settlementId) { return DeveloperSystem.DeveloperTeleport(settlementId); } public List DeveloperKingdoms() { return DeveloperSystem.DeveloperKingdoms(); } public CommandResult DeveloperSetWar(string kingdomId, bool war) { return DeveloperSystem.DeveloperSetWar(kingdomId, war); } public CommandResult DeveloperAddCrime(string settlementId, double amount) { return DeveloperSystem.DeveloperAddCrime(settlementId, amount); } public CommandResult DeveloperRuleKingdom(string kingdomId) { return DeveloperSystem.DeveloperRuleKingdom(kingdomId); } public CommandResult DeveloperCaptureLord() { return DeveloperSystem.DeveloperCaptureLord(); } public CommandResult DeveloperJailLord(string settlementId) { return DeveloperSystem.DeveloperJailLord(settlementId); } public List DeveloperClans() { return DeveloperSystem.DeveloperClans(); } public CommandResult DeveloperAdjustRelation(string clanId, int delta) { return DeveloperSystem.DeveloperAdjustRelation(clanId, delta); } public CommandResult DeveloperAlliance(string kingdomId, bool on) { return DeveloperDiplomacySystem.DeveloperAlliance(kingdomId, on); } public CommandResult DeveloperTradeAgreement(string kingdomId, bool on) { return DeveloperDiplomacySystem.DeveloperTradeAgreement(kingdomId, on); } public CommandResult DeveloperTributePeace(string kingdomId, bool theyPay) { return DeveloperDiplomacySystem.DeveloperTributePeace(kingdomId, theyPay); } public CommandResult DeveloperAllyCallsYou(string kingdomId) { return DeveloperDiplomacySystem.DeveloperAllyCallsYou(kingdomId); } public CommandResult DeveloperWeakenKingdom(string kingdomId) { return DeveloperDiplomacySystem.DeveloperWeakenKingdom(kingdomId); } public CommandResult DeveloperRulerDies(string kingdomId) { return DeveloperDiplomacySystem.DeveloperRulerDies(kingdomId); } public CommandResult DeveloperCloseCouncilVotes() { return DeveloperDiplomacySystem.DeveloperCloseCouncilVotes(); } public CommandResult DeveloperRunAiDiplomacy() { return DeveloperDiplomacySystem.DeveloperRunAiDiplomacy(); } public CommandResult DeveloperGatherArmies() { return DeveloperDiplomacySystem.DeveloperGatherArmies(); } public CommandResult DeveloperGoToArmy() { return DeveloperDiplomacySystem.DeveloperGoToArmy(); } public CommandResult SetDifficultyPreset(string preset) { if (!Difficulty.Presets.Contains(preset)) { return CommandResult.Fail("Unknown difficulty."); } Difficulty.Apply(Settings, preset); State.AddLog(LogCategory.Info, "Difficulty set to " + preset + "."); State.Touch(); return CommandResult.Success("Difficulty: " + preset + "."); } public CommandResult SetDifficultyOption(string optionId, int index) { DifficultyOption difficultyOption = Difficulty.Options.FirstOrDefault((DifficultyOption o) => o.Id == optionId); if (difficultyOption == null || index < 0 || index >= difficultyOption.Values.Length) { return CommandResult.Fail("Unknown difficulty setting."); } Difficulty.SetOption(Settings, difficultyOption, index); State.Touch(); return CommandResult.Success(difficultyOption.Name + ": " + difficultyOption.Labels[index] + "."); } public double DifficultyHealthMultiplier(Combatant c) { if (c == null) { return 1.0; } CampaignSettings settings = Settings; if (c.IsHero && c.HeroId == State.PlayerHeroId) { return 1.0 / Math.Max(0.1, settings.PlayerDamageTaken); } if (c.PartyId.Length > 0 && c.PartyId == State.PlayerPartyId) { return 1.0 / Math.Max(0.1, settings.TroopDamageTaken); } return 1.0; } public void EnsureDiplomacyFields() { DiplomacySystem.EnsureDiplomacyFields(); } public long TruceDaysRemaining(string a, string b) { return DiplomacySystem.TruceDaysRemaining(a, b); } internal bool DiplomacyFactionReserved(string factionId) { return DiplomacySystem.DiplomacyFactionReserved(factionId); } internal bool KnownDiplomacyFaction(string factionId) { return DiplomacySystem.KnownDiplomacyFaction(factionId); } internal bool HasIndependentDiplomacyObligations() { return DiplomacySystem.HasIndependentDiplomacyObligations(); } internal Clan LivingDiplomacyRuler(string kingdomId) { return DiplomacySystem.LivingDiplomacyRuler(kingdomId); } internal string PlayerDiplomacyReason(string targetKingdomId) { return DiplomacySystem.PlayerDiplomacyReason(targetKingdomId); } public string DeclareKingdomWarReason(string targetKingdomId) { return DiplomacySystem.DeclareKingdomWarReason(targetKingdomId); } public CommandResult DeclareKingdomWar(string targetKingdomId) { return DiplomacySystem.DeclareKingdomWar(targetKingdomId); } public TradeQuote QuoteKingdomPeace(string targetKingdomId) { return DiplomacySystem.QuoteKingdomPeace(targetKingdomId); } public CommandResult MakeKingdomPeace(string targetKingdomId) { return DiplomacySystem.MakeKingdomPeace(targetKingdomId); } internal void AddDiplomacyTruce(string a, string b, string payer = "", string recipient = "", long payment = 0L) { DiplomacySystem.AddDiplomacyTruce(a, b, payer, recipient, payment); } internal string DiplomacyFactionName(string id) { return DiplomacySystem.DiplomacyFactionName(id); } internal void FinishDiplomacyChange(string a, string b, string message) { DiplomacySystem.FinishDiplomacyChange(a, b, message); } internal void RemoveExpiredPairTruces(string a, string b) { DiplomacySystem.RemoveExpiredPairTruces(a, b); } internal void MigrateIndependentDiplomacy(string oldFactionId, string newFactionId) { DiplomacySystem.MigrateIndependentDiplomacy(oldFactionId, newFactionId); } public double KingdomMilitaryStrength(string kingdomId) { return DiplomacySystem.KingdomMilitaryStrength(kingdomId); } internal bool DiplomacyFrontier(string a, string b) { return DiplomacySystem.DiplomacyFrontier(a, b); } public void DailyDiplomacy() { DiplomacySystem.DailyDiplomacy(); } public void OnDiplomacyChanged() { DiplomacyConsequencesSystem.OnDiplomacyChanged(); } internal void PlaceDiscoverySites() { DiscoveriesSystem.PlaceDiscoverySites(); } public static string SiteKindName(SiteKind kind) { return DiscoveriesSystem.SiteKindName(kind); } public List KnownSites() { return DiscoveriesSystem.KnownSites(); } public DiscoverySite Site(string id) { return DiscoveriesSystem.Site(id); } internal DiscoverySite SiteHere() { return DiscoveriesSystem.SiteHere(); } internal void HourlyDiscoveries() { DiscoveriesSystem.HourlyDiscoveries(); } internal int BestScout() { return DiscoveriesSystem.BestScout(); } public StoryPrompt SitePrompt(string siteId) { return DiscoveriesSystem.SitePrompt(siteId); } public CommandResult ExploreSite(string siteId, string option) { return DiscoveriesSystem.ExploreSite(siteId, option); } public void EnsureEconomyFields() { EconomySystem.EnsureEconomyFields(); } public string PrimaryVillageGood(Settlement s) { return EconomySystem.PrimaryVillageGood(s); } public int CargoCount(Party p, string goodId) { return EconomySystem.CargoCount(p, goodId); } public double CargoWeight(Party p) { return EconomySystem.CargoWeight(p); } public double CargoCapacity(Party p) { return EconomySystem.CargoCapacity(p); } public int MarketStock(Settlement s, string goodId) { return EconomySystem.MarketStock(s, goodId); } public static double TradeRate(bool buying, int tradeSkill, double haggle = 0.0) { return EconomySystem.TradeRate(buying, tradeSkill, haggle); } public double PlayerHaggle() { return EconomySystem.PlayerHaggle(); } public int PlayerTradeSkill() { return EconomySystem.PlayerTradeSkill(); } public long CommodityPrice(Settlement s, string goodId, bool buying, int stock, int tradeSkill = 0, double haggle = 0.0) { return EconomySystem.CommodityPrice(s, goodId, buying, stock, tradeSkill, haggle); } internal string CargoCommandReason() { return EconomySystem.CargoCommandReason(); } public string MarketAccessReason() { return EconomySystem.MarketAccessReason(); } public TradeQuote QuoteTrade(string goodId, int count, bool buying) { return EconomySystem.QuoteTrade(goodId, count, buying); } public CommandResult TradeGoods(string goodId, int count, bool buying) { return EconomySystem.TradeGoods(goodId, count, buying); } public ShoppingQuote QuoteShoppingList(IEnumerable> list) { return EconomySystem.QuoteShoppingList(list); } public CommandResult BuyShoppingList(IEnumerable> list) { return EconomySystem.BuyShoppingList(list); } public string CargoDropReason(string goodId, int count) { return EconomySystem.CargoDropReason(goodId, count); } public CommandResult DropCargo(string goodId, int count) { return EconomySystem.DropCargo(goodId, count); } public void DailyMarkets() { EconomySystem.DailyMarkets(); } public void VillageTradeArrival(Party p, Settlement s) { EconomySystem.VillageTradeArrival(p, s); } public double ClaimScore(Clan clan) { return ElectionsSystem.ClaimScore(clan); } internal void NoteRulerDeath(Hero h) { ElectionsSystem.NoteRulerDeath(h); } internal void DailyElections() { ElectionsSystem.DailyElections(); } public string AbdicateReason() { return ElectionsSystem.AbdicateReason(); } public CommandResult Abdicate() { return ElectionsSystem.Abdicate(); } internal string ElectionStaleReason(KingdomDecision decision) { return ElectionsSystem.ElectionStaleReason(decision); } internal bool CouncilElectionPreference(KingdomDecision decision, Clan clan, out string reason) { return ElectionsSystem.CouncilElectionPreference(decision, clan, out reason); } internal void ApplyElection(KingdomDecision decision, out string effect) { ElectionsSystem.ApplyElection(decision, out effect); } public static double ClosestApproach(Vec2 a0, Vec2 a1, Vec2 b0, Vec2 b1, out double t) { return EncountersSystem.ClosestApproach(a0, a1, b0, b1, out t); } public bool IsInterceptable(Party p) { return EncountersSystem.IsInterceptable(p); } internal void DetectEncounters(List moves) { EncountersSystem.DetectEncounters(moves); } public Encounter StartEncounter(Party initiator, Party target) { return EncountersSystem.StartEncounter(initiator, target); } internal void ResolveAiEncounter(Encounter enc) { EncountersSystem.ResolveAiEncounter(enc); } public void CancelEncounter(Encounter enc, string reason, string disengageParty = null) { EncountersSystem.CancelEncounter(enc, reason, disengageParty); } internal void PruneEncounters() { EncountersSystem.PruneEncounters(); } public static IReadOnlyList EncyclopediaSorts(EncyclopediaCategory category) { return EncyclopediaSystem.EncyclopediaSorts(category); } public List EncyclopediaEntries(EncyclopediaCategory category) { return EncyclopediaSystem.EncyclopediaEntries(category); } public static List EncyclopediaFilter(IEnumerable entries, EncyclopediaQuery query) { return EncyclopediaSystem.EncyclopediaFilter(entries, query); } public static SortedDictionary> EncyclopediaFacets(IEnumerable entries) { return EncyclopediaSystem.EncyclopediaFacets(entries); } public List EncyclopediaSearch(string text, int max = 40) { return EncyclopediaSystem.EncyclopediaSearch(text, max); } public EncyclopediaPage EncyclopediaPage(string link) { return EncyclopediaSystem.EncyclopediaPage(link); } public string HeroWhereabouts(Hero h, out string mapTarget) { return EncyclopediaSystem.HeroWhereabouts(h, out mapTarget); } public bool KnowsHero(Hero h) { return EncyclopediaSystem.KnowsHero(h); } internal void NoteHeroesMet() { EncyclopediaSystem.NoteHeroesMet(); } public string PartyStrengthText(Party p) { return EncyclopediaSystem.PartyStrengthText(p); } public bool IsEncyclopediaBookmark(string link) { return EncyclopediaSystem.IsEncyclopediaBookmark(link); } public CommandResult ToggleEncyclopediaBookmark(string link) { return EncyclopediaSystem.ToggleEncyclopediaBookmark(link); } public void EnsureEnterpriseFields() { EnterprisesSystem.EnsureEnterpriseFields(); } public string BuyWorkshopReason(string typeId) { return EnterprisesSystem.BuyWorkshopReason(typeId); } public CommandResult BuyWorkshop(string typeId) { return EnterprisesSystem.BuyWorkshop(typeId); } public string WorkshopActionReason(string id, string action, long amount = 0L) { return EnterprisesSystem.WorkshopActionReason(id, action, amount); } public CommandResult SetWorkshopEnabled(string id, bool enabled) { return EnterprisesSystem.SetWorkshopEnabled(id, enabled); } public CommandResult FundWorkshop(string id, long amount) { return EnterprisesSystem.FundWorkshop(id, amount); } public CommandResult WithdrawWorkshop(string id, long amount) { return EnterprisesSystem.WithdrawWorkshop(id, amount); } public CommandResult SellWorkshop(string id) { return EnterprisesSystem.SellWorkshop(id); } public string AbandonWorkshopReason(string id) { return EnterprisesSystem.AbandonWorkshopReason(id); } public CommandResult AbandonWorkshop(string id) { return EnterprisesSystem.AbandonWorkshop(id); } public string RecharterWorkshopReason(string id) { return EnterprisesSystem.RecharterWorkshopReason(id); } public CommandResult RecharterWorkshop(string id) { return EnterprisesSystem.RecharterWorkshop(id); } public void DailyEnterprises() { EnterprisesSystem.DailyEnterprises(); } public void EnsureEquipmentFields() { EquipmentSystem.EnsureEquipmentFields(); } public int EquipmentCount(Party party, string itemId) { return EquipmentSystem.EquipmentCount(party, itemId); } public int EquipmentStock(Settlement settlement, string itemId) { return EquipmentSystem.EquipmentStock(settlement, itemId); } public double EquipmentWeight(Party party) { return EquipmentSystem.EquipmentWeight(party); } public OwnedItemInfo ItemInfo(string id) { return EquipmentSystem.ItemInfo(id); } internal string EquipmentCommandReason() { return EquipmentSystem.EquipmentCommandReason(); } public string EquipmentHeroReason(string heroId) { return EquipmentSystem.EquipmentHeroReason(heroId); } public List HeroArchetypes(string heroId) { return EquipmentSystem.HeroArchetypes(heroId); } public List ArchetypeReturns(string heroId, string unitId) { return EquipmentSystem.ArchetypeReturns(heroId, unitId); } public string ArchetypeChangeReason(string heroId, string unitId) { return EquipmentSystem.ArchetypeChangeReason(heroId, unitId); } public CommandResult ChangeHeroArchetype(string heroId, string unitId) { return EquipmentSystem.ChangeHeroArchetype(heroId, unitId); } public static string RoleName(TroopRole role) { return EquipmentSystem.RoleName(role); } public TroopRole? WeaponRole(string itemId) { return EquipmentSystem.WeaponRole(itemId); } public EquipmentSlot? EquipmentSlotOf(string itemId) { return EquipmentSystem.EquipmentSlotOf(itemId); } public bool IsOffHandWeapon(string itemId) { return EquipmentSystem.IsOffHandWeapon(itemId); } public bool DualWields(Hero hero) { return EquipmentSystem.DualWields(hero); } public string EquipmentEquipReason(string heroId, string itemId, bool offHand = false) { return EquipmentSystem.EquipmentEquipReason(heroId, itemId, offHand); } public CommandResult EquipHeroItem(string heroId, string itemId, bool offHand = false) { return EquipmentSystem.EquipHeroItem(heroId, itemId, offHand); } public string EquipmentUnequipReason(string heroId, EquipmentSlot slot) { return EquipmentSystem.EquipmentUnequipReason(heroId, slot); } public CommandResult UnequipHeroItem(string heroId, EquipmentSlot slot) { return EquipmentSystem.UnequipHeroItem(heroId, slot); } public EquipmentTradeQuote QuoteEquipmentTrade(string itemId, bool buying) { return EquipmentSystem.QuoteEquipmentTrade(itemId, buying); } public CommandResult TradeEquipment(string itemId, bool buying) { return EquipmentSystem.TradeEquipment(itemId, buying); } public string EquipmentDropReason(string itemId, int count) { return EquipmentSystem.EquipmentDropReason(itemId, count); } public CommandResult DropEquipment(string itemId, int count) { return EquipmentSystem.DropEquipment(itemId, count); } internal static void SetEquipmentCount(SortedDictionary inventory, string id, int count) { EquipmentSystem.SetEquipmentCount(inventory, id, count); } public EquipmentCombatStats HeroEquipmentStats(Hero hero, HeroEquipmentState loadout = null) { return EquipmentBattlesSystem.HeroEquipmentStats(hero, loadout); } public static EquipmentCombatStats LoadoutCombatStats(CampaignState state, Func unitDef, UnitDef basis, HeroEquipmentState selected) { return EquipmentBattlesSystem.LoadoutCombatStats(state, unitDef, basis, selected); } public static HeroEquipmentState CopyHeroLoadout(HeroEquipmentState loadout) { return EquipmentBattlesSystem.CopyHeroLoadout(loadout); } internal string EquipmentReunionReason(Party source, Party target) { return EquipmentBattlesSystem.EquipmentReunionReason(source, target); } internal void ReuniteEquipment(Party source, Party target) { EquipmentBattlesSystem.ReuniteEquipment(source, target); } internal string SeizeEquipment(Party source, Party captor) { return EquipmentBattlesSystem.SeizeEquipment(source, captor); } public double HeroAge(Hero h) { return FamiliesSystem.HeroAge(h); } public int HeroYears(Hero h) { return FamiliesSystem.HeroYears(h); } public bool IsChild(Hero h) { return FamiliesSystem.IsChild(h); } public bool IsGrown(Hero h) { return FamiliesSystem.IsGrown(h); } public Hero SpouseOf(Hero h) { return FamiliesSystem.SpouseOf(h); } public IEnumerable ChildrenOf(Hero h) { return FamiliesSystem.ChildrenOf(h); } public IEnumerable ParentsOf(Hero h) { return FamiliesSystem.ParentsOf(h); } public IEnumerable SiblingsOf(Hero h) { return FamiliesSystem.SiblingsOf(h); } public string MarriageReason(Hero a, Hero b) { return FamiliesSystem.MarriageReason(a, b); } public int LordPartyLimit(Clan clan) { return FamiliesSystem.LordPartyLimit(clan); } public Settlement ClanHome(Clan clan) { return FamiliesSystem.ClanHome(clan); } public string ClanSurname(Clan clan) { return FamiliesSystem.ClanSurname(clan); } public List LivingClanMembers(Clan clan) { return FamiliesSystem.LivingClanMembers(clan); } public void EnsureFamilyFields() { FamiliesSystem.EnsureFamilyFields(); } public void StartFamilies() { FamiliesSystem.StartFamilies(); } internal bool GiveIdentity(Hero h) { return FamiliesSystem.GiveIdentity(h); } internal Hero NewKin(Clan clan, HeroSex sex, double age, Settlement home, RandomStream rng, ICollection taken, bool grown, string cultureId = null) { return FamiliesSystem.NewKin(clan, sex, age, home, rng, taken, grown, cultureId); } internal void DailyFamilies() { FamiliesSystem.DailyFamilies(); } public string EducationReason(string childId, string stageId, string choiceId) { return FamiliesSystem.EducationReason(childId, stageId, choiceId); } public CommandResult ChooseEducation(string childId, string stageId, string choiceId) { return FamiliesSystem.ChooseEducation(childId, stageId, choiceId); } public List<(Hero child, EducationStageDef stage)> EducationDue() { return FamiliesSystem.EducationDue(); } internal void Marry(Hero a, Hero b, Hero mover) { FamiliesSystem.Marry(a, b, mover); } internal void DisbandLordParty(Party p, string reason) { FamiliesSystem.DisbandLordParty(p, reason); } internal bool HeroBusy(Hero h) { return FamiliesSystem.HeroBusy(h); } public void HeroDies(Hero h, string cause) { FamiliesSystem.HeroDies(h, cause); } internal void AfterHeroDeath(Hero h, string cause) { FamiliesSystem.AfterHeroDeath(h, cause); } public bool IsNoble(Hero h) { return FamiliesSystem.IsNoble(h); } internal void MoveHeroToClan(Hero h, Clan to) { FamiliesSystem.MoveToClan(h, to); } public bool ClanLineEnded(Clan clan) { return FamilyLawSystem.LineEnded(clan); } public Hero ClanHeir(Clan clan) { return FamilyLawSystem.ClanHeir(clan); } internal void InheritExtinctClans() { FamilyLawSystem.InheritExtinctClans(); } public Clan DivorceDestination(Hero spouse) { return FamilyLawSystem.DivorceDestination(spouse); } public string DivorceReason() { return FamilyLawSystem.DivorceReason(); } public CommandResult Divorce() { return FamilyLawSystem.Divorce(); } public bool GarrisonImproves(Settlement s) { return GarrisonsSystem.Improves(s); } public GarrisonOrdersState GarrisonOrders(Settlement s) { return GarrisonsSystem.OrdersOf(s); } public int GarrisonDrillXp(Settlement s) { return GarrisonsSystem.DrillXp(s); } public List GarrisonPromotions(Settlement s, string unitId) { return GarrisonsSystem.PromotionsFor(s, unitId); } public UpgradeDef GarrisonPromotion(Settlement s, string unitId) { return GarrisonsSystem.PromotionFor(s, unitId); } public int GarrisonRoom(Settlement s, string unitId) { return GarrisonsSystem.Room(s, unitId); } public int GarrisonIncoming(Settlement s) { return GarrisonsSystem.Incoming(s); } internal double GarrisonWagePerHead(Settlement s, string unitId) { return SettlementBudgetsSystem.GarrisonWagePerHead(s, unitId); } public GarrisonPartyState GarrisonPartyFor(Party p) { return GarrisonsSystem.RecordFor(p); } public GarrisonPartyState GarrisonPartyRecord(string id) { return GarrisonsSystem.Record(id); } public bool IsPlayerGarrisonParty(Party p) { return GarrisonsSystem.IsPlayerGarrisonParty(p); } public IEnumerable<(GarrisonPartyState record, Party party)> GarrisonPartiesOf(string clanId) { return GarrisonsSystem.PartiesOf(clanId); } public IEnumerable<(GarrisonPartyState record, Party party)> GarrisonPartiesFrom(Settlement s) { return GarrisonsSystem.PartiesFrom(s); } public string DescribeGarrisonParty(GarrisonPartyState r) { return GarrisonsSystem.Describe(r); } public double GarrisonPartyWages(Party p) { return GarrisonsSystem.FieldWages(p); } public IEnumerable GarrisonTransferDestinations(Settlement from) { return GarrisonsSystem.TransferDestinations(from); } public string GarrisonOrdersReason() { return GarrisonsSystem.FiefReason(); } public CommandResult SetGarrisonTraining(bool on) { return GarrisonsSystem.SetFlag("training", on); } public CommandResult SetGarrisonAutoUpgrade(bool on) { return GarrisonsSystem.SetFlag("upgrade", on); } public CommandResult SetGarrisonRecruitPrisoners(bool on) { return GarrisonsSystem.SetFlag("prisoners", on); } public CommandResult SetGarrisonTierCap(int tier) { return GarrisonsSystem.SetTierCap(tier); } public CommandResult SetGarrisonTarget(int size) { return GarrisonsSystem.SetTarget(size); } public CommandResult SetGarrisonUpgradePath(string unitId, string toUnitId) { return GarrisonsSystem.SetUpgradePath(unitId, toUnitId); } public string FormGarrisonGuardsReason(int size) { return GarrisonsSystem.FormGuardsReason(size); } public CommandResult FormGarrisonGuards(int size) { return GarrisonsSystem.FormGuards(size); } public string SendGarrisonTroopsReason(string destinationId, string unitId, int count) { return GarrisonsSystem.SendTroopsReason(destinationId, unitId, count); } public CommandResult SendGarrisonTroops(string destinationId, string unitId, int count) { return GarrisonsSystem.SendTroops(destinationId, unitId, count); } public string GarrisonPartyOrderReason(string id, GarrisonPartyOrder order, string targetId = "") { return GarrisonsSystem.OrderReason(id, order, targetId); } public CommandResult SetGarrisonPartyOrder(string id, GarrisonPartyOrder order, string targetId = "") { return GarrisonsSystem.SetOrder(id, order, targetId); } public void DailyGarrisonParties() { GarrisonsSystem.DailyParties(); } public void EnsureGovernanceFields() { GovernanceSystem.EnsureGovernanceFields(); } public static bool IsSettlementProject(string id) { return GovernanceSystem.IsSettlementProject(id); } public string ProjectName(string id) { return GovernanceSystem.ProjectName(id); } public long ProjectCost(string id) { return GovernanceSystem.ProjectCost(id); } public int ProjectTimber(string id) { return GovernanceSystem.ProjectTimber(id); } public int ProjectTools(string id) { return GovernanceSystem.ProjectTools(id); } public static int ProjectDays(string id) { return GovernanceSystem.ProjectDays(id); } public int ProjectLevel(Settlement settlement, string id) { return GovernanceSystem.ProjectLevel(settlement, id); } internal bool IsGovernedSettlement(Settlement settlement) { return GovernanceSystem.IsGovernedSettlement(settlement); } public double GovernanceTaxFactor(Settlement settlement) { return GovernanceSystem.GovernanceTaxFactor(settlement); } public double SettlementFoodConsumption(Settlement settlement, double baseConsumption) { return GovernanceSystem.SettlementFoodConsumption(settlement, baseConsumption); } public double SettlementSecurityChange(Settlement settlement) { return GovernanceSystem.SettlementSecurityChange(settlement); } public double SettlementLoyaltyChange(Settlement settlement) { return GovernanceSystem.SettlementLoyaltyChange(settlement); } public StatForecast SettlementLoyaltyForecast(Settlement settlement) { return GovernanceSystem.SettlementLoyaltyForecast(settlement); } internal string SettlementManagementReason() { return GovernanceSystem.SettlementManagementReason(); } public string SettlementPolicyReason(TaxPolicy policy) { return GovernanceSystem.SettlementPolicyReason(policy); } public CommandResult SetSettlementPolicy(TaxPolicy policy) { return GovernanceSystem.SetSettlementPolicy(policy); } public string ProjectStartReason(string id) { return GovernanceSystem.ProjectStartReason(id); } public CommandResult StartSettlementProject(string id) { return GovernanceSystem.StartSettlementProject(id); } internal void ConsumeProjectCargo(string goodId, int count) { GovernanceSystem.ConsumeProjectCargo(goodId, count); } public string CancelSettlementProjectReason() { return GovernanceSystem.CancelSettlementProjectReason(); } public CommandResult CancelSettlementProject() { return GovernanceSystem.CancelSettlementProject(); } internal bool SyncSettlementManagementOwner(Settlement settlement) { return GovernanceSystem.SyncSettlementManagementOwner(settlement); } public void DailyGovernance() { GovernanceSystem.DailyGovernance(); } public Settlement GovernorAssignedSettlement(string heroId) { return GovernorsSystem.GovernorAssignedSettlement(heroId); } public Hero SettlementGovernor(Settlement settlement) { return GovernorsSystem.SettlementGovernor(settlement); } public IEnumerable GovernorCandidates() { return GovernorsSystem.GovernorCandidates(); } internal bool IsStationedGovernor(Settlement settlement, Hero hero) { return GovernorsSystem.IsStationedGovernor(settlement, hero); } public bool GovernorActive(Settlement settlement) { return GovernorsSystem.GovernorActive(settlement); } public double GovernorTaxFactor(Settlement settlement) { return GovernorsSystem.GovernorTaxFactor(settlement); } public double GovernorLoyaltyBonus(Settlement settlement) { return GovernorsSystem.GovernorLoyaltyBonus(settlement); } public double GovernorDailyWages(Settlement settlement) { return GovernorsSystem.GovernorDailyWages(settlement); } public string GovernorAssignmentReason(string heroId) { return GovernorsSystem.GovernorAssignmentReason(heroId); } public CommandResult AssignGovernor(string heroId) { return GovernorsSystem.AssignGovernor(heroId); } public string GovernorRecallReason() { return GovernorsSystem.GovernorRecallReason(); } public CommandResult RecallGovernor() { return GovernorsSystem.RecallGovernor(); } public void ClearHeroGovernorAssignments(string heroId) { GovernorsSystem.ClearHeroGovernorAssignments(heroId); } public void ReleaseSettlementGovernor(Settlement settlement, string reason) { GovernorsSystem.ReleaseSettlementGovernor(settlement, reason); } public void CleanupGovernors() { GovernorsSystem.CleanupGovernors(); } public void DailyGovernors() { GovernorsSystem.DailyGovernors(); } public void RememberHero(Hero h, string kind, string detail = "") { HeroBondsSystem.RememberHero(h, kind, detail); } public IReadOnlyList MemoriesOf(string heroId) { return HeroBondsSystem.MemoriesOf(heroId); } internal void RememberBattle(Encounter enc, List<(string partyId, BattleSide side, string heroId)> leaders, bool playerWon, bool decided) { HeroBondsSystem.RememberBattle(enc, leaders, playerWon, decided); } internal string MemoryRemark(Hero h, Random r) { return HeroBondsSystem.MemoryRemark(h, r); } internal string RenownRemark(Random r) { return HeroBondsSystem.RenownRemark(r); } internal List OpinionLines(Hero h, Random r) { return HeroBondsSystem.OpinionLines(h, r); } public long GiftCost(Hero h) { return HeroBondsSystem.GiftCost(h); } public string GiftReason(string heroId) { return HeroBondsSystem.GiftReason(heroId); } public CommandResult GiveGift(string heroId) { return HeroBondsSystem.GiveGift(heroId); } public string FavourReason(string heroId) { return HeroBondsSystem.FavourReason(heroId); } public int FavourTroopCount(Hero h) { return HeroBondsSystem.FavourTroopCount(h); } public string FavourTroopsReason(string heroId) { return HeroBondsSystem.FavourTroopsReason(heroId); } public CommandResult AskFavourTroops(string heroId) { return HeroBondsSystem.AskFavourTroops(heroId); } public long FavourPurse(Hero h) { return HeroBondsSystem.FavourPurse(h); } public string FavourPurseReason(string heroId) { return HeroBondsSystem.FavourPurseReason(heroId); } public CommandResult AskFavourPurse(string heroId) { return HeroBondsSystem.AskFavourPurse(heroId); } public string FavourWordReason(string heroId) { return HeroBondsSystem.FavourWordReason(heroId); } public CommandResult AskFavourWord(string heroId) { return HeroBondsSystem.AskFavourWord(heroId); } public string SparReason(string heroId) { return HeroBondsSystem.SparReason(heroId); } public CommandResult Spar(string heroId) { return HeroBondsSystem.Spar(heroId); } public string LessonSkill(Hero h) { return HeroBondsSystem.LessonSkill(h); } public string LessonReason(string heroId) { return HeroBondsSystem.LessonReason(heroId); } public CommandResult TakeLesson(string heroId) { return HeroBondsSystem.TakeLesson(heroId); } public int Approval(Hero h) { return HeroBondsSystem.Approval(h); } internal void CompanionsReactToBattle(bool won) { HeroBondsSystem.CompanionsReactToBattle(won); } internal void CompanionsReactToRaid(Settlement village) { HeroBondsSystem.CompanionsReactToRaid(village); } internal void CompanionsReactToExecution(Hero victim) { HeroBondsSystem.CompanionsReactToExecution(victim); } internal void CompanionsReactToRelease(Hero freed) { HeroBondsSystem.CompanionsReactToRelease(freed); } internal void CompanionsReactToHardship() { HeroBondsSystem.CompanionsReactToHardship(); } public string CompanionGiftReason(string heroId) { return HeroBondsSystem.CompanionGiftReason(heroId); } public CommandResult GiveCompanionGift(string heroId) { return HeroBondsSystem.GiveCompanionGift(heroId); } public CompanionRequestState CompanionRequest(Hero h) { return HeroBondsSystem.CompanionRequest(h); } public string DescribeRequest(CompanionRequestState q) { return HeroBondsSystem.DescribeRequest(q); } public string AskCompanionWants(Hero h) { return HeroBondsSystem.AskCompanionWants(h); } internal void NoteCompanionTournament(IEnumerable heroIds) { HeroBondsSystem.NoteCompanionTournament(heroIds); } internal void DailyHeroBonds() { HeroBondsSystem.DailyHeroBonds(); } internal List CompanionOpinion(Hero h, Random r) { return HeroBondsSystem.CompanionOpinion(h, r); } public static int HeroFocusPointsForLevel(int level) { return HeroDevelopmentSystem.HeroFocusPointsForLevel(level); } public int HeroFocusBudget(Hero hero) { return HeroDevelopmentSystem.HeroFocusBudget(hero); } public static int ExtraFocus(Hero hero) { return HeroDevelopmentSystem.ExtraFocus(hero); } public int HeroFocusAvailable(Hero hero) { return HeroDevelopmentSystem.HeroFocusAvailable(hero); } public int HeroSkillFocus(Hero hero, string skill) { return HeroDevelopmentSystem.HeroSkillFocus(hero, skill); } public double HeroLearningRate(Hero hero, string skill) { return HeroDevelopmentSystem.HeroLearningRate(hero, skill); } public int HeroLearningLimit(Hero hero, string skill) { return HeroDevelopmentSystem.HeroLearningLimit(hero, skill); } public static int HeroAttribute(Hero hero, string attribute) { return HeroDevelopmentSystem.HeroAttribute(hero, attribute); } public int HeroAttributeBudget(Hero hero) { return HeroDevelopmentSystem.HeroAttributeBudget(hero); } public int HeroAttributePointsAvailable(Hero hero) { return HeroDevelopmentSystem.HeroAttributePointsAvailable(hero); } public string HeroAttributeChoiceReason(string heroId, string attribute) { return HeroDevelopmentSystem.HeroAttributeChoiceReason(heroId, attribute); } public CommandResult InvestHeroAttribute(string heroId, string attribute) { return HeroDevelopmentSystem.InvestHeroAttribute(heroId, attribute); } public string MainWeaponSkill(Hero hero) { return HeroDevelopmentSystem.MainWeaponSkill(hero); } public string UnitWeaponSkill(string unitId) { return HeroDevelopmentSystem.UnitWeaponSkill(UnitDef(unitId ?? "")); } public string HeroFocusChoiceReason(string heroId, string skill) { return HeroDevelopmentSystem.HeroFocusChoiceReason(heroId, skill); } public CommandResult InvestHeroFocus(string heroId, string skill) { return HeroDevelopmentSystem.InvestHeroFocus(heroId, skill); } public HeroRetrainingQuote QuoteHeroRetraining(string heroId) { return HeroDevelopmentSystem.QuoteHeroRetraining(heroId); } public CommandResult RetrainHero(string heroId, long expectedRevision) { return HeroDevelopmentSystem.RetrainHero(heroId, expectedRevision); } public void EnsureHideoutFields() { HideoutsSystem.EnsureHideoutFields(); } public HideoutRecord Hideout(string settlementId) { return HideoutsSystem.Hideout(settlementId); } public bool HideoutKnown(Settlement s) { return HideoutsSystem.HideoutKnown(s); } internal void HourlyHideouts() { HideoutsSystem.HourlyHideouts(); } public CommandResult DeveloperRevealHideouts() { return HideoutsSystem.DeveloperRevealHideouts(); } public int HideoutSquadLimit() { return HideoutsSystem.HideoutSquadLimit(); } public Settlement HideoutHere() { return HideoutsSystem.HideoutHere(); } public string HideoutAssaultReason(string settlementId) { return HideoutsSystem.HideoutAssaultReason(settlementId); } public string HideoutGangEstimate(string settlementId) { return HideoutsSystem.HideoutGangEstimate(settlementId); } public void SuggestHideoutSquad(out SortedDictionary troops, out List heroes) { HideoutsSystem.SuggestHideoutSquad(out troops, out heroes); } public string HideoutSquadReason(IDictionary troops, IList heroes) { return HideoutsSystem.HideoutSquadReason(troops, heroes); } public CommandResult StartHideoutAssault(string settlementId, IDictionary troops, IList heroes) { return HideoutsSystem.StartHideoutAssault(settlementId, troops, heroes); } internal void CancelHideoutEncounter(Encounter enc) { HideoutsSystem.CancelHideoutEncounter(enc); } internal void CompleteHideoutRaid(Encounter enc, BattleResult result, BattleReport report) { HideoutsSystem.CompleteHideoutRaid(enc, result, report); } public StoryPrompt HideoutPrompt(string settlementId) { return HideoutsSystem.HideoutPrompt(settlementId); } public CommandResult ChooseHideoutOption(string settlementId, string option) { return HideoutsSystem.ChooseHideoutOption(settlementId, option); } internal void DailyHideouts() { HideoutsSystem.DailyHideouts(); } public HerdSummary Herd(Party p) { return HorseLifeSystem.Herd(p); } internal void HorseSpeedFactors(Party p, Action factor) { HorseLifeSystem.HorseSpeedFactors(p, factor); } public double HorseCargoCapacity(Party p) { return HorseLifeSystem.HorseCargoCapacity(p); } internal void HourlyHorses() { HorseLifeSystem.HourlyHorses(); } internal void DailyHorses() { HorseLifeSystem.DailyHorses(); } internal void RaidStudFarm(Settlement village) { HorseLifeSystem.RaidStudFarm(village); } internal string SeizeHerd(Party source, ICollection keptRiders = null) { return HorseLifeSystem.SeizeHerd(source, keptRiders); } public MountSpec MountForBattle(Hero hero) { return HorseLifeSystem.MountForBattle(hero); } internal void ApplyHorseBattleOutcome(Combatant c, CombatOutcome heroOutcome, CombatOutcome mountOutcome, bool heroCaptured, bool heroDied, bool won, bool simulated, RandomStream rng, List lines, Party captor = null) { HorseLifeSystem.ApplyHorseBattleOutcome(c, heroOutcome, mountOutcome, heroCaptured, heroDied, won, simulated, rng, lines, captor); } internal void HorseFollows(Hero hero, Party from, Party to) { HorseLifeSystem.HorseFollows(hero, from, to); } internal void ReuniteHorses(Party source, Party target) { HorseLifeSystem.ReuniteHorses(source, target); } public static bool IsHorseRanch(Settlement s) { return HorseMarketsSystem.IsHorseRanch(s); } public static bool HasHorseMarket(Settlement s) { return HorseMarketsSystem.HasHorseMarket(s); } public int HorseMarketSize(Settlement s) { return HorseMarketsSystem.HorseMarketSize(s); } public List MarketHorses(string settlementId) { return HorseMarketsSystem.MarketHorses(settlementId); } internal void PruneHorseMarkets() { HorseMarketsSystem.PruneHorseMarkets(); } public string HorseMarketReason() { return HorseMarketsSystem.HorseMarketReason(); } public long HorseBuyPrice(HorseState horse) { return HorseMarketsSystem.HorseBuyPrice(horse); } public HorseTradeQuote QuoteHorsePurchase(string horseId) { return HorseMarketsSystem.QuoteHorsePurchase(horseId); } public CommandResult BuyHorse(string horseId) { return HorseMarketsSystem.BuyHorse(horseId); } public HorseTradeQuote QuoteHorseSale(string horseId) { return HorseMarketsSystem.QuoteHorseSale(horseId); } public CommandResult SellHorse(string horseId) { return HorseMarketsSystem.SellHorse(horseId); } public StudFarmState StudFarm(string settlementId) { return HorseMarketsSystem.StudFarm(settlementId); } public int StudCapacity() { return HorseMarketsSystem.StudCapacity(); } public IEnumerable StudHorses(string settlementId) { return HorseMarketsSystem.StudHorses(settlementId); } internal string StudVisitReason(string settlementId) { return HorseMarketsSystem.StudVisitReason(settlementId); } public string BuyStudFarmReason() { return HorseMarketsSystem.BuyStudFarmReason(); } public CommandResult BuyStudFarm() { return HorseMarketsSystem.BuyStudFarm(); } public string SellStudFarmReason(string settlementId) { return HorseMarketsSystem.SellStudFarmReason(settlementId); } public CommandResult SellStudFarm(string settlementId) { return HorseMarketsSystem.SellStudFarm(settlementId); } public string StableAtStudReason(string horseId) { return HorseMarketsSystem.StableAtStudReason(horseId); } public CommandResult StableAtStud(string horseId) { return HorseMarketsSystem.StableAtStud(horseId); } public string TakeFromStudReason(string horseId) { return HorseMarketsSystem.TakeFromStudReason(horseId); } public CommandResult TakeFromStud(string horseId) { return HorseMarketsSystem.TakeFromStud(horseId); } public int GestationDays() { return HorseMarketsSystem.GestationDays(); } public string BreedReason(string mareId, string stallionId) { return HorseMarketsSystem.BreedReason(mareId, stallionId); } public CommandResult BreedHorses(string mareId, string stallionId) { return HorseMarketsSystem.BreedHorses(mareId, stallionId); } internal HorseState Foal(HorseState mare, Settlement stud) { return HorseMarketsSystem.Foal(mare, stud); } public void EnsureHorseFields() { HorsesSystem.EnsureHorseFields(); } public HorseState Horse(string id) { return HorsesSystem.Horse(id); } public static HorseBreedDef BreedOf(HorseState horse) { return HorsesSystem.BreedOf(horse); } public string BreedName(HorseState horse) { return HorsesSystem.BreedName(horse); } public double HorseAge(HorseState horse) { return HorsesSystem.HorseAge(horse); } public int HorseLevel(HorseState horse) { return HorsesSystem.HorseLevel(horse); } public double HorseBond(HorseState horse, string heroId) { return HorsesSystem.HorseBond(horse, heroId); } public static string HorseQuality(HorseState horse) { return HorsesSystem.HorseQuality(horse); } public HorseStats HorseCurrentStats(HorseState horse) { return HorsesSystem.HorseCurrentStats(horse); } public int HorseDifficulty(HorseState horse, Hero rider) { return HorsesSystem.HorseDifficulty(horse, rider); } public Hero HorseRider(HorseState horse) { return HorsesSystem.HorseRider(horse); } public IEnumerable PartyHorses(Party party) { return HorsesSystem.PartyHorses(party); } public IEnumerable ClanHorses() { return HorsesSystem.ClanHorses(); } public HorseState HeroMount(Hero hero) { return HorsesSystem.HeroMount(hero); } public string HorseRideReason(HorseState horse, Hero hero) { return HorsesSystem.HorseRideReason(horse, hero); } public bool HeroRides(Hero hero) { return HorsesSystem.HeroRides(hero); } internal bool SpareRidingHorse(HorseState horse) { return HorsesSystem.SpareRidingHorse(horse); } public long HorseValue(HorseState horse) { return HorsesSystem.HorseValue(horse); } internal IEnumerable PresentClanHeroes(Party party) { return HorsesSystem.PresentClanHeroes(party); } public bool PartyHasRidingPerk(Party party, string perk) { return HorsesSystem.PartyHasRidingPerk(party, perk); } public bool ClanHasRidingPerk(string perk) { return HorsesSystem.ClanHasRidingPerk(perk); } public string AssignMountReason(string heroId, string horseId) { return HorsesSystem.AssignMountReason(heroId, horseId); } public CommandResult AssignMount(string heroId, string horseId) { return HorsesSystem.AssignMount(heroId, horseId); } public string UnassignMountReason(string heroId) { return HorsesSystem.UnassignMountReason(heroId); } public CommandResult UnassignMount(string heroId) { return HorsesSystem.UnassignMount(heroId); } public string SetRidingReason(string heroId, bool ride) { return HorsesSystem.SetRidingReason(heroId, ride); } public CommandResult SetHeroRiding(string heroId, bool ride) { return HorsesSystem.SetHeroRiding(heroId, ride); } public string RenameHorseReason(string horseId, string name) { return HorsesSystem.RenameHorseReason(horseId, name); } public CommandResult RenameHorse(string horseId, string name) { return HorsesSystem.RenameHorse(horseId, name); } public string GeldReason(string horseId) { return HorsesSystem.GeldReason(horseId); } public CommandResult GeldHorse(string horseId) { return HorsesSystem.GeldHorse(horseId); } internal string NewHorseId() { return HorsesSystem.NewHorseId(); } internal static double Gaussian(RandomStream rng) { return HorsesSystem.Gaussian(rng); } internal HorseState CreateHorse(HorseBreedDef breed, RandomStream rng, double ageYears, double qualityBias, string origin, bool assignId = true) { return HorsesSystem.CreateHorse(breed, rng, ageYears, qualityBias, origin, assignId); } public static bool HasKeep(Settlement s) { return KeepSystem.HasKeep(s); } public string KeepFreeAccessReason(Settlement s) { return KeepSystem.KeepFreeAccessReason(s); } public bool HasKeepAccess(Settlement s) { return KeepSystem.HasKeepAccess(s); } public long KeepBribeCost(Settlement s) { return KeepSystem.KeepBribeCost(s); } public string KeepBribeReason() { return KeepSystem.KeepBribeReason(); } public CommandResult BribeKeepGuards() { return KeepSystem.BribeKeepGuards(); } internal bool KingdomArmyMemberAvailable(Party party, ClanArmyMember member) { return KingdomArmySystem.KingdomArmyMemberAvailable(party, member); } public bool IsKingdomArmyParty(Party party) { return KingdomArmySystem.IsKingdomArmyParty(party); } public int KingdomArmyGuestInfluence(Party party) { return KingdomArmySystem.KingdomArmyGuestInfluence(party); } public long KingdomArmyDaysServed(string partyId) { return KingdomArmySystem.KingdomArmyDaysServed(partyId); } internal string KingdomArmyDepartureReason(Party party, ClanArmyMember member) { return KingdomArmySystem.KingdomArmyDepartureReason(party, member); } public KingdomArmyCallQuote QuoteKingdomArmyCall(string partyId) { return KingdomArmySystem.QuoteKingdomArmyCall(partyId); } public CommandResult CallKingdomArmyParty(string partyId, KingdomArmyCallQuote expectedQuote = null) { return KingdomArmySystem.CallKingdomArmyParty(partyId, expectedQuote); } public string KingdomArmyReleaseReason(string partyId) { return KingdomArmySystem.KingdomArmyReleaseReason(partyId); } public CommandResult ReleaseKingdomArmyParty(string partyId) { return KingdomArmySystem.ReleaseKingdomArmyParty(partyId); } public void DailyKingdomArmySupport() { KingdomArmySystem.DailyKingdomArmySupport(); } public string RallyArmyReason() { return KingdomArmySystem.RallyArmyReason(); } public CommandResult RallyArmy() { return KingdomArmySystem.RallyArmy(); } internal bool KingdomArmyAwaitingRelease(Party party) { return KingdomArmyAiSystem.KingdomArmyAwaitingRelease(party); } internal void KingdomArmyOptions(Party party, Clan clan, double strength, List<(Party party, double strength, double dist)> hostiles, List options) { KingdomArmyAiSystem.KingdomArmyOptions(party, clan, strength, hostiles, options); } internal void KingdomArmySettlementArrival(Party party, Settlement settlement) { KingdomArmyAiSystem.KingdomArmySettlementArrival(party, settlement); } internal string KingdomCourtReason() { return KingdomsSystem.KingdomCourtReason(); } public string FoundKingdomReason(string name) { return KingdomsSystem.FoundKingdomReason(name); } public CommandResult FoundKingdom(string name) { return KingdomsSystem.FoundKingdom(name); } public string SecedeKingdomReason() { return KingdomsSystem.SecedeKingdomReason(); } public CommandResult SecedeKingdom() { return KingdomsSystem.SecedeKingdom(); } public void EnsureLegendFields() { LegendsSystem.EnsureLegendFields(); } internal void DailyLegendSites() { LegendsSystem.DailyLegendSites(); } internal StoryPrompt LegendSitePrompt(DiscoverySite s) { return LegendsSystem.LegendSitePrompt(s); } internal CommandResult ChooseLegendSite(DiscoverySite s, StoryPrompt prompt, string option) { return LegendsSystem.ChooseLegendSite(s, prompt, option); } public string LegendSiteSummary(string siteId) { return LegendsSystem.LegendSiteSummary(siteId); } internal static IEnumerable LegendQuestTemplates() { return LegendsSystem.LegendQuestTemplates(); } public bool RidingArchetype(Hero hero) { return HorsesSystem.RidingArchetype(hero); } public bool KeepsLordHorse(Hero h) { return LordHorsesSystem.KeepsLordHorse(h); } public HorseState LordHorse(Hero h) { return LordHorsesSystem.LordHorse(h); } public void EnsureLordHorses() { LordHorsesSystem.EnsureLordHorses(); } public void EnsureLordHorsesOnLoad() { if (State.Horses != null && (State.Horses.LordHorses == null || State.Horses.LordHorses.Count == 0) && State.Horses.LordHorsesDay < 0) { EnsureLordHorses(); } } internal void DailyLordHorses() { LordHorsesSystem.DailyLordHorses(); } public MountSpec LordMountForBattle(Hero hero) { return LordHorsesSystem.LordMountForBattle(hero); } internal void BringLordHorseIntoClan(Hero h) { LordHorsesSystem.BringLordHorseIntoClan(h); } internal void ForgetLordHorse(Hero h) { LordHorsesSystem.ForgetLordHorse(h); } public static string LordUnitFor(ContentDatabase content, string cultureId, string heroId) { CultureDef cultureDef = content?.Cultures.Get(cultureId ?? ""); if (cultureDef == null) { return ""; } List list = cultureDef.LordUnits.Where((WeightedUnit w) => w.Weight > 0.0 && content.Units.Get(w.Unit) != null).ToList(); if (list.Count == 0) { return cultureDef.HeroUnit ?? ""; } double num = list.Sum((WeightedUnit w) => w.Weight); double num2 = (double)(StableHash.Fnv1a64("lord-unit|" + heroId) % 1000000) / 1000000.0 * num; foreach (WeightedUnit item in list) { if (num2 < item.Weight) { return item.Unit; } num2 -= item.Weight; } return list[list.Count - 1].Unit; } internal void EnsureLordUnitVariety() { if (State.LordUnitsVaried) { return; } foreach (Hero item in State.Heroes.ToList()) { if (item.Occupation != HeroOccupation.Lord || item.ClanId == State.PlayerClanId || item.Id == State.PlayerHero?.Id) { continue; } Clan clan = State.Clans.Get(item.ClanId ?? ""); if (clan == null || clan.IsBandit) { continue; } CultureDef cultureDef = Content.Cultures.Get(item.CultureId ?? ""); if (cultureDef == null || cultureDef.LordUnits.Count == 0 || item.UnitId != cultureDef.HeroUnit || (item.Loadout != null && item.Loadout.HasOverrides)) { continue; } Party party = State.Parties.Get(item.PartyId ?? ""); if (party == null || string.IsNullOrEmpty(party.EncounterId)) { string text = LordUnitFor(Content, item.CultureId, item.Id); if (!string.IsNullOrEmpty(text)) { item.UnitId = text; } } } State.LordUnitsVaried = true; } public bool IsMerchantCaravan(Party p) { return MerchantCaravansSystem.IsMerchantCaravan(p); } public CaravanState MerchantCaravanOf(string townId) { return MerchantCaravansSystem.MerchantCaravanOf(townId); } public void EnsureMerchantCaravans() { MerchantCaravansSystem.EnsureMerchantCaravans(); } public void StartMerchantCaravans() { MerchantCaravansSystem.StartMerchantCaravans(); } internal IEnumerable Towns() { return MerchantCaravansSystem.Towns(); } public string MerchantCaravanReason(Settlement town) { return MerchantCaravansSystem.MerchantCaravanReason(town); } public List<(string unit, int count)> MerchantCaravanEscort(string cultureId, int size) { return MerchantCaravansSystem.MerchantCaravanEscort(cultureId, size); } public int MerchantCaravanSizeFor(Settlement town) { return MerchantCaravansSystem.MerchantCaravanSizeFor(town); } internal void DailyMerchantCaravans() { MerchantCaravansSystem.DailyMerchantCaravans(); } internal bool MerchantCaravanShouldGoHome(Party p) { return MerchantCaravansSystem.MerchantCaravanShouldGoHome(p); } internal void SettleMerchantAccounts(Party p, Settlement home) { MerchantCaravansSystem.SettleMerchantAccounts(p, home); } internal void PayMarket(Party p, MarketState market, long amount) { MerchantCaravansSystem.PayMarket(p, market, amount); } internal Settlement MerchantSourceTown(Party p, Settlement current, List markets) { return MerchantCaravansSystem.MerchantSourceTown(p, current, markets); } internal bool ReconcileMerchantCaravan(CaravanState c) { return MerchantCaravansSystem.ReconcileMerchantCaravan(c); } internal IEnumerable MilitaryFriendlySettlements(Party party) { return MilitaryAiSystem.MilitaryFriendlySettlements(party); } public Settlement MilitaryRecallSettlement(Party party, MilitaryPartyState record) { return MilitaryAiSystem.MilitaryRecallSettlement(party, record); } internal void MilitaryOptions(Party party, Clan clan, double strength, List<(Party party, double strength, double dist)> hostiles, List options) { MilitaryAiSystem.MilitaryOptions(party, clan, strength, hostiles, options); } internal void MilitarySettlementArrival(Party party, Settlement settlement) { MilitaryAiSystem.MilitarySettlementArrival(party, settlement); } public void DailyMilitaryParties() { MilitaryAiSystem.DailyMilitaryParties(); } internal string MilitaryBudgetPartyReason(MilitaryPartyState record, Party party) { return MilitaryBudgetsSystem.MilitaryBudgetPartyReason(record, party); } public string MilitaryPartyBudgetReason(string id, bool autoRecruit, int target, long recruitBudget, long foodBudget, long wageLimit, long reserve) { return MilitaryBudgetsSystem.MilitaryPartyBudgetReason(id, autoRecruit, target, recruitBudget, foodBudget, wageLimit, reserve); } public CommandResult SetMilitaryPartyBudget(string id, bool autoRecruit, int target, long recruitBudget, long foodBudget, long wageLimit, long reserve) { return MilitaryBudgetsSystem.SetMilitaryPartyBudget(id, autoRecruit, target, recruitBudget, foodBudget, wageLimit, reserve); } public long MilitaryRecruitBudgetRemaining(MilitaryPartyState record) { return MilitaryBudgetsSystem.MilitaryRecruitBudgetRemaining(record); } public long MilitaryFoodBudgetRemaining(MilitaryPartyState record) { return MilitaryBudgetsSystem.MilitaryFoodBudgetRemaining(record); } internal long MilitaryAvailableTreasury(MilitaryPartyState record, Clan clan) { return MilitaryBudgetsSystem.MilitaryAvailableTreasury(record, clan); } internal long MilitaryFoodPurchaseBudget(MilitaryPartyState record, Clan clan, Settlement settlement) { return MilitaryBudgetsSystem.MilitaryFoodPurchaseBudget(record, clan, settlement); } internal void BeginMilitarySpending(MilitaryPartyState record) { MilitaryBudgetsSystem.BeginMilitarySpending(record); } internal string MilitaryRecruitmentBaseReason(MilitaryPartyState record, Party party) { return MilitaryBudgetsSystem.MilitaryRecruitmentBaseReason(record, party); } internal int MilitaryRecruitCandidate(MilitaryPartyState record, Party party, Settlement settlement) { return MilitaryBudgetsSystem.MilitaryRecruitCandidate(record, party, settlement); } public string MilitaryRecruitmentStatus(string id) { return MilitaryBudgetsSystem.MilitaryRecruitmentStatus(id); } internal void RecruitMilitaryParty(Party party, Settlement settlement) { MilitaryBudgetsSystem.RecruitMilitaryParty(party, settlement); } public void EnsureMilitaryPartyFields() { MilitaryPartiesSystem.EnsureMilitaryPartyFields(); } public MilitaryPartyState MilitaryPartyFor(Party party) { return MilitaryPartiesSystem.MilitaryPartyFor(party); } public bool IsPlayerMilitaryParty(Party party) { return MilitaryPartiesSystem.IsPlayerMilitaryParty(party); } internal static bool MilitaryFinite(double value) { return MilitaryPartiesSystem.MilitaryFinite(value); } internal static long MilitaryTroopCount(TroopRoster roster) { return MilitaryPartiesSystem.MilitaryTroopCount(roster); } public string LaunchMilitaryPartyReason(string heroId, string unitId) { return MilitaryPartiesSystem.LaunchMilitaryPartyReason(heroId, unitId); } public CommandResult LaunchMilitaryParty(string heroId, string unitId) { return MilitaryPartiesSystem.LaunchMilitaryParty(heroId, unitId); } internal string MilitaryRosterMergeReason(TroopRoster source, TroopRoster destination, bool prisoners) { return MilitaryPartiesSystem.MilitaryRosterMergeReason(source, destination, prisoners); } public string MilitaryPartyActionReason(string id, string action) { return MilitaryPartiesSystem.MilitaryPartyActionReason(id, action); } public CommandResult SetMilitaryPartyDirective(string id, MilitaryPartyDirective directive) { return MilitaryPartiesSystem.SetMilitaryPartyDirective(id, directive); } public CommandResult DisbandMilitaryParty(string id) { return MilitaryPartiesSystem.DisbandMilitaryParty(id); } internal bool MilitaryPartyReserved(string partyId) { return MilitaryRecoverySystem.MilitaryPartyReserved(partyId); } public void ReconcileMilitaryParties() { MilitaryRecoverySystem.ReconcileMilitaryParties(); } public bool TrimMilitaryPartyHistory() { return MilitaryRecoverySystem.TrimMilitaryPartyHistory(); } public string MilitaryTroopTransferReason(string id, string unitId, int count, bool toMilitary) { return MilitaryTransfersSystem.MilitaryTroopTransferReason(id, unitId, count, toMilitary); } public CommandResult TransferMilitaryTroops(string id, string unitId, int count, bool toMilitary) { return MilitaryTransfersSystem.TransferMilitaryTroops(id, unitId, count, toMilitary); } public string MilitaryFoodTransferReason(string id, double amount, bool toMilitary) { return MilitaryTransfersSystem.MilitaryFoodTransferReason(id, amount, toMilitary); } public CommandResult TransferMilitaryFood(string id, double amount, bool toMilitary) { return MilitaryTransfersSystem.TransferMilitaryFood(id, amount, toMilitary); } public SpeedBreakdown ComputeSpeed(Party p) { return MovementSystem.ComputeSpeed(p); } internal SpeedBreakdown ComputeUnaccompaniedSpeed(Party p) { return MovementSystem.ComputeUnaccompaniedSpeed(p); } public double SightRange(Party p) { return MovementSystem.SightRange(p); } public double PlayerNightSight() { return MovementSystem.PlayerNightSight(); } public double NightSight(Party p, int scouting) { return MovementSystem.NightSight(p, scouting); } public bool SetMoveOrder(Party p, OrderKind kind, Vec2 point, string targetId = "", string reason = "") { return MovementSystem.SetMoveOrder(p, kind, point, targetId, reason); } public void ClearOrder(Party p) { MovementSystem.ClearOrder(p); } internal List MoveParties(double hours) { return MovementSystem.MoveParties(hours); } public bool CanEnter(Party p, Settlement s) { return MovementSystem.CanEnter(p, s); } internal void TryEnterSettlement(Party p, Settlement s) { MovementSystem.TryEnterSettlement(p, s); } internal void LeaveSettlementInternal(Party p) { MovementSystem.LeaveSettlementInternal(p); } public bool CanSee(Party observer, Party target) { return MovementSystem.CanSee(observer, target); } internal void UpdateVisibility() { MovementSystem.UpdateVisibility(); } public static int EstimateCount(int n) { return MovementSystem.EstimateCount(n); } internal void ExpireSightings() { MovementSystem.ExpireSightings(); } public bool IsKnownToPlayer(Party p) { return MovementSystem.IsKnownToPlayer(p); } public bool IsPlayerCaravan(Party p) { return MovementSystem.IsPlayerCaravan(p); } public string NamedCustodyIntegrityReason(string heroId) { return NamedCustodySystem.NamedCustodyIntegrityReason(heroId); } public Clan HeroCaptorClan(Hero hero) { return NamedCustodySystem.HeroCaptorClan(hero); } internal bool NamedCustodyPartyReserved(string partyId) { return NamedCustodySystem.NamedCustodyPartyReserved(partyId); } public bool NamedCustodyReserved(Hero hero) { return NamedCustodySystem.NamedCustodyReserved(hero); } public string NamedPrisonerActionReason(string heroId, bool inDungeon) { return NamedCustodySystem.NamedPrisonerActionReason(heroId, inDungeon); } public string PrisonerHeroTransferReason(string heroId, bool toDungeon) { return NamedCustodySystem.PrisonerHeroTransferReason(heroId, toDungeon); } public CommandResult TransferPrisonerHero(string heroId, bool toDungeon) { return NamedCustodySystem.TransferPrisonerHero(heroId, toDungeon); } public CommandResult ReleasePrisonerHero(string heroId, bool inDungeon) { return NamedCustodySystem.ReleasePrisonerHero(heroId, inDungeon); } public void EnsureNotableFields() { NotablesSystem.EnsureNotableFields(); } public NotableState SettlementNotable(string settlementId) { return NotablesSystem.SettlementNotable(settlementId); } public int NotableRelationFor(string clanId, NotableState notable) { return NotablesSystem.NotableRelationFor(clanId, notable); } public void AdjustNotableRelation(string notableId, int delta, string reason) { NotablesSystem.AdjustNotableRelation(notableId, delta, reason); } public void ReplaceUnavailableNotables() { NotablesSystem.ReplaceUnavailableNotables(); } public bool TryBeginRecruitPoolRecovery(Settlement settlement) { return NotablesSystem.TryBeginRecruitPoolRecovery(settlement); } public string RecruitSlotRelationReason(Settlement settlement, RecruitSlot slot, string clanId) { return NotablesSystem.RecruitSlotRelationReason(settlement, slot, clanId); } public string RecruitmentReason(int slotIndex) { return NotablesSystem.RecruitmentReason(slotIndex); } internal void EnsurePactFields(ref bool changed) { PactsSystem.EnsurePactFields(ref changed); } internal static bool Pair(DiplomaticAgreement x, string a, string b) { return PactsSystem.Pair(x, a, b); } public bool Allied(string a, string b) { return PactsSystem.Allied(a, b); } public bool HasTradeAgreement(string a, string b) { return PactsSystem.HasTradeAgreement(a, b); } public DiplomaticAgreement TributeBetween(string a, string b) { return PactsSystem.TributeBetween(a, b); } public List AgreementsOf(string faction) { return PactsSystem.AgreementsOf(faction); } public List PendingCallsTo(string faction) { return PactsSystem.PendingCallsTo(faction); } public double WarAdvantage(string a, string b) { return PactsSystem.WarAdvantage(a, b); } internal void RecordWarCapture(string captorFaction, string loserFaction, string settlementId) { PactsSystem.RecordWarCapture(captorFaction, loserFaction, settlementId); } internal long TributeFor(double advantage) { return PactsSystem.TributeFor(advantage); } public List PeaceOffers(string targetKingdomId) { return PactsSystem.PeaceOffers(targetKingdomId); } public CommandResult NegotiatePeace(string targetKingdomId, PeaceTermKind kind) { return PactsSystem.NegotiatePeace(targetKingdomId, kind); } internal string MakeNegotiatedPeace(string a, string b, string payer, long dailyTribute) { return PactsSystem.MakeNegotiatedPeace(a, b, payer, dailyTribute); } internal DiplomaticAgreement AddAgreement(AgreementKind kind, string a, string b, int days, string payer = "", string recipient = "", long daily = 0L) { return PactsSystem.AddAgreement(kind, a, b, days, payer, recipient, daily); } public PactQuote QuoteAlliance(string targetKingdomId) { return PactsSystem.QuoteAlliance(targetKingdomId); } public CommandResult ProposeAlliance(string targetKingdomId) { return PactsSystem.ProposeAlliance(targetKingdomId); } public PactQuote QuoteTradeAgreement(string targetKingdomId) { return PactsSystem.QuoteTradeAgreement(targetKingdomId); } public CommandResult ProposeTradeAgreement(string targetKingdomId) { return PactsSystem.ProposeTradeAgreement(targetKingdomId); } internal void AddPactProsperity(StatForecast f, Settlement s) { PactsSystem.AddPactProsperity(f, s); } public PactQuote QuoteCallToWar(string allyId, string enemyId, long payment) { return PactsSystem.QuoteCallToWar(allyId, enemyId, payment); } public CommandResult CallAllyToWar(string allyId, string enemyId, long payment) { return PactsSystem.CallAllyToWar(allyId, enemyId, payment); } internal CallToWarRequest NewCall(string caller, string ally, string enemy, long payment) { return PactsSystem.NewCall(caller, ally, enemy, payment); } public string AnswerCallToWarReason(string callId, bool accept) { return PactsSystem.AnswerCallToWarReason(callId, accept); } public CommandResult AnswerCallToWar(string callId, bool accept) { return PactsSystem.AnswerCallToWar(callId, accept); } internal void DailyPacts() { PactsSystem.DailyPacts(); } internal void AiPacts() { PactsSystem.AiPacts(); } public bool EatsCargoFood(Party p) { return PartyFoodSystem.EatsCargoFood(p); } public int EdibleCargoTotal(Party p) { return PartyFoodSystem.EdibleCargoTotal(p); } public static double Provisions(Party p) { return PartyFoodSystem.Provisions(p); } public double FoodSupply(Party p) { return PartyFoodSystem.FoodSupply(p); } internal double TakeFood(Party p, double amount) { return PartyFoodSystem.TakeFood(p, amount); } public string FoodSupplyBreakdown(Party p) { return PartyFoodSystem.FoodSupplyBreakdown(p); } public static int ClanTier(Clan clan) { return PartySizesSystem.ClanTier(clan); } public bool IsAiLordParty(Party p) { return PartySizesSystem.IsAiLordParty(p); } internal int AiLordPartySizeLimit(Party p) { return PartySizesSystem.AiLordPartySizeLimit(p); } public static double LordTemperament(string heroId) { return PartySizesSystem.LordTemperament(heroId); } public bool ClanAtWar(Clan clan) { return PartySizesSystem.ClanAtWar(clan); } public bool ClanCanGrowParty(Clan clan, double extraDaily) { return PartySizesSystem.ClanCanGrowParty(clan, extraDaily); } public static double LordMuster(string heroId) { return PartySizesSystem.LordMuster(heroId); } public static string LordMusterName(double muster) { return PartySizesSystem.LordMusterName(muster); } internal double LordUpkeepShare(Party p) { return PartySizesSystem.LordUpkeepShare(p); } public bool LordCanGrowParty(Party p, double extraDaily) { return PartySizesSystem.LordCanGrowParty(p, extraDaily); } public int AiLordRecruitTarget(Party p) { return PartySizesSystem.AiLordRecruitTarget(p); } public static bool IsPerkActive(Hero hero, HeroPerkDef perk) { return PerksSystem.IsActive(hero, perk); } public double PersonalPerk(Hero hero, PerkEffect effect, string target = null) { return PerksSystem.PersonalPerk(hero, effect, target); } public double PartyPerk(Party party, PerkEffect effect, string target = null) { return PerksSystem.PartyPerk(party, effect, target); } public static string RoleSkillId(PartyRole role) { return CompanionsSystem.RoleSkillId(role); } public double PartyPerkFrom(Party party, PartyRole role, PerkEffect effect) { if (party == null || party.ClanId != State.PlayerClanId) { return 0.0; } Hero hero = RoleHolder(party, role); if (hero != null) { return PerksSystem.HeroValue(hero, effect, PerksSystem.RoleScope(role)); } return 0.0; } public double ClanPerk(Clan clan, PerkEffect effect) { return PerksSystem.ClanPerk(clan, effect); } public double SettlementPerk(Settlement settlement, PerkEffect effect) { return PerksSystem.SettlementPerk(settlement, effect); } internal int RelationPerkBonus() { return (int)Math.Round(Math.Max(0.0, PersonalPerk(State.PlayerHero, PerkEffect.RelationBonus))); } public string CombatantWeaponSkill(Combatant c) { return PerksSystem.CombatantWeaponSkill(c); } public double CombatantDamageMultiplier(Combatant c) { return PerksSystem.DamageMultiplier(c); } public double CombatantDamageTakenMultiplier(Combatant c) { return PerksSystem.DamageTakenMultiplier(c); } public double BattleHealthMultiplier(Combatant c) { return DifficultyHealthMultiplier(c) * PerksSystem.TroopHealthMultiplier(c); } public string PersuasionReason(PersuasionGoal goal, string heroId, string targetId = "", string partyId = "") { return PersuasionSystem.Reason(goal, heroId, targetId, partyId); } public PersuasionSession StartPersuasion(PersuasionGoal goal, string heroId, string targetId = "", string partyId = "") { return PersuasionSystem.Start(goal, heroId, targetId, partyId); } public PersuasionOutcome Argue(PersuasionSession s, string argumentId) { return PersuasionSystem.Argue(s, argumentId); } public void AbandonPersuasion(PersuasionSession s) { PersuasionSystem.Finish(s, won: false); } public bool RecruitPersuaded(string clanId) { return PersuasionSystem.RecruitPersuaded(clanId); } public List CaptivesToPlead(Hero lord) { return PersuasionSystem.CaptivesToPlead(lord); } public void UpdatePlayerTimeStates() { PlayerSystem.UpdatePlayerTimeStates(); } internal CommandResult RequireFree() { return PlayerSystem.RequireFree(); } public CommandResult MoveTo(Vec2 point) { return PlayerSystem.MoveTo(point); } public CommandResult GoToSettlement(string settlementId) { return PlayerSystem.GoToSettlement(settlementId); } public CommandResult EngageParty(string partyId) { return PlayerSystem.EngageParty(partyId); } public CommandResult FollowParty(string partyId) { return PlayerSystem.FollowParty(partyId); } public string MeetPartyReason(string partyId) { return PlayerSystem.MeetPartyReason(partyId); } public Party PartyOfHero(string heroId) { return PlayerSystem.PartyOfHero(heroId); } public CommandResult Stop() { return PlayerSystem.Stop(); } public CommandResult Wait(double hours) { return PlayerSystem.Wait(hours); } public CommandResult WaitInSettlement() { return PlayerSystem.WaitInSettlement(); } public CommandResult WaitHere() { return PlayerSystem.WaitHere(); } public CommandResult LeaveSettlement() { return PlayerSystem.LeaveSettlement(); } internal Settlement CurrentSettlement() { return PlayerSystem.CurrentSettlement(); } public CommandResult Recruit(int slotIndex) { return PlayerSystem.Recruit(slotIndex); } public CommandResult SellPrisoners() { return PlayerSystem.SellPrisoners(); } public CommandResult UpgradeTroops(string fromUnit, string toUnit, int count) { return PlayerSystem.UpgradeTroops(fromUnit, toUnit, count); } public CommandResult TransferToGarrison(string unitId, int count) { return PlayerSystem.TransferToGarrison(unitId, count); } public string TroopReleaseReason(string unitId, int count) { return PlayerSystem.TroopReleaseReason(unitId, count); } public CommandResult ReleaseTroops(string unitId, int count) { return PlayerSystem.ReleaseTroops(unitId, count); } public CommandResult TakeFromGarrison(string unitId, int count) { return PlayerSystem.TakeFromGarrison(unitId, count); } public void AcknowledgeReport() { PlayerSystem.AcknowledgeReport(); } public EncounterOptions GetEncounterOptions() { return PlayerSystem.GetEncounterOptions(); } public CommandResult ChooseLeave() { return PlayerSystem.ChooseLeave(); } public CommandResult ChooseSacrifice() { return PlayerSystem.ChooseSacrifice(); } public CommandResult ChooseSurrender() { return PlayerSystem.ChooseSurrender(); } public CommitResult ChooseAutoResolve() { return PlayerSystem.ChooseAutoResolve(); } internal BattleManifest BeginAttempt(Encounter enc, int budget) { return PlayerSystem.BeginAttempt(enc, budget); } public BattlePlan PrepareBattle(int? budgetOverride = null) { return PlayerSystem.PrepareBattle(budgetOverride); } public string ValidateInitialSelection(BattlePlan plan, IList playerChoice) { return PlayerSystem.ValidateInitialSelection(plan, playerChoice); } public CommandResult CancelPreparation() { return PlayerSystem.CancelPreparation(); } public string BeginBattle() { return PlayerSystem.BeginBattle(); } public CommitResult SubmitBattleResult(BattleResult result) { return PlayerSystem.SubmitBattleResult(result); } public void AbortBattle(string reason) { PlayerSystem.AbortBattle(reason); } public bool RecoverPlayerEncounter(string reason) { return PlayerSystem.RecoverPlayerEncounter(reason); } public (BattleMapDef map, bool standIn) SelectBattleMap(Encounter enc) { return PlayerSystem.SelectBattleMap(enc); } public bool LawInForce(string kingdomId, KingdomLaw law) { return PoliciesSystem.LawInForce(kingdomId, law); } public List LawsInForce(string kingdomId) { return PoliciesSystem.LawsInForce(kingdomId); } internal bool LawAt(Settlement s, KingdomLaw law) { return PoliciesSystem.LawAt(s, law); } public double LawTaxFactor(Settlement s) { return PoliciesSystem.LawTaxFactor(s); } internal void AddLawLoyalty(StatForecast f, Settlement s) { PoliciesSystem.AddLawLoyalty(f, s); } public double LawSecurity(Settlement s) { return PoliciesSystem.LawSecurity(s); } internal void AddLawProsperity(StatForecast f, Settlement s) { PoliciesSystem.AddLawProsperity(f, s); } public double LawMilitiaFactor(Settlement s) { return PoliciesSystem.LawMilitiaFactor(s); } public double LawGarrisonWageFactor(Settlement s) { return PoliciesSystem.LawGarrisonWageFactor(s); } public double LawPartySizeFactor(Party p) { return PoliciesSystem.LawPartySizeFactor(p); } public double LawFoodFactor(Party p) { return PoliciesSystem.LawFoodFactor(p); } public double LawInfluence(Clan clan, string kingdomId) { return PoliciesSystem.LawInfluence(clan, kingdomId); } public double LawBattleInfluenceFactor(Clan clan) { return PoliciesSystem.LawBattleInfluenceFactor(clan); } internal int LawBallotMultiplier(KingdomDecision decision, string clanId) { return PoliciesSystem.LawBallotMultiplier(decision, clanId); } public int PlayerProposalCost() { return PoliciesSystem.PlayerProposalCost(); } public int ExecutionInfluenceCost(Clan clan) { return PoliciesSystem.ExecutionInfluenceCost(clan); } internal void DailyLawIncome() { PoliciesSystem.DailyLawIncome(); } public string ProposeLawReason(KingdomLaw law, bool repeal) { return PoliciesSystem.ProposeLawReason(law, repeal); } public CommandResult ProposeLaw(KingdomLaw law, bool repeal) { return PoliciesSystem.ProposeLaw(law, repeal); } internal string LawDecisionStaleReason(KingdomDecision decision) { return PoliciesSystem.LawDecisionStaleReason(decision); } internal void ApplyLawDecision(KingdomDecision decision, out string effect) { PoliciesSystem.ApplyLawDecision(decision, out effect); } internal bool CouncilLawPreference(KingdomDecision decision, Clan clan, out string reason) { return PoliciesSystem.CouncilLawPreference(decision, clan, out reason); } internal void DailyLawProposals() { PoliciesSystem.DailyLawProposals(); } public void EnsurePoliticsFields() { PoliticsSystem.EnsurePoliticsFields(); } internal bool LivingPoliticalClan(Clan clan) { return PoliticsSystem.LivingPoliticalClan(clan); } public IEnumerable CouncilMembers(string kingdomId) { return PoliticsSystem.CouncilMembers(kingdomId); } public string PlayerCouncilReason() { return PoliticsSystem.PlayerCouncilReason(); } public void AddPoliticalInfluence(Clan clan, double amount) { PoliticsSystem.AddPoliticalInfluence(clan, amount); } public void DailyPoliticalInfluence() { PoliticsSystem.DailyPoliticalInfluence(); } public void RecordPoliticalBattleInfluence(Encounter encounter, BattleResult result, BattleReport report) { PoliticsSystem.RecordPoliticalBattleInfluence(encounter, result, report); } public int ClanRelation(string a, string b) { return PoliticsSystem.ClanRelation(a, b); } public void AdjustClanRelation(string a, string b, int delta) { PoliticsSystem.AdjustClanRelation(a, b, delta); } public string ClanGiftReason(string targetClanId, long amount) { return PoliticsSystem.ClanGiftReason(targetClanId, amount); } public CommandResult GiveClanGift(string targetClanId, long amount) { return PoliticsSystem.GiveClanGift(targetClanId, amount); } public RealmPolicy RealmPolicyFor(string kingdomId) { return PoliticsSystem.RealmPolicyFor(kingdomId); } internal RealmPolicy RealmPolicyAt(Settlement settlement) { return PoliticsSystem.RealmPolicyAt(settlement); } public double RealmPolicyTaxFactor(Settlement settlement) { return PoliticsSystem.RealmPolicyTaxFactor(settlement); } public double RealmPolicyLoyaltyChange(Settlement settlement) { return PoliticsSystem.RealmPolicyLoyaltyChange(settlement); } public TradeQuote QuotePrisonerRansom(string unitId, int count) { return PrisonerRansomsSystem.QuotePrisonerRansom(unitId, count); } public TradeQuote QuoteAllPrisonerRansom() { return PrisonerRansomsSystem.QuoteAllPrisonerRansom(); } public CommandResult RansomPrisoners(string unitId, int count) { return PrisonerRansomsSystem.RansomPrisoners(unitId, count); } public CommandResult RansomAllOrdinaryPrisoners() { return PrisonerRansomsSystem.RansomAllOrdinaryPrisoners(); } public TradeQuote HeroRansomQuote(string heroId, bool buyback, bool inDungeon = false) { return PrisonerRansomsSystem.HeroRansomQuote(heroId, buyback, inDungeon); } public CommandResult RansomPrisonerHero(string heroId, bool inDungeon = false) { return PrisonerRansomsSystem.RansomPrisonerHero(heroId, inDungeon); } public CommandResult RansomClanHero(string heroId) { return PrisonerRansomsSystem.RansomClanHero(heroId); } public double PrisonerRecruitmentDays(string unitId) { return PrisonersSystem.PrisonerRecruitmentDays(unitId); } public int PrisonerReadyCount(TroopStack stack) { return PrisonersSystem.PrisonerReadyCount(stack); } internal string PrisonerCommandReason() { return PrisonersSystem.PrisonerCommandReason(); } internal string PrisonerStackReason(TroopRoster roster, string unitId, int count) { return PrisonersSystem.PrisonerStackReason(roster, unitId, count); } public string PrisonerRecruitmentReason(string unitId, int count) { return PrisonersSystem.PrisonerRecruitmentReason(unitId, count); } public CommandResult RecruitPrisoners(string unitId, int count) { return PrisonersSystem.RecruitPrisoners(unitId, count); } public string PrisonerReleaseReason(string unitId, int count) { return PrisonersSystem.PrisonerReleaseReason(unitId, count); } public CommandResult ReleasePrisoners(string unitId, int count) { return PrisonersSystem.ReleasePrisoners(unitId, count); } public string PrisonerHeroReleaseReason(string heroId) { return PrisonersSystem.PrisonerHeroReleaseReason(heroId); } public CommandResult ReleasePrisonerHero(string heroId) { return PrisonersSystem.ReleasePrisonerHero(heroId); } public Settlement PrisonerDungeon() { return PrisonersSystem.PrisonerDungeon(); } public string PrisonerTransferReason(string unitId, int count, bool toDungeon) { return PrisonersSystem.PrisonerTransferReason(unitId, count, toDungeon); } public CommandResult TransferPrisoners(string unitId, int count, bool toDungeon) { return PrisonersSystem.TransferPrisoners(unitId, count, toDungeon); } public string PrisonerRansomReason() { return PrisonersSystem.PrisonerRansomReason(); } public void DailyPrisonerCare() { PrisonersSystem.DailyPrisonerCare(); } public void EnsureHeroProgressionFields() { ProgressionSystem.EnsureHeroProgressionFields(); } public static long HeroXpForLevel(int level) { return ProgressionSystem.HeroXpForLevel(level); } public static int HeroLevelForXp(long xp) { return ProgressionSystem.HeroLevelForXp(xp); } public double HeroBattleHealthBonus(string heroId) { return ProgressionSystem.HeroBattleHealthBonus(heroId); } public int HeroLevel(Hero hero) { return ProgressionSystem.HeroLevel(hero); } public void GrantHeroExperience(Hero hero, int xp) { ProgressionSystem.GrantHeroExperience(hero, xp); } public void GrantSkillExperience(Hero hero, string skill, double xp, bool grantHeroXp = true) { ProgressionSystem.GrantSkillExperience(hero, skill, xp, grantHeroXp); } public void ApplyRoleTraining(Party party, PartyRole role, Hero worker, double work) { ProgressionSystem.ApplyRoleTraining(party, role, worker, work); } public void GrantDailySkillExperience(Hero hero, string skill, double xp, double limit) { ProgressionSystem.GrantDailySkillExperience(hero, skill, xp, limit); } public string HeroPerkChoiceReason(string heroId, string perkId) { return ProgressionSystem.HeroPerkChoiceReason(heroId, perkId); } public bool HasPerkToChoose(string heroId) { return ProgressionSystem.HasPerkToChoose(heroId); } public CommandResult ChooseHeroPerk(string heroId, string perkId) { return ProgressionSystem.ChooseHeroPerk(heroId, perkId); } public bool HasRolePerk(Party party, PartyRole role, string perkId) { return ProgressionSystem.HasRolePerk(party, role, perkId); } internal DiscoverySite NewQuestSite(QuestState q, SiteKind kind, string name, Vec2 near, double min, double max, RandomStream rng) { return QuestChainsSystem.NewQuestSite(q, kind, name, near, min, max, rng); } internal string GiveRelicWeapon(string name, RandomStream rng) { return QuestChainsSystem.GiveRelicWeapon(name, rng); } internal UnitDef CultureSoldier(string cultureId, int maxTier, bool rare) { return QuestChainsSystem.CultureSoldier(cultureId, maxTier, rare); } public QuestState DelegatedQuestOf(string heroId) { return QuestDelegationSystem.DelegatedQuestOf(heroId); } public static bool IsDelegatedQuest(QuestState q) { return QuestDelegationSystem.IsDelegated(q); } public void EnsureQuestFields() { QuestsSystem.EnsureQuestFields(); } public QuestState Quest(string id) { return QuestsSystem.Quest(id); } internal QuestState OpenQuestFrom(string giverId) { return QuestsSystem.OpenQuestFrom(giverId); } public string QuestWorkReason(string giverId) { return QuestsSystem.QuestWorkReason(giverId); } public CommandResult DeveloperOfferQuest(string templateId, string giverId, out string questId) { return QuestsSystem.DeveloperOfferQuest(templateId, giverId, out questId); } public CommandResult DeveloperRevealSites() { return QuestsSystem.DeveloperRevealSites(); } public CommandResult AskForWork(string giverId, out string questId) { return QuestsSystem.AskForWork(giverId, out questId); } internal string QuestActionReason() { return QuestsSystem.QuestActionReason(); } public StoryPrompt QuestPrompt(string questId, string talkingToHeroId = "") { return QuestsSystem.QuestPrompt(questId, talkingToHeroId); } public CommandResult ChooseQuestOption(string questId, string optionId, string talkingToHeroId = "") { return QuestsSystem.ChooseQuestOption(questId, optionId, talkingToHeroId); } public CommandResult AbandonQuest(string questId) { return QuestsSystem.AbandonQuest(questId); } public CommandResult TrackQuest(string questId) { return QuestsSystem.TrackQuest(questId); } internal void QuestLog(QuestState q, string text) { QuestsSystem.QuestLog(q, text); } internal void EndQuest(QuestState q, QuestStatus status, string result, int relationPenalty = 0) { QuestsSystem.EndQuest(q, status, result, relationPenalty); } internal bool HoldQuestEscrow(QuestState q, long amount, Clan clan, Settlement market) { return QuestsSystem.HoldQuestEscrow(q, amount, clan, market); } internal void RefundQuestEscrow(QuestState q) { QuestsSystem.RefundQuestEscrow(q); } internal long MoveMarketGold(Settlement from, Settlement to, long amount) { return QuestsSystem.MoveMarketGold(from, to, amount); } internal bool PlayerPaysMarket(Settlement s, long amount, string reason) { return QuestsSystem.PlayerPaysMarket(s, amount, reason); } internal static double Clamp100(double v) { return QuestsSystem.Clamp100(v); } internal void DailyQuests() { QuestsSystem.DailyQuests(); } internal void HourlyQuests() { QuestsSystem.HourlyQuests(); } public void RecordQuestBattle(Encounter encounter, BattleResult result, BattleReport report) { QuestsSystem.RecordQuestBattle(encounter, result, report); } internal void RecordQuestRaid(Settlement village) { QuestsSystem.RecordQuestRaid(village); } public List JournalEntries(bool open) { return QuestsSystem.JournalEntries(open); } internal string KnownPartyWhereabouts(string partyId) { return QuestsSystem.KnownPartyWhereabouts(partyId); } public List QuestPlacesFor(string questId) { return QuestsSystem.QuestPlacesFor(questId); } public List QuestsWithDecisionHere() { return QuestsSystem.QuestsWithDecisionHere(); } internal Settlement NearestHideout(Vec2 near) { return QuestsSystem.NearestHideout(near); } internal Vec2 QuestSpotNear(Vec2 centre, double min, double max, RandomStream rng) { return QuestsSystem.QuestSpotNear(centre, min, max, rng); } internal Party SpawnQuestBand(Vec2 near, string name, int size, List units, RandomStream rng) { return QuestsSystem.SpawnQuestBand(near, name, size, units, rng); } internal static bool PartyGone(Party p) { return QuestsSystem.PartyGone(p); } internal int HandableTroops(int minTier) { return QuestsSystem.HandableTroops(minTier); } internal List TakeTroops(int count, int minTier, TroopRoster into) { return QuestsSystem.TakeTroops(count, minTier, into); } internal int JoinPlayer(string unitId, int count) { return QuestsSystem.JoinPlayer(unitId, count); } internal int Skill(string skill) { return QuestsSystem.Skill(skill); } internal bool EscortingWagons() { return ActiveQuests.Any((QuestState q) => q.TemplateId == "notable.escort" && q.Stage == "escort" && !IsDelegatedQuest(q)); } internal void AddQuestTalkOptions(Conversation c, Hero h) { QuestsLordSystem.AddQuestTalkOptions(c, h); } internal void BuildQuestTalkOptions(Conversation c, string questId) { QuestsLordSystem.BuildQuestTalkOptions(c, questId); } internal bool AnswerQuestTalk(Conversation c, Hero h, string id) { return QuestsLordSystem.AnswerQuestTalk(c, h, id); } internal static long Round10(double v) { return QuestsNotableSystem.Round10(v); } internal static void QuestLog(Campaign c, QuestState q, string text) { QuestsNotableSystem.QuestLog(c, q, text); } internal void LordRaidOptions(Party party, Clan clan, double myStrength, List<(Party party, double strength, double dist)> hostiles, List options) { RaidAiSystem.LordRaidOptions(party, clan, myStrength, hostiles, options); } public int RaidDefenders(Settlement settlement) { return RaidsSystem.RaidDefenders(settlement); } public int RaidDurationMinutes(Party party, Settlement settlement) { return RaidsSystem.RaidDurationMinutes(party, settlement); } public bool IsVillageBeingRaided(Settlement settlement) { return RaidsSystem.IsVillageBeingRaided(settlement); } public string RaidOrderReason(Party party, Settlement settlement) { return RaidsSystem.RaidOrderReason(party, settlement); } public string RaidReason(string settlementId) { return RaidsSystem.RaidReason(settlementId); } public CommandResult RaidVillage(string settlementId) { return RaidsSystem.RaidVillage(settlementId); } public CommandResult TryStartRaid(Party party, Settlement settlement) { return RaidsSystem.TryStartRaid(party, settlement); } public void CancelRaid(Party party, string reason, bool notify = true) { RaidsSystem.CancelRaid(party, reason, notify); } public void UpdateRaids(bool advanceProgress = true) { RaidsSystem.UpdateRaids(advanceProgress); } public void EnsureRebellionFields() { RebellionsSystem.EnsureRebellionFields(); } public CommandResult SetRebellionsEnabled(bool on) { return RebellionsSystem.SetRebellionsEnabled(on); } public double UnrestRate(Settlement s) { return RebellionsSystem.UnrestRate(s); } public RebellionRecord RebellionOf(string clanId) { return RebellionsSystem.RebellionOf(clanId); } public bool IsRebelClan(string clanId) { return RebellionsSystem.IsRebelClan(clanId); } public string RebellionRiskReason(Settlement s) { return RebellionsSystem.RebellionRiskReason(s); } internal void DailyRebellions() { RebellionsSystem.DailyRebellions(); } public CommandResult DeveloperStartRebellion(string settlementId) { return RebellionsSystem.DeveloperStartRebellion(settlementId); } public string RescuedTroopRecruitmentReason(string encounterId, string unitId, int count) { return RescuedTroopsSystem.RescuedTroopRecruitmentReason(encounterId, unitId, count); } public CommandResult RecruitRescuedTroops(string encounterId, string unitId, int count) { return RescuedTroopsSystem.RecruitRescuedTroops(encounterId, unitId, count); } public string RescuedTroopReleaseReason(string encounterId, string unitId, int count) { return RescuedTroopsSystem.RescuedTroopReleaseReason(encounterId, unitId, count); } public CommandResult ReleaseRescuedTroops(string encounterId, string unitId, int count) { return RescuedTroopsSystem.ReleaseRescuedTroops(encounterId, unitId, count); } public void EnsureScoutingFields() { ScoutingSystem.EnsureScoutingFields(); } public List ScoutOffers(Settlement town) { return ScoutingSystem.ScoutOffers(town); } public IEnumerable ScoutTargets() { return ScoutingSystem.ScoutTargets(); } public string ScoutHireReason(int index, string targetId) { return ScoutingSystem.ScoutHireReason(index, targetId); } public CommandResult HireScout(int index, string targetId) { return ScoutingSystem.HireScout(index, targetId); } public long ScoutTravelMinutes(Settlement from, Settlement target) { return ScoutingSystem.ScoutTravelMinutes(from, target); } public ScoutReportState ScoutReport(string settlementId) { return ScoutingSystem.ScoutReport(settlementId); } public static string ScoutRange(int low, int high) { return ScoutingSystem.Range(low, high); } internal void HourlyScouting() { ScoutingSystem.HourlyScouting(); } public void EnsureServiceFields() { ServiceSystem.EnsureServiceFields(); } public Clan ServiceRuler(string kingdomId) { return ServiceSystem.ServiceRuler(kingdomId); } public IEnumerable ServiceHoldings() { return ServiceSystem.ServiceHoldings(); } public string ServiceJoinReason(string kingdomId, bool asVassal) { return ServiceSystem.ServiceJoinReason(kingdomId, asVassal); } public CommandResult JoinKingdomService(string kingdomId, bool asVassal) { return ServiceSystem.JoinKingdomService(kingdomId, asVassal); } public string LeaveServiceReason(bool relinquishFiefs) { return ServiceSystem.LeaveServiceReason(relinquishFiefs); } public CommandResult LeaveService(bool relinquishFiefs) { return ServiceSystem.LeaveService(relinquishFiefs); } internal void BecomeIndependent() { ServiceSystem.BecomeIndependent(); } public void DailyService() { ServiceSystem.DailyService(); } public void EnsureBudgetFields() { SettlementBudgetsSystem.EnsureBudgetFields(); } public static int ProjectMaxLevel(string id) { return SettlementBudgetsSystem.ProjectMaxLevel(id); } public int PlannedProjectLevel(Settlement s, string id) { return SettlementBudgetsSystem.PlannedProjectLevel(s, id); } public string QueueProjectReason(string id) { return SettlementBudgetsSystem.QueueProjectReason(id); } public CommandResult QueueSettlementProject(string id) { return SettlementBudgetsSystem.QueueSettlementProject(id); } public string RemoveQueuedProjectReason(int index) { return SettlementBudgetsSystem.RemoveQueuedProjectReason(index); } public CommandResult RemoveQueuedProject(int index) { return SettlementBudgetsSystem.RemoveQueuedProject(index); } public long QueuedProjectCost(Settlement s, string id) { return SettlementBudgetsSystem.QueuedProjectCost(s, id); } public long ProjectMaterialsCost(Settlement s, string goodId, int count) { return SettlementBudgetsSystem.MaterialsCost(s, goodId, count); } internal bool StartNextQueuedProject(Settlement s) { return SettlementBudgetsSystem.StartNextQueuedProject(s); } public string SettlementBudgetReason() { return SettlementBudgetsSystem.BudgetReason(); } public CommandResult SetGarrisonWageLimit(long limit) { return SettlementBudgetsSystem.SetGarrisonWageLimit(limit); } public string GarrisonAutoRecruitReason(bool on) { return SettlementBudgetsSystem.GarrisonAutoRecruitReason(on); } public CommandResult SetGarrisonAutoRecruit(bool on) { return SettlementBudgetsSystem.SetGarrisonAutoRecruit(on); } public CommandResult SetGovernorBudget(long budget) { return SettlementBudgetsSystem.SetGovernorBudget(budget); } public long ImportedFoodPrice() { return SettlementBudgetsSystem.ImportedFoodPrice(); } public static string HardshipTier(double hardship) { return SettlementBudgetsSystem.HardshipTier(hardship); } public static string HardshipEffects(double hardship) { return SettlementBudgetsSystem.HardshipEffects(hardship); } public StatForecast HardshipPressure(Settlement s) { return SettlementBudgetsSystem.HardshipPressure(s); } public double HardshipChange(Settlement s) { return SettlementBudgetsSystem.HardshipChange(s); } public double HardshipTaxFactor(Settlement s) { return SettlementBudgetsSystem.HardshipTaxFactor(s); } internal double HardshipLoyalty(Settlement s) { return SettlementBudgetsSystem.HardshipLoyalty(s); } internal double HardshipProsperity(Settlement s) { return SettlementBudgetsSystem.HardshipProsperity(s); } internal double HardshipSecurity(Settlement s) { return SettlementBudgetsSystem.HardshipSecurity(s); } internal void DailySettlementBudgets(Settlement s) { SettlementBudgetsSystem.DailyBudgets(s); } public static bool IsFoodGood(string goodId) { return SettlementFoodSystem.IsFoodGood(goodId); } public double SettlementFood(Settlement s) { return SettlementFoodSystem.SettlementFood(s); } public string SettlementFoodBreakdown(Settlement s) { return SettlementFoodSystem.SettlementFoodBreakdown(s); } public string VillageFoodGood(Settlement village) { return SettlementFoodSystem.VillageFoodGood(village); } public List HomeFoods(Settlement s) { return SettlementFoodSystem.HomeFoods(s); } public static double OpeningFood(Settlement s) { return SettlementFoodSystem.OpeningFood(s); } internal double AddSettlementFood(Settlement s, string goodId, double amount) { return SettlementFoodSystem.AddSettlementFood(s, goodId, amount); } internal double TakeSettlementFood(Settlement s, double amount, out long value) { return SettlementFoodSystem.TakeSettlementFood(s, amount, out value); } internal double TakeSettlementFood(Settlement s, double amount) { return SettlementFoodSystem.TakeSettlementFood(s, amount); } public double FoodPrice(Settlement s) { return SettlementFoodSystem.FoodPrice(s); } public void SetSettlementFood(Settlement s, double amount) { SettlementFoodSystem.SetSettlementFood(s, amount); } internal bool EnsureSettlementFood() { return SettlementFoodSystem.EnsureSettlementFood(); } public static double MilitiaTradition(string settlementId) { return 0.75 + 0.5 * (double)(StableHash.Fnv1a64("militia|" + settlementId) % 1001) / 1000.0; } public static int StartingMilitia(SettlementType type, string settlementId, double prosperity) { switch (type) { case SettlementType.Town: case SettlementType.Castle: return (int)Math.Round(Math.Max(0.0, prosperity) / ((type == SettlementType.Town) ? 10.0 : 9.0) * MilitiaTradition(settlementId)); default: return 30; case SettlementType.Village: return 10; } } public IEnumerable BoundVillages(Settlement fief) { return SettlementStatsSystem.BoundVillages(fief); } public Settlement BoundFief(Settlement village) { return SettlementStatsSystem.BoundFief(village); } public VillageProductDef VillageProduct(Settlement village) { return SettlementStatsSystem.VillageProduct(village); } public double VillageFoodToFief(Settlement village) { return SettlementStatsSystem.VillageFoodToFief(village); } public bool VillageSuppliesFief(Settlement village, Settlement fief) { return SettlementStatsSystem.VillageSuppliesFief(village, fief); } public double FoodCapacity(Settlement s) { return SettlementStatsSystem.FoodCapacity(s); } public double CivilianFoodBase(Settlement s) { return SettlementStatsSystem.CivilianFoodBase(s); } public double SettlementCivilianFood(Settlement s) { return SettlementStatsSystem.SettlementCivilianFood(s); } public double SettlementMouths(Settlement s) { return SettlementStatsSystem.SettlementMouths(s); } public double SoldierFood(Settlement s) { return SettlementStatsSystem.SoldierFood(s); } public double SettlementFoodNeed(Settlement s) { return SettlementStatsSystem.SettlementFoodNeed(s); } public FoodForecast SettlementFoodForecast(Settlement s) { return SettlementStatsSystem.SettlementFoodForecast(s); } public StatForecast SettlementProsperityForecast(Settlement s) { return SettlementStatsSystem.SettlementProsperityForecast(s); } public StatForecast VillageHearthForecast(Settlement village) { return SettlementStatsSystem.VillageHearthForecast(village); } public double MilitiaTarget(Settlement s) { return SettlementStatsSystem.MilitiaTarget(s); } public StatForecast SettlementMilitiaForecast(Settlement s) { return SettlementStatsSystem.SettlementMilitiaForecast(s); } public int WallLevel(Settlement s) { return SettlementStatsSystem.WallLevel(s); } public double SiegeWallMaxHealth(SiegeState siege) { return SettlementStatsSystem.SiegeWallMaxHealth(siege); } public void DailySettlementStats() { SettlementStatsSystem.DailySettlementStats(); } internal void LordSiegeOptions(Party party, Clan clan, double strength, List<(Party party, double strength, double dist)> hostiles, List options) { SiegeAiSystem.LordSiegeOptions(party, clan, strength, hostiles, options); } public CommandResult BeginSiegeAssault(SiegeState siege) { return SiegeBattlesSystem.BeginSiegeAssault(siege); } public CommandResult SurrenderSiegeDefenders(SiegeState siege) { return SiegeBattlesSystem.SurrenderSiegeDefenders(siege); } public string SiegeBattleValidation(Encounter enc) { return SiegeBattlesSystem.SiegeBattleValidation(enc); } public void CancelSiegeBattle(Encounter enc) { SiegeBattlesSystem.CancelSiegeBattle(enc); } public void CompleteSiegeBattle(Encounter enc, BattleResult result, BattleReport report) { SiegeBattlesSystem.CompleteSiegeBattle(enc, result, report); } internal void CaptureSiegeSettlement(SiegeState siege, BattleReport report) { SiegeCaptureSystem.CaptureSiegeSettlement(siege, report); } public SiegeState SiegeForSettlement(string id) { return SiegesSystem.SiegeForSettlement(id); } public bool IsSettlementBesieged(Settlement settlement) { return SiegesSystem.IsSettlementBesieged(settlement); } public void EnsureSiegeFields() { SiegesSystem.EnsureSiegeFields(); } public IEnumerable SiegeResidentDefenders(Settlement settlement) { return SiegesSystem.SiegeResidentDefenders(settlement); } public int SiegeDefenders(Settlement settlement) { return SiegesSystem.SiegeDefenders(settlement); } public double SiegeDefenderStrength(Settlement settlement) { return SiegesSystem.SiegeDefenderStrength(settlement); } public List>> MilitiaTroops(Settlement settlement, int healthy, int wounded) { return SiegesSystem.MilitiaTroops(settlement, healthy, wounded); } public string SiegeOrderReason(Party party, Settlement settlement) { return SiegesSystem.SiegeOrderReason(party, settlement); } public string SiegeReason(string settlementId) { return SiegesSystem.SiegeReason(settlementId); } public CommandResult BesiegeSettlement(string settlementId) { return SiegesSystem.BesiegeSettlement(settlementId); } public CommandResult OrderSiege(Party party, Settlement settlement) { return SiegesSystem.OrderSiege(party, settlement); } internal string SiegeCampReason(SiegeState siege, bool ready) { return SiegesSystem.SiegeCampReason(siege, ready); } public string SiegeAssaultReason() { return SiegesSystem.SiegeAssaultReason(); } public CommandResult AssaultSettlement(SiegeCapturePolicy policy) { return SiegesSystem.AssaultSettlement(policy); } internal string SurrenderCampReason(SiegeState siege) { return SiegesSystem.SurrenderCampReason(siege); } public string SiegeSurrenderReason() { return SiegesSystem.SiegeSurrenderReason(); } public CommandResult DemandSiegeSurrender(SiegeCapturePolicy policy) { return SiegesSystem.DemandSiegeSurrender(policy); } public CommandResult AbandonSiege() { return SiegesSystem.AbandonSiege(); } public void EndPartySiege(Party party, string reason) { SiegesSystem.EndPartySiege(party, reason); } public void EndSiege(SiegeState siege, string reason) { SiegesSystem.EndSiege(siege, reason); } public void UpdateSieges(bool advanceProgress = true) { SiegesSystem.UpdateSieges(advanceProgress); } public void DailySieges() { SiegesSystem.DailySieges(); } public string SallyReason() { return SiegeSortiesSystem.SallyReason(); } public CommandResult SallyOut() { return SiegeSortiesSystem.SallyOut(); } public string BreakOutReason() { return SiegeSortiesSystem.BreakOutReason(); } public CommandResult BreakOutOfSettlement() { return SiegeSortiesSystem.BreakOutOfSettlement(); } public string BreakInReason(string settlementId) { return SiegeSortiesSystem.BreakInReason(settlementId); } public CommandResult BreakIntoSettlement(string settlementId) { return SiegeSortiesSystem.BreakIntoSettlement(settlementId); } public bool BesiegedAgainst(Party p, Settlement s) { return SiegeSortiesSystem.ShutOut(p, s); } public string SortieOf(Encounter enc) { return enc?.Sortie ?? ""; } internal void CompleteSiegeSortie(Encounter enc, BattleResult result, BattleReport report) { SiegeSortiesSystem.Complete(enc, result, report); } internal void CancelSiegeSortie(Encounter enc) { SiegeSortiesSystem.Cancel(enc); } internal void StartPendingKeepBattles() { SiegeSortiesSystem.StartPendingKeepBattles(); } public int SiegeEngineering(SiegeState siege) { return SiegeWorksSystem.SiegeEngineering(siege); } public double SiegeBuildRate(SiegeState siege) { return SiegeWorksSystem.SiegeBuildRate(siege); } public string SiegeBuildReason(int slot, SiegeEngineKind kind) { return SiegeWorksSystem.SiegeBuildReason(slot, kind); } public CommandResult BuildSiegeEngine(int slot, SiegeEngineKind kind) { return SiegeWorksSystem.BuildSiegeEngine(slot, kind); } public CommandResult ClearSiegeEngine(int slot) { return SiegeWorksSystem.ClearSiegeEngine(slot); } internal void AdvanceSiegeWorks(SiegeState siege, double elapsed) { SiegeWorksSystem.AdvanceSiegeWorks(siege, elapsed); } internal void PlanAiSiegeWorks(SiegeState siege) { SiegeWorksSystem.PlanAiSiegeWorks(siege); } internal bool AiSiegeWorksReady(SiegeState siege) { return SiegeWorksSystem.AiSiegeWorksReady(siege); } internal void TrainAthleticsOnTheMarch(Party p, double travelled) { if (p == null || travelled <= 0.0 || p.ClanId != State.PlayerClanId || (p.Kind != PartyKind.Player && !IsPlayerMilitaryParty(p))) { return; } foreach (Hero item in (from id in p.Troops.Heroes select State.Heroes.Get(id) into h where h != null && h.State == HeroState.Active && IsPresentPartyHero(p, h) select h).ToList()) { if (!HeroRides(item)) { GrantDailySkillExperience(item, "athletics", travelled * 3.0, 60.0); } } } internal void TrainRoguery(double xp) { GrantSkillExperience(State.PlayerHero, "roguery", xp); } internal void TrainCharm(int relationGained) { if (relationGained > 0 && State.PlayerHero != null) { GrantDailySkillExperience(State.PlayerHero, "charm", (double)relationGained * 6.0, 80.0); } } internal void TrainBattleSkills(Combatant fighter, Hero hero, double enemyTierDowned, HeroBattleCredit credit, bool participated = true) { if (hero != null && hero.State != HeroState.Dead) { string skill = ((credit != null && SkillIds.Weapons.Contains(credit.WeaponSkill)) ? credit.WeaponSkill : MainWeaponSkill(hero)); if (participated) { GrantSkillExperience(hero, skill, Math.Min(60.0, 10.0 + 2.0 * enemyTierDowned), grantHeroXp: false); } if (participated && fighter?.Mount == null) { GrantSkillExperience(hero, "athletics", Math.Min(40.0, 8.0 + 1.0 * enemyTierDowned), grantHeroXp: false); } if (credit != null && (credit.KilledTiers > 0 || credit.Damage > 0.0)) { GrantSkillExperience(hero, skill, Math.Min(400.0, (double)credit.KilledTiers * 12.0 + Math.Max(0.0, credit.Damage) * 0.05)); } } } internal void TrainSiegeEngineers(SiegeState siege, double hours, bool attackersBuilt, int attackersFinished, bool defendersBuilt, int defendersFinished) { SkillTrainingSystem.TrainSiegeEngineers(siege, hours, attackersBuilt, attackersFinished, defendersBuilt, defendersFinished); } internal void TrainDiplomacy(double xp) { SkillTrainingSystem.TrainDiplomacy(xp); } internal void TrainDiplomacyForRansom(long troops) { SkillTrainingSystem.TrainDiplomacyForRansom(troops); } public void EnsureSmithingFields() { SmithingSystem.EnsureSmithingFields(); } public IEnumerable PartySmiths() { return SmithingSystem.PartySmiths(); } public bool HasHeroPerk(Hero hero, string perkId) { return SmithingSystem.HasHeroPerk(hero, perkId); } public double SmithingMaxStamina(Hero hero) { return SmithingSystem.SmithingMaxStamina(hero); } public double SmithingStamina(Hero hero) { return SmithingSystem.SmithingStamina(hero); } internal void HourlySmithing() { SmithingSystem.HourlySmithing(); } public string SmithyReason() { return SmithingSystem.SmithyReason(); } public string SmithReason(string heroId) { return SmithingSystem.SmithReason(heroId); } public int MaterialCount(Party party, SmithingMaterial m) { return SmithingSystem.MaterialCount(party, m); } internal void AddMaterial(Party party, SmithingMaterial m, int delta) { SmithingSystem.AddMaterial(party, m, delta); } public IEnumerable KnownRecipes(Hero smith) { return SmithingSystem.KnownRecipes(smith); } public string RefineReason(string heroId, string recipeId) { return SmithingSystem.RefineReason(heroId, recipeId); } public CommandResult Refine(string heroId, string recipeId) { return SmithingSystem.Refine(heroId, recipeId); } public SortedDictionary SmeltingPreview(string itemId) { return SmithingSystem.SmeltingPreview(itemId); } public bool CanSmelt(string itemId) { return SmithingSystem.CanSmelt(itemId); } public string SmeltReason(string heroId, string itemId) { return SmithingSystem.SmeltReason(heroId, itemId); } public CommandResult Smelt(string heroId, string itemId) { return SmithingSystem.Smelt(heroId, itemId); } public bool PartUnlocked(string partId) { return SmithingSystem.PartUnlocked(partId); } public int ResearchPoints(WeaponClass c) { return SmithingSystem.ResearchPoints(c); } public int ResearchNeeded(WeaponClass c) { return SmithingSystem.ResearchNeeded(c); } internal List AddResearch(WeaponClass c, int points) { return SmithingSystem.AddResearch(c, points); } public WeaponDesignPreview PreviewWeapon(string heroId, WeaponClass c, IList partIds, bool forOrder = false) { return SmithingSystem.PreviewWeapon(heroId, c, partIds, forOrder); } public CommandResult Forge(string heroId, WeaponClass c, IList partIds, string name, ForgingWork work = null) { return SmithingSystem.Forge(heroId, c, partIds, name, work); } public IEnumerable OrdersAt(string settlementId) { return SmithingSystem.OrdersAt(settlementId); } public CraftingOrderState Order(string orderId) { return SmithingSystem.Order(orderId); } internal CraftingOrderState CreateOrder(Settlement town, int slot, RandomStream rng) { return SmithingSystem.CreateOrder(town, slot, rng); } internal void DailySmithingOrders() { SmithingSystem.DailySmithingOrders(); } public static OrderEvaluation EvaluateOrder(CraftingOrderState order, WeaponStats delivered, long deliveredValue) { return SmithingSystem.EvaluateOrder(order, delivered, deliveredValue); } public string OrderReason(string heroId, string orderId, IList partIds) { return SmithingSystem.OrderReason(heroId, orderId, partIds); } public CommandResult CompleteOrder(string heroId, string orderId, IList partIds, string name, ForgingWork work = null) { return SmithingSystem.CompleteOrder(heroId, orderId, partIds, name, work); } public string DeveloperSmithingReason(string heroId = null) { return SmithingDeveloperSystem.DeveloperSmithingReason(heroId); } public CommandResult DeveloperAddSmithingMaterials() { return SmithingDeveloperSystem.DeveloperAddSmithingMaterials(); } public CommandResult DeveloperClearSmithingMaterials() { return SmithingDeveloperSystem.DeveloperClearSmithingMaterials(); } public CommandResult DeveloperSetSmithingSkill(string heroId, int level) { return SmithingDeveloperSystem.DeveloperSetSmithingSkill(heroId, level); } public CommandResult DeveloperRestoreSmithingStamina(string heroId) { return SmithingDeveloperSystem.DeveloperRestoreSmithingStamina(heroId); } public CommandResult DeveloperLearnAllSmithingParts() { return SmithingDeveloperSystem.DeveloperLearnAllSmithingParts(); } public CommandResult DeveloperNewSmithingOrders() { return SmithingDeveloperSystem.DeveloperNewSmithingOrders(); } internal CommandResult DeveloperDone(string message, string link = null) { return SmithingDeveloperSystem.DeveloperDone(message, link); } public void EnsureStoryEventFields() { StoryEventsSystem.EnsureStoryEventFields(); } public CommandResult SetRandomEventsEnabled(bool on) { return StoryEventsSystem.SetRandomEventsEnabled(on); } internal void HourlyStoryEvents() { StoryEventsSystem.HourlyStoryEvents(); } public CommandResult DeveloperStartEvent(string eventId = "") { return StoryEventsSystem.DeveloperStartEvent(eventId); } public static string StoryEventContext(string id) { return StoryEventsSystem.StoryEventContext(id); } public StoryPrompt PendingEventPrompt() { return StoryEventsSystem.PendingEventPrompt(); } public CommandResult ChooseEventOption(string optionId) { return StoryEventsSystem.ChooseEventOption(optionId); } internal static StoryOption Opt(string id, string text, string reason = "", string hint = "") { return StoryEventsSystem.Opt(id, text, reason, hint); } internal static List L(params string[] lines) { return StoryEventsSystem.L(lines); } internal void AddMorale(double delta) { StoryEventsSystem.AddMorale(delta); } internal string WoundOne(RandomStream rng) { return StoryEventsSystem.WoundOne(rng); } internal Settlement NearestPlace(SettlementType? type, double within) { return StoryEventsSystem.NearestPlace(type, within); } internal Settlement EventPlace(PendingEventState p) { return StoryEventsSystem.EventPlace(p); } internal string Gold(long n) { return StoryEventsSystem.Gold(n); } internal string CantAfford(long n) { return StoryEventsSystem.CantAfford(n); } internal bool PayPlace(Settlement s, long amount, string reason) { return StoryEventsSystem.PayPlace(s, amount, reason); } internal double Chance(double baseChance, string skill, double per) { return StoryEventsSystem.Chance(baseChance, skill, per); } internal static string Pct(double chance) { return StoryEventsSystem.Pct(chance); } internal Clan FriendlyLordClan() { return StoryEventsSystem.FriendlyLordClan(); } internal void BeginSuccession(Hero deceased) { SuccessionSystem.BeginSuccession(deceased); } public List HeirCandidates() { return SuccessionSystem.HeirCandidates(); } public string HeirReason(string heroId) { return SuccessionSystem.HeirReason(heroId); } public CommandResult ChooseHeir(string heroId) { return SuccessionSystem.ChooseHeir(heroId); } public void EnsureTournamentFields() { TournamentsSystem.EnsureTournamentFields(); } public TournamentState TournamentAt(string townId) { return TournamentsSystem.TournamentAt(townId); } internal void HearOfTournament(string id) { TournamentsSystem.HearOfTournament(id); } public List> TournamentLeaderboard() { return TournamentsSystem.TournamentLeaderboard(); } public int TournamentWins(string heroId) { return TournamentsSystem.TournamentWins(heroId); } public string TournamentBusyReason() { return TournamentsSystem.TournamentBusyReason(); } public void EnsureTournaments() { TournamentsSystem.EnsureTournaments(); } public TournamentState AnnounceTournamentAt(string townId) { return TournamentsSystem.AnnounceTournamentAt(townId); } internal void DailyTournaments() { TournamentsSystem.DailyTournaments(); } internal TournamentPrizeState WeaponPrize(RandomStream rng) { return TournamentsSystem.WeaponPrize(rng); } public TournamentFighterState TournamentFighter(TournamentRunState run, int id) { return TournamentsSystem.TournamentFighter(run, id); } public IEnumerable RoundMatches(TournamentRunState run) { return TournamentsSystem.RoundMatches(run); } public TournamentMatchState PlayerMatch(TournamentRunState run) { return TournamentsSystem.PlayerMatch(run); } public (int companions, int lords) TournamentEntrantPreview(string townId) { return TournamentsSystem.TournamentEntrantPreview(townId); } public string TournamentJoinReason(string townId) { return TournamentsSystem.TournamentJoinReason(townId); } public CommandResult JoinTournament(string townId) { return TournamentsSystem.JoinTournament(townId); } public string TournamentBetReason(long amount) { return TournamentsSystem.TournamentBetReason(amount); } public CommandResult PlaceTournamentBet(long amount) { return TournamentsSystem.PlaceTournamentBet(amount); } public TournamentMatchState NextSpectatorMatch(TournamentRunState run) { return TournamentsSystem.NextSpectatorMatch(run); } public string TournamentWatchReason() { return TournamentsSystem.TournamentWatchReason(); } public CommandResult SkipSpectatorMatch() { return TournamentsSystem.SkipSpectatorMatch(); } public CommandResult CompleteSpectatorMatch(string attemptId, bool teamAWon) { return TournamentsSystem.CompleteSpectatorMatch(attemptId, teamAWon); } public string TournamentFightReason() { return TournamentsSystem.TournamentFightReason(); } public BattlePlan PrepareTournamentMatch() { return TournamentsSystem.PrepareTournamentMatch(); } public string BeginTournamentMatch(BattlePlan plan) { return TournamentsSystem.BeginTournamentMatch(plan); } public void AbortTournamentMatch(string reason) { TournamentsSystem.AbortTournamentMatch(reason); } public CommandResult CompleteTournamentMatch(string attemptId, bool playerTeamWon, bool playerKnockedOut) { return TournamentsSystem.CompleteTournamentMatch(attemptId, playerTeamWon, playerKnockedOut); } public string TournamentWithdrawReason() { return TournamentsSystem.TournamentWithdrawReason(); } public CommandResult WithdrawFromTournament() { return TournamentsSystem.WithdrawFromTournament(); } public void MarkTournamentResultSeen() { TournamentsSystem.MarkTournamentResultSeen(); } public string TownVisitReason() { return TownVisitSystem.TownVisitReason(); } public BattlePlan PrepareTownVisit() { return TownVisitSystem.PrepareTownVisit(); } public Hero KeepHolderHere(Settlement s, IList staying) { return TownVisitSystem.KeepHolderHere(s, staying); } internal static bool WalksTheStreets(UnitDef u) { return TownVisitSystem.WalksTheStreets(u); } internal UnitDef TownVisitLocal(Settlement s, UnitDef fallback) { return TownVisitSystem.TownVisitLocal(s, fallback); } public CommandResult StartTutorial(IEnumerable chapters) { return TutorialSystem.StartTutorial(chapters); } public void StopTutorial() { TutorialSystem.StopTutorial(); } public void TutorialNext() { TutorialSystem.TutorialNext(); } public void TutorialBack() { TutorialSystem.TutorialBack(); } public void SkipTutorialChapter() { TutorialSystem.SkipTutorialChapter(); } public void SetTutorialMinimised(bool minimised) { TutorialSystem.SetTutorialMinimised(minimised); } public void TutorialSignal(string name) { TutorialSystem.TutorialSignal(name); } public bool UpdateTutorial() { return TutorialSystem.UpdateTutorial(); } public TutorialView TutorialView() { return TutorialSystem.View(); } internal void EnsureAlleys() { UnderworldSystem.EnsureAlleys(); } public List AlleysOf(Settlement s) { return UnderworldSystem.AlleysOf(s); } public AlleyState Alley(string id) { return UnderworldSystem.Alley(id); } public bool OwnsAlley(AlleyState a) { return UnderworldSystem.OwnsAlley(a); } public long AlleyIncome(AlleyState a) { return UnderworldSystem.AlleyIncome(a); } internal void DailyAlleys() { UnderworldSystem.DailyAlleys(); } public string AssignOverseerReason(string alleyId, string heroId) { return UnderworldSystem.AssignOverseerReason(alleyId, heroId); } public CommandResult AssignOverseer(string alleyId, string heroId) { return UnderworldSystem.AssignOverseer(alleyId, heroId); } public string RecallOverseerReason(string alleyId) { return UnderworldSystem.RecallOverseerReason(alleyId); } public CommandResult RecallOverseer(string alleyId) { return UnderworldSystem.RecallOverseer(alleyId); } public List DungeonPrisonersHere() { return UnderworldSystem.DungeonPrisonersHere(); } public string PrisonBreakReason(string heroId) { return UnderworldSystem.PrisonBreakReason(heroId); } public string AlleyFightReason(string alleyId) { return UnderworldSystem.AlleyFightReason(alleyId); } public BattlePlan PreparePrisonBreak(string heroId) { return UnderworldSystem.PreparePrisonBreak(heroId); } public BattlePlan PrepareAlleyFight(string alleyId) { return UnderworldSystem.PrepareAlleyFight(alleyId); } public BattlePlan PrepareExecutionScene(string heroId, bool inDungeon) { return UnderworldSystem.PrepareExecutionScene(heroId, inDungeon); } public CommandResult CompleteCrimeMission(string mission, CrimeMissionResult r) { return UnderworldSystem.CompleteCrimeMission(mission, r); } public void EnsureVillageRecoveryFields() { VillageRecoverySystem.EnsureVillageRecoveryFields(); } public double VillageOutputFactor(Settlement settlement) { return VillageRecoverySystem.VillageOutputFactor(settlement); } public double VillageTaxFactor(Settlement settlement) { return VillageRecoverySystem.VillageTaxFactor(settlement); } public int VillageRecoveryDays(Settlement settlement) { return VillageRecoverySystem.VillageRecoveryDays(settlement); } public string VillageRecruitmentReason(Settlement settlement) { return VillageRecoverySystem.VillageRecruitmentReason(settlement); } public int VillageProductionAmount(Settlement settlement, string goodId, int baseUnits) { return VillageRecoverySystem.VillageProductionAmount(settlement, goodId, baseUnits); } public void RecordPlayerVillageRaid(Settlement settlement) { VillageRecoverySystem.RecordPlayerVillageRaid(settlement); } public void ApplyVillageRaidDamage(Settlement settlement, bool playerRaid) { VillageRecoverySystem.ApplyVillageRaidDamage(settlement, playerRaid); } public void DailyVillageRecovery() { VillageRecoverySystem.DailyVillageRecovery(); } public string VillageRecoveryAidReason() { return VillageRecoverySystem.VillageRecoveryAidReason(); } public CommandResult AidVillageRecovery() { return VillageRecoverySystem.AidVillageRecovery(); } public bool IsWanderer(Hero h) { return WanderersSystem.IsWanderer(h); } public WandererPlan WandererPlan(string heroId) { return WanderersSystem.WandererPlan(heroId); } public void EnsureWandererFields() { WanderersSystem.EnsureWandererFields(); } internal void NoteNewWanderer(Hero hero) { WanderersSystem.NoteNewWanderer(hero); } internal void DailyWanderers() { WanderersSystem.DailyWanderers(); } internal void HourlyWanderers() { WanderersSystem.HourlyWanderers(); } public void EnsureWardrobeFields() { WardrobeSystem.EnsureWardrobeFields(); } public ClothingPieceDef ClothingPiece(string id) { return WardrobeSystem.ClothingPiece(id); } public int ImportWardrobe(WardrobeCatalogue catalogue) { return WardrobeSystem.ImportWardrobe(catalogue); } public Dictionary> ClothingCultures() { return WardrobeSystem.ClothingCultures(); } public WornClothingState WornClothing(Hero hero, ClothingSlot slot, int layer = 1) { return WardrobeSystem.WornClothing(hero, slot, layer); } public List ExtraClothingLayers(Hero hero, ClothingSlot slot) { return WardrobeSystem.ExtraLayers(hero, slot); } public static bool SupportsWardrobe(UnitDef unit) { return WardrobeSystem.SupportsWardrobe(unit); } public string WardrobeHeroReason(string heroId) { return WardrobeSystem.WardrobeHeroReason(heroId); } public string ClothingEquipReason(string heroId, string pieceId, bool onTop = false) { return WardrobeSystem.ClothingEquipReason(heroId, pieceId, onTop); } public CommandResult EquipClothing(string heroId, string pieceId, bool onTop = false) { return WardrobeSystem.EquipClothing(heroId, pieceId, onTop); } public string ClothingLayerRemoveReason(string heroId, ClothingSlot slot, int layer) { return WardrobeSystem.ClothingLayerRemoveReason(heroId, slot, layer); } public CommandResult RemoveClothingLayer(string heroId, ClothingSlot slot, int layer) { return WardrobeSystem.RemoveClothingLayer(heroId, slot, layer); } public string ClothingResetReason(string heroId, ClothingSlot slot) { return WardrobeSystem.ClothingResetReason(heroId, slot); } public CommandResult ResetClothing(string heroId, ClothingSlot slot) { return WardrobeSystem.ResetClothing(heroId, slot); } public string ClothingBareReason(string heroId, ClothingSlot slot) { return WardrobeSystem.ClothingBareReason(heroId, slot); } public CommandResult SetClothingBare(string heroId, ClothingSlot slot) { return WardrobeSystem.SetClothingBare(heroId, slot); } public string ClothingColorReason(string heroId, ClothingSlot slot, IList colors, int layer = 1) { return WardrobeSystem.ClothingColorReason(heroId, slot, colors, layer); } public CommandResult SetClothingColors(string heroId, ClothingSlot slot, IList colors, int layer = 1) { return WardrobeSystem.SetClothingColors(heroId, slot, colors, layer); } public double HeroSize(Hero hero) { return WardrobeSystem.HeroSize(hero); } public string HeroSizeReason(string heroId, double size) { return WardrobeSystem.HeroSizeReason(heroId, size); } public CommandResult SetHeroSize(string heroId, double size) { return WardrobeSystem.SetHeroSize(heroId, size); } internal string LootClothing(Party player, IEnumerable downedUnitIds) { return WardrobeSystem.LootClothing(player, downedUnitIds); } public WeaponSheet WeaponSheet(string itemId, Hero forHero = null) { OwnedItemInfo ownedItemInfo = ItemInfo(itemId); WeaponSheet weaponSheet = ((ownedItemInfo?.Crafted != null) ? WeaponSheets.For(ownedItemInfo.Crafted) : WeaponSheets.For(EquipmentCatalog.Find(itemId), UnitDef)); if (weaponSheet == null) { return null; } if (forHero == null || !weaponSheet.Class.HasValue) { return weaponSheet; } EquipmentSlot? equipmentSlot = EquipmentSlotOf(itemId); if (!equipmentSlot.HasValue) { return weaponSheet; } EquipmentCombatStats equipmentCombatStats = HeroEquipmentStats(forHero); HeroEquipmentState heroEquipmentState = forHero.Loadout?.Copy() ?? new HeroEquipmentState(); heroEquipmentState.SetItem(equipmentSlot.Value, itemId); EquipmentCombatStats equipmentCombatStats2 = HeroEquipmentStats(forHero, heroEquipmentState); TroopRole? troopRole = WeaponRole(itemId); object obj; if (troopRole.HasValue) { TroopRole valueOrDefault = troopRole.GetValueOrDefault(); if (valueOrDefault != UnitDef(forHero.UnitId)?.Role) { obj = " (it doesn't suit them: " + valueOrDefault.ToString().ToLowerInvariant() + " weapon)"; goto IL_0125; } } obj = ""; goto IL_0125; IL_0125: string text = (string)obj; weaponSheet.Notes.Add("For " + forHero.Name + text + ": attack " + equipmentCombatStats2.Attack.ToString("0.##") + " (" + (equipmentCombatStats2.Attack - equipmentCombatStats.Attack).ToString("+0.##;-0.##;0") + "), defence " + equipmentCombatStats2.Defense.ToString("0.##") + " (" + (equipmentCombatStats2.Defense - equipmentCombatStats.Defense).ToString("+0.##;-0.##;0") + "), ranged " + equipmentCombatStats2.Ranged.ToString("0.##") + " (" + (equipmentCombatStats2.Ranged - equipmentCombatStats.Ranged).ToString("+0.##;-0.##;0") + ") in simulated battles."); return weaponSheet; } } public enum BarterKind { Trade, Bribe, Tribute, Ransom, Peace, Recruit } public enum BarterItemKind { Gold, Goods, Horse, Prisoners, Captive, Fief } public sealed class BarterItem { public BarterItemKind Kind; public string Id = ""; public string Name = ""; public bool FromPlayer; public int Count; public int Max; public string Key => (FromPlayer ? "p:" : "t:") + Kind.ToString() + ":" + Id; } public sealed class BarterSession { public BarterKind Kind; public string HeroId = ""; public string ClanId = ""; public string PartyId = ""; public string EncounterId = ""; public string TargetId = ""; public string Counterparty = ""; public string Deal = ""; public List Offer = new List(); public bool Finished; public bool Accepted; public string Result = ""; } public sealed class BarterEvaluation { public long Balance; public long Needed; public long DealValue; public bool Acceptable; public string Why = ""; public long Shortfall => Math.Max(0L, Needed - Balance); } internal sealed class BarterSystem { private readonly Campaign C; private CampaignState State => C.State; private CampaignRules Rules => C.Rules; internal BarterSystem(Campaign host) { C = host; } internal Party CaptorParty() { return State.Parties.Get(State.Player.CaptorPartyId); } internal Clan CaptorClan() { Party party = CaptorParty(); if (party != null) { return State.Clans.Get(party.ClanId); } return State.Clans.Get(State.Settlements.Get(State.Player.CaptorSettlementId)?.OwnerClanId ?? ""); } internal string Reason(BarterKind kind, string heroId, string partyId) { Hero hero = State.Heroes.Get(heroId ?? ""); Party party = State.Parties.Get(partyId ?? "") ?? ((hero == null) ? null : C.PartyOfHero(hero.Id)); Clan clan = State.Clans.Get(hero?.ClanId ?? party?.ClanId ?? ""); if (State.PlayerHero == null) { return "There is nobody to bargain for."; } switch (kind) { case BarterKind.Ransom: if (State.Player.Activity != PlayerActivity.Captive) { return "You are not a prisoner."; } if (CaptorClan() == null) { return "Nobody is holding you for ransom."; } if (CaptorClan().IsBandit && CaptorParty() == null) { return "Nobody is holding you for ransom."; } if (State.PlayerClan.Gold > 0 || State.PlayerParty.Cargo.Values.Sum() != 0) { return ""; } return "Your clan has nothing to pay with."; case BarterKind.Bribe: case BarterKind.Tribute: { Encounter pendingPlayerEncounter = C.PendingPlayerEncounter; if (pendingPlayerEncounter == null || pendingPlayerEncounter.Phase != EncounterPhase.AwaitingDecision) { return "There is no fight to bargain over."; } if (pendingPlayerEncounter.Kind != EncounterKind.FieldBattle && pendingPlayerEncounter.Kind != EncounterKind.BanditAmbush) { return "This is no place for bargaining."; } if (pendingPlayerEncounter.MustFight) { return "Ironman: you've started this battle, so it has to be settled — fight, auto-resolve or surrender."; } bool flag = pendingPlayerEncounter.InitiatorPartyId == State.PlayerPartyId; if (kind == BarterKind.Bribe && flag) { return "You started this. You can simply ride away."; } if (kind == BarterKind.Tribute && !flag) { return "They caught you: you're in no place to make demands."; } Party party2 = C.PersuasionSystem.EnemyLeaderParty(pendingPlayerEncounter); if (party2 == null) { return "There is nobody to bargain with."; } if (kind == BarterKind.Tribute) { if (party2.Kind == PartyKind.Lord) { Clan clan2 = State.Clans.Get(party2.ClanId); if (clan2 == null || !clan2.IsBandit) { Hero hero2 = State.Heroes.Get(party2.LeaderHeroId); if (hero2 != null && Campaign.PersonalityOf(hero2).Valor > 0) { return Campaign.First(hero2) + " would sooner die than pay you to leave."; } } } if (TheirWinChance(pendingPlayerEncounter) > 0.35) { return "They think they can beat you. They won't pay."; } } return ""; } case BarterKind.Peace: { if (hero == null || clan == null) { return "There is nobody to make peace with."; } string text = State.FactionOf(clan); if (!IsFactionLeader(hero)) { return "Only " + C.DiplomacyFactionName(text) + "'s ruler can make peace."; } return C.PeaceOffers(text).FirstOrDefault()?.Reason ?? "You can't make peace with them."; } case BarterKind.Recruit: { if (hero == null || clan == null || clan.LeaderHeroId != hero.Id) { return "Only the head of a house can swear it to your realm."; } ClanRecruitmentQuote clanRecruitmentQuote = C.ClanAllegianceSystem.QuoteClanRecruitment(clan.Id, ignoreRelation: false, 0L); if (!clanRecruitmentQuote.Ok && clanRecruitmentQuote.Reason.StartsWith("This clan requires", StringComparison.Ordinal)) { return "Persuade " + Campaign.First(hero) + " first: " + clanRecruitmentQuote.Reason; } return clanRecruitmentQuote.Reason; } default: if (hero == null || clan == null || clan.IsBandit) { return "There is nobody to trade with."; } if (hero.ClanId == State.PlayerClanId) { return "Your own clan shares a purse with you."; } if (C.HeroIsEnemy(hero)) { return "We do not trade with our enemies."; } if (clan.LeaderHeroId != hero.Id && party?.LeaderHeroId != hero.Id) { return Campaign.First(hero) + " has no say over their house's purse."; } return ""; } } internal bool IsFactionLeader(Hero h) { Clan clan = State.Clans.Get(h?.ClanId ?? ""); if (clan == null || clan.LeaderHeroId != h.Id) { return false; } Kingdom kingdom = State.Kingdoms.Get(clan.KingdomId ?? ""); if (kingdom != null) { return kingdom.RulerClanId == clan.Id; } return string.IsNullOrEmpty(clan.KingdomId); } internal Encounter LiveEncounter(BarterSession s) { Encounter pendingPlayerEncounter = C.PendingPlayerEncounter; if (pendingPlayerEncounter == null || !(pendingPlayerEncounter.Id == s.EncounterId) || pendingPlayerEncounter.Phase != EncounterPhase.AwaitingDecision) { return null; } return pendingPlayerEncounter; } internal double TheirWinChance(Encounter enc) { if (enc != null) { return 1.0 - AutoResolver.EstimateWinChance(C, enc, enc.PlayerSide); } return 0.5; } internal BarterSession Start(BarterKind kind, string heroId, string partyId) { if (Reason(kind, heroId, partyId).Length > 0) { return null; } Hero hero = State.Heroes.Get(heroId ?? ""); BarterSession barterSession = new BarterSession { Kind = kind, HeroId = (hero?.Id ?? "") }; Party party; switch (kind) { case BarterKind.Ransom: party = CaptorParty(); barterSession.ClanId = CaptorClan().Id; barterSession.HeroId = party?.LeaderHeroId ?? State.Clans.Get(barterSession.ClanId)?.LeaderHeroId ?? ""; barterSession.Deal = "They let you go free."; break; case BarterKind.Bribe: case BarterKind.Tribute: { Encounter pendingPlayerEncounter = C.PendingPlayerEncounter; party = C.PersuasionSystem.EnemyLeaderParty(pendingPlayerEncounter); barterSession.EncounterId = pendingPlayerEncounter.Id; barterSession.HeroId = party.LeaderHeroId ?? ""; barterSession.ClanId = party.ClanId; barterSession.Deal = ((kind == BarterKind.Bribe) ? "They let you ride on." : "You let them go on their way."); break; } default: { party = State.Parties.Get(partyId ?? "") ?? C.PartyOfHero(hero.Id); barterSession.ClanId = hero.ClanId; Clan clan = State.Clans.Get(barterSession.ClanId); barterSession.Deal = kind switch { BarterKind.Recruit => clan.Name + " swears to your realm.", BarterKind.Peace => "Peace between " + C.DiplomacyFactionName(State.FactionOf(State.PlayerClan)) + " and " + C.DiplomacyFactionName(State.FactionOf(clan)) + ".", _ => "", }; break; } } barterSession.PartyId = party?.Id ?? ""; barterSession.Counterparty = State.Heroes.Get(barterSession.HeroId)?.Name ?? party?.Name ?? State.Clans.Get(barterSession.ClanId)?.Name ?? "They"; return barterSession; } internal Party TheirParty(BarterSession s) { Party party = State.Parties.Get(s.PartyId); if (party == null || party.State == PartyState.Destroyed || party.State == PartyState.Disbanded) { return null; } return party; } internal bool PartyPurse(BarterSession s) { Party party = TheirParty(s); Clan clan = State.Clans.Get(s.ClanId); if (clan != null && !clan.IsBandit) { if (party != null && party.Kind != PartyKind.Lord) { return party.Kind != PartyKind.Player; } return false; } return true; } internal long TheirGold(BarterSession s) { if (!PartyPurse(s)) { return Math.Max(0L, State.Clans.Get(s.ClanId)?.Gold ?? 0); } return Math.Max(0L, TheirParty(s)?.Gold ?? 0); } internal bool FiefsAllowed(BarterSession s) { if (s.Kind != BarterKind.Peace) { return s.Kind == BarterKind.Recruit; } return true; } internal List PlayerFiefs() { return State.Settlements.Where((Settlement x) => x.OwnerClanId == State.PlayerClanId && (x.Type == SettlementType.Town || x.Type == SettlementType.Castle) && !C.IsSettlementBesieged(x) && C.CurrentSettlement()?.Id != x.Id).OrderBy((Settlement x) => x.Id, StringComparer.Ordinal).ToList(); } internal List PlayerCaptives() { return State.Heroes.Where((Hero x) => x.State == HeroState.Captive && !x.IsPlayer && C.HeroCaptorClan(x)?.Id == State.PlayerClanId && !C.NamedCustodyReserved(x)).OrderBy((Hero x) => x.Id, StringComparer.Ordinal).ToList(); } internal List TheirCaptives(BarterSession s) { return TheirCaptivesOf(s.ClanId); } internal List TheirCaptivesOf(string clanId) { return State.Heroes.Where((Hero x) => x.State == HeroState.Captive && !x.IsPlayer && C.HeroCaptorClan(x)?.Id == clanId && x.ClanId == State.PlayerClanId && !C.NamedCustodyReserved(x)).OrderBy((Hero x) => x.Id, StringComparer.Ordinal).ToList(); } internal List Stock(BarterSession s, bool playerSide) { List list = new List(); if (playerSide) { list.Add(new BarterItem { Kind = BarterItemKind.Gold, Id = "gold", Name = "Denars", FromPlayer = true, Max = (int)Math.Min(2147483647L, Math.Max(0L, State.PlayerClan.Gold)) }); Party playerParty = State.PlayerParty; if (State.Player.Activity != PlayerActivity.Captive) { foreach (KeyValuePair item in playerParty.Cargo.Where((KeyValuePair kv) => kv.Value > 0 && TradeGoods.Get(kv.Key) != null)) { list.Add(new BarterItem { Kind = BarterItemKind.Goods, Id = item.Key, Name = TradeGoods.Get(item.Key).Name, FromPlayer = true, Max = item.Value }); } if (s.Kind != BarterKind.Ransom) { foreach (HorseState item2 in C.PartyHorses(playerParty).Where(delegate(HorseState x) { Hero hero = C.HorseRider(x); return hero == null || !hero.IsPlayer; }).OrderBy((HorseState x) => x.Id, StringComparer.Ordinal)) { list.Add(new BarterItem { Kind = BarterItemKind.Horse, Id = item2.Id, Name = item2.Name + " (" + C.BreedName(item2) + ")", FromPlayer = true, Max = 1 }); } foreach (TroopStack item3 in playerParty.Prisoners.Stacks.Where((TroopStack x) => x.Total > 0 && C.UnitDef(x.UnitId) != null)) { list.Add(new BarterItem { Kind = BarterItemKind.Prisoners, Id = item3.UnitId, Name = C.UnitDef(item3.UnitId).Name + " (prisoners)", FromPlayer = true, Max = item3.Total }); } } } if (s.Kind == BarterKind.Trade || s.Kind == BarterKind.Peace || s.Kind == BarterKind.Ransom) { foreach (Hero item4 in PlayerCaptives()) { list.Add(new BarterItem { Kind = BarterItemKind.Captive, Id = item4.Id, Name = item4.Name + " (your captive)", FromPlayer = true, Max = 1 }); } } if (FiefsAllowed(s)) { foreach (Settlement item5 in PlayerFiefs()) { list.Add(new BarterItem { Kind = BarterItemKind.Fief, Id = item5.Id, Name = item5.Name, FromPlayer = true, Max = 1 }); } } } else if (s.Kind == BarterKind.Trade || s.Kind == BarterKind.Tribute || s.Kind == BarterKind.Peace) { list.Add(new BarterItem { Kind = BarterItemKind.Gold, Id = "gold", Name = "Denars", Max = (int)Math.Min(2147483647L, TheirGold(s)) }); Party party = TheirParty(s); if (party != null) { foreach (KeyValuePair item6 in party.Cargo.Where((KeyValuePair kv) => kv.Value > 0 && TradeGoods.Get(kv.Key) != null)) { list.Add(new BarterItem { Kind = BarterItemKind.Goods, Id = item6.Key, Name = TradeGoods.Get(item6.Key).Name, Max = item6.Value }); } if (s.Kind != BarterKind.Peace) { foreach (TroopStack item7 in party.Prisoners.Stacks.Where((TroopStack x) => x.Total > 0 && C.UnitDef(x.UnitId) != null)) { list.Add(new BarterItem { Kind = BarterItemKind.Prisoners, Id = item7.UnitId, Name = C.UnitDef(item7.UnitId).Name + " (prisoners)", Max = item7.Total }); } } } if (s.Kind != BarterKind.Tribute) { foreach (Hero item8 in TheirCaptives(s)) { list.Add(new BarterItem { Kind = BarterItemKind.Captive, Id = item8.Id, Name = item8.Name + " (held by them)", Max = 1 }); } } } return list; } internal CommandResult SetCount(BarterSession s, BarterItemKind kind, string id, bool fromPlayer, int count) { if (s == null || s.Finished) { return CommandResult.Fail("The bargaining is over."); } BarterItem barterItem = Stock(s, fromPlayer).FirstOrDefault((BarterItem x) => x.Kind == kind && x.Id == id); if (barterItem == null) { return CommandResult.Fail("That isn't on offer."); } count = Math.Max(0, Math.Min(barterItem.Max, count)); BarterItem barterItem2 = s.Offer.FirstOrDefault((BarterItem x) => x.Kind == kind && x.Id == id && x.FromPlayer == fromPlayer); if (count == 0) { if (barterItem2 != null) { s.Offer.Remove(barterItem2); } return CommandResult.Success(); } if (barterItem2 == null) { barterItem2 = new BarterItem { Kind = kind, Id = id, Name = barterItem.Name, FromPlayer = fromPlayer, Max = barterItem.Max }; s.Offer.Add(barterItem2); } barterItem2.Count = count; barterItem2.Max = barterItem.Max; return CommandResult.Success(); } internal long HeroWorth(Hero hero) { if (hero == null) { return 0L; } Clan clan = State.Clans.Get(hero.ClanId); long num = 300 + 150L * (long)Campaign.ClanTier(clan) + 25L * (long)Math.Max(1, hero.Level); if (clan != null && clan.LeaderHeroId == hero.Id) { num += 1200; } Kingdom kingdom = ((clan == null) ? null : State.Kingdoms.Get(clan.KingdomId ?? "")); if (kingdom != null && kingdom.RulerClanId == clan.Id && clan.LeaderHeroId == hero.Id) { num += 2500; } return num; } internal long FiefWorth(Settlement s) { if (s == null) { return 0L; } return ((s.Type == SettlementType.Town) ? 14000 : 9000) + 1500L * (long)State.Settlements.Count((Settlement v) => v.BoundTo == s.Id && v.Type == SettlementType.Village); } internal long PrisonerWorth(string unitId) { return (long)Math.Round((double)Math.Max(1, C.UnitDef(unitId)?.Tier ?? 1) * Rules.RansomPerTier); } internal long ItemValue(BarterSession s, BarterItem item, int count) { if (item == null || count <= 0) { return 0L; } switch (item.Kind) { case BarterItemKind.Gold: return item.FromPlayer ? count : (-count); case BarterItemKind.Goods: { long num = TradeGoods.Get(item.Id)?.BasePrice ?? 0; if (!item.FromPlayer) { return -num * count; } return (long)Math.Round((double)(num * count) * 0.8); } case BarterItemKind.Horse: { HorseState horseState = C.Horse(item.Id); if (horseState != null) { return (long)Math.Round((double)C.HorseValue(horseState) * 0.7); } return 0L; } case BarterItemKind.Prisoners: { long num2 = PrisonerWorth(item.Id); UnitDef unitDef = C.UnitDef(item.Id); Clan clan = State.Clans.Get(s.ClanId); bool flag = unitDef != null && clan != null && unitDef.Culture == clan.CultureId; if (!item.FromPlayer) { return -num2 * count; } return (long)Math.Round((double)(num2 * count) * (flag ? 1.6 : 0.8)); } case BarterItemKind.Captive: { Hero hero = State.Heroes.Get(item.Id); long num3 = HeroWorth(hero); if (!item.FromPlayer) { return -num3; } bool flag2 = hero != null && hero.ClanId == s.ClanId; bool flag3 = hero != null && !flag2 && State.FactionOf(State.Clans.Get(hero.ClanId)) == State.FactionOf(State.Clans.Get(s.ClanId)); return (long)Math.Round((double)num3 * (flag2 ? 1.2 : (flag3 ? 0.7 : 0.35))); } case BarterItemKind.Fief: if (!item.FromPlayer) { return -FiefWorth(State.Settlements.Get(item.Id)) * 13 / 10; } return FiefWorth(State.Settlements.Get(item.Id)); default: return 0L; } } internal long DealValue(BarterSession s, out string why) { why = ""; switch (s.Kind) { case BarterKind.Ransom: { long num11 = HeroWorth(State.PlayerHero) + 100L * (long)State.PlayerHero.Level; Clan clan2 = State.Clans.Get(s.ClanId); if (clan2 != null && clan2.IsBandit) { num11 /= 2; } why = "Your freedom is worth " + num11.ToString("N0", CultureInfo.InvariantCulture) + " to them."; return -num11; } case BarterKind.Bribe: { Encounter enc2 = LiveEncounter(s); double num7 = TheirWinChance(enc2); Party playerParty = State.PlayerParty; long num8 = playerParty.Cargo.Sum((KeyValuePair kv) => (TradeGoods.Get(kv.Key)?.BasePrice ?? 0) * kv.Value); double num9 = (double)State.PlayerClan.Gold * 0.15 + (double)num8 * 0.5 + (double)(25 * playerParty.Troops.TotalTroops) + 150.0; bool flag = State.Clans.Get(s.ClanId)?.IsBandit ?? false; long num10 = (long)Math.Round(num7 * num9 * (flag ? 1.3 : 1.0) + 100.0); why = ((num7 > 0.5) ? "They think they would win." : "They aren't sure they would win."); return -num10; } case BarterKind.Tribute: { Encounter enc = LiveEncounter(s); double num4 = TheirWinChance(enc); Party party = TheirParty(s); long num5 = party?.Cargo.Sum((KeyValuePair kv) => (TradeGoods.Get(kv.Key)?.BasePrice ?? 0) * kv.Value) ?? 0; double num6 = (double)(TheirGold(s) + num5) + 40.0 * (double)(party?.Troops.TotalTroops ?? 0); why = ((num4 < 0.15) ? "They know they would be beaten." : "They might yet put up a fight."); return (long)Math.Round((1.0 - num4) * num6 * 0.8); } case BarterKind.Peace: { Clan clan = State.Clans.Get(s.ClanId); string faction = State.FactionOf(clan); string other = State.FactionOf(State.PlayerClan); double num3 = C.PactsSystem.PeaceWillingness(faction, other); why = ((num3 >= 0.1) ? "They are ready to end the war." : ((num3 >= -0.25) ? "They think the war still favours them." : "They expect to win this war.")); return (long)Math.Round((num3 - 0.1) * 6000.0); } case BarterKind.Recruit: { Hero h = State.Heroes.Get(s.HeroId); ClanRecruitmentQuote clanRecruitmentQuote = C.QuoteClanRecruitment(s.ClanId); double num = 1.0 - 0.15 * (double)Campaign.PersonalityOf(h).Generosity + 0.1 * (double)Campaign.PersonalityOf(h).Calculating; long num2 = (long)Math.Round((double)clanRecruitmentQuote.GoldCost * num); why = "Their house wants " + num2.ToString("N0", CultureInfo.InvariantCulture) + " in gold or in kind to swear to you."; return -num2; } default: return 0L; } } internal BarterEvaluation Evaluate(BarterSession s) { BarterEvaluation barterEvaluation = new BarterEvaluation(); if (s == null) { return barterEvaluation; } barterEvaluation.DealValue = DealValue(s, out var why); long num = 0L; barterEvaluation.Balance = barterEvaluation.DealValue; foreach (BarterItem item in s.Offer) { long num2 = ItemValue(s, item, item.Count); barterEvaluation.Balance += num2; if (num2 < 0) { num -= num2; } } if (barterEvaluation.DealValue < 0) { num -= barterEvaluation.DealValue; } Hero hero = State.Heroes.Get(s.HeroId); int num3 = ((hero != null && !string.IsNullOrEmpty(hero.ClanId)) ? C.ClanRelation(State.PlayerClanId, hero.ClanId) : 0); Campaign.Personality personality = Campaign.PersonalityOf(hero ?? new Hero { Id = "party:" + s.PartyId }); double num4 = Math.Max(0.0, 0.1 - (double)num3 / 600.0 + 0.05 * (double)personality.Calculating - 0.05 * (double)personality.Generosity); barterEvaluation.Needed = (long)Math.Round((double)num * num4); barterEvaluation.Acceptable = barterEvaluation.Balance >= barterEvaluation.Needed && (s.Kind != BarterKind.Trade || s.Offer.Count > 0) && (s.Kind != BarterKind.Tribute || s.Offer.Count > 0); barterEvaluation.Why = (barterEvaluation.Acceptable ? "They would accept." : ((s.Offer.Count == 0 && (s.Kind == BarterKind.Trade || s.Kind == BarterKind.Tribute)) ? "Put something on the table." : ("They want " + barterEvaluation.Shortfall.ToString("N0", CultureInfo.InvariantCulture) + " more. " + why))); return barterEvaluation; } internal CommandResult Balance(BarterSession s) { BarterEvaluation barterEvaluation = Evaluate(s); if (barterEvaluation.Acceptable) { return CommandResult.Success("They would already accept this."); } long num = barterEvaluation.Shortfall; BarterItem barterItem = s.Offer.FirstOrDefault((BarterItem x) => x.Kind == BarterItemKind.Gold && !x.FromPlayer); if (barterItem != null) { int num2 = (int)Math.Min(barterItem.Count, num); SetCount(s, BarterItemKind.Gold, "gold", fromPlayer: false, barterItem.Count - num2); num -= num2; } if (num > 0) { BarterItem? barterItem2 = s.Offer.FirstOrDefault((BarterItem x) => x.Kind == BarterItemKind.Gold && x.FromPlayer); int max = Stock(s, playerSide: true).First((BarterItem x) => x.Kind == BarterItemKind.Gold).Max; int num3 = barterItem2?.Count ?? 0; SetCount(s, BarterItemKind.Gold, "gold", fromPlayer: true, (int)Math.Min(max, num3 + num)); } BarterEvaluation barterEvaluation2 = Evaluate(s); if (!barterEvaluation2.Acceptable) { return CommandResult.Fail("Even all your gold isn't enough: " + barterEvaluation2.Why); } return CommandResult.Success("That would do it."); } internal CommandResult Offer(BarterSession s) { if (s == null || s.Finished) { return CommandResult.Fail("The bargaining is over."); } string text = StillValid(s); if (text.Length > 0) { s.Finished = true; s.Result = text; return CommandResult.Fail(text); } foreach (BarterItem item in s.Offer) { BarterItem barterItem = Stock(s, item.FromPlayer).FirstOrDefault((BarterItem x) => x.Kind == item.Kind && x.Id == item.Id); if (barterItem == null || barterItem.Max < item.Count) { return CommandResult.Fail(item.Name + " is no longer on offer."); } } BarterEvaluation barterEvaluation = Evaluate(s); if (!barterEvaluation.Acceptable) { return CommandResult.Fail(s.Counterparty + " refuses. " + barterEvaluation.Why); } if (s.Kind == BarterKind.Recruit) { long value = s.Offer.Where((BarterItem x) => x.Kind == BarterItemKind.Gold && x.FromPlayer).Sum((Func)((BarterItem x) => x.Count)); ClanRecruitmentQuote clanRecruitmentQuote = C.ClanAllegianceSystem.QuoteClanRecruitment(s.ClanId, ignoreRelation: false, value); if (!clanRecruitmentQuote.Ok) { return CommandResult.Fail(clanRecruitmentQuote.Reason); } Transfer(s, includeGold: false); CommandResult commandResult = C.ClanAllegianceSystem.RecruitClan(s.ClanId, null, value); if (!commandResult.Ok) { return commandResult; } s.Result = commandResult.Message; } else { Transfer(s, includeGold: true); s.Result = Conclude(s); } s.Finished = (s.Accepted = true); C.TrainDiplomacy(4.0); C.GrantSkillExperience(State.PlayerHero, "trade", 10.0); State.AddLog((s.Kind == BarterKind.Trade) ? LogCategory.Economy : LogCategory.Politics, s.Result, s.HeroId); State.Touch(); return CommandResult.Success(s.Result); } private string StillValid(BarterSession s) { switch (s.Kind) { case BarterKind.Bribe: case BarterKind.Tribute: if (LiveEncounter(s) != null) { return ""; } return "The moment for bargaining has passed."; case BarterKind.Ransom: if (State.Player.Activity != PlayerActivity.Captive || !(CaptorClan()?.Id == s.ClanId)) { return "You are no longer their prisoner."; } return ""; case BarterKind.Peace: { Clan clan = State.Clans.Get(s.ClanId); return C.PeaceOffers(State.FactionOf(clan)).FirstOrDefault()?.Reason ?? ""; } default: return ""; } } private void Transfer(BarterSession s, bool includeGold) { Party playerParty = State.PlayerParty; Party party = TheirParty(s); Clan clan = State.Clans.Get(s.ClanId); string reason = "Barter with " + s.Counterparty; foreach (BarterItem item in s.Offer.ToList()) { int count = item.Count; switch (item.Kind) { case BarterItemKind.Gold: if (!includeGold && item.FromPlayer) { break; } if (item.FromPlayer) { State.Transact(State.PlayerClan, -count, LedgerAccount.Trade, reason); if (PartyPurse(s)) { if (party != null) { party.Gold += count; } } else { State.Transact(clan, count, LedgerAccount.Trade, reason); } } else { if (PartyPurse(s)) { party.Gold -= count; } else { State.Transact(clan, -count, LedgerAccount.Trade, reason); } State.Transact(State.PlayerClan, count, LedgerAccount.Trade, reason); } break; case BarterItemKind.Goods: { Party party3 = (item.FromPlayer ? playerParty : party); Party party4 = (item.FromPlayer ? party : playerParty); party3.Cargo[item.Id] -= count; if (party3.Cargo[item.Id] <= 0) { party3.Cargo.Remove(item.Id); } if (party4 != null) { party4.Cargo[item.Id] = (party4.Cargo.TryGetValue(item.Id, out var value) ? value : 0) + count; } break; } case BarterItemKind.Horse: { HorseState horseState = C.Horse(item.Id); Hero hero = C.HorseRider(horseState); if (hero != null) { hero.MountId = ""; } State.Horses.Horses.Remove(horseState.Id); break; } case BarterItemKind.Prisoners: { Party obj = (item.FromPlayer ? playerParty : party); Party party2 = (item.FromPlayer ? party : playerParty); int healthy = obj.Prisoners.Remove(item.Id, count); obj.Prisoners.Prune(); party2?.Prisoners.Add(item.Id, healthy); break; } case BarterItemKind.Captive: OutcomeCommitter.ReleaseHero(C, State.Heroes.Get(item.Id), item.FromPlayer ? ("released to " + (clan?.Name ?? s.Counterparty) + " in a bargain") : "released to you in a bargain"); break; case BarterItemKind.Fief: { Settlement fief = State.Settlements.Get(item.Id); C.ChangeSettlementOwner(fief, clan.Id); foreach (Settlement item2 in State.Settlements.Where((Settlement v) => v.BoundTo == fief.Id && v.Type == SettlementType.Village && v.OwnerClanId == State.PlayerClanId).ToList()) { C.ChangeSettlementOwner(item2, clan.Id); } break; } } } } private string Conclude(BarterSession s) { string text = Describe(s.Offer.Where((BarterItem x) => x.FromPlayer)); string text2 = Describe(s.Offer.Where((BarterItem x) => !x.FromPlayer)); Clan clan = State.Clans.Get(s.ClanId); switch (s.Kind) { case BarterKind.Ransom: OutcomeCommitter.ReleaseHero(C, State.PlayerHero, "you paid your ransom"); return "You paid " + text + " for your freedom."; case BarterKind.Bribe: LetPlayerGo(s.EncounterId, "paid off " + s.Counterparty); return "You paid " + s.Counterparty + " " + text + " to let you pass."; case BarterKind.Tribute: { Encounter encounter = LiveEncounter(s); if (clan != null && !clan.IsBandit && clan.Id != State.PlayerClanId) { C.AdjustClanRelation(State.PlayerClanId, clan.Id, -3); } if (encounter != null) { C.CancelEncounter(encounter, "They paid tribute to be left alone."); Party party = TheirParty(s); if (party != null) { party.DisengagedUntilMinute = State.Clock.Minute + 480; } } return s.Counterparty + " handed over " + text2 + " to be left alone."; } case BarterKind.Peace: { string a = State.FactionOf(State.PlayerClan); string b = State.FactionOf(clan); string text3 = C.PactsSystem.MakeNegotiatedPeace(a, b, "", 0L); C.TrainDiplomacy(80.0); return text3 + ((text.Length > 0) ? (" You gave " + text + ".") : "") + ((text2.Length > 0) ? (" They gave " + text2 + ".") : ""); } default: return "You traded " + ((text.Length > 0) ? text : "nothing") + " for " + ((text2.Length > 0) ? text2 : "nothing") + " with " + s.Counterparty + "."; } } internal static string Describe(IEnumerable items) { List list = items.Select((BarterItem x) => (x.Kind != BarterItemKind.Gold) ? ((x.Kind != BarterItemKind.Goods && x.Kind != BarterItemKind.Prisoners) ? x.Name : (x.Count + " " + x.Name)) : (x.Count.ToString("N0", CultureInfo.InvariantCulture) + " denars")).ToList(); if (list.Count != 0) { if (list.Count != 1) { return string.Join(", ", list.Take(list.Count - 1)) + " and " + list[list.Count - 1]; } return list[0]; } return ""; } internal void LetPlayerGo(string encounterId, string how) { Encounter pendingPlayerEncounter = C.PendingPlayerEncounter; if (pendingPlayerEncounter == null || pendingPlayerEncounter.Id != encounterId) { return; } List list = pendingPlayerEncounter.PartiesOn((pendingPlayerEncounter.PlayerSide == BattleSide.Attacker) ? BattleSide.Defender : BattleSide.Attacker).ToList(); C.CancelEncounter(pendingPlayerEncounter, "The player " + how + ".", State.PlayerPartyId); foreach (string item in list) { Party party = State.Parties.Get(item); if (party != null) { party.DisengagedUntilMinute = State.Clock.Minute + 480; } } State.AddLog(LogCategory.Battle, "You " + how + ".", list.ToArray()); } internal Conversation StartRansomTalk() { if (Reason(BarterKind.Ransom, "", "").Length > 0) { return null; } BarterSession barterSession = Start(BarterKind.Ransom, "", ""); Hero hero = State.Heroes.Get(barterSession.HeroId); return new Conversation { HeroId = "", Role = "captor", Name = barterSession.Counterparty, Title = (State.Clans.Get(barterSession.ClanId)?.Name ?? ""), Barter = barterSession, Topic = "ransom", Lines = { (hero != null) ? "So. You wish to discuss the price of your freedom." : "Want out, do you? It'll cost you." }, Options = { new ConversationOption { Id = "bye", Text = "Never mind." } } }; } } public sealed class ClanRecruitmentQuote { public string Reason = ""; public string ClanId = ""; public string LeaderHeroId = ""; public string SponsorClanId = ""; public string FromKingdomId = ""; public string ToKingdomId = ""; public long GoldCost; public long CooldownDays; public int InfluenceCost = 20; public int RequiredRelation; public int Relation; public bool StartsWar; public bool EndsWar; public List HoldingIds = new List(); public bool Ok => string.IsNullOrEmpty(Reason); } public sealed class ConversationOption { public string Id = ""; public string Text = ""; public string Reason = ""; public bool Enabled => Reason.Length == 0; } public sealed class Conversation { public string HeroId = ""; public string Role = ""; public string Name = ""; public string Title = ""; public string SettlementId = ""; public string PlayerLine = ""; public List Lines = new List(); public string Note = ""; public List Options = new List(); public bool Ended; public PersuasionSession Persuasion; public BarterSession Barter; public string EncounterId = ""; public string PartyId = ""; internal string Topic = "root"; internal int Seed; internal int Turn; } public enum CrimeTier { None, Wanted, Outlaw, Hunted } public enum CampaignEventKind { Info, EncounterStarted, ArrivedAtSettlement, ArrivedAtDestination, TargetLost, PathAdjusted, Unreachable, BattleCommitted, Captured, Released, Starvation, Unpaid, Desertion, Warning, AiBattle, Autosave, Family } public sealed class CampaignEvent { public CampaignEventKind Kind; public string Text = ""; public List Links = new List(); public bool ForcesPause; } public sealed class SpeedFactor { public string Label = ""; public double Multiplier = 1.0; } public sealed class SpeedBreakdown { public double Speed; public List Factors = new List(); } public sealed class DeveloperSkipResult { public int Minutes; public string Stopped = ""; } public sealed class DifficultyOption { public string Id = ""; public string Name = ""; public string Help = ""; public double[] Values = new double[0]; public string[] Labels = new string[0]; public Func Get; public Action Set; public int IndexOf(CampaignSettings s) { double num = Get(s); int num2 = 0; for (int i = 1; i < Values.Length; i++) { if (Math.Abs(Values[i] - num) < Math.Abs(Values[num2] - num)) { num2 = i; } } return num2; } } public static class Difficulty { public const string Easy = "Easy"; public const string Normal = "Normal"; public const string Hard = "Hard"; public const string Realistic = "Realistic"; public const string Custom = "Custom"; public static readonly string[] Presets = new string[4] { "Easy", "Normal", "Hard", "Realistic" }; public static readonly DifficultyOption[] Options = new DifficultyOption[6] { new DifficultyOption { Id = "player-damage", Name = "You take damage", Help = "How much of each blow you take in battle, and in battles resolved without you fighting.", Values = new double[3] { 1.0 / 3.0, 2.0 / 3.0, 1.0 }, Labels = new string[3] { "1/3", "2/3", "Full" }, Get = (CampaignSettings s) => s.PlayerDamageTaken, Set = delegate(CampaignSettings s, double v) { s.PlayerDamageTaken = v; } }, new DifficultyOption { Id = "troop-damage", Name = "Your troops take damage", Help = "The same for the troops and companions in your own party. Mounted troops on TABS horses take full damage.", Values = new double[3] { 0.5, 0.75, 1.0 }, Labels = new string[3] { "1/2", "3/4", "Full" }, Get = (CampaignSettings s) => s.TroopDamageTaken, Set = delegate(CampaignSettings s, double v) { s.TroopDamageTaken = v; } }, new DifficultyOption { Id = "persuasion", Name = "Persuasion", Help = "Added to the chance of every argument you make when persuading someone.", Values = new double[4] { 0.2, 0.1, 0.0, -0.1 }, Labels = new string[4] { "Easy (+20%)", "Fair (+10%)", "Hard", "Stubborn (−10%)" }, Get = (CampaignSettings s) => s.PersuasionEase, Set = delegate(CampaignSettings s, double v) { s.PersuasionEase = v; } }, new DifficultyOption { Id = "map-speed", Name = "Your speed on the map", Help = "A bonus to your party's speed on the campaign map.", Values = new double[3] { 0.1, 0.05, 0.0 }, Labels = new string[3] { "+10%", "+5%", "Normal" }, Get = (CampaignSettings s) => s.PlayerMapSpeedBonus, Set = delegate(CampaignSettings s, double v) { s.PlayerMapSpeedBonus = v; } }, new DifficultyOption { Id = "disguise", Name = "Guards and disguises", Help = "How readily guards see through a disguise, at the gate and each day you stay.", Values = new double[4] { 0.6, 0.8, 1.0, 1.25 }, Labels = new string[4] { "Easily fooled", "Lax", "Watchful", "Sharp-eyed" }, Get = (CampaignSettings s) => s.DisguiseDetection, Set = delegate(CampaignSettings s, double v) { s.DisguiseDetection = v; } }, new DifficultyOption { Id = "ai-lords", Name = "Other lords' parties", Help = "How many troops other lords can lead. They still need the money to pay them.", Values = new double[3] { 0.85, 1.0, 1.15 }, Labels = new string[3] { "Smaller", "Normal", "Larger" }, Get = (CampaignSettings s) => s.AiLordStrength, Set = delegate(CampaignSettings s, double v) { s.AiLordStrength = v; } } }; private static readonly Dictionary PresetValues = new Dictionary(StringComparer.Ordinal) { ["Easy"] = new double[6] { 1.0 / 3.0, 0.5, 0.2, 0.1, 0.6, 0.85 }, ["Normal"] = new double[6] { 2.0 / 3.0, 0.75, 0.1, 0.05, 0.8, 1.0 }, ["Hard"] = new double[6] { 1.0, 1.0, 0.0, 0.0, 1.0, 1.0 }, ["Realistic"] = new double[6] { 1.0, 1.0, -0.1, 0.0, 1.25, 1.15 } }; public static string Describe(string preset) { return preset switch { "Easy" => "You and your troops are hard to kill, persuasion comes easily and other lords field smaller parties.", "Normal" => "You take two-thirds damage and your troops three-quarters; a little help with persuasion and speed.", "Hard" => "No help: you and your troops take full damage.", "Realistic" => "Full damage, stubborn people, sharp-eyed guards and larger enemy parties.", _ => "Your own mix of settings.", }; } public static void Apply(CampaignSettings s, string preset) { if (!PresetValues.TryGetValue(preset ?? "", out var value)) { throw new ArgumentException("Unknown difficulty " + preset + "."); } for (int i = 0; i < Options.Length; i++) { Options[i].Set(s, value[i]); } s.Difficulty = preset; } public static string PresetOf(CampaignSettings s) { string[] presets = Presets; foreach (string text in presets) { double[] values = PresetValues[text]; if (Options.Select((DifficultyOption o, int num) => Math.Abs(o.Get(s) - values[num]) < 1E-06).All((bool x) => x)) { return text; } } return "Custom"; } public static void SetOption(CampaignSettings s, DifficultyOption option, int index) { if (index < 0 || index >= option.Values.Length) { throw new ArgumentOutOfRangeException("index"); } option.Set(s, option.Values[index]); s.Difficulty = PresetOf(s); } public static void Normalise(CampaignSettings s) { double[] array = PresetValues["Hard"]; for (int i = 0; i < Options.Length; i++) { double num = Options[i].Get(s); if (double.IsNaN(num) || double.IsInfinity(num) || num < Options[i].Values.Min() - 1E-06 || num > Options[i].Values.Max() + 1E-06) { Options[i].Set(s, array[i]); } } s.Difficulty = PresetOf(s); } } public sealed class TradeQuote { public long Total; public string Reason = ""; public bool Ok => Reason.Length == 0; } public sealed class ShoppingLine { public string GoodId = ""; public string Name = ""; public int Count; public long Total; public double Weight; public string Reason = ""; public long AveragePrice { get { if (Count <= 0) { return 0L; } return (long)Math.Round((double)Total / (double)Count); } } } public sealed class ShoppingQuote { public List Lines = new List(); public long Total; public double Weight; public string Reason = ""; public bool Ok { get { if (Reason.Length == 0) { return Lines.Count > 0; } return false; } } } public enum EncyclopediaCategory { Heroes, Clans, Kingdoms, Settlements, Units, Concepts } public static class EncyclopediaLinks { private static readonly string[] Prefixes = new string[6] { "hero:", "clan:", "kingdom:", "settlement:", "unit:", "concept:" }; public static string For(EncyclopediaCategory category, string id) { return Prefixes[(int)category] + id; } public static bool TryParse(string link, out EncyclopediaCategory category, out string id) { category = EncyclopediaCategory.Heroes; id = ""; if (string.IsNullOrEmpty(link)) { return false; } for (int i = 0; i < Prefixes.Length; i++) { if (link.StartsWith(Prefixes[i], StringComparison.Ordinal) && link.Length > Prefixes[i].Length) { category = (EncyclopediaCategory)i; id = link.Substring(Prefixes[i].Length); return true; } } return false; } } public sealed class EncyclopediaEntry { public string Link = ""; public string Title = ""; public string Subtitle = ""; public string Color = ""; public string Symbol = ""; public string EmblemColor = ""; public EncyclopediaCategory Category; public bool Yours; public readonly SortedDictionary Facets = new SortedDictionary(StringComparer.Ordinal); public readonly SortedDictionary Numbers = new SortedDictionary(StringComparer.Ordinal); } public sealed class EncyclopediaQuery { public const string ByName = "Name"; public string Search = ""; public readonly SortedDictionary> Filters = new SortedDictionary>(StringComparer.Ordinal); public string Sort = "Name"; public bool Descending; public bool IsTicked(string group, string value) { if (Filters.TryGetValue(group, out var value2)) { return value2.Contains(value); } return false; } public void Toggle(string group, string value) { if (!Filters.TryGetValue(group, out var value2)) { value2 = (Filters[group] = new SortedSet(StringComparer.Ordinal)); } if (!value2.Remove(value)) { value2.Add(value); } if (value2.Count == 0) { Filters.Remove(group); } } } public sealed class EncyclopediaRow { public string Label = ""; public string Value = ""; public string Link = ""; public string Tip = ""; public int Indent; } public sealed class EncyclopediaSection { public string Title = ""; public string Text = ""; public readonly List Rows = new List(); public EncyclopediaSection Row(string label, string value, string link = "", string tip = "", int indent = 0) { Rows.Add(new EncyclopediaRow { Label = (label ?? ""), Value = (value ?? ""), Link = (link ?? ""), Tip = (tip ?? ""), Indent = indent }); return this; } } public sealed class EncyclopediaPage { public string Link = ""; public string Title = ""; public string Subtitle = ""; public string Color = ""; public string Symbol = ""; public string EmblemColor = ""; public string Summary = ""; public EncyclopediaCategory Category; public string MapTarget = ""; public readonly List Sections = new List(); public IEnumerable Links => from r in Sections.SelectMany((EncyclopediaSection s) => s.Rows) where r.Link.Length > 0 select r.Link; public EncyclopediaSection Section(string title, string text = "") { EncyclopediaSection encyclopediaSection = new EncyclopediaSection { Title = title, Text = (text ?? "") }; Sections.Add(encyclopediaSection); return encyclopediaSection; } } public sealed class EquipmentTradeQuote { public long Total; public string Reason = ""; public bool Ok => string.IsNullOrEmpty(Reason); } public static class HeroMemories { public const string Captured = "captured"; public const string Released = "released"; public const string Ransomed = "ransomed"; public const string ExecutedKin = "executed_kin"; public const string Defeated = "defeated"; public const string BeatYou = "beat_you"; public const string FoughtBeside = "fought_beside"; public const string Gift = "gift"; public const string SparWon = "spar_won"; public const string SparLost = "spar_lost"; public const string Lesson = "lesson"; public const string Favour = "favour"; } public sealed class HeroRetrainingQuote { public string HeroId = ""; public long Cost; public long ExpectedRevision; public string Reason = ""; public bool Allowed => string.IsNullOrEmpty(Reason); } public sealed class HerdSummary { public int Horses; public int Riders; public int Remounted; public int PackAnimals; public int Loose; public int People; public int Footmen; public double PackCapacity; public double FeedNeed; public double Grazing; public double FeedFromFood; public double SpeedFactor = 1.0; public double HerdingFactor = 1.0; } public sealed class HorseTradeQuote { public long Total; public string Reason = ""; public bool Ok => string.IsNullOrEmpty(Reason); } public sealed class HorseStats { public double Speed; public double Manoeuvre; public double Charge; public double HitPoints; public double Stamina; } public sealed class KingdomArmyCallQuote { public string Reason = ""; public string PartyId = ""; public string OwnerClanId = ""; public string LeaderHeroId = ""; public string KingdomId = ""; public string LeaderPartyId = ""; public int InfluenceCost = 20; public int DailyInfluence = 2; public int ServiceDays = 7; public bool Ok => string.IsNullOrEmpty(Reason); } public struct MoveSegment { public string PartyId; public Vec2 From; public Vec2 To; } public enum PeaceTermKind { WhitePeace, PayTribute, DemandTribute } public sealed class PeaceOffer { public PeaceTermKind Kind; public long DailyTribute; public int Days; public bool Accepted; public string Reason = ""; public string Why = ""; public bool Ok => Reason.Length == 0; } public sealed class PactQuote { public string Reason = ""; public string Why = ""; public bool Accepted; public long Payment; public bool Ok => Reason.Length == 0; } public enum PersuasionGoal { RecruitClan, Courtship, FreePrisoner, AvoidFight } public enum PersuasionOutcome { None, CriticalSuccess, Success, Failure, CriticalFailure } public sealed class PersuasionArgument { public string Id = ""; public string Text = ""; public string Skill = ""; public string Trait = ""; public int Bent; public double Chance; public double CriticalChance; public double BlunderChance; } public sealed class PersuasionSession { public PersuasionGoal Goal; public string HeroId = ""; public string PartyId = ""; public string TargetId = ""; public string EncounterId = ""; public string Request = ""; public int Progress; public int Required; public int Round; public int Rounds; public List Arguments = new List(); public SortedDictionary Uses = new SortedDictionary(StringComparer.Ordinal); public List History = new List(); public PersuasionOutcome Last; public bool Finished; public bool Won; public string Result = ""; public int RoundsLeft => Math.Max(0, Rounds - Round); } internal sealed class PersuasionSystem { private readonly Campaign C; private static readonly Dictionary Pool = new Dictionary { [PersuasionGoal.RecruitClan] = new(string, string, string, string, int)[7] { ("safety", "Your house would be safer under my banner.", "leadership", "valor", -1), ("reward", "I reward those who serve me, with land and with gold.", "trade", "generosity", -1), ("liege", "Has your liege ever done as much for you as I would?", "diplomacy", "calculating", 1), ("victory", "Ride with me and share in the victories to come.", "tactics", "valor", 1), ("word", "I keep my word. Ask anyone who has dealt with me.", "charm", "honor", 1), ("gain", "Think what your house stands to gain, and what it stands to lose.", "trade", "honor", -1), ("people", "Your people would prosper in a realm that protects its villages.", "stewardship", "mercy", 1) }, [PersuasionGoal.Courtship] = new(string, string, string, string, int)[7] { ("family", "Tell me of your family. I would like to know them.", "charm", "honor", 1), ("deeds", "Let me tell you of the battles I have fought.", "tactics", "valor", 1), ("verse", "I have a few lines of verse, if you'll hear them.", "charm", "mercy", 1), ("fortune", "I have plans for my house, and the coin to see them through.", "trade", "calculating", 1), ("folk", "I try to look after the people who depend on me.", "leadership", "mercy", 1), ("jest", "Shall I tell you what happened at the last feast I went to?", "charm", "calculating", -1), ("ride", "Ride out with me tomorrow. I know a fine stretch of country.", "riding", "valor", 1) }, [PersuasionGoal.FreePrisoner] = new(string, string, string, string, int)[6] { ("friend", "They are worth more to you as a friend than as a captive.", "charm", "calculating", 1), ("mercy", "Show mercy. They have done you no wrong.", "leadership", "mercy", 1), ("honour", "There is no honour in keeping them. Let them go.", "diplomacy", "honor", 1), ("remember", "I will remember this kindness, and repay it.", "leadership", "generosity", 1), ("threat", "Keep them, and you will have me to deal with.", "tactics", "valor", -1), ("cost", "Feeding and guarding them costs you. Why bother?", "stewardship", "generosity", -1) }, [PersuasionGoal.AvoidFight] = new(string, string, string, string, int)[6] { ("losses", "There's nothing here worth the men you would lose.", "tactics", "calculating", 1), ("foe", "We are not your enemy today. Let us both ride on.", "diplomacy", "mercy", 1), ("look", "Look at my men. Do you really want this fight?", "leadership", "valor", -1), ("honour", "Let us part as honourable foes, and meet another day.", "diplomacy", "honor", 1), ("poor", "We have nothing worth taking. Go and find richer prey.", "trade", "generosity", -1), ("ground", "You'd be fighting on my ground. Think about it.", "tactics", "valor", -1) } }; private CampaignState State => C.State; private ConversationsState Talks => State.Conversations ?? (State.Conversations = new ConversationsState()); private SortedDictionary Barred => Talks.PersuasionBarredUntilDay ?? (Talks.PersuasionBarredUntilDay = new SortedDictionary(StringComparer.Ordinal)); private SortedDictionary Persuaded => Talks.RecruitPersuadedUntilDay ?? (Talks.RecruitPersuadedUntilDay = new SortedDictionary(StringComparer.Ordinal)); internal PersuasionSystem(Campaign host) { C = host; } internal static string BarKey(PersuasionGoal goal, string targetId) { return goal switch { PersuasionGoal.AvoidFight => "avoid:", PersuasionGoal.FreePrisoner => "free:", PersuasionGoal.RecruitClan => "recruit:", _ => "court:", } + targetId; } internal bool RecruitPersuaded(string clanId) { if (!string.IsNullOrEmpty(clanId) && Persuaded.TryGetValue(clanId, out var value)) { return value >= State.Clock.Day; } return false; } internal List CaptivesToPlead(Hero lord) { if (lord == null || string.IsNullOrEmpty(lord.ClanId)) { return new List(); } Clan clan = State.Clans.Get(lord.ClanId); string realm = State.PlayerClan?.KingdomId ?? ""; return State.Heroes.Where((Hero x) => x.State == HeroState.Captive && !x.IsPlayer && C.HeroCaptorClan(x)?.Id == lord.ClanId && (x.ClanId == State.PlayerClanId || (realm.Length > 0 && State.Clans.Get(x.ClanId)?.KingdomId == realm)) && (clan?.LeaderHeroId == lord.Id || State.Parties.Get(x.CaptorPartyId)?.LeaderHeroId == lord.Id)).OrderBy((Hero x) => x.Id, StringComparer.Ordinal).ToList(); } internal string Reason(PersuasionGoal goal, string heroId, string targetId, string partyId) { Hero playerHero = State.PlayerHero; if (playerHero == null || (playerHero.State != HeroState.Active && goal != PersuasionGoal.AvoidFight)) { return "You're not free to talk."; } Hero hero = State.Heroes.Get(heroId ?? ""); string key = BarKey(goal, goal switch { PersuasionGoal.AvoidFight => C.PendingPlayerEncounter?.Id ?? "", PersuasionGoal.RecruitClan => hero?.ClanId ?? "", _ => targetId, }); if (goal != PersuasionGoal.Courtship && Barred.TryGetValue(key, out var value) && value > State.Clock.Day) { if (goal != PersuasionGoal.AvoidFight) { return (hero?.Name ?? "They") + " won't hear it again until day " + (value + 1) + "."; } return "They have heard enough from you."; } switch (goal) { case PersuasionGoal.RecruitClan: { Clan clan = ((hero == null) ? null : State.Clans.Get(hero.ClanId)); if (clan == null || clan.LeaderHeroId != hero.Id) { return "Only the head of a house can bring it into your realm."; } return C.ClanAllegianceSystem.QuoteClanRecruitment(clan.Id, ignoreRelation: true, 0L).Reason; } case PersuasionGoal.Courtship: if (hero != null) { return C.CourtReason(hero.Id); } return "There is nobody to court."; case PersuasionGoal.FreePrisoner: { Hero hero2 = State.Heroes.Get(targetId ?? ""); if (hero == null || hero2 == null) { return "There is nobody to free."; } if (!CaptivesToPlead(hero).Contains(hero2)) { return hero.Name + " doesn't hold " + hero2.Name + "."; } if (C.NamedCustodyReserved(hero2)) { return "Wait for the fighting around " + hero2.Name + " to finish."; } return ""; } default: { Encounter pendingPlayerEncounter = C.PendingPlayerEncounter; if (pendingPlayerEncounter == null || pendingPlayerEncounter.Phase != EncounterPhase.AwaitingDecision) { return "There is no fight to talk your way out of."; } if (pendingPlayerEncounter.Kind != EncounterKind.FieldBattle && pendingPlayerEncounter.Kind != EncounterKind.BanditAmbush) { return "This is no place for talking."; } if (pendingPlayerEncounter.MustFight) { return "Ironman: you've started this battle, so it has to be settled — fight, auto-resolve or surrender."; } if (pendingPlayerEncounter.InitiatorPartyId == State.PlayerPartyId) { return "You started this. You can simply ride away."; } Party party = EnemyLeaderParty(pendingPlayerEncounter); if (party == null) { return "There is nobody to talk to."; } if (!string.IsNullOrEmpty(partyId) && party.Id != partyId) { return "Talk to the one leading them."; } return ""; } } } internal Party EnemyLeaderParty(Encounter enc) { if (enc == null) { return null; } BattleSide side = ((enc.PlayerSide == BattleSide.Attacker) ? BattleSide.Defender : BattleSide.Attacker); return (from id in enc.PartiesOn(side) select State.Parties.Get(id) into p where p != null orderby p.Id == enc.InitiatorPartyId descending, p.Troops.TotalTroops descending select p).ThenBy((Party p) => p.Id, StringComparer.Ordinal).FirstOrDefault(); } internal PersuasionSession Start(PersuasionGoal goal, string heroId, string targetId, string partyId) { if (Reason(goal, heroId, targetId, partyId).Length > 0) { return null; } PersuasionSession persuasionSession = new PersuasionSession { Goal = goal, HeroId = (heroId ?? ""), TargetId = (targetId ?? ""), PartyId = (partyId ?? "") }; Hero hero = State.Heroes.Get(persuasionSession.HeroId); switch (goal) { case PersuasionGoal.RecruitClan: persuasionSession.TargetId = hero.ClanId; persuasionSession.Required = 3; persuasionSession.Rounds = 5; persuasionSession.Request = "bring " + (State.Clans.Get(hero.ClanId)?.Name ?? "their house") + " into your realm"; break; case PersuasionGoal.Courtship: persuasionSession.TargetId = hero.Id; persuasionSession.Required = 2; persuasionSession.Rounds = 3; persuasionSession.Request = "win " + Campaign.First(hero) + "'s heart a little more"; break; case PersuasionGoal.FreePrisoner: persuasionSession.Required = 3; persuasionSession.Rounds = 4; persuasionSession.Request = "free " + State.Heroes.Get(persuasionSession.TargetId).Name; break; default: { Encounter pendingPlayerEncounter = C.PendingPlayerEncounter; Party party = EnemyLeaderParty(pendingPlayerEncounter); persuasionSession.EncounterId = pendingPlayerEncounter.Id; persuasionSession.PartyId = party.Id; persuasionSession.TargetId = pendingPlayerEncounter.Id; if (persuasionSession.HeroId.Length == 0) { persuasionSession.HeroId = party.LeaderHeroId ?? ""; } persuasionSession.Required = 2; persuasionSession.Rounds = 3; persuasionSession.Request = "let you go without a fight"; break; } } DealArguments(persuasionSession); return persuasionSession; } internal Campaign.Personality BentOf(PersuasionSession s) { return Campaign.PersonalityOf(State.Heroes.Get(s.HeroId) ?? new Hero { Id = "party:" + s.PartyId }); } private static int TraitValue(Campaign.Personality p, string trait) { return trait switch { "honor" => p.Honor, "mercy" => p.Mercy, "valor" => p.Valor, "generosity" => p.Generosity, "calculating" => p.Calculating, _ => 0, }; } internal double BaseChance(PersuasionSession s) { Hero hero = State.Heroes.Get(s.HeroId); switch (s.Goal) { case PersuasionGoal.RecruitClan: { ClanRecruitmentQuote clanRecruitmentQuote = C.ClanAllegianceSystem.QuoteClanRecruitment(s.TargetId, ignoreRelation: true, 0L); return 0.42 - ((clanRecruitmentQuote.HoldingIds.Count > 0) ? 0.06 : 0.0) - (clanRecruitmentQuote.StartsWar ? 0.08 : 0.0); } case PersuasionGoal.Courtship: return 0.45; case PersuasionGoal.FreePrisoner: { Hero hero2 = State.Heroes.Get(s.TargetId); bool flag2 = hero2 != null && State.Clans.Get(hero2.ClanId)?.LeaderHeroId == hero2.Id; bool flag3 = hero != null && C.HeroIsEnemy(hero); return 0.38 - (flag2 ? 0.1 : 0.0) - (flag3 ? 0.12 : 0.0); } default: { Encounter encounter = State.Encounters.Get(s.EncounterId); BattleSide side = encounter?.PlayerSide ?? BattleSide.Defender; double num = ((encounter == null) ? 0.5 : (1.0 - AutoResolver.EstimateWinChance(C, encounter, side))); Party party = State.Parties.Get(s.PartyId); bool flag = State.Clans.Get(party?.ClanId ?? "")?.IsBandit ?? false; return 0.5 - (num - 0.5) * 0.7 - (flag ? 0.05 : 0.0); } } } internal int Relation(PersuasionSession s) { Hero hero = State.Heroes.Get(s.HeroId); if (hero != null && !string.IsNullOrEmpty(hero.ClanId)) { return C.ClanRelation(State.PlayerClanId, hero.ClanId); } return 0; } internal void DealArguments(PersuasionSession s) { s.Arguments.Clear(); (string, string, string, string, int)[] source = Pool[s.Goal]; Random rng = new Random(Campaign.StableSeed("persuade:" + s.Goal.ToString() + ":" + s.HeroId + ":" + s.PartyId + ":" + State.Clock.Minute.ToString(CultureInfo.InvariantCulture) + ":" + s.Round)); List<(string id, string text, string skill, string trait, int bent)> list = source.OrderBy(((string id, string text, string skill, string trait, int bent) _) => rng.Next()).Take(3).ToList(); Campaign.Personality p = BentOf(s); Hero playerHero = State.PlayerHero; double num = BaseChance(s) + Math.Max(-0.25, Math.Min(0.25, (double)Relation(s) / 300.0)) + C.Settings.PersuasionEase + Math.Max(0.0, Math.Min(0.3, C.PersonalPerk(State.PlayerHero, PerkEffect.Persuasion))); foreach (var item6 in list) { string item = item6.id; string item2 = item6.text; string item3 = item6.skill; string item4 = item6.trait; int item5 = item6.bent; int value; int num2 = (s.Uses.TryGetValue(item, out value) ? value : 0); double val = num + Math.Min(0.35, (double)(playerHero?.Skill(item3) ?? 0) / 600.0) + 0.15 * (double)TraitValue(p, item4) * (double)item5 - 0.12 * (double)num2; val = Math.Max(0.05, Math.Min(0.95, val)); s.Arguments.Add(new PersuasionArgument { Id = item, Text = item2, Skill = item3, Trait = item4, Bent = item5, Chance = val, CriticalChance = val * 0.2, BlunderChance = (1.0 - val) * 0.3 }); } } internal PersuasionOutcome Argue(PersuasionSession s, string argumentId) { if (s == null || s.Finished) { return PersuasionOutcome.None; } PersuasionArgument persuasionArgument = s.Arguments.FirstOrDefault((PersuasionArgument a) => a.Id == argumentId); if (persuasionArgument == null) { return PersuasionOutcome.None; } string text = StillValid(s); if (text.Length > 0) { s.History.Add(text); Finish(s, won: false, consequences: false); return PersuasionOutcome.None; } double num = State.Random.Get("conversations").NextDouble(); PersuasionOutcome persuasionOutcome = (s.Last = ((num < persuasionArgument.CriticalChance) ? PersuasionOutcome.CriticalSuccess : ((num < persuasionArgument.Chance) ? PersuasionOutcome.Success : ((num >= 1.0 - persuasionArgument.BlunderChance) ? PersuasionOutcome.CriticalFailure : PersuasionOutcome.Failure)))); s.Round++; s.Uses[persuasionArgument.Id] = (s.Uses.TryGetValue(persuasionArgument.Id, out var value) ? value : 0) + 1; int num2 = persuasionOutcome switch { PersuasionOutcome.CriticalFailure => -1, PersuasionOutcome.Success => 1, PersuasionOutcome.CriticalSuccess => 2, _ => 0, }; s.Progress = Math.Max(0, s.Progress + num2); s.History.Add(Campaign.SkillWord(persuasionArgument.Skill) + ": " + OutcomeWord(persuasionOutcome) + ((num2 > 0) ? (" (+" + num2 + ")") : ((num2 < 0) ? " (−1)" : ""))); C.GrantSkillExperience(State.PlayerHero, persuasionArgument.Skill, 6.0 * ((num2 > 0) ? 1.5 : 1.0)); if (persuasionOutcome == PersuasionOutcome.CriticalFailure && s.Goal != PersuasionGoal.AvoidFight) { Hero hero = State.Heroes.Get(s.HeroId); if (hero != null && hero.ClanId.Length > 0 && hero.ClanId != State.PlayerClanId) { C.AdjustClanRelation(State.PlayerClanId, hero.ClanId, -1); } } if (s.Progress >= s.Required) { Finish(s, won: true); } else if (s.Required - s.Progress > 2 * s.RoundsLeft || s.RoundsLeft == 0) { Finish(s, won: false); } else { DealArguments(s); } State.Touch(); return persuasionOutcome; } internal static string OutcomeWord(PersuasionOutcome o) { return o switch { PersuasionOutcome.CriticalFailure => "a blunder", PersuasionOutcome.Success => "well argued", PersuasionOutcome.CriticalSuccess => "a telling point", _ => "not convinced", }; } private string StillValid(PersuasionSession s) { switch (s.Goal) { case PersuasionGoal.RecruitClan: return C.ClanAllegianceSystem.QuoteClanRecruitment(s.TargetId, ignoreRelation: true, 0L).Reason; case PersuasionGoal.FreePrisoner: { Hero hero = State.Heroes.Get(s.HeroId); Hero hero2 = State.Heroes.Get(s.TargetId); if (hero == null || hero2 == null || !CaptivesToPlead(hero).Contains(hero2) || C.NamedCustodyReserved(hero2)) { return "There is nobody left to free."; } return ""; } case PersuasionGoal.AvoidFight: { Encounter pendingPlayerEncounter = C.PendingPlayerEncounter; if (pendingPlayerEncounter == null || !(pendingPlayerEncounter.Id == s.EncounterId) || pendingPlayerEncounter.Phase != EncounterPhase.AwaitingDecision) { return "The moment for talking has passed."; } return ""; } default: return ""; } } internal void Finish(PersuasionSession s, bool won, bool consequences = true) { if (s == null || s.Finished) { return; } s.Finished = true; s.Won = won; Hero hero = State.Heroes.Get(s.HeroId); if (!consequences) { return; } switch (s.Goal) { case PersuasionGoal.RecruitClan: if (won) { Persuaded[s.TargetId] = State.Clock.Day + 3; } else { Barred[BarKey(s.Goal, s.TargetId)] = State.Clock.Day + 10; } State.AddLog(LogCategory.Politics, won ? ("You persuaded " + hero?.Name + " to consider joining your realm.") : (hero?.Name + " would not be persuaded to join your realm."), s.HeroId); break; case PersuasionGoal.Courtship: s.Result = C.CourtshipSystem.CourtResult(s.HeroId, won).Message; break; case PersuasionGoal.FreePrisoner: { Hero hero2 = State.Heroes.Get(s.TargetId); if (won && hero2 != null && hero2.State == HeroState.Captive) { OutcomeCommitter.ReleaseHero(C, hero2, "freed at your request by " + (hero?.Name ?? "their captor")); State.AddLog(LogCategory.Captivity, hero?.Name + " freed " + hero2.Name + " at your request.", hero2.Id, s.HeroId); } else if (!won) { Barred[BarKey(s.Goal, s.TargetId)] = State.Clock.Day + 7; } break; } default: if (won) { C.BarterSystem.LetPlayerGo(s.EncounterId, "talked their way past " + (State.Parties.Get(s.PartyId)?.Name ?? "the enemy")); } else { Barred[BarKey(s.Goal, s.EncounterId)] = State.Clock.Day + 1; } break; } State.Touch(); } } public sealed class CommandResult { public bool Ok; public string Message = ""; public static CommandResult Success(string msg = "") { return new CommandResult { Ok = true, Message = msg }; } public static CommandResult Fail(string msg) { return new CommandResult { Ok = false, Message = msg }; } } public sealed class EncounterOptions { public bool CanFight; public bool CanSimulate; public bool CanLeave; public bool CanSacrifice; public bool CanSurrender; public string FightReason = ""; public string LeaveReason = ""; public int SacrificeCount; public double WinEstimate; public int FriendlyTroops; public int EnemyEstimate; } public sealed class BattlePlan { public Encounter Encounter; public BattleManifest Manifest; public int Budget; public BattleSide PlayerSide; public int PlayerSideAllowance; public int EnemySideAllowance; public Dictionary PlayerSideShares = new Dictionary(); public Dictionary EnemySideShares = new Dictionary(); public BattleMapDef Map; public bool MapIsStandIn; public ReinforcementConfig Config; public List SuggestedInitial = new List(); public List EnemyInitial = new List(); public int Eligible(BattleSide side) { return Manifest.OnSide(side).Count(); } public int Reserves(BattleSide side, IEnumerable initial) { return Eligible(side) - initial.Count(); } } public sealed class StoryOption { public string Id = ""; public string Text = ""; public string Reason = ""; public string Hint = ""; public bool Enabled => Reason.Length == 0; } public sealed class StoryPrompt { public string Kind = ""; public string SubjectId = ""; public string Title = ""; public string Speaker = ""; public string SpeakerRole = ""; public List Lines = new List(); public List Options = new List(); public string Note = ""; public bool Optional; } public sealed class QuestObjective { public string Text = ""; public bool Done; } public sealed class JournalEntry { public string Id = ""; public string Kind = ""; public string Title = ""; public string SourceLabel = ""; public string GiverName = ""; public string GiverLink = ""; public string Summary = ""; public string StatusText = ""; public bool Open; public bool Succeeded; public bool Tracked; public bool CanAbandon; public bool HasDecisionHere; public long Reward; public long StartedMinute; public long DeadlineMinute = -1L; public long EndedMinute = -1L; public List Objectives = new List(); public List Log = new List(); public List Places = new List(); } public sealed class StatLine { public string Label = ""; public double Value; } public sealed class StatForecast { public double Current; public double Change; public readonly List Lines = new List(); public double Next => Current + Change; internal void Add(string label, double value) { if (!double.IsNaN(value) && !(Math.Abs(value) < 1E-09)) { Lines.Add(new StatLine { Label = label, Value = value }); Change += value; } } internal void Bound(double low, double high) { if (Change < 0.0 && Current + Change < low) { Add("Lower limit", Math.Min(0.0, low - Current) - Change); } else if (Change > 0.0 && Current + Change > high) { Add("Upper limit", Math.Max(0.0, high - Current) - Change); } } } public sealed class FoodSource { public string Label = ""; public string GoodId = ""; public double Amount; } public sealed class FoodForecast { public double Stock; public double Capacity; public double Supply; public double Consumption; public double SupplyStored; public double CivilianConsumption; public double Change; public bool Besieged; public readonly List Lines = new List(); public readonly List Sources = new List(); public bool Starving { get { if (Consumption > 0.0) { return Stock + Supply - Consumption <= (Besieged ? 1E-06 : (-1E-09)); } return false; } } public double DaysLeft { get { if (!(Change >= -1E-09)) { return Stock / (0.0 - Change); } return double.PositiveInfinity; } } internal void Add(string label, double value) { if (!double.IsNaN(value) && !(Math.Abs(value) < 1E-09)) { Lines.Add(new StatLine { Label = label, Value = value }); } } } public sealed class WeaponDesignPreview { public string Reason = ""; public WeaponStats Stats; public int Difficulty; public int Tier; public double TierScore; public long Value; public double Stamina; public SortedDictionary Cost = new SortedDictionary(); public ForgingSetup Forging; public string DefaultName = ""; public bool Ok => string.IsNullOrEmpty(Reason); } public sealed class OrderEvaluation { public bool Success; public double RequiredSum; public double DeliveredSum; public long Reward; } public static class TownVisitRoles { public const string Hero = "visit.hero"; public const string Guard = "visit.guard"; public const string Merchant = "visit.merchant"; public const string Worker = "visit.worker"; public const string Priest = "visit.priest"; public const string Bard = "visit.bard"; public const string Drill = "visit.drill"; public const string Folk = "visit.folk"; public const string Child = "visit.child"; public const string Hidden = "visit.hidden"; public const string Noble = "visit.noble"; public const string Companion = "visit.companion"; public const string Lord = "visit.lord"; public const string KeepGuard = "visit.keepguard"; public const string Steward = "visit.steward"; public const string Prisoner = "visit.prisoner"; public const string GaolGuard = "visit.gaolguard"; public const string Watch = "visit.watch"; public const string Gang = "visit.gang"; public const string GangLeader = "visit.gangleader"; public const string Follower = "visit.follower"; public const string Condemned = "visit.condemned"; public const string Executioner = "visit.executioner"; public const string Crowd = "visit.crowd"; public static string Named(string role, string heroId) { return role + "|" + heroId; } public static string Split(string group, out string heroId) { heroId = ""; if (string.IsNullOrEmpty(group)) { return ""; } int num = group.IndexOf('|'); if (num < 0) { return group; } heroId = group.Substring(num + 1); return group.Substring(0, num); } } public sealed class CrimeMissionResult { public bool Success; public bool Alarm; public bool HeroDown; public int GuardsDowned; } public sealed class NewCampaignOptions { public string ScenarioId = ""; public string StartId = ""; public ulong Seed = 1uL; public string PlayerName = "Commander"; public string PlayerCulture = ""; public string PlayerHeroUnit = ""; public string ClanName = ""; public string BackgroundId = ""; public string TrainingId = ""; public string TraitId = ""; public string BannerColor = ""; public string BannerSymbol = ""; public string BannerEmblemColor = ""; public SortedDictionary LifeStages = new SortedDictionary(StringComparer.Ordinal); public int StartingAge; public SortedDictionary CreationFocus = new SortedDictionary(StringComparer.Ordinal); public string StartSettlementId = ""; public HeroEquipmentState Looks; public HeroSex PlayerSex; public string CampaignId = ""; public CampaignSettings Settings = new CampaignSettings(); public bool DeveloperTools; public List Realms = new List(); public List CustomFactions = new List(); } public sealed class RealmPlan { public List Realms = new List(); public CustomContentState Custom = new CustomContentState(); public ScenarioDef Scenario; } public static class CampaignFactory { public const long FirstMinute = 480L; public static RealmPlan PlanRealms(ContentDatabase content, NewCampaignOptions o, List errors) { if (o?.Realms == null || o.Realms.Count == 0 || o.ScenarioId != "scenario.continent") { return null; } RealmPlan realmPlan = new RealmPlan(); foreach (string id in o.Realms) { RealmSpec realmSpec = ProceduralWorld.DefaultRealm(id ?? ""); if (realmSpec != null && content.Cultures.Contains(id)) { realmPlan.Realms.Add(realmSpec); continue; } CustomFactionDef customFactionDef = (o.CustomFactions ?? new List()).FirstOrDefault((CustomFactionDef f) => f != null && CustomFactions.CultureId(f) == id); if (customFactionDef == null) { errors.Add("Unknown faction " + id + "."); continue; } string text = CustomFactions.Reason(customFactionDef); if (text.Length > 0) { errors.Add(text); continue; } CustomFactions.Build(customFactionDef, out var culture, out var units); realmPlan.Custom.Cultures.Add(culture); realmPlan.Custom.Units.AddRange(units); realmPlan.Realms.Add(CustomFactions.Realm(customFactionDef)); } string text2 = ProceduralWorld.RealmsError(realmPlan.Realms); if (text2.Length > 0) { errors.Add(text2); } if (errors.Count > 0) { return null; } if (ProceduralWorld.IsDefaultSet(realmPlan.Realms)) { return null; } CustomFactions.Register(content, realmPlan.Custom, replace: false); realmPlan.Scenario = ProceduralWorld.CreateScenario(content, realmPlan.Realms); return realmPlan; } public static List ValidateOptions(ContentDatabase content, NewCampaignOptions o) { List list = new List(); if (content == null) { list.Add("Campaign content is unavailable."); return list; } if (o == null) { list.Add("Choose your campaign settings."); return list; } RealmPlan realmPlan = PlanRealms(content, o, list); if (list.Count > 0) { return list; } ScenarioDef scenarioDef = realmPlan?.Scenario ?? content.Scenarios.Get(o.ScenarioId ?? ""); if (scenarioDef == null) { list.Add("Unknown scenario " + o.ScenarioId); return list; } PlayerStartDef playerStartDef = scenarioDef.PlayerStarts.FirstOrDefault((PlayerStartDef s) => s.Id == o.StartId); if (playerStartDef == null) { list.Add("Unknown start " + o.StartId); } ValidateName(o.PlayerName, "character", optional: false, list); ValidateName(o.ClanName, "clan", optional: true, list); if (!string.IsNullOrEmpty(o.PlayerCulture) && !content.Cultures.Contains(o.PlayerCulture)) { list.Add("Unknown culture " + o.PlayerCulture); } if (!string.IsNullOrEmpty(o.PlayerHeroUnit) && !content.Units.Contains(o.PlayerHeroUnit)) { list.Add("Unknown hero archetype " + o.PlayerHeroUnit); } if (o.Settings == null) { list.Add("Choose your campaign settings."); } else if (o.Settings.ActiveUnitBudget < 20 || o.Settings.ActiveUnitBudget > 400) { list.Add("Active unit budget must be between 20 and 400."); } if (!string.IsNullOrEmpty(o.BannerColor) && !CharacterCreation.IsBannerColor(o.BannerColor)) { list.Add("Pick a banner colour."); } if (!CharacterCreation.IsEmblemColor(o.BannerEmblemColor)) { list.Add("Pick an emblem colour."); } if (!string.IsNullOrEmpty(o.BannerSymbol) && !CharacterCreation.BannerSymbols.Contains(o.BannerSymbol)) { list.Add("Pick a banner emblem."); } if (HasLifeStages(o)) { if (HasLegacyChoices(o)) { list.Add("Choose a life story, or a background, training and trait."); } string text = CharacterCreation.FocusReason(o.LifeStages, o.StartingAge, o.CreationFocus); if (text.Length > 0) { list.Add(text); } } else if (o.StartingAge != 0 || (o.CreationFocus?.Count ?? 0) > 0) { list.Add("Choose your life story."); } if (o.Looks != null) { if (!HasCreationChoices(o)) { list.Add("Only a created character can choose their looks."); } EquipmentValidation.CheckLoadout(o.Looks, "Your character's looks", list); if (o.Looks.SlotItems().Any()) { list.Add("Your character's looks cannot include equipment."); } } if (!string.IsNullOrEmpty(o.StartSettlementId) && playerStartDef != null) { if (!string.IsNullOrEmpty(playerStartDef.Kingdom) || playerStartDef.Kind != StartKind.SmallWarband) { list.Add("Only an independent start can choose where to begin."); } bool num; if (realmPlan == null) { if (!content.Worlds.ContainsKey(scenarioDef.World)) { goto IL_03e9; } num = content.World(scenarioDef.World).Locations.Any((LocationDef l) => l.Id == o.StartSettlementId && l.Type != SettlementType.Hideout); } else { num = ProceduralWorld.SettlementIds(realmPlan.Realms).Contains(o.StartSettlementId); } if (!num) { goto IL_03e9; } } goto IL_03f4; IL_03f4: if (HasCreationChoices(o) && !HasLifeStages(o)) { if (!CharacterCreation.Backgrounds.Any((CharacterChoiceDef choice) => choice.Id == o.BackgroundId)) { list.Add("Choose your family background."); } if (!CharacterCreation.Trainings.Any((CharacterChoiceDef choice) => choice.Id == o.TrainingId)) { list.Add("Choose your training."); } if (!CharacterCreation.Traits.Any((CharacterChoiceDef choice) => choice.Id == o.TraitId)) { list.Add("Choose your starting trait."); } } if (HasCreationChoices(o) && playerStartDef != null) { string cultureId = (string.IsNullOrEmpty(o.PlayerCulture) ? playerStartDef.Culture : o.PlayerCulture); string archetypeId = ResolveHeroUnit(content, o, playerStartDef, cultureId); if (!CharacterCreation.Archetypes(content, cultureId, playerStartDef).Any((UnitDef unit) => unit.Id == archetypeId)) { list.Add("Pick an archetype available for this culture and start."); } } if (playerStartDef != null) { string text2 = (string.IsNullOrEmpty(o.PlayerCulture) ? playerStartDef.Culture : o.PlayerCulture); if (content.Cultures.Contains(text2)) { string text3 = ResolveHeroUnit(content, o, playerStartDef, text2); if (string.IsNullOrEmpty(text3) || !content.Units.Contains(text3)) { list.Add("This culture and campaign start need an available hero archetype."); } } } return list; IL_03e9: list.Add("Pick a town, castle or village to start in."); goto IL_03f4; } private static bool HasLegacyChoices(NewCampaignOptions o) { if (string.IsNullOrEmpty(o.BackgroundId) && string.IsNullOrEmpty(o.TrainingId)) { return !string.IsNullOrEmpty(o.TraitId); } return true; } private static bool HasLifeStages(NewCampaignOptions o) { if (o.LifeStages != null) { return o.LifeStages.Count > 0; } return false; } private static bool HasCreationChoices(NewCampaignOptions o) { if (!HasLegacyChoices(o)) { return HasLifeStages(o); } return true; } private static void ValidateName(string name, string subject, bool optional, List errors) { if (!optional && string.IsNullOrWhiteSpace(name)) { errors.Add("Enter a name for your " + subject + "."); } if (name != null && (name.Length > 40 || name.Any(char.IsControl) || name.IndexOf('<') >= 0 || name.IndexOf('>') >= 0)) { errors.Add("Your " + subject + " name must be at most 40 characters and contain no control characters or markup."); } } private static string ResolveHeroUnit(ContentDatabase content, NewCampaignOptions options, PlayerStartDef start, string cultureId) { if (!string.IsNullOrEmpty(options.PlayerHeroUnit)) { return options.PlayerHeroUnit; } if (HasCreationChoices(options) || cultureId != start.Culture) { return CharacterCreation.DefaultArchetype(content, cultureId, start); } if (string.IsNullOrEmpty(start.HeroUnit)) { return content.Culture(cultureId).HeroUnit; } return start.HeroUnit; } private static CampaignSettings CopySettings(CampaignSettings settings) { return new CampaignSettings { Difficulty = settings.Difficulty, ActiveUnitBudget = settings.ActiveUnitBudget, PlayerDamageTaken = settings.PlayerDamageTaken, TroopDamageTaken = settings.TroopDamageTaken, PersuasionEase = settings.PersuasionEase, PlayerMapSpeedBonus = settings.PlayerMapSpeedBonus, DisguiseDetection = settings.DisguiseDetection, AiLordStrength = settings.AiLordStrength, FullInformation = settings.FullInformation, HeroesCanDie = settings.HeroesCanDie, Ironman = settings.Ironman, AutosaveSlots = settings.AutosaveSlots, AutosaveIntervalDays = settings.AutosaveIntervalDays, PeopleAge = settings.PeopleAge, OldAgeDeaths = settings.OldAgeDeaths, Births = settings.Births, LordsMarry = settings.LordsMarry, Rebellions = settings.Rebellions, RandomEvents = settings.RandomEvents, AiGarrisonsImprove = settings.AiGarrisonsImprove }; } public static Campaign Create(ContentDatabase content, NewCampaignOptions o) { List list = ValidateOptions(content, o); if (list.Count > 0) { throw new ArgumentException(string.Join(" ", list)); } RealmPlan realmPlan = PlanRealms(content, o, new List()); ScenarioDef scenarioDef = realmPlan?.Scenario ?? content.Scenarios.Get(o.ScenarioId); PlayerStartDef playerStartDef = scenarioDef.PlayerStarts.First((PlayerStartDef s) => s.Id == o.StartId); WorldDef worldDef = ((realmPlan != null) ? ProceduralWorld.Generate(o.Seed, realmPlan.Realms) : ((scenarioDef.World == "world.continent") ? ProceduralWorld.Generate(o.Seed) : content.World(scenarioDef.World))); _ = content.Rules; CampaignState campaignState = new CampaignState(); campaignState.CampaignId = (string.IsNullOrEmpty(o.CampaignId) ? ("cmp-" + StableHash.Combine(o.Seed, StableHash.Fnv1a64(o.ScenarioId + "|" + o.StartId + "|" + o.PlayerName)).ToString("x16")) : o.CampaignId); campaignState.ScenarioId = scenarioDef.Id; campaignState.WorldId = worldDef.Id; campaignState.WorldGeneration = ((worldDef.GenerationVersion == 0) ? null : new WorldGenerationState { Version = worldDef.GenerationVersion, Seed = o.Seed, Realms = realmPlan?.Realms.Select((RealmSpec r) => new RealmSpec { Culture = r.Culture, Name = r.Name, Capital = r.Capital, MarketTown = r.MarketTown, Biome = r.Biome }).ToList() }); campaignState.CustomContent = ((realmPlan == null || realmPlan.Custom.Cultures.Count == 0) ? null : realmPlan.Custom); campaignState.PlayerStartId = playerStartDef.Id; campaignState.DeveloperTools = o.DeveloperTools; campaignState.DeveloperToolsDecided = true; campaignState.Content = content.Manifest; campaignState.Settings = CopySettings(o.Settings); campaignState.Random = new RandomStreams(o.Seed); CampaignState campaignState2 = campaignState; campaignState2.Clock.Minute = 480L; campaignState2.Clock.NextHourMinute = 540L; campaignState2.Clock.NextDayMinute = 1440L; RandomStream randomStream = campaignState2.Random.Get("names"); foreach (KingdomStartDef kingdom in scenarioDef.Kingdoms) { campaignState2.Kingdoms.Add(new Kingdom { Id = kingdom.Id, Name = kingdom.Name, CultureId = kingdom.Culture, RulerClanId = kingdom.RulerClan, Color = kingdom.Color, Symbol = kingdom.Symbol }); } foreach (LocationDef location in worldDef.Locations) { Settlement settlement = new Settlement { Id = location.Id, Name = location.Name, Type = location.Type, Position = new Vec2(location.X, location.Y), CultureId = location.Culture, BoundTo = location.BoundTo, Prosperity = location.Prosperity, BanditClanId = location.BanditClan, Product = location.Product, WallLevel = location.WallLevel, Militia = Campaign.StartingMilitia(location.Type, location.Id, location.Prosperity) }; for (int num = 0; num < location.RecruitSlots; num++) { if (location.Type == SettlementType.Hideout) { break; } settlement.Recruits.Add(new RecruitSlot()); } campaignState2.Settlements.Add(settlement); } HashSet used = new HashSet(StringComparer.Ordinal); foreach (ClanStartDef clan6 in scenarioDef.Clans) { Clan clan = new Clan { Id = clan6.Id, Name = clan6.Name, KingdomId = clan6.Kingdom, CultureId = clan6.Culture, Gold = clan6.Gold, Renown = clan6.Renown, IsBandit = clan6.IsBandit, Color = clan6.Color, Symbol = clan6.Symbol, BanditTroops = clan6.BanditTroops.Select((WeightedUnit w) => new WeightedUnit { Unit = w.Unit, Weight = w.Weight }).ToList() }; campaignState2.Clans.Add(clan); foreach (string settlement5 in clan6.Settlements) { campaignState2.Settlements.Require(settlement5).OwnerClanId = clan.Id; } } foreach (GarrisonStartDef garrison in scenarioDef.Garrisons) { foreach (RosterEntryDef troop in garrison.Troops) { campaignState2.Settlements.Require(garrison.Settlement).Garrison.Add(troop.Unit, troop.Count); } } foreach (Settlement item in campaignState2.Settlements.Where((Settlement x) => x.Type == SettlementType.Village && string.IsNullOrEmpty(x.OwnerClanId))) { item.OwnerClanId = campaignState2.Settlements.Get(item.BoundTo ?? "")?.OwnerClanId ?? ""; } foreach (StanceDef item2 in new List(scenarioDef.Stances)) { campaignState2.SetStance(item2.A, item2.B, item2.War ? Stance.War : Stance.Peace); } CultureDef cultureDef = content.Culture(string.IsNullOrEmpty(o.PlayerCulture) ? playerStartDef.Culture : o.PlayerCulture); string text = o.PlayerName.Trim(); Clan clan2 = new Clan { Id = "clan.player", Name = ((!string.IsNullOrWhiteSpace(o.ClanName)) ? o.ClanName.Trim() : (string.IsNullOrEmpty(playerStartDef.ClanName) ? (text + "'s Clan") : playerStartDef.ClanName)), KingdomId = playerStartDef.Kingdom, CultureId = cultureDef.Id, Gold = playerStartDef.Gold, Renown = playerStartDef.Renown, IsPlayerClan = true, Color = (string.IsNullOrEmpty(o.BannerColor) ? "#d9a441" : o.BannerColor), Symbol = (string.IsNullOrEmpty(o.BannerSymbol) ? "★" : o.BannerSymbol), EmblemColor = (o.BannerEmblemColor ?? "") }; if (HasLifeStages(o)) { clan2.Gold += CharacterCreation.StartingAge(o.StartingAge).Gold; } campaignState2.Clans.Add(clan2); campaignState2.PlayerClanId = clan2.Id; string text2 = ResolveHeroUnit(content, o, playerStartDef, cultureDef.Id); Hero hero = new Hero { Id = "hero.player", Name = text, ClanId = clan2.Id, CultureId = cultureDef.Id, UnitId = text2, Occupation = HeroOccupation.Player, IsPlayer = true, Level = 1, Sex = ((o.PlayerSex != HeroSex.Female) ? HeroSex.Male : HeroSex.Female), IsFamily = true }; hero.BornDay = -((long)((HasLifeStages(o) && o.StartingAge > 0) ? o.StartingAge : 30) * 84L); string[] all = SkillIds.All; foreach (string text3 in all) { hero.Skills[text3] = ((text3 == "riding") ? 15 : 5); } if (HasLifeStages(o)) { hero.Skills = CharacterCreation.LifeStageSkills(o.LifeStages); hero.OriginFocus = CharacterCreation.OriginFocus(o.StartingAge); hero.Attributes = CharacterCreation.LifeStageAttributes(o.LifeStages); hero.OriginAttributes = CharacterCreation.LifeStages.Count; SortedDictionary sortedDictionary = new SortedDictionary(StringComparer.Ordinal); foreach (KeyValuePair item3 in o.CreationFocus ?? new SortedDictionary(StringComparer.Ordinal)) { if (item3.Value > 0) { sortedDictionary[item3.Key] = item3.Value; } } foreach (KeyValuePair item4 in CharacterCreation.LifeStageFocus(o.LifeStages)) { hero.SkillFocus[item4.Key] = item4.Value; } foreach (KeyValuePair item5 in sortedDictionary) { hero.SkillFocus[item5.Key] = (hero.SkillFocus.TryGetValue(item5.Key, out var value) ? value : 0) + item5.Value; } hero.Creation = new CharacterCreationState { CultureId = cultureDef.Id, ArchetypeId = text2, BannerColor = clan2.Color, BannerSymbol = clan2.Symbol, BannerEmblemColor = clan2.EmblemColor, LifeStages = new SortedDictionary(o.LifeStages, StringComparer.Ordinal), Age = o.StartingAge, Focus = sortedDictionary, StartSettlementId = (o.StartSettlementId ?? "") }; hero.Description = string.Join(" ", CharacterCreation.LifeStages.Select((LifeStageDef stage) => CharacterCreation.LifeStageChoice(stage.Id, o.LifeStages[stage.Id]).Description)); } else if (HasCreationChoices(o)) { hero.Skills = CharacterCreation.StartingSkills(o.BackgroundId, o.TrainingId, o.TraitId); hero.Creation = new CharacterCreationState { BackgroundId = o.BackgroundId, TrainingId = o.TrainingId, TraitId = o.TraitId, CultureId = cultureDef.Id, ArchetypeId = text2, BannerColor = clan2.Color, BannerSymbol = clan2.Symbol, BannerEmblemColor = clan2.EmblemColor }; CharacterChoiceDef characterChoiceDef = CharacterCreation.Backgrounds.First((CharacterChoiceDef choice) => choice.Id == o.BackgroundId); CharacterChoiceDef characterChoiceDef2 = CharacterCreation.Trainings.First((CharacterChoiceDef choice) => choice.Id == o.TrainingId); CharacterChoiceDef characterChoiceDef3 = CharacterCreation.Traits.First((CharacterChoiceDef choice) => choice.Id == o.TraitId); hero.Description = characterChoiceDef.Description + " " + characterChoiceDef2.Description + " " + characterChoiceDef3.Description; } campaignState2.Heroes.Add(hero); campaignState2.PlayerHeroId = hero.Id; clan2.LeaderHeroId = hero.Id; if (playerStartDef.Kind == StartKind.Commander) { foreach (string sid in playerStartDef.OwnedSettlements) { Settlement settlement2 = campaignState2.Settlements.Require(sid); settlement2.OwnerClanId = clan2.Id; settlement2.Garrison = new TroopRoster(); foreach (Settlement item6 in campaignState2.Settlements.Where((Settlement x) => x.Type == SettlementType.Village && x.BoundTo == sid)) { item6.OwnerClanId = clan2.Id; } } foreach (GarrisonStartDef garrison2 in playerStartDef.Garrisons) { foreach (RosterEntryDef troop2 in garrison2.Troops) { campaignState2.Settlements.Require(garrison2.Settlement).Garrison.Add(troop2.Unit, troop2.Count); } } } Settlement settlement3 = campaignState2.Settlements.Require(string.IsNullOrEmpty(o.StartSettlementId) ? playerStartDef.StartLocation : o.StartSettlementId); Party party = new Party { Id = "party.player", Name = hero.Name + "'s Warband", Kind = PartyKind.Player, ClanId = clan2.Id, LeaderHeroId = hero.Id, HomeSettlementId = settlement3.Id, Position = settlement3.Position, Food = playerStartDef.Food, Morale = 60.0, State = PartyState.InSettlement, CurrentSettlementId = settlement3.Id }; party.Troops.Heroes.Add(hero.Id); foreach (RosterEntryDef troop3 in playerStartDef.Troops) { party.Troops.Add(troop3.Unit, troop3.Count); } hero.PartyId = party.Id; campaignState2.Parties.Add(party); campaignState2.PlayerPartyId = party.Id; campaignState2.Player.Activity = PlayerActivity.InSettlement; campaignState2.Player.MenuSettlementId = settlement3.Id; campaignState2.MerchantCaravansStarted = true; Campaign campaign = new Campaign(content, campaignState2); foreach (ClanStartDef item7 in scenarioDef.Clans.Where((ClanStartDef c) => !c.IsBandit)) { Clan clan3 = campaignState2.Clans.Require(item7.Id); Settlement settlement4 = (from s in campaignState2.Settlements where s.OwnerClanId == clan3.Id orderby (s.Type == SettlementType.Village) ? 1 : 0 select s).ThenBy((Settlement s) => s.Id, StringComparer.Ordinal).FirstOrDefault(); int num3 = 0; foreach (LordStartDef lord in item7.Lords) { CultureDef cultureDef2 = content.Culture(item7.Culture); string text4 = campaignState2.Ids.Allocate("hero"); Hero hero2 = new Hero { Id = text4, Name = (string.IsNullOrEmpty(lord.Name) ? PickName(cultureDef2, randomStream, used) : lord.Name), ClanId = clan3.Id, CultureId = item7.Culture, UnitId = (string.IsNullOrEmpty(lord.Unit) ? Campaign.LordUnitFor(content, item7.Culture, text4) : lord.Unit), Occupation = HeroOccupation.Lord, Level = 5 }; all = SkillIds.Original; foreach (string text5 in all) { hero2.Skills[text5] = ((text5 == "smithing" || text5 == "riding") ? 10 : (10 + randomStream.Range(0, 30))); } campaignState2.Heroes.Add(hero2); if (num3 == 0) { clan3.LeaderHeroId = hero2.Id; } num3++; if (settlement4 == null) { hero2.SettlementId = ""; continue; } Party party2 = campaign.CreateLordParty(hero2, settlement4); if (lord.Troops.Count > 0) { foreach (RosterEntryDef troop4 in lord.Troops) { party2.Troops.Add(troop4.Unit, troop4.Count); } } else { party2.Troops.Add(cultureDef2.BasicTroop, lord.PartyTroops); } } } foreach (Settlement item8 in campaignState2.Settlements.Where((Settlement s) => s.Type == SettlementType.Village).ToList()) { for (int num4 = 0; num4 < scenarioDef.VillagerPartiesPerVillage; num4++) { Clan clan4 = campaignState2.Clans.Get(item8.OwnerClanId); string basicTroop = content.Culture(item8.CultureId).BasicTroop; Party party3 = new Party { Id = campaignState2.Ids.Allocate("party"), Name = "Villagers of " + item8.Name, Kind = PartyKind.Villager, ClanId = (clan4?.Id ?? ""), HomeSettlementId = item8.Id, Position = item8.Position, State = PartyState.InSettlement, CurrentSettlementId = item8.Id, Morale = 50.0, WaitUntilMinute = campaignState2.Clock.Minute + 60 * randomStream.Range(1, 12) }; party3.Troops.Add(basicTroop, 4 + randomStream.Range(0, 5)); campaignState2.Parties.Add(party3); } } RandomStream randomStream2 = campaignState2.Random.Get("world"); foreach (Settlement item9 in campaignState2.Settlements.Where((Settlement s) => s.Type == SettlementType.Hideout).ToList()) { Clan clan5 = campaignState2.Clans.Get(item9.BanditClanId); for (int num5 = 0; num5 < 2; num5++) { if (clan5 == null) { break; } Party party4 = campaign.SpawnBanditParty(item9, clan5, randomStream2); for (int num6 = 0; num6 < 10; num6++) { Vec2 vec = new Vec2(randomStream2.Range(-4.0, 4.0), randomStream2.Range(-4.0, 4.0)); if (campaign.Nav.IsPassable(item9.Position + vec) && campaign.Nav.SameComponent(item9.Position, item9.Position + vec)) { party4.Position = item9.Position + vec; break; } } } } RandomStream randomStream3 = campaignState2.Random.Get("recruitment"); foreach (Settlement item10 in campaignState2.Settlements.Where((Settlement x) => x.Type != SettlementType.Hideout)) { CultureDef cultureDef3 = content.Culture(item10.CultureId); List list2 = ((item10.Type == SettlementType.Village) ? cultureDef3.VillageRecruits : cultureDef3.TownRecruits); foreach (RecruitSlot recruit in item10.Recruits) { if (list2.Count != 0 && randomStream3.Chance(0.75)) { int num7 = randomStream3.PickWeighted(list2.Select((WeightedUnit w) => w.Weight).ToList()); if (num7 >= 0) { recruit.UnitId = list2[num7].Unit; recruit.Available = true; } } } } campaign.EnsureNotableFields(); campaign.HeroDevelopmentSystem.EnsureHeroAttributes(); campaign.StartFamilies(); campaign.EnsureLordHorses(); campaign.StartMerchantCaravans(); campaign.RefreshContractOffers(); campaignState2.AddLog(LogCategory.Info, hero.Name + " begins their journey at " + settlement3.Name + ".", settlement3.Id); campaignState2.Revision = 1L; return campaign; } private static string PickName(CultureDef c, RandomStream rng, HashSet used) { for (int i = 0; i < 20; i++) { if (c.HeroNames.Count <= 0) { break; } string text = c.HeroNames[rng.Range(0, c.HeroNames.Count)]; if (used.Add(text)) { return text; } } string text2 = c.Name + " Lord " + (used.Count + 1); used.Add(text2); return text2; } } internal sealed class CaravansSystem { private readonly Campaign C; private NavGrid Nav => C.Nav; private CampaignState State => C.State; internal CaravansSystem(Campaign host) { C = host; } public void EnsureCaravanFields() { bool flag = false; if (State.Caravans == null) { State.Caravans = new List(); flag = true; } foreach (CaravanState caravan in State.Caravans) { if (caravan.CargoCosts == null) { caravan.CargoCosts = new SortedDictionary(StringComparer.Ordinal); flag = true; } } if (flag) { State.Touch(); } } internal CaravanState CaravanFor(Party p) { return State.Caravans.FirstOrDefault((CaravanState c) => c.PartyId == p?.Id && c.IsActive); } internal string CaravanCommandReason() { return C.CargoCommandReason(); } public int CaravanTradeSkill(Party p) { if (p == null || p.Kind != PartyKind.Caravan || C.IsMerchantCaravan(p)) { return 0; } Hero hero = State.Heroes.Get(p.LeaderHeroId ?? ""); if (hero == null || hero.State != HeroState.Active || !Campaign.IsPresentPartyHero(p, hero)) { return 0; } double val = ((p.ClanId == State.PlayerClanId) ? C.ClanPerk(State.PlayerClan, PerkEffect.CaravanTrade) : 0.0); return Math.Max(0, Math.Min(300, hero.Skill("trade") + (int)Math.Round(Math.Max(0.0, val)))); } internal Settlement CaravanMeetingTown() { Settlement settlement = C.CurrentSettlement(); if (settlement == null || settlement.Type != SettlementType.Town || !C.CanEnter(State.PlayerParty, settlement) || !(Vec2.Distance(State.PlayerParty.Position, settlement.Position) <= 0.01)) { return null; } return settlement; } public string LaunchCaravanReason(string companionId, string unitId) { string text = CaravanCommandReason(); if (text.Length > 0) { return text; } Settlement settlement = CaravanMeetingTown(); if (settlement == null) { return "Caravans set out from friendly towns."; } if (State.Caravans.Count((CaravanState c) => c.OwnerClanId == State.PlayerClanId && c.IsActive && !c.Merchant) >= 2) { return "Two caravans is the limit."; } Hero hero = State.Heroes.Get(companionId); if (!C.IsOwnedCompanion(hero) || !hero.CanFight || !Campaign.IsPresentPartyHero(State.PlayerParty, hero)) { return "Pick a healthy companion who's with you."; } if (State.Parties.Any((Party p) => p.LeaderHeroId == hero.Id && p.State != PartyState.Destroyed && p.State != PartyState.Disbanded)) { return "This companion already leads a party."; } if (C.UnitDef(unitId) == null || State.PlayerParty.Troops.Healthy(unitId) < 5) { return "The escort is five healthy soldiers of one type."; } if (State.PlayerClan.Gold < 1000) { return "A caravan needs 1000 denars to start with."; } if (settlement.Market?.Stock == null || !settlement.Market.Initialized) { return "The market here is closed."; } return ""; } public CommandResult LaunchCaravan(string companionId, string unitId) { string text = LaunchCaravanReason(companionId, unitId); if (text.Length > 0) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Require(companionId); Settlement settlement = CaravanMeetingTown(); Party playerParty = State.PlayerParty; int xp = playerParty.Troops.Find(unitId).Xp; playerParty.Troops.RemoveHealthy(unitId, 5); int xp2 = xp - (playerParty.Troops.Find(unitId)?.Xp ?? 0); Party party = new Party { Id = State.Ids.Allocate("party"), Name = hero.Name + "'s Caravan", Kind = PartyKind.Caravan, ClanId = State.PlayerClanId, LeaderHeroId = hero.Id, HomeSettlementId = settlement.Id, State = PartyState.InSettlement, CurrentSettlementId = settlement.Id, Position = settlement.Position, Gold = 1000L, CreatedAtMinute = State.Clock.Minute, NextThinkMinute = State.Clock.Minute }; party.Troops.Add(unitId, 5, 0, xp2); party.Troops.Heroes.Add(hero.Id); C.ClearHeroRoleAssignments(hero.Id); playerParty.Troops.Heroes.Remove(hero.Id); hero.PartyId = party.Id; hero.SettlementId = ""; C.HorseFollows(hero, playerParty, party); CaravanState item = new CaravanState { Id = State.Ids.Allocate("caravan"), PartyId = party.Id, OwnerClanId = party.ClanId, HomeSettlementId = settlement.Id, StartedMinute = State.Clock.Minute }; State.Parties.Add(party); State.Caravans.Add(item); State.Transact(State.PlayerClan, -1000L, LedgerAccount.Trade, "Funded " + party.Name); ResupplyCaravan(party, settlement); State.AddLog(LogCategory.Economy, party.Name + " formed at " + settlement.Name + ".", party.Id, settlement.Id); State.Touch(); return CommandResult.Success(party.Name + " is ready to trade."); } public string CaravanActionReason(string id, string action, long amount = 0L) { string text = CaravanCommandReason(); if (text.Length > 0) { return text; } CaravanState caravanState = State.Caravans.FirstOrDefault((CaravanState x) => x.Id == id); Party party = State.Parties.Get(caravanState?.PartyId ?? ""); if (caravanState == null || !caravanState.IsActive || caravanState.Merchant || caravanState.OwnerClanId != State.PlayerClanId || party == null || party.ClanId != caravanState.OwnerClanId || party.Kind != PartyKind.Caravan || party.State == PartyState.Destroyed || party.State == PartyState.Disbanded) { return "That caravan is gone."; } Hero hero = State.Heroes.Get(party.LeaderHeroId); if (hero == null || hero.State != HeroState.Active || !Campaign.IsPresentPartyHero(party, hero)) { return "This caravan has lost its leader."; } if (action == "recall") { if (!caravanState.RecallRequested) { return ""; } return "It's already heading back."; } if (action != "fund" && action != "withdraw" && action != "disband") { return "Unknown caravan action."; } Settlement settlement = CaravanMeetingTown(); if (settlement == null || party.State != PartyState.InSettlement || party.CurrentSettlementId != settlement.Id || Vec2.Distance(party.Position, settlement.Position) > 0.01 || !C.CanEnter(party, settlement)) { return "Meet the caravan at a friendly town first."; } if (action == "fund" || action == "withdraw") { if (amount <= 0) { return "Choose a positive amount."; } if (action == "fund" && (State.PlayerClan.Gold < amount || party.Gold > long.MaxValue - amount)) { return "Not enough money, or the caravan can't take it."; } if (action == "withdraw" && (party.Gold < amount || State.PlayerClan.Gold > long.MaxValue - amount)) { return "The caravan hasn't got it, or your treasury can't take it."; } } else { Party playerParty = State.PlayerParty; double num = C.CargoCapacity(playerParty) + (double)(CaravanGuardsJoining(party) * 2) + (double)(party.Troops.Heroes.Count * 10); if (C.CargoWeight(playerParty) + C.CargoWeight(party) > num + 1E-09) { return "No room for the caravan's cargo."; } string text2 = C.EquipmentReunionReason(party, playerParty); if (text2.Length > 0) { return text2; } if (State.PlayerClan.Gold > long.MaxValue - party.Gold) { return "Your treasury can't hold that much."; } foreach (TroopStack stack in party.Troops.Stacks) { if ((long)(playerParty.Troops.Find(stack.UnitId)?.Xp ?? 0) + (long)stack.Xp > int.MaxValue) { return "Your troops cannot hold more training experience."; } } foreach (TroopStack stack2 in party.Prisoners.Stacks) { if ((long)(playerParty.Prisoners.Find(stack2.UnitId)?.Xp ?? 0) + (long)stack2.Xp > int.MaxValue) { return "Your prisoner roster cannot hold more training experience."; } } } return ""; } public CommandResult RecallCaravan(string id) { string text = CaravanActionReason(id, "recall", 0L); if (text.Length > 0) { return CommandResult.Fail(text); } CaravanState caravanState = State.Caravans.First((CaravanState x) => x.Id == id); Party party = State.Parties.Require(caravanState.PartyId); caravanState.RecallRequested = true; caravanState.Status = "Returning"; party.NextThinkMinute = State.Clock.Minute; party.WaitUntilMinute = State.Clock.Minute; if (party.State != PartyState.Engaged && party.Order.Kind != OrderKind.Flee) { C.ClearOrder(party); } State.AddLog(LogCategory.Economy, party.Name + " has been recalled to a friendly town.", party.Id); State.Touch(); return CommandResult.Success("Caravan recalled."); } public CommandResult FundCaravan(string id, long amount) { return TransferCaravanFunds(id, amount, funding: true); } public CommandResult WithdrawCaravan(string id, long amount) { return TransferCaravanFunds(id, amount, funding: false); } internal CommandResult TransferCaravanFunds(string id, long amount, bool funding) { string text = CaravanActionReason(id, funding ? "fund" : "withdraw", amount); if (text.Length > 0) { return CommandResult.Fail(text); } Party party = State.Parties.Require(State.Caravans.First((CaravanState c) => c.Id == id).PartyId); party.Gold += (funding ? amount : (-amount)); State.Transact(State.PlayerClan, funding ? (-amount) : amount, LedgerAccount.Trade, (funding ? "Funded " : "Withdrew from ") + party.Name); State.Touch(); return CommandResult.Success("Transferred " + amount + " denars."); } public CommandResult DisbandCaravan(string id) { string text = CaravanActionReason(id, "disband", 0L); if (text.Length > 0) { return CommandResult.Fail(text); } CaravanState caravanState = State.Caravans.First((CaravanState x) => x.Id == id); Party party = State.Parties.Require(caravanState.PartyId); Party playerParty = State.PlayerParty; int num = CaravanGuardsJoining(party); int num2 = party.Troops.TotalTroops - num; int num3 = num; foreach (TroopStack item in party.Troops.Stacks.OrderByDescending((TroopStack st) => C.UnitDef(st.UnitId)?.Tier ?? 0).ThenBy((TroopStack st) => st.UnitId, StringComparer.Ordinal).ToList()) { int num4 = Math.Min(item.Healthy, num); int num5 = Math.Min(item.Wounded, num - num4); num -= num4 + num5; if (num4 + num5 != 0) { int xp = (int)((item.Total != 0) ? ((long)item.Xp * (long)(num4 + num5) / item.Total) : 0); playerParty.Troops.Add(item.UnitId, num4, num5, xp); } } party.Troops.Stacks.Clear(); string text2 = string.Join(" and ", (from heroId in party.Troops.Heroes select State.Heroes.Get(heroId)?.Name into n where !string.IsNullOrEmpty(n) select n).ToArray()); foreach (string item2 in party.Troops.Heroes.ToList()) { C.JoinCompanionToPlayerParty(State.Heroes.Require(item2)); } party.Troops.Heroes.Clear(); int num6 = CaravanPrisonersJoining(party, 0); int num7 = party.Prisoners.TotalTroops - num6; foreach (TroopStack item3 in party.Prisoners.Stacks.ToList()) { int num8 = Math.Min(item3.Healthy, num6); int num9 = Math.Min(item3.Wounded, num6 - num8); num6 -= num8 + num9; if (num8 + num9 != 0) { int xp2 = (int)((item3.Total != 0) ? ((long)item3.Xp * (long)(num8 + num9) / item3.Total) : 0); playerParty.Prisoners.Add(item3.UnitId, num8, num9, xp2); playerParty.Prisoners.Find(item3.UnitId).PrisonerRecruitment += item3.PrisonerRecruitment; } } party.Prisoners.Stacks.Clear(); foreach (string hero in party.Prisoners.Heroes) { playerParty.Prisoners.Heroes.Add(hero); State.Heroes.Require(hero).CaptorPartyId = playerParty.Id; } party.Prisoners.Heroes.Clear(); foreach (TradeGoodDef item4 in TradeGoods.All) { int num10 = C.CargoCount(party, item4.Id); if (num10 > 0) { playerParty.Cargo[item4.Id] = C.CargoCount(playerParty, item4.Id) + num10; } } party.Cargo.Clear(); C.ReuniteEquipment(party, playerParty); C.ReuniteHorses(party, playerParty); caravanState.CargoCosts.Clear(); playerParty.Food += party.Food; party.Food = 0.0; State.Transact(State.PlayerClan, party.Gold, LedgerAccount.Trade, "Closed " + party.Name); party.Gold = 0L; party.State = PartyState.Disbanded; party.LeaderHeroId = ""; party.RoleAssignments.Clear(); party.CurrentSettlementId = ""; C.ClearOrder(party); caravanState.Status = "Disbanded"; string text3 = ((num2 > 0) ? ("; " + num2 + ((num2 == 1) ? " guard" : " guards") + " didn't fit in your party and went home") : "") + ((num7 > 0) ? ("; " + num7 + " prisoners you had no room for were set free") : ""); string text4 = party.Name + " disbanded. " + ((text2.Length > 0) ? (text2 + " rejoins you, bringing") : "You take back") + " its cargo and money" + ((num3 > 0) ? (" and " + num3 + ((num3 == 1) ? " guard" : " guards")) : "") + text3 + "."; State.AddLog(LogCategory.Economy, text4, party.Id); TrimCaravanHistory(); State.Touch(); return CommandResult.Success(text4); } internal int CaravanGuardsJoining(Party caravan) { Party playerParty = State.PlayerParty; return Math.Max(0, Math.Min(caravan.Troops.TotalTroops, C.PartySizeLimit(playerParty) - playerParty.Troops.TotalTroops)); } private int CaravanPrisonersJoining(Party caravan, int joiningGuards) { Party playerParty = State.PlayerParty; int totalTroops = playerParty.Troops.TotalTroops; return Math.Max(0, Math.Min(caravan.Prisoners.TotalTroops, C.PrisonerLimit(playerParty) + (totalTroops + joiningGuards) / 4 - totalTroops / 4 - playerParty.Prisoners.TotalTroops)); } public (int guards, int prisoners) CaravanDisbandLosses(string id) { CaravanState caravanState = State.Caravans.FirstOrDefault((CaravanState x) => x.Id == id); Party party = State.Parties.Get(caravanState?.PartyId ?? ""); if (party == null) { return (guards: 0, prisoners: 0); } int num = CaravanGuardsJoining(party); return (guards: party.Troops.TotalTroops - num, prisoners: party.Prisoners.TotalTroops - CaravanPrisonersJoining(party, num)); } private void CaravanArrivedForRecall(Party p, CaravanState c, Settlement town) { bool num = c.Status != "Recalled"; c.Status = "Recalled"; if (num && town != null) { Hero hero = State.Heroes.Get(p.LeaderHeroId ?? ""); string text = p.Name + " is waiting for you at " + town.Name + ". Meet it there and disband it to take " + (hero?.Name ?? "its captain") + " and its guards back."; State.AddLog(LogCategory.Economy, text, town.Id); C.Raise(CampaignEventKind.Info, text, false, town.Id); } } internal IEnumerable CaravanMarkets(Party p) { return State.Settlements.Where((Settlement s) => (s.Type == SettlementType.Town || (s.Type == SettlementType.Village && !C.IsMerchantCaravan(p))) && s.Market?.Stock != null && s.Market.Initialized && C.CanEnter(p, s) && Nav.SameComponent(p.Position, s.Position)).OrderBy((Settlement s) => s.Id, StringComparer.Ordinal); } internal Settlement CaravanRecallTown(Party p, CaravanState c) { List source = (from s in CaravanMarkets(p) where s.Type == SettlementType.Town select s).ToList(); return source.FirstOrDefault((Settlement s) => s.Id == c.HomeSettlementId) ?? source.OrderBy((Settlement s) => Vec2.Distance(p.Position, s.Position)).ThenBy((Settlement s) => s.Id, StringComparer.Ordinal).FirstOrDefault(); } internal void CaravanOptions(Party p, double strength, List<(Party party, double strength, double dist)> hostiles, List options) { CaravanState c = CaravanFor(p); if (c == null) { return; } C.AddFleeOrFight(p, strength, hostiles, options, canEngage: false); if (c.RecallRequested) { Settlement town = CaravanRecallTown(p, c); options.Add(new Campaign.AiOption { Task = "Return caravan", Score = 0.9, Detail = (town?.Name ?? "No safe town"), Apply = delegate { if (town == null) { c.Status = "Waiting"; C.ClearOrder(p); } else if (p.State == PartyState.InSettlement && p.CurrentSettlementId == town.Id) { CaravanArrivedForRecall(p, c, town); C.ClearOrder(p); } else { c.Status = "Returning"; if (p.Order.Kind != OrderKind.GoToSettlement || p.Order.TargetId != town.Id) { C.SetMoveOrder(p, OrderKind.GoToSettlement, town.Position, town.Id, "caravan recall"); } } } }); return; } Settlement settlement = State.Settlements.Get(p.Order.TargetId); if (p.Order.Kind == OrderKind.GoToSettlement && settlement != null && C.CanEnter(p, settlement) && Nav.SameComponent(p.Position, settlement.Position)) { options.Add(new Campaign.AiOption { Task = "Trade at " + settlement.Name, Score = 0.8, Detail = "carrying goods" }); return; } options.Add(new Campaign.AiOption { Task = "Plan caravan route", Score = 0.8, Detail = "compare market prices", Apply = delegate { PlanCaravanDeparture(p, c); } }); } internal void PlanCaravanDeparture(Party p, CaravanState c) { Settlement current = ((p.State == PartyState.InSettlement) ? State.Settlements.Get(p.CurrentSettlementId) : null); bool flag = C.IsMerchantCaravan(p); int tradeSkill = CaravanTradeSkill(p); if (flag && current != null && current.Id == p.MerchantTownId && C.CanEnter(p, current)) { C.SettleMerchantAccounts(p, current); } if (c.ClanCaravan && current != null && current.Id == c.HomeSettlementId && C.CanEnter(p, current)) { C.SettleClanCaravan(p, c, current); } List list = (from s in CaravanMarkets(p) where s.Id != current?.Id select s).ToList(); Settlement settlement = ((flag && current != null && C.MerchantCaravanShouldGoHome(p)) ? list.FirstOrDefault((Settlement s) => s.Id == p.MerchantTownId) : ((c.ClanCaravan && current != null && C.ClanCaravanShouldGoHome(p)) ? list.FirstOrDefault((Settlement s) => s.Id == c.HomeSettlementId) : null)); if (settlement != null) { list = new List { settlement }; } Settlement settlement2 = null; double num = 0.0; string text = ""; int num2 = 0; long num3 = 0L; if (TradeGoods.All.Any((TradeGoodDef good) => C.CargoCount(p, good.Id) > 0)) { foreach (Settlement item in list) { double num4 = (double)CaravanSaleQuote(p, item) / (10.0 + Vec2.Distance(p.Position, item.Position)); if (num4 > num) { num = num4; settlement2 = item; } } } else if (current != null && C.CanEnter(p, current)) { ResupplyCaravan(p, current); foreach (TradeGoodDef item2 in TradeGoods.All) { int num5 = C.MarketStock(current, item2.Id); int val = (int)Math.Max(0.0, Math.Floor((C.CargoCapacity(p) - C.CargoWeight(p)) / item2.Weight)); int num6 = Math.Min(C.IsMerchantCaravan(p) ? 20 : 10, Math.Min(num5, val)); if (num6 <= 0) { continue; } long[] array = new long[num6 + 1]; for (int num7 = 1; num7 <= num6; num7++) { array[num7] = array[num7 - 1] + C.CommodityPrice(current, item2.Id, buying: true, num5 - num7 + 1, tradeSkill); } foreach (Settlement item3 in list) { int num8 = C.MarketStock(item3, item2.Id); double num9 = 10.0 + Vec2.Distance(current.Position, item3.Position); long num10 = 0L; for (int num11 = 1; num11 <= num6 && num8 + num11 <= 500; num11++) { long num12 = array[num11]; long num13 = C.CommodityPrice(item3, item2.Id, buying: false, num8 + num11, tradeSkill); if (num13 <= array[num11] - array[num11 - 1]) { break; } num10 += num13; if (num12 > Math.Max(0L, p.Gold - 200) || num10 > item3.Market.Gold || current.Market.Gold > long.MaxValue - num12) { break; } double num14 = (double)(num10 - num12) / num9; if (!(num14 <= num)) { num = num14; settlement2 = item3; text = item2.Id; num2 = num11; num3 = num12; } } } } } if (settlement2 == null && settlement != null) { settlement2 = settlement; } if (settlement2 == null && flag && current != null && C.CanEnter(p, current) && !TradeGoods.All.Any((TradeGoodDef good) => C.CargoCount(p, good.Id) > 0)) { settlement2 = C.MerchantSourceTown(p, current, list); } if (settlement2 == null && (current == null || !C.CanEnter(p, current))) { settlement2 = list.OrderBy((Settlement s) => Vec2.Distance(p.Position, s.Position)).ThenBy((Settlement s) => s.Id, StringComparer.Ordinal).FirstOrDefault(); } if (settlement2 == null) { c.Status = "Waiting"; C.ClearOrder(p); p.WaitUntilMinute = State.Clock.Minute + (flag ? 720 : 360); return; } if (!Nav.FindPath(p.Position, settlement2.Position).Success) { c.Status = "Waiting"; C.ClearOrder(p); return; } if (num2 > 0) { c.CargoCosts.Clear(); current.Market.Stock[text] -= num2; C.PayMarket(p, current.Market, num3); p.Gold -= num3; p.Cargo[text] = C.CargoCount(p, text) + num2; c.CargoCosts[text] = num3; } c.Status = "Trading"; p.DestinationSettlementId = settlement2.Id; c.LastArrivalSettlementId = ""; C.SetMoveOrder(p, OrderKind.GoToSettlement, settlement2.Position, settlement2.Id, "caravan trade"); State.Touch(); } internal long CaravanSaleQuote(Party p, Settlement s) { long num = 0L; int tradeSkill = CaravanTradeSkill(p); foreach (TradeGoodDef item in TradeGoods.All) { int num2 = C.MarketStock(s, item.Id); for (int i = 0; i < C.CargoCount(p, item.Id) && num2 + i < 500; i++) { long num3 = C.CommodityPrice(s, item.Id, buying: false, num2 + i + 1, tradeSkill); if (num3 > s.Market.Gold - num) { break; } num += num3; } } return num; } public void CaravanTradeArrival(Party p, Settlement s) { CaravanState caravanState = CaravanFor(p); if (caravanState == null || s == null || State.Parties.Get(p.Id) != p || p.Kind != PartyKind.Caravan || p.State != PartyState.InSettlement || p.CurrentSettlementId != s.Id || Vec2.Distance(p.Position, s.Position) > 0.01 || !C.CanEnter(p, s) || s.Market?.Stock == null || !s.Market.Initialized || caravanState.LastArrivalSettlementId == s.Id) { return; } caravanState.LastArrivalMinute = State.Clock.Minute; caravanState.LastArrivalSettlementId = s.Id; decimal num = default(decimal); int tradeSkill = CaravanTradeSkill(p); foreach (TradeGoodDef item in TradeGoods.All) { int num2 = C.CargoCount(p, item.Id); int i = 0; int num3 = C.MarketStock(s, item.Id); long num4 = 0L; for (; i < num2 && num3 + i < 500; i++) { long num5 = C.CommodityPrice(s, item.Id, buying: false, num3 + i + 1, tradeSkill); if (num5 > s.Market.Gold - num4 || p.Gold > long.MaxValue - num4 - num5) { break; } num4 += num5; } if (i != 0) { long value; long num6 = (caravanState.CargoCosts.TryGetValue(item.Id, out value) ? value : 0); long num7 = ((i == num2) ? num6 : ((long)decimal.Floor((decimal)num6 * (decimal)i / (decimal)num2))); num += (decimal)num4 - (decimal)num7; if (i == num2) { p.Cargo.Remove(item.Id); caravanState.CargoCosts.Remove(item.Id); } else { p.Cargo[item.Id] = num2 - i; caravanState.CargoCosts[item.Id] = num6 - num7; } s.Market.Stock[item.Id] = num3 + i; s.Market.Gold -= num4; p.Gold += num4; } } caravanState.LastTradeProfit = (long)Math.Max(-9223372036854775808m, Math.Min(9223372036854775807m, num)); caravanState.TotalTradeProfit = (long)Math.Max(-9223372036854775808m, Math.Min(9223372036854775807m, (decimal)caravanState.TotalTradeProfit + num)); if (!caravanState.Merchant && num > 0m) { Hero hero = State.Heroes.Get(p.LeaderHeroId ?? ""); if (hero != null && hero.ClanId == State.PlayerClanId && Campaign.IsPresentPartyHero(p, hero)) { C.GrantDailySkillExperience(hero, "trade", (double)num * 0.1, 100.0); } } ResupplyCaravan(p, s); p.WaitUntilMinute = State.Clock.Minute + 60; if (caravanState.RecallRequested && CaravanRecallTown(p, caravanState)?.Id == s.Id) { CaravanArrivedForRecall(p, caravanState, s); } else { caravanState.Status = (caravanState.RecallRequested ? "Returning" : "Trading"); } State.Touch(); } internal void ResupplyCaravan(Party p, Settlement s) { if (s.Market != null && C.CanEnter(p, s) && p.Gold > 0 && !(C.SettlementFood(s) <= 0.0)) { double val = Math.Max(0.0, C.DailyFoodNeed(p) * 4.0 - p.Food); double num = Math.Max(1.0, C.FoodPrice(s)); double num2 = Math.Min(val, Math.Min(C.SettlementFood(s), (double)Math.Min(p.Gold, long.MaxValue - s.Market.Gold) / num)); long num3 = (long)Math.Ceiling(num2 * num); if (!(num2 <= 0.0) && num3 <= p.Gold && num3 <= long.MaxValue - s.Market.Gold) { p.Food += C.TakeSettlementFood(s, num2); p.Gold -= num3; C.PayMarket(p, s.Market, num3); } } } public void DailyCaravans() { ReconcileCaravans(); C.DailyMerchantCaravans(); C.DailyClanCaravans(); foreach (CaravanState item in State.Caravans.Where((CaravanState x) => x.IsActive)) { Party party = State.Parties.Get(item.PartyId); if (party != null && party.State == PartyState.InSettlement) { Settlement settlement = State.Settlements.Get(party.CurrentSettlementId); if (settlement != null && C.CanEnter(party, settlement)) { ResupplyCaravan(party, settlement); continue; } party.WaitUntilMinute = 0L; party.NextThinkMinute = 0L; } } } public void ReconcileCaravans() { bool flag = false; foreach (CaravanState item in State.Caravans.Where((CaravanState x) => x.IsActive).ToList()) { if (item.Merchant) { if (C.ReconcileMerchantCaravan(item)) { flag = true; } continue; } if (item.ClanCaravan) { if (C.ReconcileClanCaravan(item)) { flag = true; } continue; } Party p = State.Parties.Get(item.PartyId); Hero hero = State.Heroes.Get(p?.LeaderHeroId ?? ""); foreach (string item2 in item.CargoCosts.Keys.Where((string id) => C.CargoCount(p, id) == 0).ToList()) { item.CargoCosts.Remove(item2); flag = true; } if (p != null && p.Kind == PartyKind.Caravan && p.ClanId == item.OwnerClanId && p.State != PartyState.Destroyed && p.State != PartyState.Disbanded && hero != null && hero.State == HeroState.Active && Campaign.IsPresentPartyHero(p, hero)) { continue; } if (p != null && p.State != PartyState.Destroyed && p.State != PartyState.Disbanded) { int totalTroops = p.Troops.TotalTroops; p.Troops.Stacks.Clear(); OutcomeCommitter.DestroyParty(C, p, "caravan leader lost"); if (totalTroops > 0) { State.AddLog(LogCategory.Battle, totalTroops + " troops of " + p.Name + " scattered after losing their leader.", p.Id); } } item.Status = "Lost"; item.CargoCosts.Clear(); string text = (p?.Name ?? "Caravan") + " was lost."; if (hero != null && hero.State == HeroState.Captive) { text = text + " " + hero.Name + " is captive."; } State.AddLog(LogCategory.Economy, text, item.PartyId); if (item.OwnerClanId == State.PlayerClanId) { C.Raise(CampaignEventKind.Warning, text, false, item.PartyId, hero?.Id ?? ""); } flag = true; } if (TrimCaravanHistory()) { flag = true; } if (flag) { State.Touch(); } } internal bool TrimCaravanHistory() { List list = State.Caravans.Where((CaravanState caravanState) => !caravanState.IsActive && (caravanState.Merchant || caravanState.ClanCaravan)).Concat((from caravanState in State.Caravans where !caravanState.IsActive && !caravanState.Merchant && !caravanState.ClanCaravan orderby caravanState.StartedMinute descending select caravanState).ThenByDescending((CaravanState caravanState) => caravanState.Id, StringComparer.Ordinal).Skip(30)).ToList(); bool result = false; foreach (CaravanState c in list) { Party party = State.Parties.Get(c.PartyId); if (State.Encounters.Any((Encounter e) => e.Phase != EncounterPhase.Committed && e.Phase != EncounterPhase.Cancelled && (e.InitiatorPartyId == c.PartyId || e.AllParties.Contains(c.PartyId))) || State.Heroes.Any((Hero h) => h.PartyId == c.PartyId || h.CaptorPartyId == c.PartyId)) { continue; } if (party != null) { if (party.Kind != PartyKind.Caravan || (party.State != PartyState.Destroyed && party.State != PartyState.Disbanded) || !party.Troops.IsEmpty || !party.Prisoners.IsEmpty || party.Gold != 0L || party.Food != 0.0 || party.Cargo.Count != 0) { continue; } SortedDictionary equipment = party.Equipment; if (equipment != null && equipment.Count > 0) { continue; } State.Parties.Remove(party.Id); } State.PlayerSightings.Remove(c.PartyId); State.Caravans.Remove(c); result = true; } return result; } } internal sealed class CargoConsequencesSystem { private readonly Campaign C; private CampaignState State => C.State; internal CargoConsequencesSystem(Campaign host) { C = host; } public string SeizeCargo(Party source, Party captor) { if (source == null || source == captor) { return ""; } if (source.Cargo == null || source.Cargo.Count == 0) { return C.SeizeEquipment(source, captor); } int num = 0; int num2 = 0; bool flag = captor != null && captor.State != PartyState.Destroyed && captor.State != PartyState.Disbanded; foreach (TradeGoodDef item in TradeGoods.All.OrderBy((TradeGoodDef x) => x.Id, StringComparer.Ordinal)) { int num3 = C.CargoCount(source, item.Id); if (num3 > 0) { int val = (flag ? ((int)Math.Max(0.0, Math.Floor((C.CargoCapacity(captor) - C.CargoWeight(captor)) / item.Weight))) : 0); int num4 = Math.Min(num3, val); if (num4 > 0) { captor.Cargo[item.Id] = C.CargoCount(captor, item.Id) + num4; } num += num4; num2 += num3 - num4; } } source.Cargo.Clear(); string text = source.Name + " lost its cargo: " + num + " taken" + ((num > 0) ? (" by " + captor.Name) : "") + ((num2 > 0) ? (", " + num2 + " abandoned") : "") + "."; State.AddLog(LogCategory.Economy, text, source.Id); string text2 = C.SeizeEquipment(source, captor); if (text2.Length != 0) { return text + " " + text2; } return text; } } internal sealed class ClanAllegianceSystem { private readonly Campaign C; private CampaignState State => C.State; internal ClanAllegianceSystem(Campaign host) { C = host; } public void EnsureClanAllegianceFields() { bool flag = false; if (State.ClanAllegiance == null) { State.ClanAllegiance = new ClanAllegianceState(); flag = true; } if (State.ClanAllegiance.Records == null) { State.ClanAllegiance.Records = new List(); flag = true; } if (!State.ClanAllegiance.Initialized) { State.ClanAllegiance.Initialized = true; State.ClanAllegiance.LastAiDay = State.Clock.Day; flag = true; } if (flag) { State.Touch(); } } public long ClanAllegianceCooldown(string clanId) { return Math.Max(0L, (State.ClanAllegiance?.Records?.FirstOrDefault((ClanAllegianceRecord r) => r.ClanId == clanId)?.CooldownUntilDay ?? State.Clock.Day) - State.Clock.Day); } internal IEnumerable ClanAllegianceHoldings(string clanId) { return State.Settlements.Where((Settlement s) => s.Type != SettlementType.Hideout && s.OwnerClanId == clanId).OrderBy((Settlement s) => s.Id, StringComparer.Ordinal); } internal bool FreeClanNegotiator(Clan clan) { Hero hero = State.Heroes.Get(clan?.LeaderHeroId); if (C.LivingPoliticalClan(clan) && hero != null && hero.CanFight && string.IsNullOrEmpty(hero.CaptorPartyId)) { return string.IsNullOrEmpty(hero.CaptorSettlementId); } return false; } internal bool IsRulingClan(Clan clan) { if (clan != null) { return State.Kingdoms.Any((Kingdom k) => !k.IsEliminated && k.RulerClanId == clan.Id); } return false; } internal string RecruitmentAuthorityReason() { string text = C.KingdomCourtReason(); if (text.Length > 0) { return text; } if (State.ClanAllegiance == null || !State.ClanAllegiance.Initialized || State.Politics == null || !State.Politics.Initialized || State.Diplomacy == null || !State.Diplomacy.Initialized) { return "Clan allegiance is unavailable."; } if (State.ClanService.Kind != ClanServiceKind.Ruler || State.ClanService.KingdomId != State.PlayerClan.KingdomId || C.ServiceRuler(State.PlayerClan.KingdomId)?.Id != State.PlayerClanId) { return "Only a ruler can offer vassalage."; } return ""; } public ClanRecruitmentQuote QuoteClanRecruitment(string targetClanId) { return QuoteClanRecruitment(targetClanId, ignoreRelation: false, null); } internal ClanRecruitmentQuote QuoteClanRecruitment(string targetClanId, bool ignoreRelation, long? payment) { ClanRecruitmentQuote quote = new ClanRecruitmentQuote { ClanId = (targetClanId ?? ""), SponsorClanId = State.PlayerClanId, ToKingdomId = (State.PlayerClan?.KingdomId ?? ""), InfluenceCost = 20 }; Clan target = State.Clans.Get(targetClanId); ClanRecruitmentQuote clanRecruitmentQuote; int startsWar; if (target != null) { quote.LeaderHeroId = target.LeaderHeroId; quote.FromKingdomId = target.KingdomId; List list = ClanAllegianceHoldings(target.Id).ToList(); quote.HoldingIds = list.Select((Settlement s) => s.Id).ToList(); quote.GoldCost = payment ?? (1000 + ((IEnumerable)list).Sum((Func)((Settlement s) => (s.Type != SettlementType.Village) ? 500 : 100))); quote.CooldownDays = ClanAllegianceCooldown(target.Id); quote.Relation = C.ClanRelation(State.PlayerClanId, target.Id); Clan clan = C.ServiceRuler(target.KingdomId); quote.RequiredRelation = (string.IsNullOrEmpty(target.KingdomId) ? 10 : (((list.Count == 0) ? 20 : 30) + Math.Max(0, C.ClanRelation(target.Id, clan?.Id) / 2))); clanRecruitmentQuote = quote; if (list.Count > 0) { Kingdom kingdom = State.Kingdoms.Get(target.KingdomId); if (kingdom != null && !kingdom.IsEliminated && target.KingdomId != quote.ToKingdomId) { startsWar = ((!State.AtWar(target.KingdomId, quote.ToKingdomId)) ? 1 : 0); goto IL_0284; } } startsWar = 0; goto IL_0284; } goto IL_02ca; IL_0284: clanRecruitmentQuote.StartsWar = (byte)startsWar != 0; quote.EndsWar = string.IsNullOrEmpty(target.KingdomId) && State.AtWar(target.Id, quote.ToKingdomId); goto IL_02ca; IL_02ca: quote.Reason = RecruitmentAuthorityReason(); if (quote.Reason.Length > 0) { return quote; } if (target == null || target.Id == State.PlayerClanId || target.IsPlayerClan || !FreeClanNegotiator(target)) { quote.Reason = "Pick a noble clan whose leader is fit and free."; } else if (IsRulingClan(target)) { quote.Reason = "A ruling clan can't be recruited."; } else if (target.KingdomId == quote.ToKingdomId) { quote.Reason = "Already one of yours."; } else if (!string.IsNullOrEmpty(target.KingdomId) && !State.Kingdoms.Contains(target.KingdomId)) { quote.Reason = "Can't tell where this clan stands right now."; } else if (quote.CooldownDays > 0) { quote.Reason = "This clan can't switch sides for another " + quote.CooldownDays + " days."; } else if (C.DiplomacyFactionReserved(State.FactionOf(target)) || C.DiplomacyFactionReserved(quote.ToKingdomId) || C.DiplomacyFactionReserved(target.Id)) { quote.Reason = "Wait for the fighting involving these factions to finish."; } else if (string.IsNullOrEmpty(target.KingdomId) && State.Diplomacy.Truces.Any((DiplomaticTruce t) => t.EndsDay > State.Clock.Day && (t.A == target.Id || t.B == target.Id))) { quote.Reason = "Wait for this clan's truces to run out first."; } else if (string.IsNullOrEmpty(target.KingdomId) && State.Stances.Any((StanceRecord s) => s.Stance == Stance.War && ((s.A == target.Id && s.B != quote.ToKingdomId && C.KnownDiplomacyFaction(s.B)) || (s.B == target.Id && s.A != quote.ToKingdomId && C.KnownDiplomacyFaction(s.A))))) { quote.Reason = "This clan has wars to settle first."; } else if (quote.HoldingIds.Count > 0 && !string.IsNullOrEmpty(target.KingdomId) && C.TruceDaysRemaining(target.KingdomId, quote.ToKingdomId) > 0) { quote.Reason = "Taking this landed clan would break your truce with its kingdom."; } else if (quote.Relation < quote.RequiredRelation && !ignoreRelation && !C.RecruitPersuaded(target.Id)) { quote.Reason = "This clan requires " + quote.RequiredRelation + " relation with you (currently " + quote.Relation + ")."; } else if (State.PlayerClan.Gold < quote.GoldCost) { quote.Reason = "Your clan needs " + quote.GoldCost + " denars for the signing payment."; } else if (target.Gold < 0 || target.Gold > long.MaxValue - quote.GoldCost) { quote.Reason = "This clan can't take the signing payment."; } else if (double.IsNaN(State.PlayerClan.Influence) || double.IsInfinity(State.PlayerClan.Influence) || State.PlayerClan.Influence < 20.0) { quote.Reason = "Recruiting a clan costs " + 20 + " influence."; } return quote; } public bool ClanRecruitmentOfferMatches(ClanRecruitmentQuote expected, ClanRecruitmentQuote current) { if (expected != null && current != null && expected.ClanId == current.ClanId && expected.LeaderHeroId == current.LeaderHeroId && expected.SponsorClanId == current.SponsorClanId && expected.FromKingdomId == current.FromKingdomId && expected.ToKingdomId == current.ToKingdomId && expected.GoldCost == current.GoldCost && expected.InfluenceCost == current.InfluenceCost && expected.StartsWar == current.StartsWar && expected.EndsWar == current.EndsWar && expected.HoldingIds != null && current.HoldingIds != null) { return expected.HoldingIds.SequenceEqual(current.HoldingIds); } return false; } public CommandResult RecruitClan(string targetClanId, ClanRecruitmentQuote expectedQuote = null) { return RecruitClan(targetClanId, expectedQuote, null); } internal CommandResult RecruitClan(string targetClanId, ClanRecruitmentQuote expectedQuote, long? payment) { ClanRecruitmentQuote clanRecruitmentQuote = QuoteClanRecruitment(targetClanId, ignoreRelation: false, payment); if (!clanRecruitmentQuote.Ok) { return CommandResult.Fail(clanRecruitmentQuote.Reason); } if (expectedQuote != null && !ClanRecruitmentOfferMatches(expectedQuote, clanRecruitmentQuote)) { return CommandResult.Fail("The offer changed. Check it again."); } Clan clan = State.Clans.Require(targetClanId); Clan clan2 = C.ServiceRuler(clanRecruitmentQuote.FromKingdomId); State.Transact(State.PlayerClan, -clanRecruitmentQuote.GoldCost, LedgerAccount.Other, "Signing payment to " + clan.Name); State.Transact(clan, clanRecruitmentQuote.GoldCost, LedgerAccount.Other, "Vassalage signing payment from " + State.PlayerClan.Name); State.PlayerClan.Influence -= 20.0; ClearClanIndependentDiplomacy(clan.Id); clan.KingdomId = clanRecruitmentQuote.ToKingdomId; clan.Influence = 0.0; if (clanRecruitmentQuote.StartsWar) { State.SetStance(clanRecruitmentQuote.FromKingdomId, clanRecruitmentQuote.ToKingdomId, Stance.War); } RecordClanAllegiance(clan, clanRecruitmentQuote.FromKingdomId, clanRecruitmentQuote.SponsorClanId, ClanAllegianceChange.Recruited, clanRecruitmentQuote.GoldCost); C.AdjustClanRelation(clan.Id, State.PlayerClanId, 10); if (clan2 != null) { C.AdjustClanRelation(clan.Id, clan2.Id, -20); } string text = clan.Name + " joined " + State.Kingdoms.Require(clanRecruitmentQuote.ToKingdomId).Name + ", keeping its holdings and warbands. " + clanRecruitmentQuote.GoldCost + " denars changed hands; its influence in the old kingdom is gone."; if (clanRecruitmentQuote.StartsWar) { text += " Its former kingdom is now at war with yours."; } if (clanRecruitmentQuote.EndsWar) { text += " Its rebellion against your kingdom has ended."; } State.AddLog(LogCategory.Politics, text, clan.Id, clanRecruitmentQuote.ToKingdomId, clanRecruitmentQuote.FromKingdomId); C.OnDiplomacyChanged(); C.Raise(CampaignEventKind.Info, text, false, clan.Id, clanRecruitmentQuote.ToKingdomId); State.Touch(); return CommandResult.Success(text); } internal void ClearClanIndependentDiplomacy(string clanId) { State.Stances.RemoveAll((StanceRecord s) => s.A == clanId || s.B == clanId); State.Diplomacy.Truces.RemoveAll((DiplomaticTruce t) => t.A == clanId || t.B == clanId); } internal void RecordClanAllegiance(Clan clan, string former, string sponsor, ClanAllegianceChange kind, long payment = 0L) { ClanAllegianceRecord clanAllegianceRecord = State.ClanAllegiance.Records.FirstOrDefault((ClanAllegianceRecord r) => r.ClanId == clan.Id); if (clanAllegianceRecord == null) { clanAllegianceRecord = new ClanAllegianceRecord { ClanId = clan.Id }; State.ClanAllegiance.Records.Add(clanAllegianceRecord); } clanAllegianceRecord.PreviousKingdomId = former; clanAllegianceRecord.KingdomId = clan.KingdomId; clanAllegianceRecord.SponsorClanId = sponsor; clanAllegianceRecord.Kind = kind; clanAllegianceRecord.ChangedDay = State.Clock.Day; clanAllegianceRecord.CooldownUntilDay = State.Clock.Day + 7; clanAllegianceRecord.SigningPayment = payment; } public string ClanExpulsionStaleReason(string targetClanId, string kingdomId) { if (State.ClanAllegiance == null || !State.ClanAllegiance.Initialized) { return "Clan allegiance is unavailable."; } Clan clan = C.ServiceRuler(kingdomId); if (!C.LivingPoliticalClan(clan)) { return "The kingdom has nobody in charge right now."; } Clan clan2 = State.Clans.Get(targetClanId); if (clan2 == null || clan2.Id == State.PlayerClanId || clan2.IsPlayerClan || !FreeClanNegotiator(clan2)) { return "Pick a noble clan whose leader is fit and free."; } if (clan2.KingdomId != kingdomId) { return "This clan isn't in that kingdom any more."; } if (IsRulingClan(clan2)) { return "You can't expel the ruling clan."; } long num = ClanAllegianceCooldown(clan2.Id); if (num <= 0) { return ""; } return "This clan can't switch sides for another " + num + " days."; } public string CouncilExpulsionReason(string targetClanId, string kingdomId) { string text = ClanExpulsionStaleReason(targetClanId, kingdomId); if (text.Length > 0) { return text; } if (!C.DiplomacyFactionReserved(kingdomId) && !C.DiplomacyFactionReserved(targetClanId)) { return ""; } return "Wait for the fighting involving these factions to finish."; } public CommandResult ApplyCouncilExpulsion(KingdomDecision decision) { if (decision != null) { PoliticsState politics = State.Politics; if (politics != null && politics.Decisions.Contains(decision) && decision.Kind == KingdomDecisionKind.ClanExpulsion && decision.Status == KingdomDecisionStatus.Resolved && decision.Passed && !(C.ServiceRuler(decision.KingdomId)?.Id != decision.RulerClanId) && !State.AppliedEventIds.Contains("politics.expulsion:" + decision.Id)) { string text = CouncilExpulsionReason(decision.TargetClanId, decision.KingdomId); if (text.Length > 0) { return CommandResult.Fail(text); } Clan target = State.Clans.Require(decision.TargetClanId); State.AppliedEventIds.Add("politics.expulsion:" + decision.Id); foreach (Clan item in (from c in C.CouncilMembers(decision.KingdomId) where c.Id != target.Id && c.Id != decision.RulerClanId select c).ToList()) { C.AdjustClanRelation(item.Id, decision.RulerClanId, -5); } return LeaveNpcKingdom(target, ClanAllegianceChange.Expelled); } } return CommandResult.Fail("The council hasn't voted to expel them."); } public string ClanDefectionReason(string clanId) { Clan clan = State.Clans.Get(clanId); string text = ClanExpulsionStaleReason(clanId, clan?.KingdomId ?? ""); if (text.Length > 0) { return text; } Clan clan2 = C.ServiceRuler(clan.KingdomId); if (C.ClanRelation(clan.Id, clan2.Id) > -40) { return "Clans consider secession only at " + -40 + " relation or worse with their ruler."; } if (!C.DiplomacyFactionReserved(clan.KingdomId) && !C.DiplomacyFactionReserved(clan.Id)) { return ""; } return "The clan will see its kingdom's fights through before thinking of leaving."; } internal CommandResult LeaveNpcKingdom(Clan clan, ClanAllegianceChange kind) { string kingdomId = clan.KingdomId; Clan clan2 = C.ServiceRuler(kingdomId); bool flag = ClanAllegianceHoldings(clan.Id).Any(); ClearClanIndependentDiplomacy(clan.Id); clan.KingdomId = ""; clan.Influence = 0.0; State.SetStance(clan.Id, kingdomId, flag ? Stance.War : Stance.Peace); RecordClanAllegiance(clan, kingdomId, clan2.Id, kind, 0L); C.AdjustClanRelation(clan.Id, clan2.Id, (kind == ClanAllegianceChange.Expelled) ? (-30) : (-10)); string text = clan.Name + ((kind == ClanAllegianceChange.Expelled) ? " was expelled from " : " seceded from ") + State.Kingdoms.Require(kingdomId).Name + ", keeping its people and holdings. " + (flag ? "It kept its land, so now it's at war with its old kingdom." : "Having no land, the clan left in peace."); State.AddLog(LogCategory.Politics, text, clan.Id, kingdomId); C.OnDiplomacyChanged(); C.Raise(CampaignEventKind.Warning, text, State.PlayerClan?.KingdomId == kingdomId, clan.Id, kingdomId); State.Touch(); return CommandResult.Success(text); } public void DailyClanAllegiance() { ClanAllegianceState clanAllegiance = State.ClanAllegiance; if (clanAllegiance == null || !clanAllegiance.Initialized || State.Clock.Day - clanAllegiance.LastAiDay < 7) { return; } clanAllegiance.LastAiDay = State.Clock.Day; State.Touch(); foreach (Clan item in State.Clans.OrderBy((Clan c) => c.Id, StringComparer.Ordinal)) { if (ClanDefectionReason(item.Id).Length <= 0) { LeaveNpcKingdom(item, ClanAllegianceChange.Seceded); break; } } } } internal sealed class ClanArmyDynamicsSystem { private readonly Campaign C; private bool IsBattleFrozen => C.IsBattleFrozen; private NavGrid Nav => C.Nav; private CampaignState State => C.State; internal ClanArmyDynamicsSystem(Campaign host) { C = host; } internal bool ArmyPartyAvailable(Party party) { if (party == null || (party.ClanId != State.PlayerClanId && !C.IsKingdomArmyParty(party)) || (party.State != PartyState.Active && party.State != PartyState.InSettlement) || C.MilitaryPartyReserved(party.Id) || !string.IsNullOrEmpty(party.EncounterId)) { return false; } Hero hero = State.Heroes.Get(party.LeaderHeroId); if (hero != null && hero.State == HeroState.Active && hero.ClanId == party.ClanId) { return Campaign.IsPresentPartyHero(party, hero); } return false; } internal Settlement ArmyRestingPlace(Party party) { if (!ArmyPartyAvailable(party) || party.State != PartyState.InSettlement || party.Order.Kind != OrderKind.None) { return null; } Settlement settlement = State.Settlements.Get(party.CurrentSettlementId); if (settlement != null && (settlement.Type == SettlementType.Town || settlement.Type == SettlementType.Castle)) { Clan clan = State.Clans.Get(settlement.OwnerClanId); if (clan != null && !clan.IsEliminated && C.CanEnter(party, settlement) && Vec2.Distance(party.Position, settlement.Position) <= 0.01) { return settlement; } } return null; } public bool ArmyPartyGathered(Party party) { ClanArmyState clanArmy = State.ClanArmy; if (clanArmy == null || !clanArmy.Active || party == null || !C.ClanArmyContains(party.Id) || State.Player.Activity == PlayerActivity.Captive || IsBattleFrozen) { return false; } Party party2 = State.Parties.Get(clanArmy.LeaderPartyId); if (!ArmyPartyAvailable(party2) || !ArmyPartyAvailable(party)) { return false; } if (party.Id != party2.Id && !C.IsPlayerMilitaryParty(party) && !C.IsKingdomArmyParty(party)) { return false; } if (party2.State == PartyState.InSettlement && party.State == PartyState.InSettlement && party2.CurrentSettlementId == party.CurrentSettlementId) { Settlement settlement = State.Settlements.Get(party2.CurrentSettlementId); if (settlement != null && settlement.Type != SettlementType.Hideout) { Clan clan = State.Clans.Get(settlement.OwnerClanId); if (clan != null && !clan.IsEliminated && C.CanEnter(party2, settlement) && C.CanEnter(party, settlement) && Nav.IsPassable(settlement.Position) && Vec2.Distance(party2.Position, settlement.Position) <= 0.01) { return Vec2.Distance(party.Position, settlement.Position) <= 0.01; } } return false; } if (party2.State == PartyState.Active && party.State == PartyState.Active && Vec2.Distance(party2.Position, party.Position) <= 1.25) { return Nav.LineWalkable(party2.Position, party.Position); } return false; } public IEnumerable AssembledArmyParties() { ClanArmyState army = State.ClanArmy; if (army == null || !army.Active) { return Enumerable.Empty(); } return (from p in C.ClanArmyParties().Where(ArmyPartyGathered) orderby (!(p.Id == army.LeaderPartyId)) ? 1 : 0 select p).ThenBy((Party p) => p.Id, StringComparer.Ordinal).ToList(); } internal void ShareArmyFood(List assembled) { ShareArmyFood(assembled, 1.0, 1.0); } internal void ShareArmyFood(List assembled, double targetDays, double keepDays) { Dictionary needs = assembled.ToDictionary((Party p) => p.Id, C.DailyFoodNeed); List source = assembled.Where((Party p) => Campaign.MilitaryFinite(p.Food) && p.Food >= 0.0 && Campaign.MilitaryFinite(needs[p.Id]) && needs[p.Id] > 0.0).ToList(); List list = (from p in source where C.FoodSupply(p) < needs[p.Id] * targetDays - 1E-09 orderby C.FoodSupply(p) / needs[p.Id] select p).ThenBy((Party p) => p.Id, StringComparer.Ordinal).ToList(); List list2 = source.Where((Party p) => C.FoodSupply(p) > needs[p.Id] * keepDays + 1E-09).OrderBy((Party p) => p.Id, StringComparer.Ordinal).ToList(); foreach (Party item in list) { foreach (Party item2 in list2) { if (item2.Id == item.Id) { continue; } double num = Math.Min(needs[item.Id] * targetDays - C.FoodSupply(item), C.FoodSupply(item2) - needs[item2.Id] * keepDays); if (num <= 1E-09) { continue; } if (Campaign.Provisions(item2) >= num) { double num2 = item2.Food - num; double num3 = item2.Food - num2; double num4 = item.Food + num3; double num5 = num4 - item.Food; if (!Campaign.MilitaryFinite(num2) || !Campaign.MilitaryFinite(num4) || num3 <= 0.0 || num3 > num + 1E-09 || num5 != num3) { continue; } item2.Food = num2; item.Food = num4; } else { double num6 = C.TakeFood(item2, num); double num7 = item.Food + num6; if (!Campaign.MilitaryFinite(num7) || num6 <= 0.0) { continue; } item.Food = num7; } State.Touch(); } } } internal HashSet ArmyUnpaidForecast() { HashSet hashSet = new HashSet(StringComparer.Ordinal); HashSet hashSet2 = new HashSet(from p in C.ClanArmyParties() select p.ClanId, StringComparer.Ordinal); Dictionary dictionary = hashSet2.ToDictionary((string id) => id, (string id) => Math.Max(0L, State.Clans.Get(id)?.Gold ?? 0), StringComparer.Ordinal); foreach (Party party in State.Parties) { if (!hashSet2.Contains(party.ClanId) || party.Kind == PartyKind.Caravan || !C.UsesLogistics(party) || (party.State != PartyState.Active && party.State != PartyState.InSettlement)) { continue; } double num = Math.Ceiling(C.DailyWages(party)); if (!Campaign.MilitaryFinite(num) || num >= 9.223372036854776E+18) { hashSet.Add(party.Id); dictionary[party.ClanId] = 0L; continue; } long num2 = (long)Math.Max(0.0, num); if (num2 > dictionary[party.ClanId]) { hashSet.Add(party.Id); } dictionary[party.ClanId] -= Math.Min(dictionary[party.ClanId], num2); } return hashSet; } public void DailyClanArmy() { ClanArmyState clanArmy = State.ClanArmy; if (clanArmy == null || clanArmy.LastDailyDay >= State.Clock.Day || C.ClanArmyBattleReserved() || IsBattleFrozen || C.MilitaryPartyReserved(State.PlayerPartyId) || !string.IsNullOrEmpty(State.PlayerParty?.EncounterId)) { return; } C.ReconcileClanArmy(); C.DailyKingdomArmySupport(); clanArmy = State.ClanArmy; if (clanArmy == null) { return; } clanArmy.LastDailyDay = State.Clock.Day; if (!clanArmy.Active) { if (State.Player.Activity != PlayerActivity.Captive && ArmyRestingPlace(State.PlayerParty) != null) { clanArmy.Cohesion = Math.Min(100.0, clanArmy.Cohesion + 15.0); } State.Touch(); return; } List source = C.ClanArmyParties().ToList(); List list = AssembledArmyParties().ToList(); ShareArmyFood(list); HashSet gathered = new HashSet(list.Select((Party p) => p.Id), StringComparer.Ordinal); int num = clanArmy.Members.Count((ClanArmyMember member) => !gathered.Contains(member.PartyId)); HashSet unpaid = ArmyUnpaidForecast(); int num2 = source.Count((Party p) => !Campaign.MilitaryFinite(p.Food) || p.Food + 1E-09 < C.DailyFoodNeed(p) || unpaid.Contains(p.Id)); Settlement rest = ArmyRestingPlace(State.Parties.Get(clanArmy.LeaderPartyId)); double num3 = ((rest != null && num == 0 && source.All((Party p) => ArmyRestingPlace(p)?.Id == rest.Id) && num2 == 0) ? 15 : (-10 - num * 5 - num2 * 5)); clanArmy.Cohesion = Math.Max(0.0, Math.Min(100.0, clanArmy.Cohesion + num3)); State.Touch(); if (clanArmy.Cohesion <= 0.0) { C.EndClanArmy("Cohesion's gone; the warbands are going back to their own orders."); } } } internal sealed class ClanArmySystem { private readonly Campaign C; private NavGrid Nav => C.Nav; private CampaignState State => C.State; internal ClanArmySystem(Campaign host) { C = host; } public void EnsureClanArmyFields() { bool flag = false; if (State.ClanArmy == null) { State.ClanArmy = new ClanArmyState(); flag = true; } ClanArmyState clanArmy = State.ClanArmy; if (!clanArmy.Active && clanArmy.Members == null) { clanArmy.Members = new List(); flag = true; } if (clanArmy.LastDailyDay == -1) { clanArmy.LastDailyDay = State.Clock.Day; flag = true; } if (flag) { State.Touch(); } } public bool ClanArmyContains(string partyId) { ClanArmyState clanArmy = State.ClanArmy; if (!string.IsNullOrEmpty(partyId) && clanArmy != null && clanArmy.Active) { if (!(clanArmy.LeaderPartyId == partyId)) { return clanArmy.Members?.Any((ClanArmyMember member) => member.PartyId == partyId) ?? false; } return true; } return false; } public IEnumerable ClanArmyParties() { ClanArmyState army = State.ClanArmy; ClanArmyState clanArmyState = army; if (clanArmyState == null || !clanArmyState.Active) { yield break; } Party party = State.Parties.Get(army.LeaderPartyId); if (ClanArmyLiveParty(party, army.OwnerClanId)) { yield return party; } foreach (ClanArmyMember item in (from m in army.Members ?? new List() where m.PartyId != army.LeaderPartyId group m by m.PartyId into g select g.First()).OrderBy((ClanArmyMember m) => m.PartyId, StringComparer.Ordinal)) { Party party2 = State.Parties.Get(item.PartyId); if (item.KingdomCall ? C.KingdomArmyMemberAvailable(party2, item) : ClanArmyLiveParty(party2, army.OwnerClanId)) { yield return party2; } } } internal static bool ClanArmyLiveParty(Party party, string clanId) { if (party != null && party.ClanId == clanId && party.State != PartyState.Destroyed) { return party.State != PartyState.Disbanded; } return false; } internal bool ClanArmyPartyReserved(string partyId) { if (!string.IsNullOrEmpty(partyId)) { if (!C.MilitaryPartyReserved(partyId)) { return !string.IsNullOrEmpty(State.Parties.Get(partyId)?.EncounterId); } return true; } return false; } internal bool ClanArmyBattleReserved() { ClanArmyState clanArmy = State.ClanArmy; if (clanArmy != null && clanArmy.Active) { if (!ClanArmyPartyReserved(clanArmy.LeaderPartyId)) { return clanArmy.Members?.Any((ClanArmyMember member) => ClanArmyPartyReserved(member.PartyId)) ?? false; } return true; } return false; } internal bool ClanArmyPlayerAvailable() { Party playerParty = State.PlayerParty; Hero playerHero = State.PlayerHero; if (ClanArmyLiveParty(playerParty, State.PlayerClanId) && playerParty.LeaderHeroId == State.PlayerHeroId && playerHero != null && playerHero.State == HeroState.Active && playerHero.ClanId == State.PlayerClanId && Campaign.IsPresentPartyHero(playerParty, playerHero) && State.Player.Activity != PlayerActivity.Captive) { Clan playerClan = State.PlayerClan; if (playerClan == null) { return false; } return !playerClan.IsEliminated; } return false; } internal bool ClanArmyMemberAvailable(Party party, MilitaryPartyState record) { if (record == null || !record.IsActive || record.OwnerClanId != State.PlayerClanId || !ClanArmyLiveParty(party, record.OwnerClanId) || party.Kind != PartyKind.Lord || party.LeaderHeroId != record.LeaderHeroId) { return false; } Hero hero = State.Heroes.Get(record.LeaderHeroId); if (C.IsOwnedCompanion(hero) && hero.State == HeroState.Active) { return Campaign.IsPresentPartyHero(party, hero); } return false; } public string ClanArmyActionReason(string militaryId, string action) { if (action != "form" && action != "add" && action != "release" && action != "disband") { return "Unknown army action."; } string text = C.CargoCommandReason(); if (text.Length > 0) { return text; } if (!ClanArmyPlayerAvailable()) { return "Your commander has to be here to lead an army."; } if ((action == "form" || action == "add") && !State.PlayerHero.CanFight) { return "Let your commander recover before gathering more warbands."; } if (!string.IsNullOrEmpty(State.Player.PendingEncounterId) || ClanArmyPartyReserved(State.PlayerPartyId)) { return "Resolve your current encounter first."; } ClanArmyState clanArmy = State.ClanArmy; if (clanArmy == null || clanArmy.Members == null) { return "Clan armies are unavailable."; } if (action == "form") { if (clanArmy.Active) { return "Your clan already has an army."; } if (!Campaign.MilitaryFinite(clanArmy.Cohesion) || clanArmy.Cohesion < 20.0) { return "Clan cohesion has to be back to 20 before you form another army."; } if (clanArmy.Members.Count != 0) { return "Sort out the last army's orders first."; } } else { if (!clanArmy.Active || clanArmy.OwnerClanId != State.PlayerClanId || clanArmy.LeaderPartyId != State.PlayerPartyId) { return "You have no clan army out."; } if (ClanArmyBattleReserved()) { return "Wait until every party in the army has finished its battle."; } } if (action == "disband") { return ""; } MilitaryPartyState record = State.MilitaryParties?.FirstOrDefault((MilitaryPartyState candidate) => candidate.Id == militaryId); Party party = State.Parties.Get(record?.PartyId ?? ""); if (record == null || record.OwnerClanId != State.PlayerClanId) { return "Pick one of your companion warbands."; } bool flag = clanArmy.Members.Any((ClanArmyMember candidate) => candidate.PartyId == record.PartyId); if (action == "release") { if (!flag) { return "This warband is not in your army."; } return ""; } if (!ClanArmyMemberAvailable(party, record)) { return "This warband needs its commander before it can join."; } if (!State.Heroes.Require(record.LeaderHeroId).CanFight) { return "Let this warband's commander recover before gathering."; } if (ClanArmyPartyReserved(party.Id)) { return "Wait until this warband resolves its battle."; } if (flag) { return "This warband is already in your army."; } if (clanArmy.Members.Count((ClanArmyMember m) => !m.KingdomCall) >= 2 || clanArmy.Members.Count >= 5) { return "No companion slots left."; } if (!Nav.IsPassable(State.PlayerParty.Position) || !Nav.IsPassable(party.Position) || !Nav.SameComponent(State.PlayerParty.Position, party.Position)) { return "This warband can't reach your army."; } return ""; } internal void AttachClanArmyParty(MilitaryPartyState record) { Party party = State.Parties.Require(record.PartyId); State.ClanArmy.Members.Add(new ClanArmyMember { PartyId = party.Id, PreviousDirective = record.Directive }); State.ClanArmy.Members.Sort((ClanArmyMember a, ClanArmyMember b) => StringComparer.Ordinal.Compare(a.PartyId, b.PartyId)); record.Directive = MilitaryPartyDirective.Follow; WakeClanArmyParty(party); } internal void WakeClanArmyParty(Party party) { C.ClearOrder(party); party.NextThinkMinute = State.Clock.Minute; party.WaitUntilMinute = State.Clock.Minute; } public CommandResult FormClanArmy(string militaryId) { string text = ClanArmyActionReason(militaryId, "form"); if (text.Length > 0) { return CommandResult.Fail(text); } ClanArmyState clanArmy = State.ClanArmy; clanArmy.Active = true; clanArmy.Id = State.Ids.Allocate("army"); clanArmy.OwnerClanId = State.PlayerClanId; clanArmy.LeaderPartyId = State.PlayerPartyId; clanArmy.StartedMinute = State.Clock.Minute; MilitaryPartyState militaryPartyState = State.MilitaryParties.First((MilitaryPartyState candidate) => candidate.Id == militaryId); AttachClanArmyParty(militaryPartyState); string text2 = "Your clan army is gathering. " + State.Parties.Require(militaryPartyState.PartyId).Name + " will join your warband."; State.AddLog(LogCategory.Travel, text2, clanArmy.Id, militaryPartyState.PartyId); State.Touch(); return CommandResult.Success(text2); } public CommandResult AddClanArmyParty(string militaryId) { string text = ClanArmyActionReason(militaryId, "add"); if (text.Length > 0) { return CommandResult.Fail(text); } MilitaryPartyState militaryPartyState = State.MilitaryParties.First((MilitaryPartyState candidate) => candidate.Id == militaryId); AttachClanArmyParty(militaryPartyState); string text2 = State.Parties.Require(militaryPartyState.PartyId).Name + " is gathering with your army."; State.AddLog(LogCategory.Travel, text2, State.ClanArmy.Id, militaryPartyState.PartyId); State.Touch(); return CommandResult.Success(text2); } internal void RestoreClanArmyMember(ClanArmyMember member) { Party party = State.Parties.Get(member.PartyId); if (member.KingdomCall) { if (ClanArmyLiveParty(party, member.OwnerClanId) && !ClanArmyPartyReserved(party.Id)) { WakeClanArmyParty(party); } return; } MilitaryPartyState militaryPartyState = C.MilitaryPartyFor(party); if (militaryPartyState != null && !(militaryPartyState.OwnerClanId != State.ClanArmy.OwnerClanId) && ClanArmyLiveParty(party, militaryPartyState.OwnerClanId)) { militaryPartyState.Directive = member.PreviousDirective; WakeClanArmyParty(party); } } public CommandResult ReleaseClanArmyParty(string militaryId) { string text = ClanArmyActionReason(militaryId, "release"); if (text.Length > 0) { return CommandResult.Fail(text); } MilitaryPartyState record = State.MilitaryParties.First((MilitaryPartyState candidate) => candidate.Id == militaryId); ClanArmyState clanArmy = State.ClanArmy; if (clanArmy.Members.Count == 1) { EndClanArmy("The last companion warband was released.", notify: false); return CommandResult.Success("Your army has broken up. The warbands go back to their own orders."); } ClanArmyMember clanArmyMember = clanArmy.Members.First((ClanArmyMember candidate) => candidate.PartyId == record.PartyId); RestoreClanArmyMember(clanArmyMember); clanArmy.Members.Remove(clanArmyMember); string text2 = (State.Parties.Get(record.PartyId)?.Name ?? "The warband") + " left your army and went back to its old orders."; State.AddLog(LogCategory.Travel, text2, clanArmy.Id, clanArmyMember.PartyId); State.Touch(); return CommandResult.Success(text2); } public CommandResult DisbandClanArmy() { string text = ClanArmyActionReason("", "disband"); if (text.Length > 0) { return CommandResult.Fail(text); } EndClanArmy("Your commander dismissed the army.", notify: false); return CommandResult.Success("Your army has broken up. The warbands go back to their own orders."); } public void EndClanArmy(string reason, bool notify = true) { ClanArmyState clanArmy = State.ClanArmy; if (clanArmy == null || !clanArmy.Active || ClanArmyBattleReserved()) { return; } foreach (ClanArmyMember item in clanArmy.Members.OrderBy((ClanArmyMember member) => member.PartyId, StringComparer.Ordinal)) { RestoreClanArmyMember(item); } clanArmy.Members.Clear(); clanArmy.Active = false; string text = "Your army dispersed. " + reason; State.AddLog(LogCategory.Travel, text, clanArmy.Id); if (notify) { C.Raise(CampaignEventKind.Warning, text, false, clanArmy.Id); } State.Touch(); } public void ReconcileClanArmy() { ClanArmyState clanArmy = State.ClanArmy; if (clanArmy == null || !clanArmy.Active || ClanArmyBattleReserved()) { return; } if (clanArmy.OwnerClanId != State.PlayerClanId || clanArmy.LeaderPartyId != State.PlayerPartyId || !ClanArmyPlayerAvailable()) { EndClanArmy("Your commander can't lead it any more."); return; } bool flag = false; foreach (ClanArmyMember item in clanArmy.Members.ToList()) { Party party = State.Parties.Get(item.PartyId); MilitaryPartyState record = C.MilitaryPartyFor(party); if (!(item.KingdomCall ? C.KingdomArmyMemberAvailable(party, item) : ClanArmyMemberAvailable(party, record))) { RestoreClanArmyMember(item); clanArmy.Members.Remove(item); if (item.KingdomCall) { string text = (party?.Name ?? "An allied warband") + " left your army: " + C.KingdomArmyDepartureReason(party, item); State.AddLog(LogCategory.Politics, text, clanArmy.Id, item.PartyId); C.Raise(CampaignEventKind.Warning, text, false, clanArmy.Id, item.PartyId); } flag = true; } } if (clanArmy.Members.Count == 0) { EndClanArmy("No supporting warbands remain."); } else if (flag) { State.AddLog(LogCategory.Travel, "Warbands that couldn't stay have left your army.", clanArmy.Id); State.Touch(); } } } internal sealed class ClanCaravansSystem { private readonly Campaign C; private CampaignState State => C.State; private ContentDatabase Content => C.Content; internal ClanCaravansSystem(Campaign host) { C = host; } public void EnsureClanCaravanFields() { if (State.ClanCaravanDue == null) { State.ClanCaravanDue = new SortedDictionary(StringComparer.Ordinal); State.Touch(); } } public bool IsClanCaravan(Party p) { if (p != null && p.Kind == PartyKind.Caravan) { return C.CaravanFor(p)?.ClanCaravan ?? false; } return false; } public IEnumerable ClanCaravans(string clanId) { return State.Caravans.Where((CaravanState c) => c.ClanCaravan && c.IsActive && c.OwnerClanId == clanId); } internal static bool AiClan(Clan clan, string playerClanId) { if (clan != null && !clan.IsBandit && !clan.IsEliminated) { return clan.Id != playerClanId; } return false; } public int ClanCaravanLimit(Clan clan) { if (clan != null) { if (clan.Gold < 30000) { return 1; } return 2; } return 0; } public Settlement ClanCaravanHome(Clan clan) { if (clan == null) { return null; } Settlement settlement = State.Settlements.Where((Settlement s) => s.OwnerClanId == clan.Id && Usable(s)).OrderBy((Settlement s) => s.Id, StringComparer.Ordinal).FirstOrDefault(); if (settlement != null) { return settlement; } Settlement seat = State.Settlements.Where((Settlement s) => s.OwnerClanId == clan.Id && s.Type != SettlementType.Hideout).OrderBy((Settlement s) => s.Id, StringComparer.Ordinal).FirstOrDefault(); if (seat == null) { return null; } return (from s in State.Settlements.Where(Usable) orderby Vec2.Distance(seat.Position, s.Position) select s).ThenBy((Settlement s) => s.Id, StringComparer.Ordinal).FirstOrDefault(); bool Usable(Settlement s) { if (s.Type == SettlementType.Town && s.Market?.Stock != null && s.Market.Initialized && !C.IsSettlementBesieged(s)) { return !State.AreHostile(clan, State.Clans.Get(s.OwnerClanId)); } return false; } } public long ClanCaravanCost(Clan clan, Settlement home) { if (clan == null || home == null) { return long.MaxValue; } return 1500 + C.MerchantCaravanEscort(clan.CultureId, 16).Sum(((string unit, int count) e) => (long)(C.UnitDef(e.unit)?.RecruitCost ?? 0) * (long)e.count); } public string ClanCaravanReason(Clan clan) { if (!AiClan(clan, State.PlayerClanId)) { return "Only AI clans run their own caravans this way."; } Hero hero = State.Heroes.Get(clan.LeaderHeroId); if (hero == null || hero.State == HeroState.Dead) { return "The clan has no leader."; } if (!State.Settlements.Any((Settlement s) => s.OwnerClanId == clan.Id && (s.Type == SettlementType.Town || s.Type == SettlementType.Castle))) { return "The clan holds no town or castle."; } if (ClanCaravans(clan.Id).Count() >= ClanCaravanLimit(clan)) { return "The clan already runs as many caravans as it can."; } Settlement settlement = ClanCaravanHome(clan); if (settlement == null) { return "There is no town to trade from."; } if (C.MerchantCaravanEscort(clan.CultureId, 16).Count == 0) { return "Nobody to guard a caravan."; } if (clan.Gold < 5000 + ClanCaravanCost(clan, settlement)) { return "The clan cannot spare the money."; } return ""; } internal Party FormClanCaravan(Clan clan) { Settlement settlement = ClanCaravanHome(clan); RandomStream randomStream = State.Random.Get("clancaravans"); long minute = State.Clock.Minute; Party party = new Party { Id = State.Ids.Allocate("party"), Name = clan.Name + " caravan", Kind = PartyKind.Caravan, ClanId = clan.Id, HomeSettlementId = settlement.Id, State = PartyState.InSettlement, CurrentSettlementId = settlement.Id, Position = settlement.Position, Gold = 1500L, Morale = 50.0, CreatedAtMinute = minute, NextThinkMinute = minute, WaitUntilMinute = minute + 60 * randomStream.Range(1, 13) }; long num = 0L; foreach (var (text, num2) in C.MerchantCaravanEscort(clan.CultureId, 16)) { party.Troops.Add(text, num2); num += (long)(C.UnitDef(text)?.RecruitCost ?? 0) * (long)num2; } CaravanState item = new CaravanState { Id = State.Ids.Allocate("caravan"), PartyId = party.Id, OwnerClanId = clan.Id, HomeSettlementId = settlement.Id, StartedMinute = minute, ClanCaravan = true }; State.Transact(clan, -(1500 + num), LedgerAccount.Trade, "Fitted out " + party.Name); State.Parties.Add(party); State.Caravans.Add(item); C.ResupplyCaravan(party, settlement); State.ClanCaravanDue[clan.Id] = minute + 14400; State.AddLog(LogCategory.Economy, clan.Name + " sent out a caravan from " + settlement.Name + ".", party.Id, clan.Id, settlement.Id); State.Touch(); return party; } internal bool ClanCaravanShouldGoHome(Party p) { if (p.Troops.TotalHealthy >= 8) { return p.Gold > 4500; } return true; } internal void SettleClanCaravan(Party p, CaravanState c, Settlement home) { Clan clan = State.Clans.Get(c.OwnerClanId); if (clan == null || !AiClan(clan, State.PlayerClanId)) { return; } if (p.Gold > 1500) { long num = p.Gold - 1500; p.Gold = 1500L; if (clan.Gold <= long.MaxValue - num) { State.Transact(clan, num, LedgerAccount.Trade, "Profit from " + p.Name); } State.AddLog(LogCategory.Economy, p.Name + " brought " + num + " denars home to " + clan.Name + ".", p.Id, clan.Id, home.Id); } else if (p.Gold < 1500 && clan.Gold > 5000) { long num2 = Math.Min(1500 - p.Gold, clan.Gold - 5000); State.Transact(clan, -num2, LedgerAccount.Trade, "Funds for " + p.Name); p.Gold += num2; } int num3 = 16 - p.Troops.TotalTroops; if (num3 > 0) { int num4 = 0; foreach (var item3 in C.MerchantCaravanEscort(clan.CultureId, num3)) { string item = item3.unit; int item2 = item3.count; long num5 = Math.Max(0, C.UnitDef(item)?.RecruitCost ?? 0); int num6 = (int)((num5 == 0L) ? item2 : Math.Min(item2, Math.Max(0L, clan.Gold - 5000) / num5)); if (num6 > 0) { p.Troops.Add(item, num6); State.Transact(clan, -num6 * num5, LedgerAccount.Recruitment, "Guards for " + p.Name); num4 += num6; } } if (num4 > 0) { State.AddLog(LogCategory.Economy, p.Name + " hired " + num4 + " new guards at " + home.Name + ".", p.Id, home.Id); } } State.Touch(); } internal bool ReconcileClanCaravan(CaravanState c) { Party party = State.Parties.Get(c.PartyId); Clan clan = State.Clans.Get(c.OwnerClanId); bool flag = party != null && party.Kind == PartyKind.Caravan && party.ClanId == c.OwnerClanId && party.State != PartyState.Destroyed && party.State != PartyState.Disbanded; if (flag && party.Troops.TotalTroops > 0 && AiClan(clan, State.PlayerClanId)) { Settlement settlement = State.Settlements.Get(c.HomeSettlementId); if (settlement == null || State.AreHostile(clan, State.Clans.Get(settlement.OwnerClanId))) { Settlement settlement2 = ClanCaravanHome(clan); if (settlement2 != null && settlement2.Id != c.HomeSettlementId) { c.HomeSettlementId = settlement2.Id; party.HomeSettlementId = settlement2.Id; return true; } } return false; } if (flag) { party.Troops.Stacks.Clear(); party.Gold = 0L; party.Cargo.Clear(); OutcomeCommitter.DestroyParty(C, party, AiClan(clan, State.PlayerClanId) ? "no guards left" : "its clan is no more"); } c.Status = "Lost"; c.CargoCosts.Clear(); if (AiClan(clan, State.PlayerClanId)) { State.ClanCaravanDue[clan.Id] = Math.Max(State.ClanCaravanDue.TryGetValue(clan.Id, out var value) ? value : 0, State.Clock.Minute + 28800); } State.AddLog(LogCategory.Economy, (party?.Name ?? "A clan caravan") + " was lost.", c.PartyId, c.OwnerClanId); return true; } internal void DailyClanCaravans() { EnsureClanCaravanFields(); foreach (Clan item in State.Clans.Where((Clan x) => AiClan(x, State.PlayerClanId)).OrderBy((Clan x) => x.Id, StringComparer.Ordinal).ToList()) { if (!State.ClanCaravanDue.TryGetValue(item.Id, out var value)) { State.ClanCaravanDue[item.Id] = State.Clock.Minute + (long)((2 + StableHash.Fnv1a64("clan-caravan|" + item.Id) % 12) * 1440); State.Touch(); } else if (State.Clock.Minute >= value && ClanCaravanReason(item).Length <= 0) { FormClanCaravan(item); } } } } internal sealed class CompanionRecoverySystem { private readonly Campaign C; private NavGrid Nav => C.Nav; private CampaignState State => C.State; internal CompanionRecoverySystem(Campaign host) { C = host; } public void RecoverSeparatedCompanions() { Party party = State.PlayerParty; if (party == null || (party.State != PartyState.Disbanded && party.State != PartyState.Destroyed)) { return; } foreach (Hero item in State.Heroes.Where((Hero h) => h.Occupation == HeroOccupation.Companion && h.State == HeroState.Active && (h.PartyId == party.Id || party.Troops.Heroes.Contains(h.Id))).ToList()) { ShelterCompanion(item, party.Position, "separated when your party scattered"); } foreach (string item2 in party.Prisoners.Heroes.ToList()) { OutcomeCommitter.ReleaseHero(C, State.Heroes.Get(item2), "freed when their captors scattered"); } party.Prisoners.Heroes.Clear(); party.RoleAssignments?.Clear(); } internal void ShelterCompanion(Hero hero, Vec2 from, string reason) { if (hero == null || hero.Occupation != HeroOccupation.Companion || hero.State != HeroState.Active) { return; } Clan clan = State.Clans.Get(hero.ClanId); List source = State.Settlements.Where((Settlement s) => s.Type != SettlementType.Hideout && Nav.IsPassable(s.Position)).ToList(); List list = source.Where((Settlement s) => !State.AreHostile(clan, State.Clans.Get(s.OwnerClanId))).ToList(); IEnumerable source2; if (!list.Any((Settlement s) => s.Type == SettlementType.Town)) { if (list.Count <= 0) { source2 = source.Where((Settlement s) => s.Type == SettlementType.Town); } else { IEnumerable enumerable = list; source2 = enumerable; } } else { source2 = list.Where((Settlement s) => s.Type == SettlementType.Town); } Settlement settlement = source2.OrderBy((Settlement s) => Vec2.Distance(from, s.Position)).ThenBy((Settlement s) => s.Id, StringComparer.Ordinal).FirstOrDefault() ?? source.OrderBy((Settlement s) => Vec2.Distance(from, s.Position)).ThenBy((Settlement s) => s.Id, StringComparer.Ordinal).FirstOrDefault(); C.ClearHeroRoleAssignments(hero.Id); foreach (Party party in State.Parties) { party.Troops.Heroes.Remove(hero.Id); } hero.PartyId = ""; hero.SettlementId = settlement?.Id ?? ""; hero.CaptorPartyId = ""; hero.CaptorSettlementId = ""; string text = ((settlement == null) ? "Their destination is unknown." : ("They're waiting at " + settlement.Name + ". Meet them there.")); State.AddLog(LogCategory.Captivity, hero.Name + " is free (" + reason + "). " + text, hero.Id, settlement?.Id ?? ""); if (hero.ClanId == State.PlayerClanId) { C.Raise(CampaignEventKind.Released, hero.Name + " is free. " + text, false, hero.Id, settlement?.Id ?? ""); } } } internal sealed class CompanionsSystem { private readonly Campaign C; private ContentDatabase Content => C.Content; private CampaignRules Rules => C.Rules; private CampaignState State => C.State; internal CompanionsSystem(Campaign host) { C = host; } public void EnsureCompanions() { ScenarioDef scenarioDef = Content.Scenarios.Get(State.ScenarioId); bool flag = false; foreach (CompanionDef item in scenarioDef?.Companions ?? new List()) { if (!State.Heroes.Contains(item.Id) && State.Settlements.Contains(item.Settlement)) { Hero hero = new Hero { Id = item.Id, Name = item.Name, Description = item.Description, CultureId = item.Culture, UnitId = item.Unit, Occupation = HeroOccupation.Companion, SettlementId = item.Settlement, HireCost = item.HireCost, DailyWage = item.DailyWage, Skills = new SortedDictionary(item.Skills, StringComparer.Ordinal) }; State.Heroes.Add(hero); C.HeroDevelopmentSystem.InitialiseHero(hero); FamiliesState families = State.Families; if (families != null && families.Started) { C.GiveIdentity(hero); } flag = true; } } foreach (Party party in State.Parties) { if (party.RoleAssignments == null) { party.RoleAssignments = new Dictionary(); flag = true; } } if (flag) { State.Touch(); } } public int CompanionCount() { return State.Heroes.Count((Hero h) => h.Occupation == HeroOccupation.Companion && h.ClanId == State.PlayerClanId && h.State != HeroState.Dead && !h.IsFamily); } public int CompanionLimit() { double num = Math.Floor(Math.Max(0.0, State.PlayerClan?.Renown ?? 0.0) / 100.0); return (int)Math.Min(Rules.CompanionMaxLimit, (double)Rules.CompanionBaseLimit + num); } public IEnumerable AvailableCompanions() { Settlement town = CompanionMeetingSettlement(townOnly: true); if (town == null || !string.IsNullOrEmpty(CompanionCommandReason())) { return Enumerable.Empty(); } return State.Heroes.Where((Hero h) => h.Occupation == HeroOccupation.Companion && string.IsNullOrEmpty(h.ClanId) && IsWaitingCompanion(h, town)).OrderBy((Hero h) => h.Name, StringComparer.Ordinal).ThenBy((Hero h) => h.Id, StringComparer.Ordinal) .ToList(); } public string CompanionRecruitmentReason(string heroId) { string text = C.DisguiseBlockReason(); if (text.Length > 0) { return text; } string text2 = CompanionCommandReason(); if (!string.IsNullOrEmpty(text2)) { return text2; } Settlement settlement = CompanionMeetingSettlement(townOnly: true); if (settlement == null) { return "Companions are hired in friendly towns."; } Hero hero = State.Heroes.Get(heroId); if (hero == null || hero.Occupation != HeroOccupation.Companion) { return "That person isn't for hire."; } if (!string.IsNullOrEmpty(hero.ClanId)) { return "Already sworn to a clan."; } if (!IsWaitingCompanion(hero, settlement)) { return "Not in this town."; } if (CompanionCount() >= CompanionLimit()) { return $"You can have {CompanionLimit()} companions; every 100 renown adds one, up to {Rules.CompanionMaxLimit}."; } if (State.PlayerClan.Gold < hero.HireCost) { return $"You need {hero.HireCost} denars to hire {hero.Name}."; } return ""; } public CommandResult RecruitCompanion(string heroId) { string text = CompanionRecruitmentReason(heroId); if (!string.IsNullOrEmpty(text)) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Require(heroId); Settlement settlement = CompanionMeetingSettlement(townOnly: true); State.Transact(State.PlayerClan, -hero.HireCost, LedgerAccount.CompanionHire, "Hired " + hero.Name + " at " + settlement.Name); hero.ClanId = State.PlayerClanId; JoinCompanionToPlayerParty(hero); State.Wanderers?.Plans?.Remove(hero.Id); State.AddLog(LogCategory.Recruitment, $"{hero.Name} joined your clan at {settlement.Name} for {hero.HireCost} denars ({hero.DailyWage}/day while with the party).", hero.Id, settlement.Id); State.Touch(); return CommandResult.Success(hero.Name + " joins your party."); } public string CompanionDismissalReason(string heroId) { string text = CompanionCommandReason(); if (!string.IsNullOrEmpty(text)) { return text; } if (CompanionMeetingSettlement(townOnly: true) == null) { return "Companions can only be let go in a friendly town."; } Hero hero = State.Heroes.Get(heroId); if (!IsOwnedCompanion(hero)) { return "That isn't one of your companions."; } if (hero.IsFamily) { return hero.Name + " is family, not hired help."; } if (hero.State != HeroState.Active || !IsPresentPartyHero(State.PlayerParty, hero)) { return "They have to be with you to be dismissed."; } if (State.Parties.Any((Party p) => p.LeaderHeroId == hero.Id && p.State != PartyState.Destroyed && p.State != PartyState.Disbanded)) { return "A party leader can't be dismissed while running a party."; } return ""; } public CommandResult DismissCompanion(string heroId) { string text = CompanionDismissalReason(heroId); if (!string.IsNullOrEmpty(text)) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Require(heroId); Settlement settlement = CompanionMeetingSettlement(townOnly: true); ClearHeroRoleAssignments(hero.Id); State.PlayerParty.Troops.Heroes.Remove(hero.Id); hero.ClanId = ""; hero.PartyId = ""; hero.SettlementId = settlement.Id; C.NoteNewWanderer(hero); State.AddLog(LogCategory.Recruitment, hero.Name + " left your clan and is staying at " + settlement.Name + ". No refund.", hero.Id, settlement.Id); State.Touch(); return CommandResult.Success(hero.Name + " stays at " + settlement.Name + ". No refund."); } public string CompanionRejoinReason(string heroId) { string text = CompanionCommandReason(); if (!string.IsNullOrEmpty(text)) { return text; } Settlement settlement = CompanionMeetingSettlement(townOnly: false); if (settlement == null) { return "Meet them at a friendly settlement to take them back."; } Hero hero = State.Heroes.Get(heroId); if (!IsOwnedCompanion(hero)) { return "That isn't one of your companions."; } if (C.GovernorAssignedSettlement(heroId) != null) { return "Recall this governor from the settlement first."; } QuestState questState = C.DelegatedQuestOf(heroId); if (questState != null) { return "They're away on a task (" + questState.Title + "), back about day " + (questState.DelegateDueMinute / 1440 + 1) + "."; } if (!IsWaitingCompanion(hero, settlement)) { return "They're not waiting here."; } return ""; } public CommandResult RejoinCompanion(string heroId) { string text = CompanionRejoinReason(heroId); if (!string.IsNullOrEmpty(text)) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Require(heroId); string settlementId = hero.SettlementId; JoinCompanionToPlayerParty(hero); State.AddLog(LogCategory.Recruitment, hero.Name + " rejoined your party.", hero.Id, settlementId); State.Touch(); return CommandResult.Success(hero.Name + " rejoins your party. No new fee."); } public string PartyRoleAssignmentReason(PartyRole role, string heroId) { string text = CompanionCommandReason(); if (!string.IsNullOrEmpty(text)) { return text; } if (!Enum.IsDefined(typeof(PartyRole), role)) { return "Unknown party role."; } if (string.IsNullOrEmpty(heroId)) { return ""; } Party playerParty = State.PlayerParty; Hero hero = State.Heroes.Get(heroId); if (!IsEligibleRoleHero(playerParty, hero)) { return "Pick a healthy hero who's in your party."; } if (playerParty.RoleAssignments != null && playerParty.RoleAssignments.Any((KeyValuePair a) => a.Key != role && a.Value == hero.Id)) { return "This hero already has a role. Clear it first."; } return ""; } public CommandResult AssignPartyRole(PartyRole role, string heroId) { string text = PartyRoleAssignmentReason(role, heroId); if (!string.IsNullOrEmpty(text)) { return CommandResult.Fail(text); } Party playerParty = State.PlayerParty; if (playerParty.RoleAssignments == null) { playerParty.RoleAssignments = new Dictionary(); } if (string.IsNullOrEmpty(heroId)) { playerParty.RoleAssignments.Remove(role); } else { playerParty.RoleAssignments[role] = heroId; } Hero hero = RoleHolder(playerParty, role); string text2 = (string.IsNullOrEmpty(heroId) ? string.Format("{0} assignment cleared; {1}.", role, (hero == null) ? "no healthy leader is available" : (hero.Name + " covers the role")) : (hero.Name + " is now your " + role.ToString().ToLowerInvariant() + ".")); State.AddLog(LogCategory.Info, text2, heroId, playerParty.Id); State.Touch(); return CommandResult.Success(text2); } public Hero RoleHolder(Party party, PartyRole role) { if (party == null || !Enum.IsDefined(typeof(PartyRole), role) || party.State == PartyState.Destroyed || party.State == PartyState.Disbanded) { return null; } if (party.RoleAssignments != null && party.RoleAssignments.TryGetValue(role, out var heroId)) { Hero hero = State.Heroes.Get(heroId); if (IsEligibleRoleHero(party, hero) && party.RoleAssignments.Count((KeyValuePair a) => a.Value == heroId) == 1) { return hero; } } if (role == PartyRole.Engineer) { Hero hero2 = C.SkillTrainingSystem.PartyEngineer(party); if (!IsEligibleRoleHero(party, hero2)) { return null; } return hero2; } Hero hero3 = State.Heroes.Get(party.LeaderHeroId); if (!IsEligibleRoleHero(party, hero3)) { return null; } return hero3; } public static string RoleSkillId(PartyRole role) { return role switch { PartyRole.Scout => "scouting", PartyRole.Surgeon => "medicine", PartyRole.Engineer => "engineering", _ => "stewardship", }; } public int RoleSkill(Party party, PartyRole role) { return Math.Max(0, Math.Min(300, RoleHolder(party, role)?.Skill(RoleSkillId(role)) ?? 0)); } public void ClearHeroRoleAssignments(string heroId) { foreach (Party party in State.Parties) { if (party.RoleAssignments == null) { continue; } foreach (PartyRole item in (from a in party.RoleAssignments where a.Value == heroId select a.Key).ToList()) { party.RoleAssignments.Remove(item); } } } internal string CompanionCommandReason() { CommandResult commandResult = C.RequireFree(); if (!commandResult.Ok) { return commandResult.Message; } if (State.PlayerClan == null) { return "You have no clan."; } if (State.PlayerParty.State != PartyState.Active && State.PlayerParty.State != PartyState.InSettlement) { return "Can't manage companions right now."; } if (State.PlayerHero == null || State.PlayerHero.State != HeroState.Active) { return "You're not free to manage companions."; } return ""; } internal Settlement CompanionMeetingSettlement(bool townOnly) { Settlement settlement = C.CurrentSettlement(); Party playerParty = State.PlayerParty; if (settlement == null || (townOnly && settlement.Type != SettlementType.Town) || !C.CanEnter(playerParty, settlement)) { return null; } if (!(Vec2.Distance(playerParty.Position, settlement.Position) <= Rules.SettlementEnterRadius + 0.01)) { return null; } return settlement; } internal bool IsOwnedCompanion(Hero hero) { if (hero != null && hero.Occupation == HeroOccupation.Companion) { return hero.ClanId == State.PlayerClanId; } return false; } internal bool IsWaitingCompanion(Hero hero, Settlement settlement) { if (hero.State == HeroState.Active && hero.SettlementId == settlement.Id && string.IsNullOrEmpty(hero.PartyId) && string.IsNullOrEmpty(hero.CaptorPartyId) && string.IsNullOrEmpty(hero.CaptorSettlementId) && !State.Parties.Any((Party p) => p.Troops.Heroes.Contains(hero.Id) || p.Prisoners.Heroes.Contains(hero.Id))) { return !State.Settlements.Any((Settlement s) => s.Garrison.Heroes.Contains(hero.Id) || s.Prisoners.Heroes.Contains(hero.Id)); } return false; } internal static bool IsPresentPartyHero(Party party, Hero hero) { if (party != null && hero != null && hero.PartyId == party.Id && party.Troops.Heroes.Contains(hero.Id) && string.IsNullOrEmpty(hero.CaptorPartyId)) { return string.IsNullOrEmpty(hero.CaptorSettlementId); } return false; } internal bool IsEligibleRoleHero(Party party, Hero hero) { if (hero != null && hero.CanFight && IsPresentPartyHero(party, hero) && hero.ClanId == party.ClanId) { if (!(party.Id != State.PlayerPartyId) && !(hero.Id == State.PlayerHeroId)) { return IsOwnedCompanion(hero); } return true; } return false; } internal void JoinCompanionToPlayerParty(Hero hero) { ClearHeroRoleAssignments(hero.Id); hero.PartyId = State.PlayerPartyId; hero.SettlementId = ""; State.PlayerParty.Troops.Heroes.Add(hero.Id); } } internal sealed class ContractsSystem { private readonly Campaign C; private CampaignState State => C.State; internal ContractsSystem(Campaign host) { C = host; } public void EnsureContractFields() { if (State.Contracts == null) { State.Contracts = new List(); State.Touch(); } } public void RefreshContractOffers() { long day = State.Clock.Day; long week = day / 7; bool flag = false; foreach (ContractState item in State.Contracts.Where((ContractState x) => x.Status == ContractStatus.Offered && x.OfferedDay / 7 < week)) { item.Status = ContractStatus.Cancelled; flag = true; } foreach (Settlement town in State.Settlements.Where((Settlement x) => x.Type != SettlementType.Hideout).OrderBy((Settlement x) => x.Id, StringComparer.Ordinal)) { if (!ContractFriendlySettlement(town) || town.OwnerClanId == State.PlayerClanId) { continue; } string prefix = "contract." + town.Id + "." + week + "."; string text = C.SettlementNotable(town.Id)?.Id ?? ""; if (text.Length == 0) { continue; } if (!State.Contracts.Any((ContractState x) => x.Id == prefix + "supply") && MakeContractSpace(week)) { string goodId = ((town.Type == SettlementType.Village) ? "good.tools" : "good.cloth"); TradeGoodDef tradeGoodDef = TradeGoods.All.First((TradeGoodDef x) => x.Id == goodId); State.Contracts.Add(new ContractState { Id = prefix + "supply", Kind = ContractKind.SettlementSupply, IssuerSettlementId = town.Id, IssuerClanId = town.OwnerClanId, IssuerNotableId = text, TargetSettlementId = town.Id, GoodId = tradeGoodDef.Id, Quantity = 3, Reward = tradeGoodDef.BasePrice * 3 * 2 + 60, OfferedDay = week * 7, DeadlineMinute = (week * 7 + 7) * 1440, Description = "Bring " + 3 + " " + tradeGoodDef.Name.ToLowerInvariant() + " to " + town.Name + "." }); flag = true; } if (town.Type == SettlementType.Town) { Settlement settlement = (from x in State.Settlements where x.Id != town.Id && (x.Type == SettlementType.Town || x.Type == SettlementType.Village) && ContractFriendlySettlement(x) orderby Vec2.Distance(town.Position, x.Position) select x).ThenBy((Settlement x) => x.Id, StringComparer.Ordinal).FirstOrDefault(); if (settlement != null && !State.Contracts.Any((ContractState x) => x.Id == prefix + "delivery") && MakeContractSpace(week)) { TradeGoodDef tradeGoodDef2 = TradeGoods.All[(int)(StableHash.Fnv1a64(town.Id) % (ulong)TradeGoods.All.Count)]; State.Contracts.Add(new ContractState { Id = prefix + "delivery", Kind = ContractKind.Delivery, IssuerSettlementId = town.Id, IssuerClanId = town.OwnerClanId, IssuerNotableId = text, TargetSettlementId = settlement.Id, GoodId = tradeGoodDef2.Id, Quantity = 4, Reward = tradeGoodDef2.BasePrice * 4 * 2 + 80, OfferedDay = week * 7, DeadlineMinute = (week * 7 + 7) * 1440, Description = "Supply " + 4 + " " + tradeGoodDef2.Name.ToLowerInvariant() + " to " + settlement.Name + ". Buy it or bring your own." }); flag = true; } Party party = (from x in State.ActiveParties where x.Kind == PartyKind.Bandit && string.IsNullOrEmpty(x.HideoutGuardOf) && State.AreHostile(State.PlayerClan, State.Clans.Get(x.ClanId)) where Vec2.Distance(town.Position, x.Position) <= 45.0 orderby Vec2.Distance(town.Position, x.Position) select x).ThenBy((Party x) => x.Id, StringComparer.Ordinal).FirstOrDefault(); if (party != null && !State.Contracts.Any((ContractState x) => x.Id == prefix + "bounty") && MakeContractSpace(week)) { State.Contracts.Add(new ContractState { Id = prefix + "bounty", Kind = ContractKind.BanditBounty, IssuerSettlementId = town.Id, IssuerClanId = town.OwnerClanId, IssuerNotableId = text, TargetPartyId = party.Id, Reward = 250L, OfferedDay = week * 7, DeadlineMinute = (week * 7 + 7) * 1440, Description = "Defeat " + party.Name + " and return to " + town.Name + "." }); flag = true; } } } if (flag) { State.Touch(); } } internal bool MakeContractSpace(long week) { if (State.Contracts.Count < 60) { return true; } ContractState contractState = (from x in State.Contracts where x.Status != ContractStatus.Active && x.Escrow == 0L && x.OfferedDay / 7 < week orderby x.OfferedDay select x).ThenBy((ContractState x) => x.Id, StringComparer.Ordinal).FirstOrDefault(); if (contractState == null) { return false; } State.Contracts.Remove(contractState); return true; } public IEnumerable CurrentContractOffers() { Settlement town = C.CompanionMeetingSettlement(townOnly: false); if (town == null) { return Enumerable.Empty(); } return (from x in State.Contracts where x.Status == ContractStatus.Offered && x.IssuerSettlementId == town.Id && x.DeadlineMinute > State.Clock.Minute orderby x.Kind select x).ThenBy((ContractState x) => x.Id, StringComparer.Ordinal).ToList(); } internal bool ContractFriendlySettlement(Settlement settlement) { Clan clan = ((settlement == null) ? null : State.Clans.Get(settlement.OwnerClanId)); if (clan != null && !clan.IsEliminated && !clan.IsBandit) { return !State.AreHostile(State.PlayerClan, clan); } return false; } internal string ContractValidityReason(ContractState contract) { Settlement issuer = State.Settlements.Get(contract.IssuerSettlementId); if (!ContractFriendlySettlement(issuer) || issuer.OwnerClanId != contract.IssuerClanId) { return "The issuer can't honour this any more."; } if (contract.IssuerClanId == State.PlayerClanId) { return "Your own clan can't hire you."; } if (!string.IsNullOrEmpty(contract.IssuerNotableId) && !State.Notables.Any((NotableState x) => x.Id == contract.IssuerNotableId && x.IsAlive && x.SettlementId == issuer.Id)) { return "Whoever asked for this is gone."; } if (IsCargoContract(contract)) { if (contract.Kind == ContractKind.SettlementSupply && contract.TargetSettlementId != contract.IssuerSettlementId) { return "This local supply request has an invalid destination."; } Settlement settlement = State.Settlements.Get(contract.TargetSettlementId); if (!ContractFriendlySettlement(settlement)) { return "The destination's gone."; } if (contract.Quantity <= 0 || !TradeGoods.All.Any((TradeGoodDef x) => x.Id == contract.GoodId)) { return "This delivery is invalid."; } } else { if (contract.Kind != ContractKind.BanditBounty) { return "Unknown contract type."; } Party party = State.Parties.Get(contract.TargetPartyId); if (contract.Progress == 0 && (party == null || party.Kind != PartyKind.Bandit || party.State == PartyState.Destroyed || party.State == PartyState.Disbanded)) { return "Someone else got the bounty target."; } } if (contract.DeadlineMinute <= State.Clock.Minute) { return "This contract expired."; } return ""; } public static bool IsCargoContract(ContractState contract) { if (contract != null) { if (contract.Kind != ContractKind.Delivery) { return contract.Kind == ContractKind.SettlementSupply; } return true; } return false; } public string ContractAcceptReason(string id) { string text = C.DisguiseBlockReason(); if (text.Length > 0) { return text; } string text2 = C.CargoCommandReason(); if (text2.Length > 0) { return text2; } ContractState contractState = State.Contracts.FirstOrDefault((ContractState x) => x.Id == id); if (contractState == null || contractState.Status != ContractStatus.Offered) { return "That offer's gone."; } Settlement settlement = C.CompanionMeetingSettlement(townOnly: false); if (settlement == null || settlement.Id != contractState.IssuerSettlementId) { return "Accept it where it was offered."; } text2 = ContractValidityReason(contractState); if (text2.Length > 0) { return text2; } if (State.Contracts.Count((ContractState x) => x.Status == ContractStatus.Active) >= 3) { return "Three contracts at a time. Finish one first."; } if (contractState.Reward <= 0 || State.Clans.Get(contractState.IssuerClanId).Gold < contractState.Reward) { return "They can't pay what they promised."; } return ""; } public CommandResult AcceptContract(string id) { string text = ContractAcceptReason(id); if (text.Length > 0) { return CommandResult.Fail(text); } ContractState contractState = State.Contracts.First((ContractState x) => x.Id == id); State.Transact(State.Clans.Get(contractState.IssuerClanId), -contractState.Reward, LedgerAccount.Quest, "Reward held until done"); contractState.Escrow = contractState.Reward; contractState.Status = ContractStatus.Active; contractState.WasAccepted = true; contractState.DeadlineMinute = State.Clock.Minute + 10080; State.AddLog(LogCategory.Info, "Accepted: " + contractState.Description, contractState.IssuerSettlementId); State.Touch(); return CommandResult.Success("Accepted. You have seven days."); } public string ContractCompleteReason(string id) { string text = C.CargoCommandReason(); if (text.Length > 0) { return text; } ContractState contractState = State.Contracts.FirstOrDefault((ContractState x) => x.Id == id); if (contractState == null || contractState.Status != ContractStatus.Active) { return "That contract isn't active."; } text = ContractValidityReason(contractState); if (text.Length > 0) { return text; } Settlement settlement = C.CompanionMeetingSettlement(townOnly: false); string text2 = (IsCargoContract(contractState) ? contractState.TargetSettlementId : contractState.IssuerSettlementId); if (settlement == null || settlement.Id != text2) { return "Visit " + State.Settlements.Get(text2)?.Name + " to complete this contract."; } if (contractState.Escrow != contractState.Reward || contractState.Escrow <= 0) { return "The contract has no valid reward escrow."; } if (State.PlayerClan.Gold > long.MaxValue - contractState.Escrow) { return "Your treasury can't take the reward."; } if (IsCargoContract(contractState)) { if (C.CargoCount(State.PlayerParty, contractState.GoodId) < contractState.Quantity) { return "Bring " + contractState.Quantity + " units of the requested cargo."; } if (C.MarketStock(settlement, contractState.GoodId) > 500 - contractState.Quantity) { return "The market there has no room for it."; } } else if (contractState.Progress <= 0) { return "Beat the named bandits first."; } return ""; } public CommandResult CompleteContract(string id) { string text = ContractCompleteReason(id); if (text.Length > 0) { return CommandResult.Fail(text); } ContractState contractState = State.Contracts.First((ContractState x) => x.Id == id); if (IsCargoContract(contractState)) { int num = C.CargoCount(State.PlayerParty, contractState.GoodId) - contractState.Quantity; if (num == 0) { State.PlayerParty.Cargo.Remove(contractState.GoodId); } else { State.PlayerParty.Cargo[contractState.GoodId] = num; } Settlement settlement = State.Settlements.Require(contractState.TargetSettlementId); settlement.Market.Stock[contractState.GoodId] = C.MarketStock(settlement, contractState.GoodId) + contractState.Quantity; } State.Transact(State.PlayerClan, contractState.Escrow, LedgerAccount.Quest, "Contract completed"); contractState.Escrow = 0L; contractState.Status = ContractStatus.Completed; C.GrantSkillExperience(State.PlayerHero, IsCargoContract(contractState) ? "trade" : "leadership", 20.0); if (!string.IsNullOrEmpty(contractState.IssuerNotableId)) { C.AdjustNotableRelation(contractState.IssuerNotableId, 5, "contract completed"); if (contractState.Kind == ContractKind.Delivery && contractState.TargetSettlementId != contractState.IssuerSettlementId) { C.AdjustNotableRelation(C.SettlementNotable(contractState.TargetSettlementId)?.Id, 5, "supplies delivered"); } } State.PlayerClan.Renown += 1.0; State.AddLog(LogCategory.Economy, "Contract completed for " + contractState.Reward + " denars: " + contractState.Description, contractState.IssuerSettlementId); State.Touch(); return CommandResult.Success("Contract completed: " + contractState.Reward + " denars."); } public string ContractAbandonReason(string id) { string text = C.CargoCommandReason(); if (text.Length > 0) { return text; } ContractState contractState = State.Contracts.FirstOrDefault((ContractState x) => x.Id == id); if (contractState == null || contractState.Status != ContractStatus.Active) { return "That contract isn't active."; } return ""; } public CommandResult AbandonContract(string id) { string text = ContractAbandonReason(id); if (text.Length > 0) { return CommandResult.Fail(text); } ContractState contractState = State.Contracts.First((ContractState x) => x.Id == id); string text2 = ContractValidityReason(contractState); RefundContract(contractState); contractState.Status = ContractStatus.Cancelled; if (text2.Length == 0 || text2 == "This contract expired.") { C.AdjustNotableRelation(contractState.IssuerNotableId, -2, "contract abandoned"); } State.AddLog(LogCategory.Info, "Abandoned: " + contractState.Description, contractState.IssuerSettlementId); State.Touch(); return CommandResult.Success("Contract dropped; the reward went back to the issuer."); } internal void RefundContract(ContractState contract) { Clan clan = State.Clans.Get(contract.IssuerClanId); if (clan != null && contract.Escrow > 0 && clan.Gold <= long.MaxValue - contract.Escrow) { State.Transact(clan, contract.Escrow, LedgerAccount.Quest, "Unused contract escrow returned"); contract.Escrow = 0L; } } public void DailyContracts() { bool flag = false; foreach (ContractState item in State.Contracts.Where((ContractState x) => x.Status == ContractStatus.Active)) { string text = ContractValidityReason(item); if (text.Length != 0) { RefundContract(item); item.Status = ContractStatus.Failed; if (text == "This contract expired.") { C.AdjustNotableRelation(item.IssuerNotableId, -2, "contract expired"); } State.AddLog(LogCategory.Info, "Contract closed: " + text + " " + item.Description, item.IssuerSettlementId); flag = true; } } foreach (ContractState item2 in State.Contracts.Where((ContractState x) => x.Status != ContractStatus.Active && x.Escrow > 0)) { long escrow = item2.Escrow; RefundContract(item2); flag |= escrow != item2.Escrow; } if (flag) { State.Touch(); } RefreshContractOffers(); } public void RecordContractBattle(Encounter encounter, BattleResult result, BattleReport report) { if (encounter == null || result == null || report == null || !encounter.PlayerInvolved || !encounter.PartiesOn(encounter.PlayerSide).Contains(State.PlayerPartyId) || (result.Winner != WinnerSide.Attacker && result.Winner != WinnerSide.Defender) || result.Winner == WinnerSide.Attacker != (encounter.PlayerSide == BattleSide.Attacker)) { return; } BattleSide losingSide = ((result.Winner == WinnerSide.Attacker) ? BattleSide.Defender : BattleSide.Attacker); foreach (ContractState contract in State.Contracts.Where((ContractState x) => x.Status == ContractStatus.Active && x.Kind == ContractKind.BanditBounty && x.Progress == 0)) { if (contract.DeadlineMinute > State.Clock.Minute && encounter.PartiesOn(losingSide).Contains(contract.TargetPartyId) && report.Parties.FirstOrDefault((PartyBattleReport x) => x.PartyId == contract.TargetPartyId && x.Side == losingSide) != null) { contract.Progress = 1; report.Lines.Add("Bounty fulfilled: return to " + State.Settlements.Get(contract.IssuerSettlementId)?.Name + "."); } } } } internal sealed class ConversationsSystem { private readonly Campaign C; private CampaignState State => C.State; internal ConversationsSystem(Campaign host) { C = host; } public static Campaign.Personality PersonalityOf(Hero h) { ulong x = StableHash.Fnv1a64("personality:" + h?.Id); return new Campaign.Personality { Honor = Trait(0), Mercy = Trait(8), Valor = Trait(16), Generosity = Trait(24), Calculating = Trait(32) }; int Trait(int shift) { return (int)((x >> shift) % 5) switch { 3 => (int)((x >> shift + 3) & 1), 4 => 1, 0 => -1, _ => 0, }; } } public static string DescribePersonality(Hero h) { Campaign.Personality personality = PersonalityOf(h); List list = new List(); if (personality.Honor != 0) { list.Add((personality.Honor > 0) ? "honest" : "devious"); } if (personality.Mercy != 0) { list.Add((personality.Mercy > 0) ? "merciful" : "cruel"); } if (personality.Valor != 0) { list.Add((personality.Valor > 0) ? "daring" : "cautious"); } if (personality.Generosity != 0) { list.Add((personality.Generosity > 0) ? "generous" : "closefisted"); } if (personality.Calculating != 0) { list.Add((personality.Calculating > 0) ? "calculating" : "impulsive"); } if (list.Count == 0) { return ""; } if (list.Count == 1) { return list[0]; } return string.Join(", ", list.Take(list.Count - 1)) + " and " + list[list.Count - 1]; } public string TalkReason(string heroId) { Hero h = State.Heroes.Get(heroId); if (h == null || h.IsPlayer) { return "There is nobody to talk to."; } if (h.State == HeroState.Dead) { return h.Name + " is dead."; } if (C.AwaitingHeir) { return "Choose your heir first."; } Hero playerHero = State.PlayerHero; if (playerHero == null || playerHero.State != HeroState.Active) { return "You're not free to talk."; } Party party = ((h.State == HeroState.Active) ? C.PartyOfHero(h.Id) : null); if (party != null && party.Id != State.PlayerPartyId && C.MeetPartyReason(party.Id).Length == 0) { return ""; } if (h.ClanId == State.PlayerClanId && h.ClanId.Length > 0) { if (h.State == HeroState.Active && h.PartyId == State.PlayerPartyId) { return ""; } Settlement settlement = C.CurrentSettlement(); if (settlement != null && h.State == HeroState.Active && string.IsNullOrEmpty(h.PartyId) && h.SettlementId == settlement.Id) { return ""; } return h.Name + " is not with you."; } if (C.AvailableCompanions().Any((Hero x) => x.Id == h.Id)) { return ""; } if (C.NoblesHere().Any((Hero x) => x.Id == h.Id)) { if (!C.HasKeepAccess(C.MeetingPlace())) { return "You need to get into the keep to meet " + h.Name + ": bribe the guards, or come as a member of the realm."; } return ""; } return h.Name + " is not here."; } public Conversation StartConversation(string heroId) { string text = TalkReason(heroId); Hero h = State.Heroes.Get(heroId); if (text.Length > 0) { if (h != null && C.NoblesHere().Any((Hero x) => x.Id == h.Id) && Campaign.HasKeep(C.MeetingPlace()) && !C.HasKeepAccess(C.MeetingPlace())) { Conversation conversation = StartTownConversation("visit.guard", StableSeed("keepguard:" + C.MeetingPlace().Id)); conversation.Lines.Clear(); conversation.Lines.Add("A guard steps in front of you before you can reach " + h.Name + ". \"The keep is not open to strangers.\""); conversation.Topic = "root"; BuildTownOptions(conversation); return conversation; } return null; } Conversation conversation2 = new Conversation { HeroId = h.Id, Name = h.Name, Title = HeroTitle(h), SettlementId = (C.CurrentSettlement()?.Id ?? ""), Seed = StableSeed("talk:" + h.Id + ":" + State.Clock.Day.ToString(CultureInfo.InvariantCulture)) }; bool first = !State.MetHeroes.Contains(h.Id) && h.ClanId != State.PlayerClanId; if (State.MetHeroes.Add(h.Id)) { State.Touch(); } conversation2.Lines.Add(HeroGreeting(h, first, conversation2)); BuildHeroOptions(conversation2); return conversation2; } public Conversation StartTownConversation(string role, int person) { Settlement settlement = C.CurrentSettlement(); Conversation conversation = new Conversation(); conversation.Role = role ?? "visit.folk"; conversation.SettlementId = settlement?.Id ?? ""; conversation.Seed = StableSeed("town:" + role + ":" + person.ToString(CultureInfo.InvariantCulture) + ":" + State.Clock.Day.ToString(CultureInfo.InvariantCulture)); Conversation conversation2 = conversation; conversation2.Name = TownRoleName(conversation2.Role, settlement); conversation2.Title = ((settlement == null) ? "" : settlement.Name); conversation2.Lines.Add(TownGreeting(conversation2, settlement)); BuildTownOptions(conversation2); return conversation2; } public void ChooseConversationOption(Conversation c, string optionId) { if (c == null || c.Ended) { return; } ConversationOption conversationOption = c.Options.FirstOrDefault((ConversationOption o) => o.Id == optionId); if (conversationOption == null || !conversationOption.Enabled) { return; } c.Turn++; c.PlayerLine = conversationOption.Text; c.Lines.Clear(); c.Note = ""; if (c.Persuasion != null && !c.Persuasion.Finished) { AnswerPersuasion(c, optionId); } else if (c.Barter != null) { if (optionId == "bye") { c.Barter.Result = ""; CloseBarter(c); } } else if (c.EncounterId.Length > 0) { AnswerEncounter(c, optionId); } else if (c.HeroId.Length <= 0 || !AnswerDeal(c, optionId)) { if (c.HeroId.Length > 0) { AnswerHero(c, optionId); } else { AnswerTown(c, optionId); } } } internal string HeroTitle(Hero h) { Clan clan = State.Clans.Get(h.ClanId); if (h.ClanId == State.PlayerClanId) { if (h.IsFamily) { return "Your family"; } return "Your companion"; } if (h.Occupation == HeroOccupation.Companion) { return "Wanderer"; } Kingdom kingdom = ((clan == null) ? null : State.Kingdoms.Get(clan.KingdomId)); return ((clan != null && clan.LeaderHeroId == h.Id) ? ("Head of " + clan.Name) : (Families.Noun(h.Sex, "Lord", "Lady", "Noble") + " of " + (clan?.Name ?? "no clan"))) + ((kingdom != null) ? (" · " + kingdom.Name) : ""); } internal static string First(Hero h) { return (h?.Name ?? "").Split(new char[1] { ' ' })[0]; } internal string TimeGreeting() { return DayNight.Phase(State.Clock.Minute) switch { "Dawn" => "Good morning", "Dusk" => "Good evening", "Night" => "You keep late hours", _ => "Good day", }; } internal int HeroRelation(Hero h) { if (!(h.ClanId == State.PlayerClanId)) { return C.ClanRelation(State.PlayerClanId, h.ClanId); } return 100; } internal bool HeroIsEnemy(Hero h) { if (h.ClanId != State.PlayerClanId) { return State.AreHostile(State.PlayerClan, State.Clans.Get(h.ClanId)); } return false; } internal static T Pick(Random r, params T[] options) { return options[r.Next(options.Length)]; } internal static int StableSeed(string key) { return (int)(StableHash.Fnv1a64(key) & 0x7FFFFFFF); } internal Random TalkRandom(Conversation c, string topic) { return new Random(c.Seed ^ StableSeed(topic + ":" + c.Turn.ToString(CultureInfo.InvariantCulture))); } internal string HeroGreeting(Hero h, bool first, Conversation c) { Random random = TalkRandom(c, "greet"); Hero playerHero = State.PlayerHero; string text = First(playerHero); string text2 = TimeGreeting(); Campaign.Personality personality = PersonalityOf(h); Clan clan = State.Clans.Get(h.ClanId); if (h.ClanId == State.PlayerClanId) { if (h.SpouseId == playerHero.Id || playerHero.SpouseId == h.Id) { return Pick(random, new string[3] { "There you are, " + text + ". I was beginning to worry.", text2 + ", my love. What's on your mind?", "Ah, " + text + ". Sit with me a moment." }); } if (h.FatherId == playerHero.Id || h.MotherId == playerHero.Id) { return Pick(random, new string[3] { text2 + ", " + Families.Noun(playerHero.Sex, "father", "mother", "parent") + ".", "You wanted to see me?", "Is something the matter?" }); } if (h.IsFamily) { return Pick(random, new string[2] { text2 + ", " + text + ".", "What is it, " + text + "?" }); } int num = C.Approval(h); if (num >= 40) { return Pick(random, new string[3] { text2 + ", captain! Good to see you.", "Captain! What can I do for you?", "At your side as always, captain." }); } if (num <= -40) { return Pick(random, "Captain.", "What now?", "Yes, captain?"); } return Pick(random, new string[3] { text2 + ", captain.", "Captain. What do you need?", "Captain! Something on your mind?" }); } if (h.Occupation == HeroOccupation.Companion) { if (first) { return Pick(random, new string[3] { "Looking for a sword arm? The name's " + h.Name + ".", text2 + ". I'm " + h.Name + ". You have the look of someone who is hiring.", h.Name + ", at your service. For the right price." }) + (string.IsNullOrWhiteSpace(h.Description) ? "" : (" " + h.Description)); } return Pick(random, new string[3] { text2 + ". Still thinking it over?", "Back again? My offer stands.", "Ah, it's you. Buy me a drink and we'll talk." }); } if (HeroIsEnemy(h)) { string text3 = Pick(random, new string[3] { "We are at war, " + playerHero.Name + ". Say what you must and be gone.", "Bold of you to come to me, with our realms at war.", "Speak quickly. I do not chat with my enemies." }); string text4 = C.MemoryRemark(h, random); if (text4.Length <= 0) { return text3; } return text3 + " " + text4; } int num2 = HeroRelation(h); string text5 = ((num2 <= -30) ? Pick(random, new string[3] { "Oh. It's you.", "What do you want, " + playerHero.Name + "?", "I have little time for you." }) : ((num2 < -10) ? Pick(random, new string[3] { text + ".", text2 + ". What brings you to me?", "Yes? Be brief." }) : ((num2 <= 10) ? Pick(random, new string[3] { text2 + ", " + playerHero.Name + ". What can I do for you?", text2 + ". Have we business?", "Well met, " + playerHero.Name + "." }) : ((num2 > 40) ? Pick(random, new string[3] { text + ", my friend! Come, sit with me a while.", "There's a face I'm glad to see. " + text2 + ", " + text + "!", "My friend! What news do you bring?" }) : Pick(random, new string[3] { text2 + ", " + text + "! Good to see you.", "Ah, " + text + ". Always a pleasure.", "Welcome, " + text + ". Come in." }))))); if (first) { Kingdom kingdom = ((clan == null) ? null : State.Kingdoms.Get(clan.KingdomId)); string text6 = " I am " + h.Name + " of " + (clan?.Name ?? "no clan") + ((kingdom != null) ? (", sworn to " + kingdom.Name + ".") : "."); if (personality.Honor > 0) { text6 += " I speak plainly, and I hope you will too."; } else if (personality.Honor < 0) { text6 += " I have heard a great deal about you. Some of it may even be true."; } else if (personality.Valor > 0) { text6 += " I hope you are as bold as they say."; } else if (personality.Calculating > 0) { text6 += " I like to know who I am dealing with."; } text5 += text6; } string text7 = C.MemoryRemark(h, random); if (text7.Length > 0 && random.Next(10) < 7) { text5 = text5 + " " + text7; } else if (first || random.Next(4) == 0) { string text8 = C.RenownRemark(random); if (text8.Length > 0) { text5 = text5 + " " + text8; } } return text5; } internal void BuildHeroOptions(Conversation c) { c.Options.Clear(); Hero hero = State.Heroes.Get(c.HeroId); if (hero == null || hero.State == HeroState.Dead) { c.Ended = true; return; } if (c.Topic.StartsWith("quest:", StringComparison.Ordinal)) { C.BuildQuestTalkOptions(c, c.Topic.Substring(6)); if (c.Topic != "root") { return; } } if (c.Topic == "us") { c.Options.Add(new ConversationOption { Id = "think", Text = "What do you think of me?" }); c.Options.Add(new ConversationOption { Id = "gift", Text = "Please accept a gift. (" + C.GiftCost(hero).ToString("N0") + " denars)", Reason = C.GiftReason(hero.Id) }); c.Options.Add(new ConversationOption { Id = "spar", Text = "Shall we spar? A friendly bout.", Reason = C.SparReason(hero.Id) }); string text = C.LessonSkill(hero); c.Options.Add(new ConversationOption { Id = "lesson", Text = ((text.Length > 0) ? ("Would you teach me something of " + SkillWord(text) + "?") : "Would you teach me something?"), Reason = C.LessonReason(hero.Id) }); c.Options.Add(new ConversationOption { Id = "favour", Text = "I have a favour to ask.", Reason = C.FavourReason(hero.Id) }); c.Options.Add(new ConversationOption { Id = "back", Text = "Never mind." }); return; } if (c.Topic == "favour") { c.Options.Add(new ConversationOption { Id = "favour:troops", Text = "Could you spare a few soldiers? (" + C.FavourTroopCount(hero) + ")", Reason = C.FavourTroopsReason(hero.Id) }); c.Options.Add(new ConversationOption { Id = "favour:purse", Text = "Could your house lend me a purse? (" + C.FavourPurse(hero).ToString("N0") + " denars)", Reason = C.FavourPurseReason(hero.Id) }); c.Options.Add(new ConversationOption { Id = "favour:word", Text = "Would you speak well of me at court?", Reason = C.FavourWordReason(hero.Id) }); c.Options.Add(new ConversationOption { Id = "back", Text = "Never mind." }); return; } if (c.Topic == "where") { foreach (Hero item in WhereaboutsCandidates(hero)) { c.Options.Add(new ConversationOption { Id = "where:" + item.Id, Text = "Where is " + item.Name + "?" }); } c.Options.Add(new ConversationOption { Id = "back", Text = "Never mind." }); return; } int num; int num2; if (hero.ClanId == State.PlayerClanId) { num = ((hero.ClanId.Length > 0) ? 1 : 0); if (num != 0) { num2 = 0; goto IL_0438; } } else { num = 0; } num2 = ((hero.Occupation == HeroOccupation.Companion) ? 1 : 0); goto IL_0438; IL_0438: bool flag = (byte)num2 != 0; if (num != 0) { c.Options.Add(new ConversationOption { Id = "health", Text = "How are you holding up?" }); if (hero.PartyId == State.PlayerPartyId) { c.Options.Add(new ConversationOption { Id = "company", Text = "What do you make of our company?" }); } c.Options.Add(new ConversationOption { Id = "news", Text = "Heard any news?" }); if (C.IsOwnedCompanion(hero) && !hero.IsFamily) { c.Options.Add(new ConversationOption { Id = "opinion", Text = "What do you think of how I lead?" }); c.Options.Add(new ConversationOption { Id = "wants", Text = "Is there anything you need?" }); c.Options.Add(new ConversationOption { Id = "cgift", Text = "Here, something for your trouble. (" + 100 + " denars)", Reason = C.CompanionGiftReason(hero.Id) }); } } else if (flag) { c.Options.Add(new ConversationOption { Id = "about", Text = "Tell me about yourself." }); c.Options.Add(new ConversationOption { Id = "news", Text = "Heard any news?" }); string reason = C.CompanionRecruitmentReason(hero.Id); c.Options.Add(new ConversationOption { Id = "hire", Text = "Join my company. (" + hero.HireCost.ToString("N0") + " denars, " + hero.DailyWage + " a day)", Reason = reason }); } else { string reason2 = ""; long value; if (HeroIsEnemy(hero)) { reason2 = First(hero) + " has no wish to pass the time with an enemy."; } else if (State.Conversations != null && State.Conversations.SmallTalkDay.TryGetValue(hero.Id, out value) && value == State.Clock.Day) { reason2 = "You have already passed the time with " + First(hero) + " today."; } c.Options.Add(new ConversationOption { Id = "smalltalk", Text = "How do you fare these days?", Reason = reason2 }); c.Options.Add(new ConversationOption { Id = "news", Text = "What news is there?" }); c.Options.Add(new ConversationOption { Id = "about", Text = "Tell me about yourself." }); if (WhereaboutsCandidates(hero).Count > 0) { c.Options.Add(new ConversationOption { Id = "where", Text = "Do you know where someone is?" }); } Settlement settlement = C.CurrentSettlement(); if (settlement != null && Campaign.HasKeep(settlement) && settlement.OwnerClanId == hero.ClanId && !HeroIsEnemy(hero)) { c.Options.Add(new ConversationOption { Id = "fief", Text = "How fares " + settlement.Name + "?" }); } if (hero.Occupation == HeroOccupation.Lord) { C.AddQuestTalkOptions(c, hero); } if (hero.Occupation == HeroOccupation.Lord && !HeroIsEnemy(hero)) { c.Options.Add(new ConversationOption { Id = "us", Text = "Let us talk about the two of us…" }); } if (hero.Occupation == HeroOccupation.Lord) { AddDealOptions(c, hero); } Hero playerHero = State.PlayerHero; if (hero.Occupation == HeroOccupation.Lord && C.MarriageReason(playerHero, hero).Length == 0) { CourtshipState courtshipState = C.CourtshipOf(hero.Id); if (courtshipState != null && courtshipState.Won) { c.Options.Add(new ConversationOption { Id = "propose", Text = "Will you marry me? (a gift of " + C.MarriageGiftFor(hero).ToString("N0") + " denars to " + (State.Clans.Get(hero.ClanId)?.Name ?? "their clan") + ")", Reason = C.ProposeReason(hero.Id) }); } else { c.Options.Add(new ConversationOption { Id = "court", Text = "I would like to get to know you better. (Persuade)", Reason = C.CourtReason(hero.Id) }); } } } c.Options.Add(new ConversationOption { Id = "bye", Text = Pick(TalkRandom(c, "bye"), "Farewell.", "I must be going.", "Until next time.") }); } internal List WhereaboutsCandidates(Hero h) { List list = new List(); Add(C.SpouseOf(h)); Clan clan = State.Clans.Get(h.ClanId); if (clan != null) { Add(State.Heroes.Get(clan.LeaderHeroId)); } Kingdom kingdom = ((clan == null) ? null : State.Kingdoms.Get(clan.KingdomId)); Clan clan2 = ((kingdom == null) ? null : State.Clans.Get(kingdom.RulerClanId)); if (clan2 != null) { Add(State.Heroes.Get(clan2.LeaderHeroId)); } foreach (CourtshipState item in C.PlayerCourtships()) { Add(State.Heroes.Get(item.HeroId)); } if (clan != null) { foreach (Hero item2 in State.Heroes.Where((Hero x) => x.ClanId == clan.Id && x.Occupation == HeroOccupation.Lord).OrderBy((Hero x) => x.Id, StringComparer.Ordinal)) { if (list.Count >= 6) { break; } Add(item2); } } return list.Take(6).ToList(); void Add(Hero x) { if (x != null && !x.IsPlayer && x.Id != h.Id && x.State != HeroState.Dead && C.IsGrown(x) && !list.Contains(x)) { list.Add(x); } } } internal void AnswerHero(Conversation c, string id) { Hero hero = State.Heroes.Get(c.HeroId); Hero playerHero = State.PlayerHero; Random r = TalkRandom(c, id); Campaign.Personality p = PersonalityOf(hero); if (C.AnswerQuestTalk(c, hero, id)) { if (!c.Ended) { BuildHeroOptions(c); } return; } switch (id.StartsWith("where:", StringComparison.Ordinal) ? "where:" : id) { case "bye": c.Lines.Add((hero.ClanId == State.PlayerClanId) ? Pick(r, "Of course.", "I'll be around.", "Call if you need me.") : (HeroIsEnemy(hero) ? "Go, then." : Pick(r, new string[3] { "Farewell, " + First(playerHero) + ".", "Safe travels.", "Until we meet again." }))); c.Ended = true; return; case "back": c.Topic = "root"; c.Lines.Add(Pick(r, "Anything else?", "What else is on your mind?")); break; case "where": c.Topic = "where"; c.Lines.Add(Pick(r, "Who are you looking for?", "Whom do you seek?")); break; case "where:": { Hero hero2 = State.Heroes.Get(id.Substring(6)); string mapTarget; string text = HeroWhereaboutsForTalk(hero2, out mapTarget); bool flag = hero2 != null && (hero2.ClanId == hero.ClanId || hero2.Id == hero.SpouseId); c.Lines.Add((hero2 == null) ? "I don't know who you mean." : (flag ? Pick(r, new string[2] { "Last I heard, " + First(hero2) + " was " + text + ".", First(hero2) + "? " + Cap(text) + ", I believe." }) : Pick(r, "Word is that " + hero2.Name + " is " + text + ".", "I heard " + First(hero2) + " was " + text + ". But don't hold me to it."))); c.Topic = "root"; break; } case "smalltalk": { if (State.Conversations == null) { State.Conversations = new ConversationsState(); } State.Conversations.SmallTalkDay[hero.Id] = State.Clock.Day; c.Lines.AddRange(HeroSmallTalk(hero, r)); double probability = Math.Max(0.2, Math.Min(0.85, 0.35 + (double)playerHero.Skill("charm") / 600.0 + 0.1 * (double)(p.Generosity + p.Mercy) - 0.05 * (double)p.Calculating + (double)HeroRelation(hero) / 400.0)); C.GrantSkillExperience(playerHero, "charm", 4.0); if (State.Random.Get("conversations").Chance(probability)) { C.AdjustClanRelation(State.PlayerClanId, hero.ClanId, 1); c.Lines.Add(Pick(r, new string[3] { "It is good to talk with someone who listens.", "You are better company than most, " + First(playerHero) + ".", "We should do this more often." })); c.Note = "Relation with " + (State.Clans.Get(hero.ClanId)?.Name ?? "their clan") + " +" + 1 + "."; } else { c.Note = First(hero) + " is polite, but the talk goes nowhere."; } State.Touch(); break; } case "news": c.Lines.AddRange(Rumours(r, 2, p)); break; case "us": c.Topic = "us"; c.Lines.Add(Pick(r, "Oh? What did you have in mind?", "I am listening.", "Go on.")); break; case "think": c.Lines.AddRange(C.OpinionLines(hero, r)); c.Topic = "us"; break; case "gift": { CommandResult commandResult3 = C.GiveGift(hero.Id); c.Lines.Add((!commandResult3.Ok) ? "That is kind, but no." : ((p.Generosity < 0) ? Pick(r, "Now that is a gift worth having.", "Most generous. I will not forget it.") : Pick(r, "You are too kind.", "Thank you. That was thoughtful."))); c.Note = commandResult3.Message; c.Topic = "us"; break; } case "spar": { CommandResult commandResult8 = C.Spar(hero.Id); bool flag2 = commandResult8.Ok && commandResult8.Message.StartsWith("You won", StringComparison.Ordinal); c.Lines.Add((!commandResult8.Ok) ? "Not now." : (flag2 ? Pick(r, "Hah! You have a quick arm. Well fought.", "Enough, enough! I yield. You fight well.") : Pick(r, "Keep your guard up next time.", "Not bad. But not good enough, today."))); c.Note = commandResult8.Message; c.Topic = "us"; break; } case "lesson": { string id2 = C.LessonSkill(hero); CommandResult commandResult5 = C.TakeLesson(hero.Id); c.Lines.Add(commandResult5.Ok ? (Pick(r, "Watch closely, then. This is how it is done.", "Very well. Pay attention.") + " (" + First(hero) + " spends an hour showing you " + SkillWord(id2) + ".)") : "Not today."); c.Note = commandResult5.Message; c.Topic = "us"; break; } case "favour": c.Topic = "favour"; c.Lines.Add(Pick(r, "What do you need?", "Ask, and we shall see.", "A favour? Name it.")); break; case "favour:troops": case "favour:purse": case "favour:word": { CommandResult commandResult6 = ((id == "favour:troops") ? C.AskFavourTroops(hero.Id) : ((id == "favour:purse") ? C.AskFavourPurse(hero.Id) : C.AskFavourWord(hero.Id))); c.Lines.Add(commandResult6.Ok ? Pick(r, "Consider it done.", "For you, gladly. Remember it.", "Very well. Do not make a habit of asking.") : "I am afraid I cannot."); c.Note = commandResult6.Message; c.Topic = "root"; break; } case "opinion": c.Lines.AddRange(C.CompanionOpinion(hero, r)); break; case "wants": c.Lines.Add(C.AskCompanionWants(hero)); break; case "cgift": { CommandResult commandResult4 = C.GiveCompanionGift(hero.Id); c.Lines.Add(commandResult4.Ok ? Pick(r, "Much obliged, captain.", "That'll buy a few rounds. Thank you.") : "Keep it, captain."); c.Note = commandResult4.Message; break; } case "fief": { Settlement s = C.CurrentSettlement(); c.Lines.Add(Pick(r, "You take an interest in our affairs? Very well.", "Since you ask.", "It is kind of you to ask.")); c.Lines.AddRange(FiefReport(s, r, steward: false)); if (p.Generosity > 0) { c.Lines.Add("We look after our own here."); } else if (p.Calculating > 0) { c.Lines.Add("And it pays, which is what matters."); } break; } case "about": c.Lines.AddRange(HeroAbout(hero, r)); break; case "health": c.Lines.Add((hero.Health < 0.5) ? Pick(r, "Badly hurt, if I'm honest. I need rest.", "I've been better. These wounds are slow to close.") : ((hero.Health < 0.9) ? Pick(r, "Still sore from the last fight, but I'll manage.", "A few new scars. Nothing that won't heal.") : Pick(r, new string[3] { "Fit and ready.", "Never better, " + First(playerHero) + ".", "Well enough. Thank you for asking." }))); if (C.HeroYears(hero) >= 55) { c.Lines.Add("Though my bones ache more each winter."); } break; case "company": { Party playerParty = State.PlayerParty; double num = C.FoodSupply(playerParty); int totalTroops = playerParty.Troops.TotalTroops; c.Lines.Add((totalTroops < 10) ? "We are few. A few more good fighters would not go amiss." : ((totalTroops < 40) ? "A decent band. They follow you willingly enough." : "A real company now. Men talk about us in the taverns.")); c.Lines.Add((num < (double)totalTroops * 0.5) ? "But the food is running low. The men are grumbling." : "Food is fine, for now."); if ((State.PlayerClan?.Gold ?? 0) < 300) { c.Lines.Add("And our purse is thin. Wages will come due."); } break; } case "hire": { CommandResult commandResult7 = C.RecruitCompanion(hero.Id); if (commandResult7.Ok) { c.Lines.Add(Pick(r, "You won't regret this, captain.", "Then I'm yours. Let's go and make some coin.", "Done. Point me at whoever needs a beating.")); c.Note = commandResult7.Message; c.Title = HeroTitle(hero); } else { c.Lines.Add("Hm. Come back when you can manage it."); c.Note = commandResult7.Message; } break; } case "court-done": { CommandResult commandResult2 = CommandResult.Success(c.Note); CourtshipState courtshipState = C.CourtshipOf(hero.Id); if (!commandResult2.Ok) { c.Lines.Add("Perhaps another time."); c.Note = commandResult2.Message; break; } if (courtshipState != null && courtshipState.Won) { c.Lines.Add(Pick(r, new string[2] { "I confess I have grown fond of you, " + First(playerHero) + ".", "You may speak to my family, if you wish. I would not refuse you." })); } else if (courtshipState != null && courtshipState.Refused) { c.Lines.Add(Pick(r, "I think we are not well suited. Forgive me.", "I am sorry. I do not feel as you do.")); } else if (commandResult2.Message.Contains("goes well")) { c.Lines.Add(Pick(r, "I enjoyed that. Come and see me again.", "You have an interesting way of seeing the world.", "I would like to hear more, another day.")); } else { c.Lines.Add(Pick(r, "Hm. I am not sure we understand each other.", "That was... awkward.", "Perhaps we should talk of something else.")); } c.Note = commandResult2.Message; break; } case "propose": { CommandResult commandResult = C.Propose(hero.Id); c.Lines.Add(commandResult.Ok ? Pick(r, "Yes. Yes, I will.", "I was hoping you would ask.") : "Not now. There are things to settle first."); c.Note = commandResult.Message; if (commandResult.Ok) { c.Title = HeroTitle(hero); } break; } } if (!c.Ended) { BuildHeroOptions(c); } } internal static string Cap(string s) { if (!string.IsNullOrEmpty(s)) { return char.ToUpperInvariant(s[0]) + s.Substring(1); } return s; } internal string HeroWhereaboutsForTalk(Hero other, out string mapTarget) { string text = C.HeroWhereabouts(other, out mapTarget); if (!string.IsNullOrEmpty(text)) { switch (text) { case "Unknown": case "Away": break; case "Dead": return "dead, I'm afraid"; case "In your party": return "riding with you"; default: return char.ToLowerInvariant(text[0]) + text.Substring(1); } } return "somewhere far from here"; } internal List HeroSmallTalk(Hero h, Random r) { List list = new List(); Clan clan = State.Clans.Get(h.ClanId); Kingdom kingdom = ((clan == null) ? null : State.Kingdoms.Get(clan.KingdomId)); string faction = State.FactionOf(clan); List list2 = (from s in State.Stances where s.Stance == Stance.War && (s.A == faction || s.B == faction) select TalkFactionName((s.A == faction) ? s.B : s.A) into n where n.Length > 0 select n).Distinct().ToList(); Campaign.Personality personality = PersonalityOf(h); if (list2.Count > 0) { list.Add(((kingdom != null) ? kingdom.Name : "My clan") + " is at war with " + JoinAnd(list2.Take(3).ToList()) + ". " + ((personality.Valor > 0) ? "I look forward to meeting them in the field." : ((personality.Valor < 0) ? "I pray it ends soon." : "These are hard times."))); } else if (kingdom != null) { list.Add("Peace holds across " + kingdom.Name + ", for now. Long may it last."); } else { list.Add("My clan answers to no king. It is a freedom, and a burden."); } Hero hero = C.SpouseOf(h); int num = C.ChildrenOf(h).Count((Hero x) => x.State != HeroState.Dead); if (hero != null && r.Next(2) == 0) { list.Add("My " + Families.Noun(hero.Sex, "husband", "wife", "spouse") + ", " + First(hero) + ", is well" + ((num > 0) ? (", and our " + ((num == 1) ? "child grows" : (num + " children grow")) + " fast.") : ".")); } else if (hero == null && C.IsGrown(h) && r.Next(3) == 0) { list.Add(Pick(r, "My family keeps asking when I will marry.", "I have not yet found anyone worth marrying. Perhaps one day.")); } if (h.Health < 0.7) { list.Add("I am still healing from my last battle."); } else if (C.HeroYears(h) >= 55 && r.Next(2) == 0) { list.Add("I am not as young as I was. My bones tell me when the rain is coming."); } return list; } internal List HeroAbout(Hero h, Random r) { List list = new List(); Clan clan = State.Clans.Get(h.ClanId); if (h.Occupation == HeroOccupation.Companion && h.ClanId != State.PlayerClanId) { list.Add(string.IsNullOrWhiteSpace(h.Description) ? "Not much to tell. I go where the work is." : h.Description); List list2 = (from x in h.Skills.OrderByDescending((KeyValuePair x) => x.Value).Take(2) select SkillWord(x.Key)).ToList(); if (list2.Count > 0) { list.Add("I'm best at " + JoinAnd(list2) + "."); } list.Add("I'd want " + h.HireCost.ToString("N0") + " denars up front, and " + h.DailyWage + " a day after that."); return list; } Kingdom kingdom = ((clan == null) ? null : State.Kingdoms.Get(clan.KingdomId)); string text = "I am " + h.Name + ", " + C.HeroYears(h) + " years old, of " + (clan?.Name ?? "no clan") + ((kingdom != null) ? (", sworn to " + kingdom.Name) : "") + "."; if (clan != null && clan.LeaderHeroId == h.Id) { text += " I lead my house."; } list.Add(text); if (clan != null) { List list3 = (from s in State.Settlements where s.OwnerClanId == clan.Id && s.Type != SettlementType.Village && s.Type != SettlementType.Hideout select s.Name).ToList(); if (list3.Count > 0) { list.Add("Our house holds " + JoinAnd(list3.Take(3).ToList()) + ((list3.Count > 3) ? " and more besides" : "") + "."); } } Campaign.Personality personality = PersonalityOf(h); List list4 = new List(); if (personality.Honor > 0) { list4.Add("I keep my word, whatever it costs me."); } if (personality.Honor < 0) { list4.Add("A promise is a tool, like any other."); } if (personality.Mercy > 0) { list4.Add("I take no joy in cruelty."); } if (personality.Mercy < 0) { list4.Add("Mercy is a luxury in times like these."); } if (personality.Valor > 0) { list4.Add("I have never shied from a fight."); } if (personality.Valor < 0) { list4.Add("I see no glory in dying young."); } if (personality.Generosity > 0) { list4.Add("What is mine I share with those who are loyal to me."); } if (personality.Generosity < 0) { list4.Add("I count every coin, and so should you."); } if (personality.Calculating > 0) { list4.Add("I like to think three moves ahead."); } if (personality.Calculating < 0) { list4.Add("I trust my gut. It has not failed me yet."); } if (list4.Count > 0) { list.Add(list4[r.Next(list4.Count)]); } string text2 = DescribePersonality(h); if (text2.Length > 0) { list.Add("(" + First(h) + " strikes you as " + text2 + ".)"); } return list; } internal static string SkillWord(string id) { if (!string.IsNullOrEmpty(id)) { return id.Replace('_', ' ').ToLowerInvariant(); } return ""; } internal static string JoinAnd(List items) { if (items.Count == 0) { return ""; } if (items.Count == 1) { return items[0]; } return string.Join(", ", items.Take(items.Count - 1)) + " and " + items[items.Count - 1]; } internal string TalkFactionName(string id) { Kingdom kingdom = State.Kingdoms.Get(id); if (kingdom != null) { if (!kingdom.IsEliminated) { return kingdom.Name; } return ""; } Clan clan = State.Clans.Get(id); if (clan != null && !clan.IsBandit) { return clan.Name; } return ""; } public List Rumours(Random r, int count, Campaign.Personality p = default(Campaign.Personality)) { List list = new List(); Dictionary dictionary = new Dictionary(StringComparer.Ordinal); long minute = State.Clock.Minute; foreach (StanceRecord stance in State.Stances) { string text = TalkFactionName(stance.A); string text2 = TalkFactionName(stance.B); if (text.Length != 0 && text2.Length != 0 && (State.Kingdoms.Contains(stance.A) || State.Kingdoms.Contains(stance.B))) { long num = (minute - stance.SinceMinute) / 1440; bool flag = stance.SinceMinute > 480; if (stance.Stance == Stance.War) { list.Add(text + " and " + text2 + " are at war" + ((flag && num <= 5) ? ("; the fighting began only " + ((num <= 0) ? "today" : ((num == 1) ? "yesterday" : (num + " days ago")))) : "") + "."); } else if (flag && num <= 10) { list.Add(text + " and " + text2 + " have made peace" + ((num <= 1) ? " just now" : "") + "."); } } } foreach (SiegeState item in (State.Sieges ?? new List()).Where((SiegeState x) => x.Stage != SiegeStage.Ended && x.Stage != SiegeStage.Marching)) { Settlement settlement = State.Settlements.Get(item.SettlementId); Party party = State.Parties.Get(item.BesiegerPartyId); Clan clan = ((party == null) ? null : State.Clans.Get(party.ClanId)); if (settlement != null) { list.Add(((clan != null) ? (clan.Name + " have") : "An army has") + " laid siege to " + settlement.Name + "."); } } foreach (TournamentState item2 in State.Tournaments?.Active ?? new List()) { Settlement settlement2 = State.Settlements.Get(item2.TownId); if (settlement2 != null) { string text3 = "There is a tournament at " + settlement2.Name + (string.IsNullOrEmpty(item2.Prize?.Name) ? "." : (". The prize is " + item2.Prize.Name + ".")); list.Add(text3); dictionary[text3] = item2.Id; } } foreach (Settlement item3 in State.Settlements.Where((Settlement x) => x.Type == SettlementType.Village && (x.VillageRecovery?.Damage ?? 0) > 0).OrderBy((Settlement x) => x.Id, StringComparer.Ordinal).Take(4)) { list.Add(item3.Name + " was raided not long ago. The villagers are still rebuilding."); } Clan clan2 = (from x in State.Clans where !x.IsBandit && x.Id != State.PlayerClanId orderby x.Renown descending select x).ThenBy((Clan x) => x.Id, StringComparer.Ordinal).FirstOrDefault(); if (clan2 != null) { list.Add("Nobody's name carries further than " + clan2.Name + "'s these days."); } Clan playerClan = State.PlayerClan; if (playerClan != null && playerClan.Renown >= 150.0) { list.Add("Folk have started to talk about " + playerClan.Name + ". About you, I mean."); } List list2 = new List(); if (list.Count == 0) { list2.Add("All quiet, as far as I know."); return list2; } string[] array = ((p.Calculating <= 0) ? ((p.Honor >= 0) ? new string[3] { "They say", "I have heard that", "Word is that" } : new string[2] { "They say", "If the whispers are true," }) : new string[2] { "My sources tell me", "I have it on good authority that" }); List list3 = list.OrderBy((string x) => r.Next()).Take(Math.Max(1, count)).ToList(); foreach (string item4 in list3) { if (dictionary.TryGetValue(item4, out var value)) { C.HearOfTournament(value); } } int num2 = r.Next(array.Length); for (int num3 = 0; num3 < list3.Count; num3++) { list2.Add(num3 switch { 1 => "And " + Uncap(array[(num2 + num3) % array.Length]), 0 => array[(num2 + num3) % array.Length], _ => array[(num2 + num3) % array.Length], } + " " + LowerLead(list3[num3])); } return list2; } internal static string Uncap(string s) { if (!string.IsNullOrEmpty(s) && !s.StartsWith("I ", StringComparison.Ordinal)) { return char.ToLowerInvariant(s[0]) + s.Substring(1); } return s; } internal static string LowerLead(string news) { string[] array = new string[4] { "There ", "Nobody's ", "An ", "Folk " }; foreach (string value in array) { if (news.StartsWith(value, StringComparison.Ordinal)) { return char.ToLowerInvariant(news[0]) + news.Substring(1); } } return news; } public static string TownRoleName(string role, Settlement s) { bool flag = s != null && s.Type == SettlementType.Castle; switch (role) { case "visit.guard": if (!flag) { return "Town guard"; } return "Castle guard"; case "visit.merchant": return "Merchant"; case "visit.worker": return "Smith"; case "visit.priest": return "Priest"; case "visit.bard": return "Bard"; case "visit.drill": return "Soldier"; case "visit.child": return "Child"; case "visit.keepguard": return "Keep guard"; case "visit.steward": return "Steward"; default: if (!flag) { return "Townsperson"; } return "Castle servant"; } } internal string TownGreeting(Conversation c, Settlement s) { Random r = TalkRandom(c, "greet"); Hero playerHero = State.PlayerHero; Clan playerClan = State.PlayerClan; bool flag = s != null && playerClan != null && s.OwnerClanId == playerClan.Id; string text = ((playerHero == null) ? "traveller" : Families.Noun(playerHero.Sex, "my lord", "my lady", "my lord")); bool flag2 = playerClan != null && playerClan.Renown >= 300.0; switch (c.Role) { case "visit.child": return Pick(r, new string[4] { "Are you a real " + ((playerHero != null && playerHero.Sex == HeroSex.Female) ? "warrior" : "knight") + "?", "Is that sword sharp? Can I hold it?", "Hello! Do you want to play?", "My papa says I'm not to talk to strangers." }); case "visit.guard": if (flag) { return Pick(r, "Welcome home, " + text + ". All quiet on the walls.", text.Substring(0, 1).ToUpperInvariant() + text.Substring(1) + "! Good to have you back."); } return Pick(r, new string[4] { "Keep your blade sheathed and we'll have no trouble.", "Move along, unless you've business with me.", "Mind yourself in " + (s?.Name ?? "here") + ", stranger.", "What is it?" }); case "visit.keepguard": if (flag) { return Pick(r, "The hall is yours, " + text + ".", "All in order in the hall, " + text + "."); } return Pick(r, "No trouble in the hall, mind.", "Hands where I can see them in here.", "Speak softly. There are lords at table.", "You've leave to be here. Don't make me regret it."); case "visit.steward": { Clan clan = ((s == null) ? null : State.Clans.Get(s.OwnerClanId)); Hero hero = ((clan == null) ? null : State.Heroes.Get(clan.LeaderHeroId)); if (flag) { return Pick(r, "Welcome home, " + text + ". The household is in good order.", "Ah, " + text + "! Your hall awaits. Shall I have the fire built up?"); } return Pick(r, new string[3] { "Welcome to the hall of " + ((hero != null) ? hero.Name : (clan?.Name ?? "my masters")) + ". I keep the household here.", "A guest! I am the steward of this house. How may I help?", "Good " + ((TimeGreeting() == "Good evening") ? "evening" : "day") + ". The household is at your service, within reason." }); } case "visit.merchant": return Pick(r, "Fine goods, fair prices! Well, fair-ish.", "Come, come! Take a look.", "Looking to buy? Or just looking?", "Ah, a customer! Or a thief. Which is it?"); case "visit.worker": return Pick(r, "Mind the sparks.", "If it's steel you want, I'm your smith.", "Can't stop long. The forge won't wait."); case "visit.priest": return Pick(r, "Peace be with you, child.", "The gods see all you do, traveller.", "Welcome. Do you seek comfort?"); case "visit.bard": return Pick(r, "A song for a coin? Or a coin for a song?", "Ah, a listener! At last.", "Every hero needs a song. Are you a hero?"); case "visit.drill": if (!flag) { return Pick(r, "Can't talk long. The sergeant has eyes in the back of his head.", "We drill every day. Every. Single. Day.", "Mm? You lost?"); } return Pick(r, text.Substring(0, 1).ToUpperInvariant() + text.Substring(1) + "! Drills are going well.", "At your command, " + text + "."); default: if (flag) { return Pick(r, "Welcome home, " + text + "!", "Bless you, " + text + ". Things are better since you came."); } if (flag2) { return Pick(r, new string[2] { "You're " + playerHero?.Name + ", aren't you? I've heard of you!", "Is it true what they say about you?" }); } return Pick(r, new string[4] { TimeGreeting() + ".", "Hm? Can I help you?", "Not from round here, are you?", "Lovely day for it. For something, anyway." }); } } internal void BuildTownOptions(Conversation c) { c.Options.Clear(); Settlement settlement = State.Settlements.Get(c.SettlementId); bool flag = settlement != null && settlement.Type == SettlementType.Castle; if (c.Topic == "directions") { c.Options.Add(new ConversationOption { Id = "to:keep", Text = "...the keep?" }); if (!flag) { c.Options.Add(new ConversationOption { Id = "to:tavern", Text = "...the tavern?" }); } c.Options.Add(new ConversationOption { Id = "to:temple", Text = (flag ? "...the chapel?" : "...the temple?") }); c.Options.Add(new ConversationOption { Id = "to:smithy", Text = "...the smithy?" }); if (!flag) { c.Options.Add(new ConversationOption { Id = "to:market", Text = "...the market?" }); } else { c.Options.Add(new ConversationOption { Id = "to:barracks", Text = "...the barracks?" }); } c.Options.Add(new ConversationOption { Id = "to:gate", Text = "...the way out?" }); c.Options.Add(new ConversationOption { Id = "back", Text = "Never mind." }); return; } if (c.Role == "visit.child") { c.Options.Add(new ConversationOption { Id = "play", Text = "What are you playing?" }); c.Options.Add(new ConversationOption { Id = "bye", Text = "Run along, now." }); return; } switch (c.Role) { case "visit.guard": c.Options.Add(new ConversationOption { Id = "holder", Text = "Who holds this place?" }); if (Campaign.HasKeep(settlement) && !C.HasKeepAccess(settlement)) { c.Options.Add(new ConversationOption { Id = "bribe", Text = "Let me into the keep. (" + C.KeepBribeCost(settlement).ToString("N0") + " denars)", Reason = C.KeepBribeReason() }); } break; case "visit.merchant": c.Options.Add(new ConversationOption { Id = "trade", Text = "How is trade?" }); break; case "visit.worker": c.Options.Add(new ConversationOption { Id = "work", Text = "Tell me about your work." }); break; case "visit.priest": c.Options.Add(new ConversationOption { Id = "bless", Text = "Will you bless me?" }); c.Options.Add(new ConversationOption { Id = "people", Text = "How fare the people here?" }); break; case "visit.bard": c.Options.Add(new ConversationOption { Id = "song", Text = "Sing me something." }); break; case "visit.drill": c.Options.Add(new ConversationOption { Id = "garrison", Text = "How is the garrison?" }); break; case "visit.keepguard": c.Options.Add(new ConversationOption { Id = "inkeep", Text = "Who is in the keep today?" }); c.Options.Add(new ConversationOption { Id = "holder", Text = "Who holds this place?" }); break; case "visit.steward": c.Options.Add(new ConversationOption { Id = "inkeep", Text = "Who is staying in the hall?" }); c.Options.Add(new ConversationOption { Id = "fief", Text = "How fares " + (settlement?.Name ?? "this place") + "?" }); c.Options.Add(new ConversationOption { Id = "holder", Text = "Who holds this place?" }); break; default: c.Options.Add(new ConversationOption { Id = "life", Text = "How is life here?" }); break; } c.Options.Add(new ConversationOption { Id = "news", Text = "Any news?" }); c.Options.Add(new ConversationOption { Id = "directions", Text = "Where can I find..." }); c.Options.Add(new ConversationOption { Id = "bye", Text = Pick(TalkRandom(c, "bye"), "Farewell.", "Thanks. Goodbye.", "I'll leave you to it.") }); } internal void AnswerTown(Conversation c, string id) { Settlement settlement = State.Settlements.Get(c.SettlementId); Random random = TalkRandom(c, id); bool flag = settlement != null && settlement.Type == SettlementType.Castle; Clan clan = ((settlement == null) ? null : State.Clans.Get(settlement.OwnerClanId)); if (id.StartsWith("to:", StringComparison.Ordinal)) { c.Lines.Add(Directions(id.Substring(3), flag, random)); c.Topic = "root"; BuildTownOptions(c); return; } switch (id) { case "bye": c.Lines.Add((c.Role == "visit.child") ? Pick(random, "Bye!", "Bye bye!") : Pick(random, "Farewell.", "Mind how you go.", "Gods keep you.")); c.Ended = true; return; case "back": c.Topic = "root"; c.Lines.Add("Anything else?"); break; case "directions": c.Topic = "directions"; c.Lines.Add(Pick(random, "Where to?", "What are you looking for?", "Lost, are we?")); break; case "news": c.Lines.AddRange(Rumours(random, 1)); break; case "play": c.Lines.Add(Pick(random, "Knights and bandits! I'm the knight. You can be the bandit.", "We're hunting the big rat that lives behind the smithy.", "Hide and seek! But you're too big to hide.")); break; case "holder": { Kingdom kingdom = ((clan == null) ? null : State.Kingdoms.Get(clan.KingdomId)); c.Lines.Add((clan == null) ? "Nobody, rightly. Strange times." : ((flag ? "This castle" : "This town") + " is held by " + clan.Name + ((kingdom != null) ? (", for " + kingdom.Name) : "") + ".")); double num5 = settlement?.Security ?? 50.0; c.Lines.Add((num5 < 30.0) ? "Between you and me, the streets aren't safe at night. Too few of us, too many cutpurses." : ((num5 > 70.0) ? "Quiet streets. We keep them that way." : "We do what we can to keep the peace.")); break; } case "inkeep": c.Lines.AddRange(WhoIsInTheKeep(settlement, random)); break; case "fief": c.Lines.AddRange(FiefReport(settlement, random, steward: true)); break; case "bribe": { CommandResult commandResult = C.BribeKeepGuards(); c.Lines.Add(commandResult.Ok ? Pick(random, "The guard pockets the coins. \"Go on, then. I never saw you.\"", "\"Generous. The keep's that way. Be quick about it.\"") : "\"Nice try.\""); c.Note = commandResult.Message; break; } case "trade": { double num4 = settlement?.Prosperity ?? 500.0; c.Lines.Add((num4 < 2500.0) ? "Slow. Folk have no coin to spend." : ((num4 > 6000.0) ? "Never better! Coin is flowing like wine." : "Steady enough. Can't complain. Well, I can, but I won't.")); if (settlement != null && C.SettlementFood(settlement) < 30.0) { c.Lines.Add("And food's dear. The granaries are near empty."); } if (settlement != null && C.IsSettlementBesieged(settlement)) { c.Lines.Add("With the siege on, nothing comes in or out."); } break; } case "work": c.Lines.Add(Pick(random, "Swords, axes, spearheads. Bring me good iron and I'll make it sing.", "Horseshoes mostly, these days. But I can make a fine blade.")); c.Lines.Add((C.SmithyReason().Length == 0) ? "If you've a mind to work the forge yourself, the smithy is open to you." : "The smithy's busy just now."); break; case "bless": c.Lines.Add(Pick(random, "May your sword be swift, your shield strong and your heart kind. Go in peace.", "The gods walk with you. Try not to make them regret it.", "Be blessed, child. And give alms when you can.")); break; case "people": { double num3 = settlement?.Loyalty ?? 60.0; c.Lines.Add((num3 < 30.0) ? ("Restless. They grumble against " + (clan?.Name ?? "their masters") + ", and I cannot blame them.") : ((num3 > 70.0) ? ("Content, praise be. " + (clan?.Name ?? "Their lords") + " treat them well.") : "They endure, as people do.")); break; } case "song": { Clan clan2 = (from x in State.Clans where !x.IsBandit orderby x.Renown descending select x).ThenBy((Clan x) => x.Id, StringComparer.Ordinal).FirstOrDefault(); Hero hero = ((clan2 == null) ? null : State.Heroes.Get(clan2.LeaderHeroId)); Clan playerClan = State.PlayerClan; bool flag2 = playerClan != null && playerClan.Renown >= 200.0 && random.Next(2) == 0; string text = (flag2 ? State.PlayerHero.Name : (hero?.Name ?? "a nameless knight")); c.Lines.Add(Pick(random, "♪ Oh, " + text + " rode out at dawn, with banner high and sword half-drawn... ♪", "♪ Raise your cups to " + text + ", who never once was known to run... ♪", "♪ The ravens wait, the ravens know, where " + text + " goes, the foes lie low... ♪")); c.Lines.Add(flag2 ? "Ha! You look surprised. Yes, they sing about you now." : "Thank you, thank you. Coins are welcome."); break; } case "garrison": c.Lines.Add("We're " + (settlement?.Garrison?.TotalTroops).GetValueOrDefault() + " strong in the garrison" + (((settlement?.Militia ?? 0) > 0) ? (", with " + settlement.Militia + " militia besides") : "") + "."); c.Lines.Add(((settlement?.Garrison?.TotalTroops).GetValueOrDefault() < 20) ? "Too few, if anyone comes knocking." : "Enough to give anyone pause."); break; case "life": { double num = settlement?.Prosperity ?? 500.0; double num2 = settlement?.Loyalty ?? 60.0; if (settlement != null && C.IsSettlementBesieged(settlement)) { c.Lines.Add("Life? Under siege? We eat rats and pray."); } else if (settlement != null && C.SettlementFood(settlement) < 30.0) { c.Lines.Add("Hungry. The market's nearly bare."); } else if (num > 6000.0) { c.Lines.Add(Pick(random, "Good! Plenty of work, plenty of coin.", "Can't complain. Busy streets, full bellies.")); } else if (num < 2500.0) { c.Lines.Add(Pick(random, "Hard. Work's scarce.", "We get by. Barely.")); } else { c.Lines.Add(Pick(random, "Same as ever.", "Could be worse. Could be better.")); } if (num2 < 30.0 && clan != null) { c.Lines.Add("Don't tell anyone I said so, but " + clan.Name + " can rot."); } break; } } if (!c.Ended) { BuildTownOptions(c); } } internal List WhoIsInTheKeep(Settlement s, Random r) { List list = new List(); List list2 = C.NoblesHere(); if (list2.Count == 0) { list.Add(Pick(r, "Nobody of note, today. The hall is quiet.", "No lords or ladies of other houses stay here just now.")); return list; } Hero holder = C.KeepHolderHere(s, list2); if (holder != null) { list.Add(holder.Name + " " + Pick(r, "sits the high seat today.", "is receiving before the throne.", "is here, at the head of the hall.")); } List list3 = list2.Where((Hero h) => h != holder).Take(6).Select(delegate(Hero h) { Clan clan = State.Clans.Get(h.ClanId); return h.Name + ((clan != null) ? (" of " + clan.Name) : ""); }) .ToList(); if (list3.Count > 0) { list.Add(((holder != null) ? "Staying with them: " : "Staying here: ") + JoinAnd(list3) + "."); } if (list2.Count > 6) { list.Add("And others besides. It's a full hall."); } return list; } internal List FiefReport(Settlement s, Random r, bool steward) { List list = new List(); if (s == null) { list.Add("I could not say."); return list; } double prosperity = s.Prosperity; double loyalty = s.Loyalty; double security = s.Security; bool flag = s.Type == SettlementType.Town; if (C.IsSettlementBesieged(s)) { list.Add("We are besieged. Every day is harder than the last."); } list.Add((!flag) ? ((prosperity > 2500.0) ? "The lands about the castle are well kept and the villages pay their dues." : "The lands about us are thin. The villages struggle.") : ((prosperity > 6000.0) ? "The town is rich. The markets have never been busier." : ((prosperity < 2500.0) ? "Trade is poor and the people poorer." : "Trade is steady, the workshops busy enough."))); double num = C.SettlementFood(s); list.Add((num < 30.0) ? ("The granaries are near empty. " + (steward ? "I ration what we have." : "We must find grain.")) : ((num > 150.0) ? "The stores are full." : "There is food enough, for now.")); list.Add((loyalty < 30.0) ? "The people are restless. There is talk against their masters." : ((loyalty > 70.0) ? "The people are content. Loyal, even." : "The people grumble no more than usual.")); int num2 = s.Garrison?.TotalTroops ?? 0; list.Add("The garrison is " + num2 + " strong" + ((s.Militia > 0) ? (", with " + s.Militia + " militia") : "") + ". " + ((security < 30.0) ? "The roads aren't safe. Nor the streets, after dark." : ((security > 70.0) ? "The peace is well kept." : "The watch does what it can."))); return list; } internal static string Directions(string place, bool castle, Random r) { if (castle) { return place switch { "keep" => "The keep? It's right in the middle. You can't miss it.", "temple" => "The chapel's on the west side, behind the barracks.", "smithy" => "By the gate, on the east side. Follow the hammering.", "barracks" => "West side of the yard. Mind the sergeant.", "gate" => "Back the way you came. South.", _ => "Not in a castle, friend.", }; } return place switch { "keep" => "Straight up the main street, past the square, to the north. The big stone hall with the banners.", "tavern" => "On the cross street, east of the square. Look for the sign. And the noise.", "temple" => "West of the square, on the cross street.", "smithy" => "Down by the gate, on the west side. Follow the smoke.", "market" => "Stalls all round the square and along the main street.", "gate" => Pick(r, "South, down the main street.", "Back down the main street, southwards. Leaving so soon?"), _ => "Couldn't tell you.", }; } internal void AddDealOptions(Conversation c, Hero h) { Clan clan = State.Clans.Get(h.ClanId); if (clan == null || clan.IsBandit) { return; } if (clan.LeaderHeroId == h.Id && C.ClanAllegianceSystem.RecruitmentAuthorityReason().Length == 0 && !C.ClanAllegianceSystem.IsRulingClan(clan) && clan.KingdomId != State.PlayerClan.KingdomId) { if (C.BarterReason(BarterKind.Recruit, h.Id).Length == 0) { c.Options.Add(new ConversationOption { Id = "deal:recruit", Text = "Swear your house to my realm. (Barter)" }); } else { c.Options.Add(new ConversationOption { Id = "persuade:recruit", Text = "Your house belongs in my realm. (Persuade)", Reason = C.PersuasionReason(PersuasionGoal.RecruitClan, h.Id) }); } } foreach (Hero item in C.CaptivesToPlead(h).Take(2)) { c.Options.Add(new ConversationOption { Id = "persuade:free:" + item.Id, Text = "Let " + item.Name + " go free. (Persuade)", Reason = C.PersuasionReason(PersuasionGoal.FreePrisoner, h.Id, item.Id) }); } if (C.BarterSystem.IsFactionLeader(h) && State.AtWar(State.FactionOf(clan), State.FactionOf(State.PlayerClan))) { c.Options.Add(new ConversationOption { Id = "deal:peace", Text = "Let us talk of peace. (Barter)", Reason = C.BarterReason(BarterKind.Peace, h.Id) }); } if (!HeroIsEnemy(h)) { bool num = C.BarterSystem.TheirCaptivesOf(clan.Id).Any(); bool flag = C.BarterSystem.PlayerCaptives().Any((Hero x) => x.ClanId == clan.Id); string text = (num ? "I would buy back my people. (Barter)" : (flag ? "I hold some of your house. Shall we bargain? (Barter)" : "Shall we trade? (Barter)")); string text2 = C.BarterReason(BarterKind.Trade, h.Id); if (text2.Length == 0 || clan.LeaderHeroId == h.Id || C.PartyOfHero(h.Id)?.LeaderHeroId == h.Id) { c.Options.Add(new ConversationOption { Id = "deal:trade", Text = text, Reason = text2 }); } } } internal bool AnswerDeal(Conversation c, string id) { Hero h = State.Heroes.Get(c.HeroId); Random r = TalkRandom(c, id); switch (id.StartsWith("persuade:free:", StringComparison.Ordinal) ? "persuade:free" : id) { case "court": return BeginPersuasion(c, PersuasionGoal.Courtship, h, "", Pick(r, "Oh? Then tell me something about yourself.", "I am listening. Go on.", "Very well. Let us talk, you and I.")); case "persuade:recruit": return BeginPersuasion(c, PersuasionGoal.RecruitClan, h, "", Pick(r, "You want my house to swear to you? You had better make a good case.", "Bold. Convince me, then.", "I have sworn oaths before. Why should I swear one to you?")); case "persuade:free": { Hero hero = State.Heroes.Get(id.Substring("persuade:free:".Length)); return BeginPersuasion(c, PersuasionGoal.FreePrisoner, h, hero?.Id ?? "", Pick(r, new string[2] { First(hero) + "? Why should I let a prize like that go?", "And what makes you think I would do that?" })); } case "deal:recruit": return BeginBarter(c, BarterKind.Recruit, h, Pick(r, "Then let us speak of terms.", "My house will want something for its oath.")); case "deal:peace": return BeginBarter(c, BarterKind.Peace, h, Pick(r, "Peace? Let us hear what you offer.", "Name your terms, and I will name mine.")); case "deal:trade": return BeginBarter(c, BarterKind.Trade, h, Pick(r, "Let us see what you have.", "What did you have in mind?")); default: return false; } } private bool BeginPersuasion(Conversation c, PersuasionGoal goal, Hero h, string targetId, string line) { PersuasionSession persuasionSession = C.StartPersuasion(goal, h?.Id ?? "", targetId, c.PartyId); if (persuasionSession == null) { c.Lines.Add("Not now."); c.Note = C.PersuasionReason(goal, h?.Id ?? "", targetId, c.PartyId); RebuildOptions(c); return true; } c.Persuasion = persuasionSession; c.Lines.Add(line); BuildPersuasionOptions(c); return true; } private bool BeginBarter(Conversation c, BarterKind kind, Hero h, string line) { BarterSession barterSession = C.StartBarter(kind, h?.Id ?? "", c.PartyId); if (barterSession == null) { c.Lines.Add("I think not."); c.Note = C.BarterReason(kind, h?.Id ?? "", c.PartyId); RebuildOptions(c); return true; } if (kind == BarterKind.Trade) { foreach (Hero item in C.BarterSystem.TheirCaptives(barterSession)) { C.SetBarterCount(barterSession, BarterItemKind.Captive, item.Id, fromPlayer: false, 1); } } c.Barter = barterSession; c.Lines.Add(line); c.Options.Clear(); c.Options.Add(new ConversationOption { Id = "bye", Text = "Never mind." }); return true; } private void RebuildOptions(Conversation c) { if (!c.Ended) { if (c.EncounterId.Length > 0) { BuildEncounterOptions(c); } else { BuildHeroOptions(c); } } } internal void BuildPersuasionOptions(Conversation c) { c.Options.Clear(); foreach (PersuasionArgument argument in c.Persuasion.Arguments) { c.Options.Add(new ConversationOption { Id = "arg:" + argument.Id, Text = argument.Text + " (" + SkillWord(argument.Skill) + ", " + (argument.Chance * 100.0).ToString("0", CultureInfo.InvariantCulture) + "%)" }); } c.Options.Add(new ConversationOption { Id = "giveup", Text = "Let us leave it there." }); } internal void AnswerPersuasion(Conversation c, string id) { PersuasionSession persuasion = c.Persuasion; Hero h = State.Heroes.Get(persuasion.HeroId); Random r = TalkRandom(c, "persuade:" + id); if (id == "giveup") { C.AbandonPersuasion(persuasion); } else { PersuasionOutcome o = C.Argue(persuasion, id.StartsWith("arg:", StringComparison.Ordinal) ? id.Substring(4) : id); c.Lines.Add(Reaction(o, r)); if (!persuasion.Finished) { c.Note = "Persuasion " + persuasion.Progress + " of " + persuasion.Required + " · " + persuasion.RoundsLeft + " left"; BuildPersuasionOptions(c); return; } } c.Persuasion = null; switch (persuasion.Goal) { case PersuasionGoal.Courtship: c.Note = persuasion.Result; AnswerHero(c, "court-done"); return; case PersuasionGoal.RecruitClan: if (persuasion.Won) { c.Lines.Add(Pick(r, "You make a fair case. Very well, let us talk of terms.", "I am persuaded. Now, what would you give for our oath?")); BeginBarter(c, BarterKind.Recruit, h, ""); c.Lines.RemoveAll((string x) => x.Length == 0); return; } c.Lines.Add(Pick(r, "No. My house stays where it is.", "I have heard enough. The answer is no.")); c.Note = "Try again on day " + (State.Clock.Day + 10 + 1) + "."; break; case PersuasionGoal.FreePrisoner: { Hero hero = State.Heroes.Get(persuasion.TargetId); if (persuasion.Won) { c.Lines.Add(Pick(r, "Very well. " + First(hero) + " may go.", "You have a way with words. I will let " + First(hero) + " go.")); c.Note = hero?.Name + " is free."; } else { c.Lines.Add(Pick(r, new string[2] { "No. " + First(hero) + " stays where they are.", "I am not moved." })); c.Note = "Try again in " + 7 + " days."; } break; } default: if (persuasion.Won) { c.Lines.Add(Pick(r, "Go, then. Before I change my mind.", "Fine. Ride on, and don't let me see you again today.")); c.Note = "You ride on without a fight."; c.Ended = true; return; } c.Lines.Add(Pick(r, "Enough talk!", "Your words won't save you.", "Draw your sword.")); c.Note = "They won't hear any more of it."; break; } RebuildOptions(c); } private static string Reaction(PersuasionOutcome o, Random r) { return o switch { PersuasionOutcome.CriticalSuccess => Pick(r, "Hm. I had not thought of it like that.", "That is a fair point. A very fair point.", "You may be right."), PersuasionOutcome.Success => Pick(r, "Perhaps.", "There is something in that.", "Go on."), PersuasionOutcome.CriticalFailure => Pick(r, "Do you take me for a fool?", "That is an insult.", "You'd do better to keep quiet."), PersuasionOutcome.Failure => Pick(r, "I am not convinced.", "Words. Only words.", "That does not move me."), _ => "Let us leave it.", }; } internal void CloseBarter(Conversation c) { BarterSession barterSession = c?.Barter; if (barterSession == null) { return; } c.Barter = null; c.PlayerLine = ""; c.Lines.Clear(); Random r = TalkRandom(c, "barter"); c.Turn++; if (barterSession.Accepted) { c.Note = barterSession.Result; c.Lines.Add(Pick(r, "Then we have a deal.", "Agreed.", "Done. I will hold you to it.")); if (barterSession.Kind == BarterKind.Ransom || barterSession.Kind == BarterKind.Bribe || barterSession.Kind == BarterKind.Tribute) { c.Ended = true; return; } } else { c.Lines.Add(Pick(r, "As you wish.", "Another time, then.")); if (barterSession.Result.Length > 0) { c.Note = barterSession.Result; } if (barterSession.Kind == BarterKind.Ransom) { c.Ended = true; return; } } if (c.HeroId.Length > 0) { Hero hero = State.Heroes.Get(c.HeroId); if (hero != null && hero.State == HeroState.Dead) { c.Ended = true; return; } } if (c.EncounterId.Length > 0 && C.PendingPlayerEncounter?.Id != c.EncounterId) { c.Ended = true; } else if (c.HeroId.Length == 0 && c.EncounterId.Length == 0) { c.Ended = true; } else { RebuildOptions(c); } } internal string EncounterTalkReason() { Encounter pendingPlayerEncounter = C.PendingPlayerEncounter; if (pendingPlayerEncounter == null || pendingPlayerEncounter.Phase != EncounterPhase.AwaitingDecision) { return "There is nobody to talk to."; } if (pendingPlayerEncounter.Kind != EncounterKind.FieldBattle && pendingPlayerEncounter.Kind != EncounterKind.BanditAmbush) { return "This is no place for talking."; } if (pendingPlayerEncounter.MustFight) { return "Ironman: you've started this battle, so it has to be settled — fight, auto-resolve or surrender."; } if (C.PersuasionSystem.EnemyLeaderParty(pendingPlayerEncounter) != null) { return ""; } return "There is nobody to talk to."; } internal Conversation StartEncounterTalk() { if (EncounterTalkReason().Length > 0) { return null; } Encounter pendingPlayerEncounter = C.PendingPlayerEncounter; Party party = C.PersuasionSystem.EnemyLeaderParty(pendingPlayerEncounter); Hero hero = State.Heroes.Get(party.LeaderHeroId ?? ""); Clan clan = State.Clans.Get(party.ClanId); Conversation conversation = new Conversation { HeroId = (hero?.Id ?? ""), Role = "encounter", EncounterId = pendingPlayerEncounter.Id, PartyId = party.Id, Name = (hero?.Name ?? party.Name), Title = ((hero != null) ? HeroTitle(hero) : (clan?.Name ?? "")), Seed = StableSeed("encounter:" + pendingPlayerEncounter.Id), Topic = "encounter" }; if (hero != null && State.MetHeroes.Add(hero.Id)) { State.Touch(); } Random r = TalkRandom(conversation, "greet"); bool flag = clan?.IsBandit ?? false; bool flag2 = pendingPlayerEncounter.InitiatorPartyId == State.PlayerPartyId; conversation.Lines.Add((!flag2) ? (flag ? Pick(r, "Your money or your life. Your choice.", "Hand over what you've got and nobody gets hurt.", "Well, well. Look what wandered into our hands.") : Pick(r, "You are caught. Yield, or fight.", "There is no escape for you here.", "Lay down your arms.")) : (flag ? Pick(r, "What do you want? We've done nothing to you.", "Back off, or you'll regret it.") : Pick(r, "Why do you bar our way?", "What is the meaning of this?"))); BuildEncounterOptions(conversation); return conversation; } internal void BuildEncounterOptions(Conversation c) { c.Options.Clear(); State.Heroes.Get(c.HeroId); Encounter pendingPlayerEncounter = C.PendingPlayerEncounter; if (pendingPlayerEncounter == null || pendingPlayerEncounter.Id != c.EncounterId) { c.Ended = true; return; } if (pendingPlayerEncounter.InitiatorPartyId == State.PlayerPartyId) { c.Options.Add(new ConversationOption { Id = "tribute", Text = "Hand over what you carry and you may go. (Barter)", Reason = C.BarterReason(BarterKind.Tribute, c.HeroId, c.PartyId) }); } else { c.Options.Add(new ConversationOption { Id = "avoid", Text = "Must we fight? (Persuade)", Reason = C.PersuasionReason(PersuasionGoal.AvoidFight, c.HeroId, "", c.PartyId) }); c.Options.Add(new ConversationOption { Id = "bribe", Text = "Perhaps some coin would settle this. (Barter)", Reason = C.BarterReason(BarterKind.Bribe, c.HeroId, c.PartyId) }); } c.Options.Add(new ConversationOption { Id = "bye", Text = "Enough talk." }); } internal void AnswerEncounter(Conversation c, string id) { Hero h = State.Heroes.Get(c.HeroId); Random r = TalkRandom(c, id); switch (id) { case "bye": c.Lines.Add(Pick(r, "So be it.", "Then let it be settled with steel.")); c.Ended = true; break; case "avoid": BeginPersuasion(c, PersuasionGoal.AvoidFight, h, "", Pick(r, "Talk, then. Quickly.", "You have until I lose patience.", "Convince me.")); break; case "bribe": BeginBarter(c, BarterKind.Bribe, h, Pick(r, "Now you're talking sense. How much?", "Coin, you say? Let's hear it.")); break; case "tribute": BeginBarter(c, BarterKind.Tribute, h, Pick(r, "All right, all right. What do you want?", "Take it, then. Just let us go.")); break; default: BuildEncounterOptions(c); break; } } } internal sealed class CouncilDiplomacySystem { private readonly Campaign C; private CampaignState State => C.State; internal CouncilDiplomacySystem(Campaign host) { C = host; } internal static bool CouncilDiplomacyDecision(KingdomDecision decision) { if (decision != null) { if (decision.Kind != KingdomDecisionKind.DeclareWar) { return decision.Kind == KingdomDecisionKind.MakePeace; } return true; } return false; } internal bool CouncilDiplomacyReserved(KingdomDecision decision) { if (CouncilDiplomacyDecision(decision)) { if (!C.DiplomacyFactionReserved(decision.KingdomId)) { return C.DiplomacyFactionReserved(decision.TargetKingdomId); } return true; } return false; } internal bool CouncilDiplomacyPending(string a, string b) { PoliticsState politics = State.Politics; if (politics == null) { return false; } return politics.Decisions?.Any((KingdomDecision d) => Campaign.CouncilIsLive(d) && CouncilDiplomacyDecision(d) && ((d.KingdomId == a && d.TargetKingdomId == b) || (d.KingdomId == b && d.TargetKingdomId == a))) == true; } internal string CouncilDiplomacyTermsReason(string kingdomId, string targetKingdomId, bool peace) { if (State.Diplomacy == null || !State.Diplomacy.Initialized) { return "Diplomacy is unavailable."; } Clan clan = C.LivingDiplomacyRuler(kingdomId); Clan clan2 = C.LivingDiplomacyRuler(targetKingdomId); if (clan == null || clan2 == null) { return "Both kingdoms need a living ruler."; } if (kingdomId == targetKingdomId) { return "Choose another kingdom."; } if (State.AtWar(kingdomId, targetKingdomId) != peace) { if (!peace) { return "These kingdoms are already at war."; } return "These kingdoms are already at peace."; } if (!peace) { if (C.Allied(kingdomId, targetKingdomId)) { return "These kingdoms are allies."; } long num = C.TruceDaysRemaining(kingdomId, targetKingdomId); if (num <= 0) { return ""; } return "The truce lasts another " + num + " days."; } if (clan.Gold < 1000) { return clan.Name + " needs " + 1000L + " denars to fund the peace treaty."; } if (clan2.Gold < 0 || clan2.Gold > 9223372036854774807L) { return "The other ruler can't take the payment."; } if (State.Clock.Day <= 9223372036854775800L) { return ""; } return "A truce cannot be recorded at this date."; } internal string ProposeCouncilDiplomacyReason(string targetKingdomId, bool peace) { string text = C.NewCouncilProposalReason(); if (text.Length > 0) { return text; } text = CouncilDiplomacyTermsReason(State.PlayerClan.KingdomId, targetKingdomId, peace); if (text.Length > 0) { return text; } if (!C.DiplomacyFactionReserved(targetKingdomId)) { return ""; } return "Wait for the fighting involving these kingdoms to finish."; } public string ProposeKingdomWarReason(string targetKingdomId) { return ProposeCouncilDiplomacyReason(targetKingdomId, peace: false); } public string ProposeKingdomPeaceReason(string targetKingdomId) { return ProposeCouncilDiplomacyReason(targetKingdomId, peace: true); } public CommandResult ProposeKingdomWar(string targetKingdomId) { return ProposeCouncilDiplomacy(targetKingdomId, peace: false); } public CommandResult ProposeKingdomPeace(string targetKingdomId) { return ProposeCouncilDiplomacy(targetKingdomId, peace: true); } internal CommandResult ProposeCouncilDiplomacy(string targetKingdomId, bool peace) { string text = ProposeCouncilDiplomacyReason(targetKingdomId, peace); if (text.Length > 0) { return CommandResult.Fail(text); } string kingdomId = State.PlayerClan.KingdomId; KingdomDecision kingdomDecision = C.NewCouncilDecision(kingdomId, State.PlayerClanId, peace ? KingdomDecisionKind.MakePeace : KingdomDecisionKind.DeclareWar); kingdomDecision.TargetKingdomId = targetKingdomId; kingdomDecision.TargetRulerClanId = C.ServiceRuler(targetKingdomId).Id; kingdomDecision.TargetStanceSinceMinute = State.FindStance(kingdomId, targetKingdomId)?.SinceMinute ?? (-1); kingdomDecision.TreatyPayment = (peace ? 1000 : 0); State.PlayerClan.Influence -= C.PlayerProposalCost(); State.Politics.Decisions.Add(kingdomDecision); C.OpenCouncilDecision(kingdomDecision); C.TrainDiplomacy(50.0); State.Touch(); return CommandResult.Success((peace ? "Peace" : "War") + " proposed. The council has two days to vote; " + (peace ? "the ruler only pays if it passes and the terms still hold." : "the fighting only starts if it passes.")); } internal string CouncilDiplomacyStaleReason(KingdomDecision decision) { if (C.LivingDiplomacyRuler(decision.KingdomId)?.Id != decision.RulerClanId || C.LivingDiplomacyRuler(decision.TargetKingdomId)?.Id != decision.TargetRulerClanId) { return "A ruler in the treaty has changed."; } if (decision.TreatyPayment != ((decision.Kind == KingdomDecisionKind.MakePeace) ? 1000 : 0)) { return "The payment no longer matches the terms you saw."; } if ((State.FindStance(decision.KingdomId, decision.TargetKingdomId)?.SinceMinute ?? (-1)) != decision.TargetStanceSinceMinute) { return "Diplomacy changed after this was proposed."; } return CouncilDiplomacyTermsReason(decision.KingdomId, decision.TargetKingdomId, decision.Kind == KingdomDecisionKind.MakePeace); } public CommandResult ApplyCouncilDiplomacy(KingdomDecision decision) { if (CouncilDiplomacyDecision(decision)) { PoliticsState politics = State.Politics; if (politics != null && politics.Decisions?.Contains(decision) == true && decision.Status == KingdomDecisionStatus.Resolved && decision.Passed && !State.AppliedEventIds.Contains("politics.diplomacy:" + decision.Id)) { if (CouncilDiplomacyReserved(decision)) { return CommandResult.Fail("Wait for the fighting involving these kingdoms to finish."); } string text = C.CouncilStaleReason(decision); if (text.Length > 0) { return CommandResult.Fail(text); } State.AppliedEventIds.Add("politics.diplomacy:" + decision.Id); string kingdomId = decision.KingdomId; string targetKingdomId = decision.TargetKingdomId; string text2; if (decision.Kind == KingdomDecisionKind.MakePeace) { Clan clan = State.Clans.Require(decision.RulerClanId); Clan clan2 = State.Clans.Require(decision.TargetRulerClanId); text2 = C.DiplomacyFactionName(kingdomId) + "'s council agreed to peace with " + C.DiplomacyFactionName(targetKingdomId) + ". " + clan.Name + " paid " + decision.TreatyPayment + " denars to " + clan2.Name + " for a " + 7 + "-day truce."; State.Transact(clan, -decision.TreatyPayment, LedgerAccount.Other, text2); State.Transact(clan2, decision.TreatyPayment, LedgerAccount.Other, text2); State.SetStance(kingdomId, targetKingdomId, Stance.Peace); C.AddDiplomacyTruce(kingdomId, targetKingdomId, clan.Id, clan2.Id, decision.TreatyPayment); } else { C.RemoveExpiredPairTruces(kingdomId, targetKingdomId); State.SetStance(kingdomId, targetKingdomId, Stance.War); text2 = C.DiplomacyFactionName(kingdomId) + "'s council declared war on " + C.DiplomacyFactionName(targetKingdomId) + "."; } C.FinishDiplomacyChange(kingdomId, targetKingdomId, text2); return CommandResult.Success(text2); } } return CommandResult.Fail("There is no unused, passed council mandate for this treaty."); } internal bool CouncilDiplomacyPreference(KingdomDecision decision, Clan clan, out string reason) { bool flag = decision.Kind == KingdomDecisionKind.MakePeace; if (clan.Id == decision.ProposerClanId) { reason = "For: it proposed it."; return true; } if (C.ClanRelation(clan.Id, decision.TargetRulerClanId) >= 20) { reason = (flag ? "For peace: their ruler's a friend." : "Against attacking a friend."); return flag; } if (State.Settlements.Any((Settlement s) => s.OwnerClanId == clan.Id && s.Type != SettlementType.Hideout && (s.Loyalty < 40.0 || C.SiegeForSettlement(s.Id) != null))) { reason = (flag ? "For peace: its own lands are under pressure." : "Against another war while its lands are under pressure."); return flag; } if (State.Stances.Any((StanceRecord s) => s.Stance == Stance.War && ((s.A == decision.KingdomId && s.B != decision.TargetKingdomId && C.KnownDiplomacyFaction(s.B)) || (s.B == decision.KingdomId && s.A != decision.TargetKingdomId && C.KnownDiplomacyFaction(s.A))))) { reason = (flag ? "For: too many wars at once." : "Opposes opening another front."); return flag; } double num = C.KingdomMilitaryStrength(decision.KingdomId); double num2 = C.KingdomMilitaryStrength(decision.TargetKingdomId); if (flag) { StanceRecord stanceRecord = State.FindStance(decision.KingdomId, decision.TargetKingdomId); if (stanceRecord != null && State.Clock.Minute - stanceRecord.SinceMinute >= 30240) { reason = "Favours ending a long war."; return true; } if (num < num2 * 1.1) { reason = "For peace: nobody's clearly winning."; return true; } if (clan.Gold < 1000) { reason = "For peace: its coffers need it."; return true; } reason = "Against paying for peace while we're winning."; return false; } if (clan.Gold < 500) { reason = "Against war: its coffers are low."; return false; } bool flag2 = C.DiplomacyFrontier(decision.KingdomId, decision.TargetKingdomId) && num > 0.0 && num >= num2 * 1.25; reason = (flag2 ? "For war: a rival next door, and we're stronger." : "Against war: no shared border, no clear edge."); return flag2; } } internal sealed class CouncilSystem { private readonly Campaign C; private CampaignState State => C.State; private bool _processingCouncil => C._processingCouncil; internal CouncilSystem(Campaign host) { C = host; } internal static bool CouncilIsLive(KingdomDecision decision) { if (decision != null) { if (decision.Status != KingdomDecisionStatus.Queued) { return decision.Status == KingdomDecisionStatus.Voting; } return true; } return false; } internal bool CouncilMember(string kingdomId, string clanId) { return C.CouncilMembers(kingdomId).Any((Clan clan) => clan.Id == clanId); } internal string NewCouncilProposalReason() { string text = C.PlayerCouncilReason(); if (text.Length > 0) { return text; } if (State.Politics == null || !State.Politics.Initialized || State.Politics.Decisions == null) { return "The council can't sit right now."; } Clan clan = C.ServiceRuler(State.PlayerClan.KingdomId); if (clan == null || !CouncilMember(State.PlayerClan.KingdomId, clan.Id)) { return "The kingdom needs a living ruler before the council can sit."; } if (State.Politics.Decisions.Any((KingdomDecision d) => CouncilIsLive(d) && d.KingdomId == State.PlayerClan.KingdomId)) { return "The council already has a vote open."; } if (State.Clock.Minute > 9223372036854772927L) { return "A council deadline cannot be recorded at this date."; } if (double.IsNaN(State.PlayerClan.Influence) || double.IsInfinity(State.PlayerClan.Influence) || State.PlayerClan.Influence < (double)C.PlayerProposalCost()) { return "Proposing a council decision costs " + C.PlayerProposalCost() + " influence."; } return ""; } public string ProposePolicyReason(RealmPolicy policy) { string text = NewCouncilProposalReason(); if (text.Length > 0) { return text; } if (!Enum.IsDefined(typeof(RealmPolicy), policy)) { return "Unknown realm policy."; } if (C.RealmPolicyFor(State.PlayerClan.KingdomId) != policy) { return ""; } return "Your kingdom already follows this policy."; } public CommandResult ProposeRealmPolicy(RealmPolicy policy) { string text = ProposePolicyReason(policy); if (text.Length > 0) { return CommandResult.Fail(text); } KingdomDecision kingdomDecision = NewCouncilDecision(State.PlayerClan.KingdomId, State.PlayerClanId, KingdomDecisionKind.Policy); kingdomDecision.Policy = policy; State.PlayerClan.Influence -= C.PlayerProposalCost(); State.Politics.Decisions.Add(kingdomDecision); OpenCouncilDecision(kingdomDecision); C.TrainDiplomacy(50.0); State.Touch(); return CommandResult.Success("Policy proposed. The council has two days to vote; the influence is spent."); } public string ProposeFiefGrantReason(string settlementId, string recipientClanId) { string text = NewCouncilProposalReason(); if (text.Length > 0) { return text; } Settlement settlement = State.Settlements.Get(settlementId); if (settlement == null || (settlement.Type != SettlementType.Town && settlement.Type != SettlementType.Castle)) { return "Pick a town or castle. Its villages go with it."; } string kingdomId = State.PlayerClan.KingdomId; if (!CouncilMember(kingdomId, settlement.OwnerClanId)) { return "This fief doesn't belong to a full member of your kingdom."; } if (State.PlayerClanId != settlement.OwnerClanId && C.ServiceRuler(kingdomId)?.Id != State.PlayerClanId) { return "Only the owner or the ruler can propose giving it away."; } if (!CouncilMember(kingdomId, recipientClanId)) { return "Pick a clan of your kingdom to receive the fief."; } if (recipientClanId == settlement.OwnerClanId) { return "This clan already owns the fief."; } if (C.SiegeForSettlement(settlement.Id) != null) { return "Finish the siege first."; } return ""; } public CommandResult ProposeFiefGrant(string settlementId, string recipientClanId) { string text = ProposeFiefGrantReason(settlementId, recipientClanId); if (text.Length > 0) { return CommandResult.Fail(text); } Settlement settlement = State.Settlements.Require(settlementId); KingdomDecision kingdomDecision = NewCouncilDecision(State.PlayerClan.KingdomId, State.PlayerClanId, KingdomDecisionKind.FiefGrant); kingdomDecision.SettlementId = settlement.Id; kingdomDecision.OwnerClanId = settlement.OwnerClanId; kingdomDecision.RecipientClanId = recipientClanId; State.PlayerClan.Influence -= C.PlayerProposalCost(); State.Politics.Decisions.Add(kingdomDecision); OpenCouncilDecision(kingdomDecision); C.TrainDiplomacy(50.0); State.Touch(); return CommandResult.Success("Fief grant proposed. The owner keeps it until the council decides."); } public string ProposeClanExpulsionReason(string targetClanId) { string text = NewCouncilProposalReason(); if (text.Length > 0) { return text; } string kingdomId = State.PlayerClan.KingdomId; if (C.ServiceRuler(kingdomId)?.Id != State.PlayerClanId) { return "Only the ruler can propose an expulsion."; } return C.CouncilExpulsionReason(targetClanId, kingdomId); } public CommandResult ProposeClanExpulsion(string targetClanId) { string text = ProposeClanExpulsionReason(targetClanId); if (text.Length > 0) { return CommandResult.Fail(text); } KingdomDecision kingdomDecision = NewCouncilDecision(State.PlayerClan.KingdomId, State.PlayerClanId, KingdomDecisionKind.ClanExpulsion); kingdomDecision.TargetClanId = targetClanId; State.PlayerClan.Influence -= C.PlayerProposalCost(); State.Politics.Decisions.Add(kingdomDecision); OpenCouncilDecision(kingdomDecision); C.TrainDiplomacy(50.0); State.Touch(); return CommandResult.Success("Expulsion proposed. The clan stays a member during the two-day vote; if expelled it keeps everything, and goes to war if it has land."); } internal KingdomDecision NewCouncilDecision(string kingdomId, string proposer, KingdomDecisionKind kind) { string id; do { id = State.Ids.Allocate("council"); } while (State.Politics.Decisions.Any((KingdomDecision d) => d.Id == id)); return new KingdomDecision { Id = id, KingdomId = kingdomId, ProposerClanId = proposer, RulerClanId = C.ServiceRuler(kingdomId).Id, Kind = kind, CreatedMinute = State.Clock.Minute, Status = KingdomDecisionStatus.Queued }; } internal void OpenCouncilDecision(KingdomDecision decision) { decision.Status = KingdomDecisionStatus.Voting; decision.OpenedMinute = State.Clock.Minute; decision.ClosesMinute = State.Clock.Minute + 2880; decision.EligibleClanIds = (from c in C.CouncilMembers(decision.KingdomId) select c.Id).OrderBy((string id) => id, StringComparer.Ordinal).ToList(); string text = ((decision.Kind == KingdomDecisionKind.Policy) ? "realm policy" : ((decision.Kind == KingdomDecisionKind.RulerElection) ? ("its ruler: " + (State.Clans.Get(decision.CandidateClanId)?.Name ?? "a claimant") + " or " + (State.Clans.Get(decision.RivalClanId)?.Name ?? "a claimant")) : ((decision.Kind == KingdomDecisionKind.Law) ? ((decision.Repeal ? "repealing " : "enacting ") + KingdomLaws.Name(decision.Law)) : ((decision.Kind == KingdomDecisionKind.ClanExpulsion) ? ("expelling " + (State.Clans.Get(decision.TargetClanId)?.Name ?? "a clan")) : (Campaign.CouncilDiplomacyDecision(decision) ? (((decision.Kind == KingdomDecisionKind.MakePeace) ? "peace with " : "war against ") + C.DiplomacyFactionName(decision.TargetKingdomId)) : (State.Settlements.Get(decision.SettlementId)?.Name ?? "a fief")))))); State.AddLog(LogCategory.Politics, State.Kingdoms.Require(decision.KingdomId).Name + " opened a two-day council vote on " + text + ".", decision.KingdomId, decision.Id); if (decision.EligibleClanIds.Contains(State.PlayerClanId)) { C.Raise(CampaignEventKind.Info, "The council is voting, for two days. See Realm → Council.", false, decision.Id); } State.Touch(); } public string CouncilVoteReason(string decisionId, bool support, int influence) { string text = C.PlayerCouncilReason(); if (text.Length > 0) { return text; } if (State.Politics == null || !State.Politics.Initialized || State.Politics.Decisions == null) { return "The council can't sit right now."; } KingdomDecision kingdomDecision = State.Politics.Decisions.FirstOrDefault((KingdomDecision d) => d.Id == decisionId); if (kingdomDecision == null || kingdomDecision.Status != KingdomDecisionStatus.Voting) { return "That vote isn't open."; } if (kingdomDecision.KingdomId != State.PlayerClan.KingdomId || !kingdomDecision.EligibleClanIds.Contains(State.PlayerClanId)) { return "Your clan wasn't on the council when this vote opened."; } if (State.Clock.Minute >= kingdomDecision.ClosesMinute) { return "Too late; voting's closed."; } if (C.CouncilDiplomacyReserved(kingdomDecision)) { return "Wait for both kingdoms' fighting to finish."; } text = CouncilStaleReason(kingdomDecision); if (text.Length > 0) { return text; } if (kingdomDecision.Ballots.Any((CouncilBallot b) => b.ClanId == State.PlayerClanId)) { return "Your clan has already voted."; } if (influence != 0 && influence != 10 && influence != 30) { return "Choose 0, 10 or 30 influence, for a weight of 1, 2 or 4."; } if (double.IsNaN(State.PlayerClan.Influence) || double.IsInfinity(State.PlayerClan.Influence) || State.PlayerClan.Influence < (double)influence) { return "Not enough influence for that."; } return ""; } public CommandResult VoteCouncil(string decisionId, bool support, int influence) { string text = CouncilVoteReason(decisionId, support, influence); if (text.Length > 0) { return CommandResult.Fail(text); } KingdomDecision kingdomDecision = State.Politics.Decisions.First((KingdomDecision d) => d.Id == decisionId); State.PlayerClan.Influence -= influence; kingdomDecision.Ballots.Add(new CouncilBallot { ClanId = State.PlayerClanId, Support = support, InfluenceSpent = influence }); State.AddLog(LogCategory.Politics, State.PlayerClan.Name + " voted " + (support ? "for" : "against") + " the council proposal, spending " + influence + " influence.", kingdomDecision.Id, State.PlayerClanId); C.TrainDiplomacy(20.0 + (double)influence * 0.5); State.Touch(); return CommandResult.Success("Vote cast. The influence is spent and there's no changing it."); } public int CouncilSupportWeight(KingdomDecision decision, bool support) { if (decision?.Ballots == null || decision.EligibleClanIds == null) { return 0; } if (decision.Status == KingdomDecisionStatus.Resolved) { if (!support) { return decision.FinalOppositionWeight; } return decision.FinalSupportWeight; } if (decision.Status == KingdomDecisionStatus.Cancelled) { return 0; } HashSet eligible = new HashSet(decision.EligibleClanIds, StringComparer.Ordinal); if (CouncilIsLive(decision)) { eligible.IntersectWith(from c in C.CouncilMembers(decision.KingdomId) select c.Id); } return decision.Ballots.Where((CouncilBallot b) => b != null && b.Support == support && eligible.Contains(b.ClanId)).GroupBy((CouncilBallot b) => b.ClanId, StringComparer.Ordinal).Sum((IGrouping group) => (1 + group.First().InfluenceSpent / 10) * C.LawBallotMultiplier(decision, group.Key)); } internal int ClanFortCount(string clanId) { return State.Settlements.Count((Settlement s) => s.OwnerClanId == clanId && (s.Type == SettlementType.Town || s.Type == SettlementType.Castle)); } public bool CouncilPreference(KingdomDecision decision, Clan clan) { if (decision == null || clan == null) { return false; } string reason; if (Campaign.CouncilDiplomacyDecision(decision)) { return C.CouncilDiplomacyPreference(decision, clan, out reason); } if (decision.Kind == KingdomDecisionKind.Law) { return C.CouncilLawPreference(decision, clan, out reason); } if (decision.Kind == KingdomDecisionKind.RulerElection) { return C.CouncilElectionPreference(decision, clan, out reason); } if (decision.Kind == KingdomDecisionKind.ClanExpulsion) { if (clan.Id == decision.TargetClanId) { return false; } if (clan.Id == decision.ProposerClanId) { return true; } int num = C.ClanRelation(clan.Id, decision.TargetClanId); if (C.ClanRelation(decision.TargetClanId, decision.RulerClanId) > -20 || num >= 0) { if (C.ClanRelation(clan.Id, decision.ProposerClanId) >= 20) { return num < 20; } return false; } return true; } if (decision.Kind == KingdomDecisionKind.FiefGrant) { if (clan.Id == decision.RecipientClanId) { return true; } if (clan.Id == decision.OwnerClanId) { return false; } if (decision.RecipientClanId == decision.OwnerClanId) { if (ClanFortCount(decision.RecipientClanId) > 1) { return C.ClanRelation(clan.Id, decision.RecipientClanId) >= 0; } return true; } return (ClanFortCount(decision.OwnerClanId) - ClanFortCount(decision.RecipientClanId)) * 5 + C.ClanRelation(clan.Id, decision.RecipientClanId) - C.ClanRelation(clan.Id, decision.OwnerClanId) + C.ClanRelation(clan.Id, decision.ProposerClanId) / 2 > 0; } int num2 = C.ClanRelation(clan.Id, decision.ProposerClanId); if (num2 >= 20) { return true; } if (num2 <= -20) { return false; } bool flag = State.Stances.Any((StanceRecord s) => s.Stance == Stance.War && (s.A == decision.KingdomId || s.B == decision.KingdomId)); bool flag2 = State.Settlements.Any((Settlement s) => s.OwnerClanId == clan.Id && s.Type != SettlementType.Hideout && s.Loyalty < 55.0); if (decision.Policy == RealmPolicy.LocalCharters) { return !flag || flag2; } if (decision.Policy == RealmPolicy.WarLevy) { if (flag) { return !flag2; } return false; } if (!(!flag || flag2)) { if (C.RealmPolicyFor(decision.KingdomId) == RealmPolicy.LocalCharters) { return clan.Gold < 1000; } return false; } return true; } public string CouncilPreferenceReason(KingdomDecision decision, Clan clan) { if (decision == null || clan == null) { return "No idea how they'll vote."; } if (Campaign.CouncilDiplomacyDecision(decision)) { C.CouncilDiplomacyPreference(decision, clan, out var reason); return reason; } if (decision.Kind == KingdomDecisionKind.RulerElection) { C.CouncilElectionPreference(decision, clan, out var reason2); return reason2; } if (decision.Kind == KingdomDecisionKind.Law) { C.CouncilLawPreference(decision, clan, out var reason3); return reason3; } bool flag = CouncilPreference(decision, clan); if (decision.Kind == KingdomDecisionKind.ClanExpulsion) { if (clan.Id == decision.TargetClanId) { return "Against its own expulsion, naturally."; } if (clan.Id == decision.ProposerClanId) { return "For the expulsion it proposed."; } if (flag && C.ClanRelation(decision.TargetClanId, decision.RulerClanId) <= -20 && C.ClanRelation(clan.Id, decision.TargetClanId) < 0) { return "For: it dislikes the clan, and the clan's feuding with the ruler."; } if (flag) { return "For: the proposer's a friend, the target isn't."; } if (C.ClanRelation(clan.Id, decision.TargetClanId) < 20) { return "Against: no feud with the target, no close ties to the proposer."; } return "Against: the target's a friend."; } if (decision.Kind == KingdomDecisionKind.FiefGrant) { if (clan.Id == decision.RecipientClanId) { return "For: it's their own claim."; } if (clan.Id == decision.OwnerClanId) { return "Against: it's their fief."; } if (decision.RecipientClanId == decision.OwnerClanId) { if (!flag) { return "Against: doesn't want a clan it dislikes getting more land."; } return "Happy for the captor to keep it."; } return (flag ? "Supports" : "Opposes") + " the grant based on current holdings and clan relations."; } if (Math.Abs(C.ClanRelation(clan.Id, decision.ProposerClanId)) >= 20) { if (!flag) { return "At feud with the proposer, so leaning against."; } return "On friendly terms with the proposer, so leaning for."; } return (flag ? "Supports" : "Opposes") + " this policy based on war, treasury and loyalty pressure."; } public void QueueCapturedFiefCouncil(SiegeState siege, Clan captor, Settlement settlement) { if (State.Politics == null || !State.Politics.Initialized || siege == null || captor == null || settlement == null || !State.Sieges.Contains(siege) || siege.Stage != SiegeStage.Assault || siege.SettlementId != settlement.Id || State.Settlements.Get(settlement.Id) != settlement || settlement.OwnerClanId != captor.Id || State.Clans.Get(captor.Id) != captor || !CouncilMember(captor.KingdomId, captor.Id) || State.Politics.Decisions.Any((KingdomDecision d) => d.SourceSiegeId == siege.Id)) { return; } Encounter encounter = State.Encounters.FirstOrDefault((Encounter e) => e.SiegeId == siege.Id && e.Phase == EncounterPhase.Committed); if (encounter != null && State.CommittedEncounters.Contains(encounter.Id)) { Clan clan = (from c in C.CouncilMembers(captor.KingdomId) orderby ClanFortCount(c.Id), (!(c.Id == captor.Id)) ? 1 : 0 select c).ThenBy((Clan c) => c.Id, StringComparer.Ordinal).FirstOrDefault(); Clan clan2 = C.ServiceRuler(captor.KingdomId); if (clan != null && clan2 != null && CouncilMember(captor.KingdomId, clan2.Id)) { KingdomDecision kingdomDecision = NewCouncilDecision(captor.KingdomId, captor.Id, KingdomDecisionKind.FiefGrant); kingdomDecision.SettlementId = settlement.Id; kingdomDecision.OwnerClanId = captor.Id; kingdomDecision.RecipientClanId = clan.Id; kingdomDecision.SourceSiegeId = siege.Id; State.Politics.Decisions.Add(kingdomDecision); State.AddLog(LogCategory.Politics, settlement.Name + " remains under " + captor.Name + " pending the kingdom council's fief award.", kingdomDecision.Id, settlement.Id); State.Touch(); } } } internal string CouncilStaleReason(KingdomDecision decision) { Kingdom kingdom = State.Kingdoms.Get(decision.KingdomId); if (kingdom == null || kingdom.IsEliminated || C.ServiceRuler(decision.KingdomId)?.Id != decision.RulerClanId || !CouncilMember(decision.KingdomId, decision.RulerClanId)) { return "The kingdom's ruler has changed."; } if (!CouncilMember(decision.KingdomId, decision.ProposerClanId)) { return "The proposing clan has left the council."; } if (Campaign.CouncilDiplomacyDecision(decision)) { return C.CouncilDiplomacyStaleReason(decision); } if (decision.Kind == KingdomDecisionKind.Law) { return C.LawDecisionStaleReason(decision); } if (decision.Kind == KingdomDecisionKind.RulerElection) { return C.ElectionStaleReason(decision); } if (decision.Kind == KingdomDecisionKind.Policy) { if (C.RealmPolicyFor(decision.KingdomId) != decision.Policy) { return ""; } return "That policy's already in force."; } if (decision.Kind == KingdomDecisionKind.ClanExpulsion) { if (!(decision.ProposerClanId != decision.RulerClanId)) { return C.ClanExpulsionStaleReason(decision.TargetClanId, decision.KingdomId); } return "The expulsion was not proposed by the ruler."; } Settlement settlement = State.Settlements.Get(decision.SettlementId); if (settlement == null || (settlement.Type != SettlementType.Town && settlement.Type != SettlementType.Castle) || settlement.OwnerClanId != decision.OwnerClanId || !CouncilMember(decision.KingdomId, decision.OwnerClanId)) { return "The fief has changed hands or sides."; } if (CouncilMember(decision.KingdomId, decision.RecipientClanId)) { return ""; } return "The chosen clan can no longer receive this fief."; } internal bool CouncilDeferred(KingdomDecision decision) { if (!C.DiplomacyFactionReserved(decision.KingdomId) && !C.CouncilDiplomacyReserved(decision)) { if (decision.Kind == KingdomDecisionKind.FiefGrant) { return C.SiegeForSettlement(decision.SettlementId) != null; } return false; } return true; } public void ReconcileCouncil() { if (State.Politics == null || !State.Politics.Initialized || State.Politics.Decisions == null) { return; } foreach (KingdomDecision item in State.Politics.Decisions.Where(CouncilIsLive).ToList()) { if (!C.DiplomacyFactionReserved(item.KingdomId) && !C.CouncilDiplomacyReserved(item)) { string text = CouncilStaleReason(item); if (text.Length != 0) { item.Status = KingdomDecisionStatus.Cancelled; item.ResolvedMinute = State.Clock.Minute; item.Passed = false; item.Result = text + " The influence isn't refunded."; State.AddLog(LogCategory.Politics, "Council decision cancelled: " + item.Result, item.Id, item.KingdomId); State.Touch(); } } } PruneCouncilHistory(); } public void DailyCouncil() { if (_processingCouncil || State.Politics == null || !State.Politics.Initialized || State.Politics.Decisions == null) { return; } C._processingCouncil = true; try { ReconcileCouncil(); foreach (KingdomDecision item in (from d in State.Politics.Decisions where d.Status == KingdomDecisionStatus.Voting && d.ClosesMinute <= State.Clock.Minute orderby d.ClosesMinute select d).ThenBy((KingdomDecision d) => d.Id, StringComparer.Ordinal).ToList()) { if (item.Status == KingdomDecisionStatus.Voting && State.Politics.Decisions.Contains(item) && !CouncilDeferred(item)) { CastNpcCouncilBallots(item); ResolveCouncilDecision(item); } } foreach (KingdomDecision decision in (from d in State.Politics.Decisions where d.Status == KingdomDecisionStatus.Queued orderby d.CreatedMinute select d).ThenBy((KingdomDecision d) => d.Id, StringComparer.Ordinal).ToList()) { if (!State.Politics.Decisions.Any((KingdomDecision d) => d.Status == KingdomDecisionStatus.Voting && d.KingdomId == decision.KingdomId) && State.Clock.Minute <= 9223372036854772927L && !CouncilDeferred(decision)) { OpenCouncilDecision(decision); } } PruneCouncilHistory(); } finally { C._processingCouncil = false; } } internal void CastNpcCouncilBallots(KingdomDecision decision) { foreach (Clan item in (from c in C.CouncilMembers(decision.KingdomId) where c.Id != State.PlayerClanId && decision.EligibleClanIds.Contains(c.Id) && !decision.Ballots.Any((CouncilBallot b) => b.ClanId == c.Id) select c).OrderBy((Clan c) => c.Id, StringComparer.Ordinal)) { int num = ((item.Influence >= 10.0) ? 10 : 0); item.Influence -= num; decision.Ballots.Add(new CouncilBallot { ClanId = item.Id, Support = CouncilPreference(decision, item), InfluenceSpent = num }); } } internal void ResolveCouncilDecision(KingdomDecision decision) { int num = CouncilSupportWeight(decision, support: true); int num2 = CouncilSupportWeight(decision, support: false); decision.FinalSupportWeight = num; decision.FinalOppositionWeight = num2; decision.Passed = num > num2; decision.Status = KingdomDecisionStatus.Resolved; decision.ResolvedMinute = State.Clock.Minute; string effect = "The status quo remains."; if (decision.Kind == KingdomDecisionKind.RulerElection) { C.ApplyElection(decision, out effect); } else if (decision.Passed && decision.Kind == KingdomDecisionKind.Policy) { KingdomPolicyState kingdomPolicyState = State.Politics.KingdomPolicies.FirstOrDefault((KingdomPolicyState p) => p.KingdomId == decision.KingdomId); if (kingdomPolicyState == null) { kingdomPolicyState = new KingdomPolicyState { KingdomId = decision.KingdomId }; State.Politics.KingdomPolicies.Add(kingdomPolicyState); } kingdomPolicyState.Policy = decision.Policy; kingdomPolicyState.ChangedMinute = State.Clock.Minute; effect = decision.Policy.ToString() + " is now the realm policy."; } else if (decision.Passed && decision.Kind == KingdomDecisionKind.Law) { C.ApplyLawDecision(decision, out effect); } else if (decision.Passed && decision.Kind == KingdomDecisionKind.ClanExpulsion) { CommandResult commandResult = C.ApplyCouncilExpulsion(decision); if (!commandResult.Ok) { decision.Status = KingdomDecisionStatus.Cancelled; decision.Passed = false; decision.FinalSupportWeight = 0; decision.FinalOppositionWeight = 0; decision.Result = commandResult.Message + " The influence isn't refunded."; State.AddLog(LogCategory.Politics, "Council decision cancelled: " + decision.Result, decision.Id, decision.KingdomId); State.Touch(); return; } effect = commandResult.Message; } else if (decision.Passed && Campaign.CouncilDiplomacyDecision(decision)) { CommandResult commandResult2 = C.ApplyCouncilDiplomacy(decision); if (!commandResult2.Ok) { decision.Status = KingdomDecisionStatus.Cancelled; decision.Passed = false; decision.FinalSupportWeight = (decision.FinalOppositionWeight = 0); decision.Result = commandResult2.Message + " The influence isn't refunded."; State.AddLog(LogCategory.Politics, "Council decision cancelled: " + decision.Result, decision.Id, decision.KingdomId); State.Touch(); return; } effect = commandResult2.Message; } else if (decision.Passed && decision.Kind == KingdomDecisionKind.FiefGrant) { Settlement settlement = State.Settlements.Require(decision.SettlementId); Clan clan = State.Clans.Require(decision.RecipientClanId); if (clan.Id == decision.OwnerClanId) { effect = clan.Name + " retains " + settlement.Name + "."; } else { List list = State.Settlements.Where((Settlement s) => s.Id == settlement.Id || (s.Type == SettlementType.Village && s.BoundTo == settlement.Id && s.OwnerClanId == decision.OwnerClanId)).ToList(); foreach (Settlement item in list) { C.ChangeSettlementOwner(item, clan.Id); } C.AdjustClanRelation(decision.ProposerClanId, clan.Id, 10); C.AdjustClanRelation(decision.ProposerClanId, decision.OwnerClanId, -10); effect = clan.Name + " receives " + settlement.Name + ((list.Count > 1) ? " and its bound villages." : "."); C.OnDiplomacyChanged(); } } foreach (CouncilBallot item2 in decision.Ballots.Where((CouncilBallot b) => decision.Kind != KingdomDecisionKind.ClanExpulsion && CouncilMember(decision.KingdomId, b.ClanId))) { C.AdjustClanRelation(decision.ProposerClanId, item2.ClanId, item2.Support ? 2 : (-2)); } decision.Result = (decision.Passed ? "Passed" : ((num == num2) ? "Tied; rejected" : "Rejected")) + " (" + num + "–" + num2 + "). " + effect; State.AddLog(LogCategory.Politics, "Council: " + decision.Result, decision.Id, decision.KingdomId); if (State.PlayerClan?.KingdomId == decision.KingdomId) { C.Raise(CampaignEventKind.Info, "Council: " + decision.Result, false, decision.Id); } State.Touch(); } internal void PruneCouncilHistory() { List list = (from d in State.Politics.Decisions where !CouncilIsLive(d) orderby d.ResolvedMinute descending select d).ThenByDescending((KingdomDecision d) => d.Id, StringComparer.Ordinal).Skip(24).ToList(); foreach (KingdomDecision item in list) { State.Politics.Decisions.Remove(item); } if (list.Count > 0) { State.Touch(); } } } internal sealed class CourtshipSystem { private readonly Campaign C; private CampaignState State => C.State; public bool PlayerSexChoiceNeeded { get { if (State.Families != null && State.Families.Started && !State.Families.PlayerSexChosen) { return State.PlayerHero != null; } return false; } } internal CourtshipSystem(Campaign host) { C = host; } public Settlement MeetingPlace() { Party playerParty = State.PlayerParty; if (playerParty == null || playerParty.State != PartyState.InSettlement || State.Player.Activity != PlayerActivity.InSettlement) { return null; } Settlement settlement = State.Settlements.Get(playerParty.CurrentSettlementId); if (settlement != null && settlement.Type != SettlementType.Hideout) { return settlement; } return null; } public List NoblesHere() { Settlement settlement = MeetingPlace(); if (settlement == null) { return new List(); } List list = new List(); foreach (Party party in State.Parties) { if (party.State != PartyState.InSettlement || !(party.CurrentSettlementId == settlement.Id) || !(party.Id != State.PlayerPartyId)) { continue; } foreach (string hero in party.Troops.Heroes) { if (!list.Contains(hero)) { list.Add(hero); } } } foreach (Hero hero2 in State.Heroes) { if (hero2.State == HeroState.Active && hero2.SettlementId == settlement.Id && string.IsNullOrEmpty(hero2.PartyId) && !list.Contains(hero2.Id)) { list.Add(hero2.Id); } } return list.Select((string id) => State.Heroes.Get(id)).Where(delegate(Hero h) { if (h != null && h.State == HeroState.Active && h.ClanId != State.PlayerClanId && h.Occupation == HeroOccupation.Lord && C.IsGrown(h)) { Clan clan = State.Clans.Get(h.ClanId); if (clan == null) { return false; } return !clan.IsBandit; } return false; }).OrderBy((Hero h) => h.Name, StringComparer.Ordinal) .ThenBy((Hero h) => h.Id, StringComparer.Ordinal) .ToList(); } public CourtshipState CourtshipOf(string heroId) { return State.Families?.Courtships?.FirstOrDefault((CourtshipState c) => c.HeroId == heroId && c.SuitorId == State.PlayerHeroId); } public List PlayerCourtships() { return State.Families?.Courtships?.Where((CourtshipState c) => c.SuitorId == State.PlayerHeroId).ToList() ?? new List(); } public long MarriageGiftFor(Hero noble) { return Families.MarriageGift(Campaign.ClanTier(State.Clans.Get(noble?.ClanId ?? ""))); } internal string FamilyCommandReason() { if (C.AwaitingHeir) { return "Choose your heir first."; } if (C.LineEnded) { return "Your line has ended."; } CommandResult commandResult = C.RequireFree(); if (!commandResult.Ok) { return commandResult.Message; } if (State.PlayerHero == null || State.PlayerHero.State != HeroState.Active) { return "You're not free to do this."; } return ""; } internal string NobleHereReason(Hero noble, bool mustJoinYou) { if (noble == null || !NoblesHere().Any((Hero h) => h.Id == noble.Id)) { return "That person is not here."; } if (C.IsSettlementBesieged(MeetingPlace())) { return "Not while this place is under siege."; } if (!C.HasKeepAccess(MeetingPlace())) { return "You need to get into the keep to meet " + noble.Name + ": bribe the guards, or come as a member of the realm."; } if (C.HeroBusy(noble)) { return noble.Name + " is busy with their duties just now."; } Clan clan = State.Clans.Get(noble.ClanId); if (clan != null && State.AreHostile(State.PlayerClan, clan)) { return "Your realm is at war with " + clan.Name + "."; } if (mustJoinYou && clan?.LeaderHeroId == noble.Id) { return noble.Name + " leads " + clan.Name + " and will not leave it to marry."; } return ""; } public string CourtReason(string heroId) { string text = FamilyCommandReason(); if (text.Length > 0) { return text; } Hero hero = State.Heroes.Get(heroId); text = NobleHereReason(hero, mustJoinYou: true); if (text.Length > 0) { return text; } Hero playerHero = State.PlayerHero; text = C.MarriageReason(playerHero, hero); if (text.Length > 0) { return text.Replace(playerHero.Name + " is", "You are").Replace(playerHero.Name + "'s", "Your"); } int num = C.ClanRelation(State.PlayerClanId, hero.ClanId); if (num < -10) { return $"Relations with {State.Clans.Get(hero.ClanId)?.Name} are too poor ({num}) for a courtship."; } CourtshipState courtshipState = CourtshipOf(heroId); if (courtshipState != null && courtshipState.Refused && courtshipState.RefusedUntilDay > State.Clock.Day) { return $"{hero.Name} isn't interested in you for now (try again on day {courtshipState.RefusedUntilDay + 1})."; } if (courtshipState != null && courtshipState.Won) { return "You have won " + hero.Name + "'s favour: ask for their hand."; } if (courtshipState != null && courtshipState.LastTalkDay >= 0 && State.Clock.Day - courtshipState.LastTalkDay < 2) { return $"You spoke with {hero.Name} recently. Give it {2 - (State.Clock.Day - courtshipState.LastTalkDay)} day(s)."; } return ""; } public CommandResult Court(string heroId) { string text = CourtReason(heroId); if (text.Length > 0) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Require(heroId); CourtshipState courtshipState = CourtshipOf(heroId); if (courtshipState == null || courtshipState.Refused) { State.Families.Courtships.RemoveAll((CourtshipState x) => x.HeroId == heroId && x.SuitorId == State.PlayerHeroId); courtshipState = new CourtshipState { HeroId = heroId, SuitorId = State.PlayerHeroId, StartedDay = State.Clock.Day }; State.Families.Courtships.Add(courtshipState); } double probability = Families.CourtshipChance(State.PlayerHero.Skill("charm"), C.ClanRelation(State.PlayerClanId, hero.ClanId)); return CourtResult(heroId, State.Random.Get("families").Chance(probability)); } internal CommandResult CourtResult(string heroId, bool good) { Hero hero = State.Heroes.Require(heroId); CourtshipState courtshipState = CourtshipOf(heroId); if (courtshipState == null || courtshipState.Refused) { State.Families.Courtships.RemoveAll((CourtshipState x) => x.HeroId == heroId && x.SuitorId == State.PlayerHeroId); courtshipState = new CourtshipState { HeroId = heroId, SuitorId = State.PlayerHeroId, StartedDay = State.Clock.Day }; State.Families.Courtships.Add(courtshipState); } courtshipState.LastTalkDay = State.Clock.Day; C.GrantSkillExperience(State.PlayerHero, "charm", 15.0); string text; if (good) { courtshipState.Progress++; text = (courtshipState.Won ? (hero.Name + " is fond of you. Ask for their hand when you're ready.") : $"Your conversation with {hero.Name} goes well ({courtshipState.Progress} of {3})."); } else { courtshipState.Failures++; if (courtshipState.Failures >= 3) { courtshipState.RefusedUntilDay = State.Clock.Day + 28; courtshipState.Progress = 0; courtshipState.Failures = 0; text = hero.Name + " has lost interest in you."; } else { text = $"Your conversation with {hero.Name} goes poorly ({3 - courtshipState.Failures} more and they lose interest)."; } } State.AddLog(LogCategory.Info, text, hero.Id); State.Touch(); return CommandResult.Success(text); } public string ProposeReason(string heroId) { string text = FamilyCommandReason(); if (text.Length > 0) { return text; } Hero hero = State.Heroes.Get(heroId); text = NobleHereReason(hero, mustJoinYou: true); if (text.Length > 0) { return text; } Hero playerHero = State.PlayerHero; text = C.MarriageReason(playerHero, hero); if (text.Length > 0) { return text.Replace(playerHero.Name + " is", "You are").Replace(playerHero.Name + "'s", "Your"); } CourtshipState courtshipState = CourtshipOf(heroId); if (courtshipState == null || !courtshipState.Won) { return $"Win {hero.Name}'s favour first ({courtshipState?.Progress ?? 0} of {3} good conversations)."; } return AgreementReason(hero); } internal string AgreementReason(Hero noble) { Clan clan = State.Clans.Get(noble.ClanId); int num = C.ClanRelation(State.PlayerClanId, noble.ClanId); if (num < 0) { return string.Format("{0} won't agree while relations between your clans are {1} (needs {2}).", State.Heroes.Get(clan?.LeaderHeroId ?? "")?.Name ?? "Their clan's leader", num, 0); } long num2 = MarriageGiftFor(noble); if (State.PlayerClan.Gold < num2) { return $"The marriage gift to {clan?.Name} is {num2:N0} denars."; } return ""; } internal void PayMarriageGift(Hero noble) { long num = MarriageGiftFor(noble); Clan clan = State.Clans.Get(noble.ClanId); State.Transact(State.PlayerClan, -num, LedgerAccount.Marriage, "Marriage gift to " + clan?.Name); if (clan != null) { State.Transact(clan, num, LedgerAccount.Marriage, "Marriage gift from " + State.PlayerClan.Name); } } public CommandResult Propose(string heroId) { string text = ProposeReason(heroId); if (text.Length > 0) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Require(heroId); Hero playerHero = State.PlayerHero; long num = MarriageGiftFor(hero); PayMarriageGift(hero); C.Marry(playerHero, hero, hero); JoinFamilyToPlayerParty(hero); string msg = $"You and {hero.Name} are married. {hero.Name} joins your clan and your party (marriage gift {num:N0} denars)."; State.Touch(); return CommandResult.Success(msg); } internal void JoinFamilyToPlayerParty(Hero h) { if (!(h.ClanId != State.PlayerClanId) && h.State == HeroState.Active) { Party playerParty = State.PlayerParty; if (playerParty != null && playerParty.State != PartyState.Destroyed && playerParty.State != PartyState.Disbanded) { C.JoinCompanionToPlayerParty(h); } } } public List MarriageableFamily() { return State.Heroes.Where((Hero h) => h.ClanId == State.PlayerClanId && !h.IsPlayer && h.IsFamily && h.State == HeroState.Active && C.IsGrown(h) && C.SpouseOf(h) == null).OrderBy((Hero h) => h.Name, StringComparer.Ordinal).ToList(); } public string ArrangeReason(string memberId, string nobleId) { string text = FamilyCommandReason(); if (text.Length > 0) { return text; } Hero member = State.Heroes.Get(memberId); if (member == null || !MarriageableFamily().Any((Hero h) => h.Id == memberId)) { return "Pick a grown, unmarried member of the family."; } Hero hero = State.Heroes.Get(nobleId); Hero hero2 = ((member.Sex == HeroSex.Male) ? hero : member); text = NobleHereReason(hero, hero2 == hero); if (text.Length > 0) { return text; } text = C.MarriageReason(member, hero); if (text.Length > 0) { return text; } if (hero2 == member && State.Parties.Any((Party p) => p.LeaderHeroId == member.Id && p.Id != State.PlayerPartyId && p.State != PartyState.Destroyed && p.State != PartyState.Disbanded)) { return member.Name + " leads a party; call them back first."; } if (hero2 == member && C.HeroBusy(member)) { return member.Name + " is busy with their duties just now."; } return AgreementReason(hero); } public CommandResult ArrangeMarriage(string memberId, string nobleId) { string text = ArrangeReason(memberId, nobleId); if (text.Length > 0) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Require(memberId); Hero hero2 = State.Heroes.Require(nobleId); Hero hero3 = ((hero.Sex == HeroSex.Male) ? hero2 : hero); long num = MarriageGiftFor(hero2); Clan clan = State.Clans.Get(hero2.ClanId); PayMarriageGift(hero2); C.Marry(hero, hero2, hero3); if (hero3 == hero2) { JoinFamilyToPlayerParty(hero2); } string msg = ((hero3 == hero2) ? $"{hero.Name} and {hero2.Name} are married; {hero2.Name} joins your clan and your party (marriage gift {num:N0} denars)." : $"{hero.Name} and {hero2.Name} are married; {hero.Name} joins {clan?.Name} (marriage gift {num:N0} denars)."); State.Touch(); return CommandResult.Success(msg); } public CommandResult SetPlayerSex(HeroSex sex) { if (sex == HeroSex.Unspecified) { return CommandResult.Fail("Choose a man or a woman."); } if (!PlayerSexChoiceNeeded) { return CommandResult.Fail("Your character's sex is already decided."); } Hero playerHero = State.PlayerHero; if (C.SpouseOf(playerHero) != null || C.ChildrenOf(playerHero).Any()) { return CommandResult.Fail("It can no longer change."); } playerHero.Sex = sex; State.Families.PlayerSexChosen = true; State.Touch(); return CommandResult.Success((sex == HeroSex.Female) ? "Your character is a woman." : "Your character is a man."); } public CommandResult SetFamilyRule(string rule, bool on) { CampaignSettings settings = C.Settings; string text; switch (rule) { case "aging": settings.PeopleAge = on; text = "People grow older"; break; case "oldage": settings.OldAgeDeaths = on; text = "Deaths of old age"; break; case "births": settings.Births = on; text = "Children are born"; break; case "marriage": settings.LordsMarry = on; text = "Lords and ladies marry"; break; default: return CommandResult.Fail("Unknown family rule."); } State.AddLog(LogCategory.Info, text + (on ? ": on." : ": off.")); State.Touch(); return CommandResult.Success(text + (on ? " (on)." : " (off).")); } } internal sealed class CreationLooksSystem { private readonly Campaign C; private ContentDatabase Content => C.Content; private CampaignState State => C.State; internal CreationLooksSystem(Campaign host) { C = host; } public SortedSet CreationClothing(string cultureId) { SortedSet sortedSet = CharacterCreation.CultureClothing(Content, State.Wardrobe?.UnitPieces, cultureId); sortedSet.RemoveWhere((string id) => C.ClothingPiece(id) == null || C.ClothingPiece(id).Tier > 3); return sortedSet; } public CommandResult ApplyCreationLooks(HeroEquipmentState looks) { if (looks == null) { return CommandResult.Success(); } Hero playerHero = State.PlayerHero; if (playerHero?.Creation == null) { return CommandResult.Fail("Only a created character can choose their looks."); } if (State.Clock.Minute == 480 && playerHero.Loadout == null) { Party playerParty = State.PlayerParty; if (playerParty != null && playerParty.State == PartyState.InSettlement) { if (!Campaign.SupportsWardrobe(C.UnitDef(playerHero.UnitId))) { return CommandResult.Fail("This archetype can't change clothes."); } SortedSet sortedSet = CreationClothing(playerHero.CultureId); SortedDictionary sortedDictionary = new SortedDictionary(StringComparer.Ordinal); int num = 0; foreach (KeyValuePair item in looks.Clothing ?? new SortedDictionary(StringComparer.Ordinal)) { WornClothingState value = item.Value; if (value == null || !Wardrobe.TryParseSlotKey(item.Key, out var slot)) { num++; continue; } if (value.Bare) { if (!string.IsNullOrEmpty(value.PieceId) || (value.Colors?.Count ?? 0) > 0) { num++; continue; } sortedDictionary[item.Key] = new WornClothingState { Bare = true }; continue; } ClothingPieceDef clothingPieceDef = C.ClothingPiece(value.PieceId); List list = Wardrobe.NormalizeColors(value.Colors); if (clothingPieceDef == null || clothingPieceDef.Slot != slot || !sortedSet.Contains(clothingPieceDef.Id) || list.Count > clothingPieceDef.ColorChannels || list.Any((int c) => c < -1 || c > 255)) { num++; continue; } sortedDictionary[item.Key] = new WornClothingState { PieceId = clothingPieceDef.Id, Colors = list }; } double num2 = (Wardrobe.ValidSize(looks.Size) ? Wardrobe.RoundSize(looks.Size) : 1.0); HeroEquipmentState heroEquipmentState = new HeroEquipmentState { Clothing = sortedDictionary, Size = num2 }; if (heroEquipmentState.HasOverrides) { playerHero.Loadout = heroEquipmentState; } State.Touch(); string text = ((sortedDictionary.Count == 0 && Math.Abs(num2 - 1.0) < 1E-09) ? "" : (playerHero.Name + " is dressed as you chose.")); if (num > 0) { text = (text + " " + num + " chosen piece" + ((num == 1) ? " is" : "s are") + " not available in this game and " + ((num == 1) ? "was" : "were") + " left out.").Trim(); } if (num > 0) { State.AddLog(LogCategory.Info, text, playerHero.Id); } return CommandResult.Success(text); } } return CommandResult.Fail("Looks are chosen when the character is created."); } } internal sealed class CrimeSystem { private readonly Campaign C; private CampaignState State => C.State; public bool InDisguise { get { Settlement settlement = C.CurrentSettlement(); if (settlement != null && State.Crime != null) { return State.Crime.DisguisedSettlementId == settlement.Id; } return false; } } internal CrimeSystem(Campaign host) { C = host; } public void EnsureCrimeFields() { if (State.Crime == null) { State.Crime = new CrimeState(); } CrimeState crime = State.Crime; if (crime.Rating == null) { crime.Rating = new SortedDictionary(StringComparer.Ordinal); } if (crime.SneakBarredUntil == null) { crime.SneakBarredUntil = new SortedDictionary(StringComparer.Ordinal); } if (crime.Alleys == null) { crime.Alleys = new List(); } if (crime.Executed == null) { crime.Executed = new List(); } if (crime.GateSettlementId == null) { crime.GateSettlementId = ""; } if (crime.DisguisedSettlementId == null) { crime.DisguisedSettlementId = ""; } C.EnsureAlleys(); } public double CrimeRating(string faction) { if (string.IsNullOrEmpty(faction) || State.Crime?.Rating == null || !State.Crime.Rating.TryGetValue(faction, out var value)) { return 0.0; } return value; } public static CrimeTier CrimeTierOf(double rating) { if (!(rating >= 90.0)) { if (!(rating >= 60.0)) { if (!(rating >= 30.0)) { return CrimeTier.None; } return CrimeTier.Wanted; } return CrimeTier.Outlaw; } return CrimeTier.Hunted; } public static string CrimeTierName(CrimeTier tier) { return tier switch { CrimeTier.Wanted => "Wanted", CrimeTier.Outlaw => "Outlaw", CrimeTier.Hunted => "Hunted", _ => "Clean", }; } public static string CrimeTierEffect(CrimeTier tier) { return tier switch { CrimeTier.Wanted => "Their guards demand a fine at the gates.", CrimeTier.Outlaw => "Their gates are shut to you: only a disguise gets you into their towns.", CrimeTier.Hunted => "Their lords and soldiers attack you on sight, and their gates are shut.", _ => "Nothing held against you.", }; } public string CrimeFactionOf(Settlement s) { if (s != null) { return State.FactionOf(State.Clans.Get(s.OwnerClanId)); } return ""; } public string CrimeFactionName(string faction) { Kingdom kingdom = State.Kingdoms.Get(faction); if (kingdom != null) { return kingdom.Name; } return State.Clans.Get(faction)?.Name ?? faction; } public CrimeTier CrimeTierWith(Settlement s) { return CrimeTierOf(CrimeRating(CrimeFactionOf(s))); } public List> CrimeRecords() { return (from x in State.Crime?.Rating ?? new SortedDictionary() where x.Value >= 0.5 orderby x.Value descending select x).ThenBy, string>((KeyValuePair x) => x.Key, StringComparer.Ordinal).ToList(); } internal string RulingClanOf(string faction) { Kingdom kingdom = State.Kingdoms.Get(faction); if (kingdom == null) { return faction; } return kingdom.RulerClanId; } internal void AddCrime(string faction, double amount, string what, params string[] links) { if (string.IsNullOrEmpty(faction) || amount <= 0.0 || State.Crime == null) { return; } Clan clan = State.Clans.Get(faction); if ((clan == null || (!clan.IsBandit && !(clan.Id == State.PlayerClanId))) && (State.Kingdoms.Contains(faction) || clan != null)) { double num = CrimeRating(faction); double num2 = Math.Min(150.0, num + amount); if (faction == State.FactionOf(State.PlayerClan)) { num2 = Math.Min(num2, 89.0); } State.Crime.Rating[faction] = num2; string text = RulingClanOf(faction); if (!string.IsNullOrEmpty(text) && text != State.PlayerClanId) { C.AdjustClanRelation(State.PlayerClanId, text, -(int)Math.Ceiling(amount / 6.0)); } string text2 = CrimeFactionName(faction); List list = new List(links ?? new string[0]) { faction }; State.AddLog(LogCategory.Warning, "Crime against " + text2 + ": " + what + " (criminal rating " + num2.ToString("0") + ").", list.ToArray()); CrimeTier crimeTier = CrimeTierOf(num); CrimeTier crimeTier2 = CrimeTierOf(num2); if (crimeTier2 > crimeTier) { C.Raise(CampaignEventKind.Warning, text2 + " now holds you " + CrimeTierName(crimeTier2).ToLowerInvariant() + ". " + CrimeTierEffect(crimeTier2), crimeTier2 >= CrimeTier.Outlaw, list.ToArray()); } State.Touch(); } } internal void DailyCrime() { CrimeState crime = State.Crime; if (crime == null) { return; } foreach (string item in crime.Rating.Keys.ToList()) { double num = crime.Rating[item] - 0.6 * (1.0 + Math.Max(0.0, C.PersonalPerk(State.PlayerHero, PerkEffect.CrimeDecay))); if (num <= 0.0 || (!State.Kingdoms.Contains(item) && State.Clans.Get(item) == null)) { crime.Rating.Remove(item); } else { crime.Rating[item] = num; } } foreach (string item2 in (from x in crime.SneakBarredUntil where x.Value < State.Clock.Minute select x.Key).ToList()) { crime.SneakBarredUntil.Remove(item2); } DailyDisguise(); C.DailyAlleys(); } public long CrimeFine(string faction, bool inDisguise) { double num = CrimeRating(faction); if (num < 0.5) { return 0L; } return (long)(Math.Round((100.0 + num * 18.0) * (inDisguise ? 1.5 : 1.0) / 10.0) * 10.0); } public string PayCrimeFineReason(Settlement s) { CommandResult commandResult = C.RequireFree(); if (!commandResult.Ok) { return commandResult.Message; } if (s == null) { return "You're not at a town or castle."; } string text = CrimeFactionOf(s); if (CrimeRating(text) < 0.5) { return CrimeFactionName(text) + " holds nothing against you."; } bool flag = C.CurrentSettlement() == s; bool flag2 = !flag && CrimeGate() == s; if (!flag && !flag2) { return "Pay at one of their towns or castles."; } if (flag2 && CrimeTierWith(s) >= CrimeTier.Outlaw) { return "The gate guards won't deal with an outlaw. Get inside first."; } if (flag2 && State.AtWar(text, State.FactionOf(State.PlayerClan))) { return "You are at war with " + CrimeFactionName(text) + "."; } long num = CrimeFine(text, flag && InDisguise); if ((State.PlayerClan?.Gold ?? 0) < num) { return "You need " + num.ToString("N0") + " denars to pay the fine."; } return ""; } public CommandResult PayCrimeFine(Settlement s) { string text = PayCrimeFineReason(s); if (text.Length > 0) { return CommandResult.Fail(text); } string text2 = CrimeFactionOf(s); bool flag = C.CurrentSettlement() == s; long num = CrimeFine(text2, flag && InDisguise); State.Transact(State.PlayerClan, -num, LedgerAccount.Other, "Fine for crimes against " + CrimeFactionName(text2)); State.Crime.Rating.Remove(text2); State.Crime.DisguisedSettlementId = ""; State.AddLog(LogCategory.Info, "You paid " + num.ToString("N0") + " denars to " + CrimeFactionName(text2) + " for your crimes. The slate is clean.", text2, s.Id); string text3 = "You pay " + num.ToString("N0") + " denars. " + CrimeFactionName(text2) + " holds nothing more against you."; if (!flag) { State.Crime.GateSettlementId = ""; EnterSettlementAsPlayer(s); text3 += " The gates open."; } State.Touch(); return CommandResult.Success(text3); } internal bool StopAtGate(Party p, Settlement s) { if (p.Id != State.PlayerPartyId || s == null || (s.Type != SettlementType.Town && s.Type != SettlementType.Castle)) { return false; } if (s.OwnerClanId == State.PlayerClanId) { return false; } SiegeState siegeState = C.SiegeForSettlement(s.Id); if (siegeState != null && siegeState.Stage == SiegeStage.Assault) { return false; } if (C.CanEnter(p, s)) { return CrimeTierWith(s) >= CrimeTier.Wanted; } return true; } internal void StopPlayerAtGate(Party p, Settlement s) { C.ClearOrder(p); p.Position = s.Position; State.Crime.GateSettlementId = s.Id; C.UpdatePlayerTimeStates(); string text = ((!C.CanEnter(p, s)) ? (s.Name + " will not open its gates to you.") : ((CrimeTierWith(s) >= CrimeTier.Outlaw) ? ("The gates of " + s.Name + " are shut to an outlaw.") : ("The guards at the gate of " + s.Name + " know your face: there is a fine to pay."))); C.Raise(CampaignEventKind.Warning, text, true, s.Id); State.Touch(); } public Settlement CrimeGate() { string text = State.Crime?.GateSettlementId ?? ""; if (text.Length == 0) { return null; } Settlement settlement = State.Settlements.Get(text); Party playerParty = State.PlayerParty; if (settlement == null || playerParty == null || playerParty.State != PartyState.Active || playerParty.Order.Kind != OrderKind.None || Vec2.Distance(playerParty.Position, settlement.Position) > 0.6 || State.Player.Activity == PlayerActivity.InEncounter || State.Player.Activity == PlayerActivity.Captive) { State.Crime.GateSettlementId = ""; return null; } return settlement; } public CommandResult LeaveGate() { State.Crime.GateSettlementId = ""; State.Touch(); return CommandResult.Success(); } internal void EnterSettlementAsPlayer(Settlement s) { Party playerParty = State.PlayerParty; playerParty.State = PartyState.InSettlement; playerParty.CurrentSettlementId = s.Id; playerParty.Position = s.Position; C.ClearOrder(playerParty); State.Player.MenuSettlementId = s.Id; State.Player.KeepAccessSettlementId = ""; State.Player.Activity = PlayerActivity.InSettlement; C.RefreshContractOffers(); C.Raise(CampaignEventKind.ArrivedAtSettlement, "Arrived at " + s.Name + ".", true, s.Id); } public string DisguiseBlockReason() { if (!InDisguise) { return ""; } return "You're in disguise. Do that and you'll be recognised."; } public double SneakChance(Settlement s) { Hero playerHero = State.PlayerHero; int num = State.PlayerParty?.Troops.TotalTroops ?? 0; double num2 = 0.78 - CrimeRating(CrimeFactionOf(s)) / 350.0 + (double)(playerHero?.Skill("scouting") ?? 0) / 400.0 - (double)num / 500.0; if (State.AtWar(CrimeFactionOf(s), State.FactionOf(State.PlayerClan))) { num2 -= 0.08; } num2 += Math.Max(0.0, C.PersonalPerk(playerHero, PerkEffect.SneakChance)); num2 = 1.0 - (1.0 - num2) * C.Settings.DisguiseDetection; return Math.Max(0.15, Math.Min((C.Settings.DisguiseDetection < 1.0) ? 0.97 : 0.92, num2)); } public string SneakInReason() { CommandResult commandResult = C.RequireFree(); if (!commandResult.Ok) { return commandResult.Message; } Settlement settlement = CrimeGate(); if (settlement == null) { return "You are not at a gate."; } if (settlement.Type != SettlementType.Town) { return "You can't slip into a castle: the gate's the only way in, and it's watched."; } if (C.IsSettlementBesieged(settlement)) { return settlement.Name + " is under siege."; } if (State.Crime.SneakBarredUntil.TryGetValue(settlement.Id, out var value) && value > State.Clock.Minute) { return "The guards at " + settlement.Name + " are still watching for you. Try again later."; } Hero playerHero = State.PlayerHero; if (playerHero == null || playerHero.State != HeroState.Active || !playerHero.CanFight) { return "You're in no state to sneak anywhere."; } return ""; } public CommandResult SneakIn() { string text = SneakInReason(); if (text.Length > 0) { return CommandResult.Fail(text); } Settlement settlement = CrimeGate(); RandomStream randomStream = State.Random.Get("crime"); C.GrantSkillExperience(State.PlayerHero, "scouting", 12.0); C.TrainRoguery(20.0); if (!randomStream.Chance(SneakChance(settlement))) { State.Crime.SneakBarredUntil[settlement.Id] = State.Clock.Minute + 720; State.Crime.GateSettlementId = ""; AddCrime(CrimeFactionOf(settlement), 6.0, "caught sneaking into " + settlement.Name, settlement.Id); Hero playerHero = State.PlayerHero; playerHero.Health = Math.Max(0.35, playerHero.Health - 0.2); State.Touch(); return CommandResult.Fail("A guard sees through your disguise. You are beaten and driven off from " + settlement.Name + "."); } State.Crime.GateSettlementId = ""; State.Crime.DisguisedSettlementId = settlement.Id; EnterSettlementAsPlayer(settlement); State.AddLog(LogCategory.Info, "You slipped into " + settlement.Name + " in disguise.", settlement.Id); State.Touch(); return CommandResult.Success("You slip in with a crowd of farmers. Keep your head down: nobody must know you are here."); } internal void DailyDisguise() { CrimeState crime = State.Crime; if (crime.DisguisedSettlementId.Length == 0) { return; } Settlement settlement = C.CurrentSettlement(); if (settlement == null || settlement.Id != crime.DisguisedSettlementId) { crime.DisguisedSettlementId = ""; return; } RandomStream randomStream = State.Random.Get("crime"); double num = 0.1 - (double)(State.PlayerHero?.Skill("scouting") ?? 0) / 1500.0 + CrimeRating(CrimeFactionOf(settlement)) / 1500.0; num *= C.Settings.DisguiseDetection; if (C.IsSettlementBesieged(settlement) || randomStream.Chance(Math.Max(0.03 * C.Settings.DisguiseDetection, num))) { crime.DisguisedSettlementId = ""; C.LeaveSettlementInternal(State.PlayerParty); crime.SneakBarredUntil[settlement.Id] = State.Clock.Minute + 1440; AddCrime(CrimeFactionOf(settlement), 6.0, "recognised in " + settlement.Name, settlement.Id); C.UpdatePlayerTimeStates(); C.Raise(CampaignEventKind.Warning, "You were recognised in " + settlement.Name + " and had to flee the town.", true, settlement.Id); } } public string ExecuteReason(string heroId, bool inDungeon) { string text = C.NamedPrisonerActionReason(heroId, inDungeon); if (text.Length > 0) { return text; } Hero hero = State.Heroes.Get(heroId); if (hero == null || hero.State != HeroState.Captive) { return "That hero isn't your prisoner."; } if (hero.Occupation != HeroOccupation.Lord) { return "Only lords and ladies are put to death for their crimes."; } if (hero.ClanId == State.PlayerClanId) { return hero.Name + " is of your own clan."; } if (!C.IsGrown(hero)) { return hero.Name + " is a child."; } int num = C.ExecutionInfluenceCost(State.PlayerClan); if (num > 0 && State.PlayerClan.Influence < (double)num) { return "Trial by Jury: putting a captive to death costs " + num + " influence."; } return ""; } public CommandResult ExecutePrisoner(string heroId, bool inDungeon) { string text = ExecuteReason(heroId, inDungeon); if (text.Length > 0) { return CommandResult.Fail(text); } Hero h = State.Heroes.Get(heroId); Clan clan = State.Clans.Get(h.ClanId); string text2 = State.FactionOf(clan); int num = C.ExecutionInfluenceCost(State.PlayerClan); if (num > 0) { State.PlayerClan.Influence = Math.Max(0.0, State.PlayerClan.Influence - (double)num); } C.HeroDies(h, "by execution"); State.Crime.Executed.Add(h.Id); foreach (Hero item in State.Heroes.Where((Hero x) => x.ClanId == h.ClanId && x.Id != h.Id && x.State != HeroState.Dead && !string.IsNullOrEmpty(h.ClanId)).ToList()) { C.RememberHero(item, "executed_kin", h.Name); } C.CompanionsReactToExecution(h); if (clan != null) { C.AdjustClanRelation(State.PlayerClanId, clan.Id, -60); } foreach (Clan item2 in State.Clans.Where((Clan c) => !c.IsBandit && c.Id != State.PlayerClanId && c.Id != clan?.Id && !c.IsEliminated).ToList()) { if (text2.Length > 0 && State.FactionOf(item2) == text2) { C.AdjustClanRelation(State.PlayerClanId, item2.Id, -15); continue; } Hero hero = State.Heroes.Get(item2.LeaderHeroId); if (hero != null) { Campaign.Personality personality = Campaign.PersonalityOf(hero); if (personality.Honor > 0 || personality.Mercy > 0) { C.AdjustClanRelation(State.PlayerClanId, item2.Id, -8); } else if (personality.Mercy < 0) { C.AdjustClanRelation(State.PlayerClanId, item2.Id, 2); } } } AddCrime(text2, 40.0, "the execution of " + h.Name, h.Id); string text3 = "You had " + h.Name + ((clan != null) ? (" of " + clan.Name) : "") + " put to death. Word of it will spread."; State.AddLog(LogCategory.Politics, text3, h.Id); C.Raise(CampaignEventKind.Warning, text3, false, h.Id); State.Touch(); return CommandResult.Success(text3); } } internal sealed class DailySystem { private readonly Campaign C; private ContentDatabase Content => C.Content; private CampaignRules Rules => C.Rules; private CampaignState State => C.State; internal DailySystem(Campaign host) { C = host; } internal bool UsesLogistics(Party p) { if (p.Kind != PartyKind.Player && p.Kind != PartyKind.Lord) { return p.Kind == PartyKind.Caravan; } return true; } public double SettlementDailyTax(Settlement s) { if (s.Type == SettlementType.Hideout) { return 0.0; } return Math.Round(((s.Type == SettlementType.Town) ? Rules.TownDailyTax : ((s.Type == SettlementType.Castle) ? Rules.CastleDailyTax : Rules.VillageDailyTax)) * Math.Max(0.5, Math.Min(2.0, s.Prosperity / 500.0)) * C.GovernanceTaxFactor(s) * C.VillageTaxFactor(s) * (1.0 + Math.Max(0.0, C.SettlementPerk(s, PerkEffect.Tax)))); } public double GarrisonDailyWages(Settlement s) { double num = 0.0; foreach (TroopStack stack in s.Garrison.Stacks) { num += (double)stack.Total * (C.UnitDef(stack.UnitId)?.DailyWage ?? 0.0); } return Math.Ceiling(num * Rules.GarrisonWageFactor * C.LawGarrisonWageFactor(s) * (1.0 - Math.Max(0.0, Math.Min(0.5, C.SettlementPerk(s, PerkEffect.GarrisonWages))))); } public double DailyIncome(string clanId) { return State.Settlements.Where((Settlement s) => s.OwnerClanId == clanId).Sum((Func)SettlementDailyTax) + ((clanId == State.PlayerClanId) ? C.ServiceRetainerForecast() : 0.0); } public double DailyExpenses(string clanId) { double num = 0.0; foreach (Party party in State.Parties) { if (party.ClanId == clanId && UsesLogistics(party) && party.Kind != PartyKind.Caravan && (party.State == PartyState.Active || party.State == PartyState.InSettlement || party.State == PartyState.Engaged)) { num += Math.Ceiling(C.DailyWages(party)) + C.DailyFoodNeed(party) * Rules.FoodPrice; } } foreach (Settlement settlement in State.Settlements) { if (settlement.OwnerClanId == clanId) { num += GarrisonDailyWages(settlement) + C.GovernorDailyWages(settlement); } } num += C.GarrisonsSystem.FieldWagesOf(clanId); if (C.ServiceRuler(State.ClanService?.KingdomId ?? "")?.Id == clanId) { num += C.ServiceRetainerForecast(); } return num; } public bool ClanCanAffordUpkeep(Clan clan, double extraDaily) { if (clan == null) { return false; } double num = DailyIncome(clan.Id); double num2 = DailyExpenses(clan.Id) + extraDaily; if (!(num2 <= num * 1.1)) { return (double)clan.Gold > num2 * 30.0; } return true; } internal void DailyLogistics() { foreach (Party item in State.Parties.ToList()) { if ((item.State != PartyState.Active && item.State != PartyState.InSettlement) || item.Kind == PartyKind.SiegeDefender) { continue; } bool flag = item.Id == State.PlayerPartyId; Clan clan = State.Clans.Get(item.ClanId); if (UsesLogistics(item)) { double num = C.DailyFoodNeed(item); Hero worker = C.RoleHolder(item, PartyRole.Quartermaster); double num2 = (C.EatsCargoFood(item) ? C.FoodSupply(item) : item.Food); double work = Math.Min(Math.Max(0.0, num2), num); if (num2 + 1E-09 >= num) { C.TakeFood(item, num); item.StarvingDays = 0; } else { if (C.EatsCargoFood(item)) { C.TakeFood(item, Math.Max(0.0, num2)); } item.Food = 0.0; item.StarvingDays++; item.Morale = Math.Max(0.0, item.Morale - 8.0); if (flag) { C.CompanionsReactToHardship(); } if (flag) { C.Raise(CampaignEventKind.Starvation, (item.StarvingDays > Rules.StarvationGraceDays) ? "Your party is starving and men are deserting. Buy food at a village or town." : $"Your party is out of food (day {item.StarvingDays}). Morale is falling; men start deserting after {Rules.StarvationGraceDays} days.", item.StarvingDays == 1); } if (item.StarvingDays > Rules.StarvationGraceDays) { Desert(item, Rules.StarvationDesertionRate, "starvation"); } } C.ApplyRoleTraining(item, PartyRole.Quartermaster, worker, work); long num3 = (C.IsMerchantCaravan(item) ? 0 : ((long)Math.Ceiling(C.DailyWages(item)))); if (num3 > 0 && (clan != null || item.Kind == PartyKind.Caravan)) { long num4; if (item.Kind == PartyKind.Caravan) { num4 = Math.Min(Math.Max(0L, item.Gold), num3); item.Gold -= num4; } else { num4 = -State.Transact(clan, -num3, LedgerAccount.Wages, "Wages for " + item.Name, allowPartial: true); } if (num4 < num3) { item.UnpaidDays++; item.Morale = Math.Max(0.0, item.Morale - 6.0); if (flag) { C.CompanionsReactToHardship(); } if (flag) { C.Raise(CampaignEventKind.Unpaid, $"You could only pay {num4} of {num3} denars in wages. Unpaid men will start to desert.", item.UnpaidDays == 1); } if (item.UnpaidDays > Rules.UnpaidGraceDays) { Desert(item, Rules.UnpaidDesertionRate, "unpaid wages"); } } else { item.UnpaidDays = 0; } } } Hero worker2 = C.RoleHolder(item, PartyRole.Surgeon); double num5 = (double)C.RoleSkill(item, PartyRole.Surgeon) / 100.0; double num6 = ((item.State == PartyState.InSettlement) ? Rules.SettlementHealMultiplier : 1.0) * (1.0 + num5) * (C.HasRolePerk(item, PartyRole.Surgeon, "perk.surgeon.field_medic") ? 1.2 : 1.0) * (1.0 + C.PartyPerk(item, PerkEffect.Healing)); double num7 = Rules.DailyHealFraction * num6; double num8 = 0.0; foreach (TroopStack item2 in item.Troops.Stacks.ToList()) { if (item2.Wounded != 0) { int count = Math.Max(1, (int)Math.Round((double)item2.Wounded * num7)); int wounded = item2.Wounded; item.Troops.Heal(item2.UnitId, count); num8 += (double)((wounded - item2.Wounded) * 5); } } List<(Hero, double)> list = new List<(Hero, double)>(); foreach (string hero2 in item.Troops.Heroes) { Hero hero = State.Heroes.Get(hero2); if (hero != null && hero.State == HeroState.Active) { double num9 = Math.Min(1.0, hero.Health + Rules.HeroDailyHeal * num6); num8 += Math.Max(0.0, num9 - hero.Health) * 20.0; list.Add((hero, num9)); } } C.ApplyRoleTraining(item, PartyRole.Surgeon, worker2, num8); foreach (var item3 in list) { item3.Item1.Health = item3.Item2; } int num10 = (int)Math.Round(C.PartyPerk(item, PerkEffect.TroopDailyXp)); if (num10 > 0) { foreach (TroopStack item4 in item.Troops.Stacks.ToList()) { if (item4.Healthy > 0) { item.Troops.AddXp(item4.UnitId, (int)Math.Min(2147483647L, (long)item4.Healthy * (long)num10)); } } } double num11 = Rules.BaseMorale + (double)((item.StarvingDays > 0) ? (-20) : 0) + (double)((item.UnpaidDays > 0) ? (-15) : 0) + C.PartyPerk(item, PerkEffect.Morale); if (item.Morale < num11) { item.Morale = Math.Min(num11, item.Morale + Rules.MoraleDriftPerDay); } else if (item.Morale > num11) { item.Morale = Math.Max(num11, item.Morale - Rules.MoraleDriftPerDay / 2.0); } } foreach (Hero hero3 in State.Heroes) { if (hero3.State == HeroState.Active && string.IsNullOrEmpty(hero3.PartyId)) { hero3.Health = Math.Min(1.0, hero3.Health + Rules.HeroDailyHeal * 2.0); } } RespawnIdleLords(); } internal void Desert(Party p, double rate, string reason) { int totalTroops = p.Troops.TotalTroops; int num = Math.Max(1, (int)Math.Round((double)totalTroops * rate)); if (totalTroops == 0) { return; } int num2 = 0; foreach (TroopStack item in p.Troops.Stacks.OrderBy((TroopStack s) => C.UnitDef(s.UnitId)?.Tier ?? 1).ThenBy((TroopStack s) => s.UnitId, StringComparer.Ordinal).ToList()) { if (num2 >= num) { break; } num2 += p.Troops.Remove(item.UnitId, num - num2); } State.AddLog(LogCategory.Warning, $"{num2} troops deserted {p.Name} ({reason}).", p.Id); if (p.Id == State.PlayerPartyId) { C.Raise(CampaignEventKind.Desertion, $"{num2} troops deserted ({reason}).", false, p.Id); } } internal void DailySettlements() { C.ReplaceUnavailableNotables(); RandomStream randomStream = State.Random.Get("recruitment"); foreach (Settlement settlement in State.Settlements) { if (settlement.Type == SettlementType.Hideout) { continue; } SiegeState siegeState = C.SiegeForSettlement(settlement.Id); if (siegeState != null && siegeState.Stage == SiegeStage.Assault) { continue; } CultureDef cultureDef = Content.Cultures.Get(settlement.CultureId); if (!C.IsSettlementBesieged(settlement) && C.TryBeginRecruitPoolRecovery(settlement)) { foreach (RecruitSlot recruit in settlement.Recruits) { if (recruit.Available || !randomStream.Chance(Rules.RecruitRefillChancePerDay)) { continue; } List list = ((settlement.Type != SettlementType.Village) ? cultureDef?.TownRecruits : cultureDef?.VillageRecruits); if (list != null && list.Count != 0) { int num = randomStream.PickWeighted(list.Select((WeightedUnit w) => w.Weight).ToList()); if (num >= 0) { recruit.UnitId = list[num].Unit; recruit.Available = true; } } } } Clan clan = State.Clans.Get(settlement.OwnerClanId); if (clan == null || clan.IsBandit) { continue; } State.Transact(clan, (long)SettlementDailyTax(settlement), LedgerAccount.Taxes, "Taxes from " + settlement.Name); long num2 = (long)GarrisonDailyWages(settlement); if (num2 > 0) { long num3 = -State.Transact(clan, -num2, LedgerAccount.GarrisonWages, "Garrison of " + settlement.Name, allowPartial: true); if (num3 < num2 && clan.IsPlayerClan) { C.Raise(CampaignEventKind.Unpaid, $"The garrison of {settlement.Name} was not fully paid ({num3}/{num2}).", false, settlement.Id); } } bool flag = settlement.StarvingDays == 0; if (!C.IsSettlementBesieged(settlement) && flag) { foreach (TroopStack item in settlement.Garrison.Stacks.ToList()) { if (item.Wounded > 0) { settlement.Garrison.Heal(item.UnitId, Math.Max(1, item.Wounded / 4)); } } } if (!C.IsSettlementBesieged(settlement) && flag && settlement.WoundedMilitia > 0) { int num4 = Math.Min(settlement.WoundedMilitia, Math.Max(1, settlement.WoundedMilitia / 4)); settlement.WoundedMilitia -= num4; settlement.Militia += num4; } } } internal void DailyBanditSpawns() { RandomStream randomStream = State.Random.Get("world"); foreach (Settlement hideout in State.Settlements.Where((Settlement s) => s.Type == SettlementType.Hideout && s.HideoutActive)) { Clan clan = State.Clans.Get(hideout.BanditClanId); if (clan != null && clan.BanditTroops.Count != 0 && State.Parties.Count((Party p) => p.HomeSettlementId == hideout.Id && p.Kind == PartyKind.Bandit && (p.State == PartyState.Active || p.State == PartyState.Engaged)) < Rules.MaxBanditsPerHideout && randomStream.Chance(Rules.BanditSpawnChancePerDay)) { SpawnBanditParty(hideout, clan, randomStream); } } } public void EnsureOutlawPartySizes() { if (State.OutlawPartiesDoubled) { return; } foreach (Party item in State.Parties.Where((Party p) => p.Kind == PartyKind.Bandit && (p.State == PartyState.Active || p.State == PartyState.InSettlement) && string.IsNullOrEmpty(p.EncounterId) && !C.MilitaryPartyReserved(p.Id))) { foreach (TroopStack item2 in item.Troops.Stacks.ToList()) { if (item2.Healthy > 0) { item.Troops.Add(item2.UnitId, item2.Healthy); } } } State.OutlawPartiesDoubled = true; State.Touch(); } internal Party SpawnBanditParty(Settlement hideout, Clan clan, RandomStream rng) { Party party = new Party { Id = State.Ids.Allocate("party"), Name = clan.Name, Kind = PartyKind.Bandit, ClanId = clan.Id, HomeSettlementId = hideout.Id, Position = hideout.Position, CreatedAtMinute = State.Clock.Minute, Gold = rng.Range(20, 120), Morale = 50.0 }; double num = rng.NextDouble(); int num2; if (num < 0.2) { num2 = rng.Range(Math.Max(3, Rules.BanditPartyMinSize / 2), Math.Max(4, Rules.BanditPartyMinSize)); } else if (num < 0.875) { num2 = rng.Range(Rules.BanditPartyMinSize, Rules.BanditPartyMaxSize + 1); } else { num2 = rng.Range((int)Math.Round((double)Rules.BanditPartyMaxSize * 1.2), (int)Math.Round((double)Rules.BanditPartyMaxSize * 1.75) + 1); party.Name = clan.Name + " Warband"; } List weights = clan.BanditTroops.Select((WeightedUnit w) => w.Weight).ToList(); for (int num3 = 0; num3 < num2; num3++) { int num4 = rng.PickWeighted(weights); if (num4 >= 0) { party.Troops.Add(clan.BanditTroops[num4].Unit, 1); } } State.Parties.Add(party); return party; } internal void RespawnIdleLords() { Dictionary dictionary = new Dictionary(StringComparer.Ordinal); FamiliesState families = State.Families; if (families != null && families.Started) { foreach (Party item in State.Parties.Where((Party p) => p.Kind == PartyKind.Lord && p.State != PartyState.Destroyed && p.State != PartyState.Disbanded && !string.IsNullOrEmpty(p.ClanId) && p.Id != State.PlayerPartyId && C.MilitaryPartyFor(p) == null)) { dictionary[item.ClanId] = (dictionary.TryGetValue(item.ClanId, out var value) ? value : 0) + 1; } } foreach (Hero item2 in State.Heroes.Where((Hero h) => h.Occupation == HeroOccupation.Lord && h.State == HeroState.Active && string.IsNullOrEmpty(h.PartyId) && h.Health >= 0.5).ToList()) { Clan clan = State.Clans.Get(item2.ClanId); if (clan == null || clan.IsEliminated) { continue; } FamiliesState families2 = State.Families; if (families2 != null && families2.Started) { dictionary.TryGetValue(clan.Id, out var value2); if (value2 >= C.LordPartyLimit(clan) || C.IsChild(item2)) { continue; } } Settlement settlement = State.Settlements.Get(item2.SettlementId) ?? State.Settlements.FirstOrDefault((Settlement s) => s.OwnerClanId == clan.Id); if (settlement == null || settlement.OwnerClanId != clan.Id) { settlement = State.Settlements.FirstOrDefault((Settlement s) => s.OwnerClanId == clan.Id); } if (settlement == null || C.IsSettlementBesieged(settlement)) { continue; } Party party = CreateLordParty(item2, settlement); dictionary[clan.Id] = (dictionary.TryGetValue(clan.Id, out var value3) ? value3 : 0) + 1; string text = Content.Cultures.Get(settlement.CultureId)?.BasicTroop ?? Content.Cultures.Get(clan.CultureId)?.BasicTroop; int num = Rules.LordRecruitThreshold; foreach (TroopStack item3 in settlement.Garrison.Stacks.OrderByDescending((TroopStack s) => C.UnitDef(s.UnitId)?.Tier ?? 1).ToList()) { if (num <= 0 || settlement.Garrison.TotalHealthy <= 10) { break; } int num2 = Math.Min(num, Math.Min(item3.Healthy, settlement.Garrison.TotalHealthy - 10)); if (num2 > 0) { settlement.Garrison.RemoveHealthy(item3.UnitId, num2); party.Troops.Add(item3.UnitId, num2); num -= num2; } } if (C.PartyCombatants(party) < 3 && text != null) { party.Troops.Add(text, Rules.LordEmergencyLevy); } State.AddLog(LogCategory.Politics, item2.Name + " has raised a new party at " + settlement.Name + ".", item2.Id, settlement.Id); } } internal Party CreateLordParty(Hero h, Settlement home) { Party party = new Party { Id = State.Ids.Allocate("party"), Name = h.Name + "'s Party", Kind = PartyKind.Lord, ClanId = h.ClanId, LeaderHeroId = h.Id, HomeSettlementId = home.Id, Position = home.Position, State = PartyState.InSettlement, CurrentSettlementId = home.Id, CreatedAtMinute = State.Clock.Minute, Food = 6.0, Morale = 60.0 }; party.Troops.Heroes.Add(h.Id); h.PartyId = party.Id; h.SettlementId = ""; State.Parties.Add(party); return party; } internal void DailyCaptivity() { RandomStream randomStream = State.Random.Get("captivity"); Hero playerHero; if (State.Player.Activity == PlayerActivity.Captive) { playerHero = State.PlayerHero; Party party = State.Parties.Get(State.Player.CaptorPartyId); Settlement settlement = State.Settlements.Get(State.Player.CaptorSettlementId); double num = (double)(State.Clock.Minute - State.Player.CaptiveSinceMinute) / 1440.0; bool num2; if (string.IsNullOrEmpty(State.Player.CaptorSettlementId)) { if (party == null || party.State == PartyState.Destroyed) { goto IL_00df; } num2 = party.State == PartyState.Disbanded; } else { num2 = settlement == null; } if (num2) { goto IL_00df; } if (num >= (double)State.Player.CaptivityMaxDays) { OutcomeCommitter.ReleaseHero(C, playerHero, "your captors released you"); } else if (randomStream.Chance(Rules.EscapeChancePerDay + num * Rules.EscapeChanceGrowthPerDay + C.PersonalPerk(playerHero, PerkEffect.EscapeChance))) { OutcomeCommitter.ReleaseHero(C, playerHero, "you escaped"); } } goto IL_015d; IL_00df: OutcomeCommitter.ReleaseHero(C, playerHero, "your captors were scattered"); goto IL_015d; IL_015d: foreach (Hero item in State.Heroes.Where((Hero x) => x.State == HeroState.Captive && !x.IsPlayer).ToList()) { if (!C.NamedCustodyReserved(item)) { Party party2 = State.Parties.Get(item.CaptorPartyId); Settlement settlement2 = State.Settlements.Get(item.CaptorSettlementId); double num3 = (double)(State.Clock.Minute - item.CaptiveSinceMinute) / 1440.0; bool num4 = (!string.IsNullOrEmpty(item.CaptorPartyId) && (party2 == null || party2.State == PartyState.Destroyed || party2.State == PartyState.Disbanded)) || (!string.IsNullOrEmpty(item.CaptorSettlementId) && settlement2 == null); bool flag = party2?.ClanId == State.PlayerClanId || settlement2?.OwnerClanId == State.PlayerClanId; if (num4) { OutcomeCommitter.ReleaseHero(C, item, "their captors were scattered"); } else if (num3 >= (double)Rules.LordMaxCaptivityDays && !flag) { OutcomeCommitter.ReleaseHero(C, item, "released after captivity"); } else if (randomStream.Chance(Rules.EscapeChancePerDay * 0.5)) { OutcomeCommitter.ReleaseHero(C, item, "escaped"); } } } } internal void OnPlayerReleased(string reason) { Hero playerHero = State.PlayerHero; Party party = State.PlayerParty; playerHero.Health = Math.Max(playerHero.Health, 0.4); playerHero.State = HeroState.Active; Vec2 from = State.Parties.Get(State.Player.CaptorPartyId)?.Position ?? State.Settlements.Get(State.Player.CaptorSettlementId)?.Position ?? party.Position; Settlement settlement = (from s in State.Settlements where s.Type != SettlementType.Hideout && C.CanEnter(party, s) orderby Vec2.Distance(s.Position, @from) select s).ThenBy((Settlement s) => s.Id, StringComparer.Ordinal).FirstOrDefault(); State.Player.CaptorPartyId = ""; State.Player.CaptorSettlementId = ""; party.State = PartyState.Active; party.EncounterId = ""; party.Morale = 40.0; if (!party.Troops.Heroes.Contains(playerHero.Id)) { party.Troops.Heroes.Insert(0, playerHero.Id); } playerHero.PartyId = party.Id; party.DisengagedUntilMinute = State.Clock.Minute + (long)(Rules.DisengageHours * 60.0); C.ClearOrder(party); State.Player.Activity = PlayerActivity.Idle; if (settlement != null) { party.Position = settlement.Position; party.State = PartyState.InSettlement; party.CurrentSettlementId = settlement.Id; State.Player.MenuSettlementId = settlement.Id; State.Player.Activity = PlayerActivity.InSettlement; } State.AddLog(LogCategory.Captivity, "You are free: " + reason + ".", settlement?.Id ?? ""); C.Raise(CampaignEventKind.Released, "You are free: " + reason + "." + ((settlement != null) ? (" You make your way to " + settlement.Name + ".") : ""), true, settlement?.Id ?? ""); } internal void OnHeroDied(Hero hero) { C.AfterHeroDeath(hero, "in battle"); } } internal sealed class DeveloperDiplomacySystem { private readonly Campaign C; private CampaignState State => C.State; internal DeveloperDiplomacySystem(Campaign host) { C = host; } internal string DevDiplomacyReason(string kingdomId, out Kingdom kingdom) { kingdom = State.Kingdoms.Get(kingdomId ?? ""); string text = C.DeveloperCampaignReason(); if (text.Length > 0) { return text; } if (kingdom == null || kingdom.IsEliminated) { return "Choose a living kingdom."; } if (State.FactionOf(State.PlayerClan) == kingdom.Id) { return "That is your own realm."; } if (C.DiplomacyFactionReserved(kingdom.Id) || C.DiplomacyFactionReserved(State.FactionOf(State.PlayerClan))) { return "Wait for the battles to finish."; } return ""; } internal void DevMakePeace(string a, string b) { State.SetStance(a, b, Stance.Peace); State.Diplomacy.Truces.RemoveAll((DiplomaticTruce t) => (t.A == a && t.B == b) || (t.A == b && t.B == a)); } public CommandResult DeveloperAlliance(string kingdomId, bool on) { Kingdom k; string text = DevDiplomacyReason(kingdomId, out k); if (text.Length > 0) { return CommandResult.Fail(text); } string me = State.FactionOf(State.PlayerClan); State.Diplomacy.Agreements.RemoveAll((DiplomaticAgreement x) => x.Kind == AgreementKind.Alliance && Campaign.Pair(x, me, k.Id)); if (on) { DevMakePeace(me, k.Id); C.AddAgreement(AgreementKind.Alliance, me, k.Id, 84, "", "", 0L); } C.OnDiplomacyChanged(); State.Touch(); return CommandResult.Success("Developer: " + (on ? "allied with " : "no longer allied with ") + k.Name + "."); } public CommandResult DeveloperTradeAgreement(string kingdomId, bool on) { Kingdom k; string text = DevDiplomacyReason(kingdomId, out k); if (text.Length > 0) { return CommandResult.Fail(text); } string me = State.FactionOf(State.PlayerClan); State.Diplomacy.Agreements.RemoveAll((DiplomaticAgreement x) => x.Kind == AgreementKind.TradeAgreement && Campaign.Pair(x, me, k.Id)); if (on) { DevMakePeace(me, k.Id); C.AddAgreement(AgreementKind.TradeAgreement, me, k.Id, 84, "", "", 0L); } State.Touch(); return CommandResult.Success("Developer: " + (on ? "trade agreement with " : "no trade agreement with ") + k.Name + "."); } public CommandResult DeveloperTributePeace(string kingdomId, bool theyPay) { Kingdom k; string text = DevDiplomacyReason(kingdomId, out k); if (text.Length > 0) { return CommandResult.Fail(text); } string me = State.FactionOf(State.PlayerClan); if (!State.AtWar(me, k.Id)) { State.SetStance(me, k.Id, Stance.War); } State.Diplomacy.Truces.RemoveAll((DiplomaticTruce t) => (t.A == me && t.B == k.Id) || (t.A == k.Id && t.B == me)); return CommandResult.Success("Developer: " + C.MakeNegotiatedPeace(me, k.Id, theyPay ? k.Id : me, 50L)); } public CommandResult DeveloperAllyCallsYou(string kingdomId) { Kingdom k; string text = DevDiplomacyReason(kingdomId, out k); if (text.Length > 0) { return CommandResult.Fail(text); } string me = State.FactionOf(State.PlayerClan); if (!C.Allied(me, k.Id)) { DevMakePeace(me, k.Id); C.AddAgreement(AgreementKind.Alliance, me, k.Id, 84, "", "", 0L); } Kingdom enemy = State.Kingdoms.Where((Kingdom x) => !x.IsEliminated && x.Id != k.Id && x.Id != me && State.AtWar(k.Id, x.Id) && !State.AtWar(me, x.Id) && !C.Allied(me, x.Id)).OrderBy((Kingdom x) => x.Id, StringComparer.Ordinal).FirstOrDefault() ?? State.Kingdoms.Where((Kingdom x) => !x.IsEliminated && x.Id != k.Id && x.Id != me && !State.AtWar(me, x.Id) && !C.Allied(me, x.Id) && !C.Allied(k.Id, x.Id)).OrderBy((Kingdom x) => x.Id, StringComparer.Ordinal).FirstOrDefault(); if (enemy == null) { return CommandResult.Fail("No third realm for them to be at war with."); } if (!State.AtWar(k.Id, enemy.Id)) { State.SetStance(k.Id, enemy.Id, Stance.War); } State.Diplomacy.Truces.RemoveAll((DiplomaticTruce t) => (t.A == me && t.B == enemy.Id) || (t.A == enemy.Id && t.B == me)); State.Diplomacy.Calls.RemoveAll((CallToWarRequest c) => c.Status == CallToWarStatus.Pending && c.AllyFactionId == me); C.NewCall(k.Id, me, enemy.Id, 1000L); C.OnDiplomacyChanged(); State.Touch(); return CommandResult.Success("Developer: " + k.Name + " calls you to war against " + enemy.Name + " (offering 1,000). Answer in Realm → Diplomacy."); } public CommandResult DeveloperWeakenKingdom(string kingdomId) { Kingdom k; string text = DevDiplomacyReason(kingdomId, out k); if (text.Length > 0) { return CommandResult.Fail(text); } int num = 0; foreach (Party item in State.Parties.Where((Party p) => p.Kind == PartyKind.Lord && State.FactionOfParty(p) == k.Id && string.IsNullOrEmpty(p.EncounterId))) { foreach (TroopStack item2 in item.Troops.Stacks.ToList()) { num += item.Troops.RemoveHealthy(item2.UnitId, item2.Healthy / 2); } } foreach (Settlement item3 in State.Settlements.Where((Settlement s) => State.FactionOf(State.Clans.Get(s.OwnerClanId)) == k.Id && C.SiegeForSettlement(s.Id) == null)) { foreach (TroopStack item4 in item3.Garrison.Stacks.ToList()) { num += item3.Garrison.RemoveHealthy(item4.UnitId, item4.Healthy / 2); } } State.Touch(); return CommandResult.Success("Developer: " + k.Name + " lost " + num + " soldiers. The war now stands at " + C.WarAdvantage(State.FactionOf(State.PlayerClan), k.Id).ToString("+0.00;-0.00;0") + " for you."); } public CommandResult DeveloperRulerDies(string kingdomId) { string text = C.DeveloperCampaignReason(); if (text.Length > 0) { return CommandResult.Fail(text); } Kingdom k = State.Kingdoms.Get(kingdomId ?? ""); Clan obj = ((k == null) ? null : C.ServiceRuler(k.Id)); Hero hero = State.Heroes.Get(obj?.LeaderHeroId ?? ""); if (hero == null || hero.State == HeroState.Dead) { return CommandResult.Fail("That kingdom has no living ruler."); } if (hero.IsPlayer) { return CommandResult.Fail("That is you. Abdicate from Realm → Council instead."); } C.HeroDies(hero, "suddenly"); State.Politics.Decisions.Where((KingdomDecision d) => d.KingdomId == k.Id && Campaign.CouncilIsLive(d) && d.Kind != KingdomDecisionKind.RulerElection).ToList().ForEach(delegate(KingdomDecision d) { d.Status = KingdomDecisionStatus.Cancelled; d.ResolvedMinute = State.Clock.Minute; d.Passed = false; d.Result = "Cancelled for the ruler's election."; }); C.DailyElections(); KingdomDecision kingdomDecision = State.Politics.Decisions.FirstOrDefault((KingdomDecision d) => d.KingdomId == k.Id && d.Kind == KingdomDecisionKind.RulerElection && Campaign.CouncilIsLive(d)); State.Touch(); return CommandResult.Success("Developer: " + hero.Name + " is dead. " + ((kingdomDecision != null) ? ("The council of " + k.Name + " votes for two days.") : "No election (the council is too small, or the clan has no grown heir yet).")); } public CommandResult DeveloperCloseCouncilVotes() { string text = C.DeveloperCampaignReason(); if (text.Length > 0) { return CommandResult.Fail(text); } int num = 0; foreach (KingdomDecision item in State.Politics.Decisions.Where((KingdomDecision d) => d.Status == KingdomDecisionStatus.Voting)) { item.ClosesMinute = State.Clock.Minute; item.OpenedMinute = Math.Max(0L, item.ClosesMinute - 2880); item.ClosesMinute = item.OpenedMinute + 2880; item.CreatedMinute = Math.Min(item.CreatedMinute, item.OpenedMinute); num++; } C.DailyCouncil(); State.Touch(); return CommandResult.Success("Developer: " + num + " council vote" + ((num == 1) ? "" : "s") + " decided."); } public CommandResult DeveloperRunAiDiplomacy() { string text = C.DeveloperCampaignReason(); if (text.Length > 0) { return CommandResult.Fail(text); } int count = State.Diplomacy.Agreements.Count; int count2 = State.Diplomacy.Calls.Count; C.AiPacts(); return CommandResult.Success("Developer: the AI realms met. " + (State.Diplomacy.Agreements.Count - count) + " new agreement(s), " + (State.Diplomacy.Calls.Count - count2) + " call(s) to war."); } public CommandResult DeveloperGatherArmies() { string text = C.DeveloperCampaignReason(); if (text.Length > 0) { return CommandResult.Fail(text); } int num = C.FormAiArmies(force: true); if (num <= 0) { return CommandResult.Fail("No realm at war has free lords for an army (or each already has one)."); } return CommandResult.Success("Developer: " + num + " army" + ((num == 1) ? "" : "ies") + " gathered (see Realm → Army → Realm armies)."); } public CommandResult DeveloperGoToArmy() { string text = C.DeveloperFreeReason(); if (text.Length > 0) { return CommandResult.Fail(text); } AiArmy aiArmy = C.AiArmies.FirstOrDefault((AiArmy a) => a.KingdomId == State.PlayerClan.KingdomId) ?? C.AiArmies.FirstOrDefault(); Party party = ((aiArmy == null) ? null : State.Parties.Get(aiArmy.LeaderPartyId)); if (party == null) { return CommandResult.Fail("No army is gathered. Gather one first."); } Party playerParty = State.PlayerParty; if (playerParty.State == PartyState.InSettlement) { playerParty.State = PartyState.Active; playerParty.CurrentSettlementId = ""; State.Player.Activity = PlayerActivity.Idle; State.Player.MenuSettlementId = ""; } C.ClearOrder(playerParty); playerParty.Position = party.Position; State.Touch(); string text2 = C.JoinAiArmyReason(aiArmy.Id); return CommandResult.Success("Developer: you are beside " + (State.Heroes.Get(aiArmy.LeaderHeroId)?.Name ?? "the marshal") + "'s army." + ((text2.Length == 0) ? " March with it from Realm → Army." : (" (" + text2 + ")"))); } } internal sealed class DeveloperSystem { private readonly Campaign C; private static int[] ClanTierRenown => Campaign.ClanTierRenown; private ContentDatabase Content => C.Content; private CampaignRules Rules => C.Rules; private CampaignState State => C.State; internal DeveloperSystem(Campaign host) { C = host; } internal void EnsureDeveloperChoice() { if (!State.DeveloperToolsDecided) { State.DeveloperTools = true; State.DeveloperToolsDecided = true; State.Touch(); } } public string DeveloperCampaignReason() { if (!State.DeveloperTools) { return "Developer tools were not enabled when this campaign was created."; } if (State.PlayerParty == null || State.PlayerClan == null || State.PlayerHero == null) { return "This campaign has no player party."; } if (State.Player.Activity == PlayerActivity.InBattle) { return "A battle is in progress."; } return ""; } internal string DeveloperFreeReason() { string text = DeveloperCampaignReason(); if (text.Length > 0) { return text; } CommandResult commandResult = C.RequireFree(); if (!commandResult.Ok) { return commandResult.Message; } if (!string.IsNullOrEmpty(State.Player.PendingEncounterId) || !string.IsNullOrEmpty(State.PlayerParty.EncounterId) || C.MilitaryPartyReserved(State.PlayerPartyId)) { return "Resolve the current encounter first."; } return ""; } public List DeveloperHeroes() { return (from h in State.Heroes where h.State != HeroState.Dead && h.ClanId == State.PlayerClanId && (h.Id == State.PlayerHeroId || C.IsOwnedCompanion(h)) orderby (!(h.Id == State.PlayerHeroId)) ? 1 : 0 select h).ThenBy((Hero h) => h.Name, StringComparer.Ordinal).ThenBy((Hero h) => h.Id, StringComparer.Ordinal).ToList(); } internal string DeveloperHeroReason(string heroId) { string text = DeveloperCampaignReason(); if (text.Length > 0) { return text; } Hero hero = State.Heroes.Get(heroId ?? ""); if (hero == null || hero.State == HeroState.Dead || hero.ClanId != State.PlayerClanId || (hero.Id != State.PlayerHeroId && !C.IsOwnedCompanion(hero))) { return "Choose your character or one of your companions."; } return ""; } public CommandResult DeveloperAddYears(string heroId, int years) { string text = DeveloperHeroReason(heroId); if (text.Length > 0) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Require(heroId); if (hero.Sex == HeroSex.Unspecified) { return CommandResult.Fail(hero.Name + " has no age yet."); } long num = hero.BornDay - (long)years * 84L; if (num > State.Clock.Day) { return CommandResult.Fail("Nobody can be younger than a newborn."); } hero.BornDay = num; State.Touch(); return CommandResult.Success(hero.Name + " is now " + C.HeroYears(hero) + "."); } public CommandResult DeveloperAddGold(long amount) { string text = DeveloperCampaignReason(); if (text.Length > 0) { return CommandResult.Fail(text); } Clan playerClan = State.PlayerClan; long num = Math.Max(0L, Math.Min(1000000000L, (amount < 0) ? (playerClan.Gold + amount) : ((playerClan.Gold > 1000000000 - amount) ? 1000000000 : (playerClan.Gold + amount)))) - playerClan.Gold; if (num == 0L) { return CommandResult.Fail((amount >= 0) ? "Your treasury is already at the developer limit." : "Your treasury is already empty."); } State.Transact(playerClan, num, LedgerAccount.Developer, "Developer tools"); return C.DeveloperDone("Developer: " + ((num > 0) ? "added " : "removed ") + Math.Abs(num).ToString("N0", CultureInfo.InvariantCulture) + " denars. Your clan has " + playerClan.Gold.ToString("N0", CultureInfo.InvariantCulture) + "."); } public CommandResult DeveloperSetSkill(string heroId, string skill, int level) { string text = DeveloperHeroReason(heroId); if (text.Length > 0) { return CommandResult.Fail(text); } if (!SkillIds.All.Contains(skill)) { return CommandResult.Fail("Unknown skill."); } Hero hero = State.Heroes.Require(heroId); level = Math.Max(0, Math.Min(300, level)); if (hero.Skill(skill) == level) { return CommandResult.Fail(hero.Name + " already has " + level + " " + SkillName(skill) + "."); } hero.Skills[skill] = level; hero.SkillXp?.Remove(skill); hero.SkillXpRemainders?.Remove(skill); return C.DeveloperDone("Developer: " + hero.Name + "'s " + SkillName(skill) + " is now " + level + ".", hero.Id); } public CommandResult DeveloperSetAllSkills(string heroId, int level) { string text = DeveloperHeroReason(heroId); if (text.Length > 0) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Require(heroId); level = Math.Max(0, Math.Min(300, level)); if (SkillIds.All.All((string s) => hero.Skill(s) == level)) { return CommandResult.Fail("Every skill of " + hero.Name + " is already " + level + "."); } string[] all = SkillIds.All; foreach (string key in all) { hero.Skills[key] = level; hero.SkillXp?.Remove(key); hero.SkillXpRemainders?.Remove(key); } return C.DeveloperDone("Developer: every skill of " + hero.Name + " is now " + level + ".", hero.Id); } public static string SkillName(string skill) { return Skills.Name(skill); } public CommandResult DeveloperSetHeroLevel(string heroId, int level) { string text = DeveloperHeroReason(heroId); if (text.Length > 0) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Require(heroId); level = Math.Max(1, Math.Min(50, level)); if (C.HeroLevel(hero) == level && hero.Xp == Campaign.HeroXpForLevel(level)) { return CommandResult.Fail(hero.Name + " is already level " + level + "."); } int num = hero.SkillFocus?.Values.Sum() ?? 0; int num2 = Campaign.HeroFocusPointsForLevel(level) + Campaign.ExtraFocus(hero); if (num > num2) { return CommandResult.Fail(hero.Name + " has spent " + num + " focus points; level " + level + " allows " + num2 + ". Clear their focus first."); } hero.Xp = Campaign.HeroXpForLevel(level); hero.Level = level; return C.DeveloperDone("Developer: " + hero.Name + " is now level " + level + ".", hero.Id); } public CommandResult DeveloperAddFocus(string heroId, int points) { string text = DeveloperHeroReason(heroId); if (text.Length > 0) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Require(heroId); int num = Math.Max(0, Math.Min(100, hero.BonusFocus + points)); if (num == hero.BonusFocus) { return CommandResult.Fail(hero.Name + " already has the most extra focus points (" + 100 + ")."); } hero.BonusFocus = num; return C.DeveloperDone("Developer: " + hero.Name + " has " + C.HeroFocusAvailable(hero) + " focus points to spend.", hero.Id); } public CommandResult DeveloperClearFocus(string heroId) { string text = DeveloperHeroReason(heroId); if (text.Length > 0) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Require(heroId); if (hero.SkillFocus == null || hero.SkillFocus.Values.Sum() == 0) { return CommandResult.Fail(hero.Name + " has no focus spent."); } hero.SkillFocus.Clear(); return C.DeveloperDone("Developer: " + hero.Name + "'s focus was cleared (" + C.HeroFocusAvailable(hero) + " points to spend).", hero.Id); } public CommandResult DeveloperClearPerks(string heroId) { string text = DeveloperHeroReason(heroId); if (text.Length > 0) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Require(heroId); if (hero.Perks == null || hero.Perks.Count == 0) { return CommandResult.Fail(hero.Name + " has no perks chosen."); } int count = hero.Perks.Count; hero.Perks.Clear(); return C.DeveloperDone("Developer: cleared " + count + " perk" + ((count == 1) ? "" : "s") + " of " + hero.Name + ".", hero.Id); } public CommandResult DeveloperAddRenown(double amount) { string text = DeveloperCampaignReason(); if (text.Length > 0) { return CommandResult.Fail(text); } Clan playerClan = State.PlayerClan; double num = ((double.IsNaN(playerClan.Renown) || double.IsInfinity(playerClan.Renown)) ? 0.0 : playerClan.Renown); double num2 = Math.Max(0.0, Math.Min(100000.0, num + amount)); if (Math.Abs(num2 - num) < 1E-09) { return CommandResult.Fail((amount >= 0.0) ? "Your renown is already at the developer limit." : "Your clan has no renown."); } playerClan.Renown = num2; return C.DeveloperDone("Developer: your clan has " + num2.ToString("0", CultureInfo.InvariantCulture) + " renown (tier " + Campaign.ClanTier(playerClan) + ")."); } public double DeveloperRenownToNextTier() { Clan playerClan = State.PlayerClan; int num = Campaign.ClanTier(playerClan); if (playerClan != null && num + 1 < ClanTierRenown.Length) { return Math.Max(0.0, (double)ClanTierRenown[num + 1] - playerClan.Renown); } return 0.0; } public CommandResult DeveloperAddInfluence(double amount) { string text = DeveloperCampaignReason(); if (text.Length > 0) { return CommandResult.Fail(text); } Clan playerClan = State.PlayerClan; double num = ((double.IsNaN(playerClan.Influence) || double.IsInfinity(playerClan.Influence)) ? 0.0 : playerClan.Influence); double num2 = Math.Max(0.0, Math.Min(1000.0, num + amount)); if (Math.Abs(num2 - num) < 1E-09) { return CommandResult.Fail((amount >= 0.0) ? ("Your influence is already at its limit (" + 1000.0.ToString("0", CultureInfo.InvariantCulture) + ").") : "Your clan has no influence."); } playerClan.Influence = num2; return C.DeveloperDone("Developer: your clan has " + num2.ToString("0", CultureInfo.InvariantCulture) + " influence."); } public CommandResult DeveloperHealParty() { string text = DeveloperCampaignReason(); if (text.Length > 0) { return CommandResult.Fail(text); } Party playerParty = State.PlayerParty; int num = 0; int num2 = 0; foreach (string hero2 in playerParty.Troops.Heroes) { Hero hero = State.Heroes.Get(hero2); if (hero != null && hero.State == HeroState.Active && !(hero.Health >= 1.0)) { hero.Health = 1.0; num++; } } foreach (TroopStack item in playerParty.Troops.Stacks.ToList()) { if (item.Wounded > 0) { num2 += playerParty.Troops.Heal(item.UnitId, item.Wounded); } } if (num == 0 && num2 == 0) { return CommandResult.Fail("Nobody in your party is wounded."); } return C.DeveloperDone("Developer: healed " + num + " hero" + ((num == 1) ? "" : "es") + " and " + num2 + " troop" + ((num2 == 1) ? "" : "s") + "."); } public CommandResult DeveloperAddFood(double amount) { string text = DeveloperCampaignReason(); if (text.Length > 0) { return CommandResult.Fail(text); } Party playerParty = State.PlayerParty; double num = ((double.IsNaN(playerParty.Food) || double.IsInfinity(playerParty.Food)) ? 0.0 : Math.Max(0.0, playerParty.Food)); double num2 = Math.Min(100000.0, num + Math.Max(0.0, amount)); if (num2 <= num) { return CommandResult.Fail("Your party already carries the developer limit of food."); } playerParty.Food = num2; playerParty.StarvingDays = 0; return C.DeveloperDone("Developer: your party has " + num2.ToString("0", CultureInfo.InvariantCulture) + " food."); } public CommandResult DeveloperAddHorse(string breedId) { string text = DeveloperCampaignReason(); if (text.Length > 0) { return CommandResult.Fail(text); } HorseBreedDef horseBreedDef = Horses.Breed(breedId ?? ""); if (horseBreedDef == null) { return CommandResult.Fail("Unknown breed."); } C.EnsureHorseFields(); RandomStream rng = new RandomStream("developer.horse." + State.Horses.NextHorseNumber.ToString(CultureInfo.InvariantCulture), State.Random.Seed); HorseState horseState = C.CreateHorse(horseBreedDef, rng, 6.0, 0.0, "Developer tools"); horseState.Place = HorsePlace.Party; horseState.PlaceId = State.PlayerPartyId; State.Horses.Horses[horseState.Id] = horseState; return C.DeveloperDone("Developer: " + horseState.Name + ", a " + horseBreedDef.Name.ToLowerInvariant() + " " + horseState.Sex.ToString().ToLowerInvariant() + ", joined your herd."); } internal string DeveloperHorseReason(string horseId) { string text = DeveloperCampaignReason(); if (text.Length > 0) { return text; } HorseState horseState = C.Horse(horseId); if (horseState != null && horseState.Place != HorsePlace.Market) { return ""; } return "Choose one of your horses."; } public CommandResult DeveloperRestoreHorse(string horseId) { string text = DeveloperHorseReason(horseId); if (text.Length > 0) { return CommandResult.Fail(text); } HorseState horseState = C.Horse(horseId); if (horseState.Injury == HorseInjury.None && horseState.InjuryDays == 0 && horseState.Condition >= 1.0 && horseState.Fatigue <= 0.0) { return CommandResult.Fail(horseState.Name + " is already sound, fed and rested."); } horseState.Injury = HorseInjury.None; horseState.InjuryDays = 0; horseState.Condition = 1.0; horseState.Fatigue = 0.0; return C.DeveloperDone("Developer: " + horseState.Name + " is sound, fed and rested."); } public CommandResult DeveloperTrainHorse(string horseId) { string text = DeveloperHorseReason(horseId); if (text.Length > 0) { return CommandResult.Fail(text); } HorseState horseState = C.Horse(horseId); double num = Horses.TrainingThresholds[Horses.TrainingThresholds.Length - 1]; if (horseState.Experience >= num) { return CommandResult.Fail(horseState.Name + " is already " + Horses.TrainingNames[Horses.TrainingNames.Length - 1] + "."); } horseState.Experience = num; return C.DeveloperDone("Developer: " + horseState.Name + " is now " + Horses.TrainingNames[Horses.TrainingNames.Length - 1] + "."); } public List DeveloperUnits() { return Content.Units.OrderBy((UnitDef u) => u.Culture, StringComparer.Ordinal).ThenBy((UnitDef u) => u.Tier).ThenBy((UnitDef u) => u.Name, StringComparer.Ordinal) .ThenBy((UnitDef u) => u.Id, StringComparer.Ordinal) .ToList(); } public CommandResult DeveloperAddTroops(string unitId, int count) { string text = DeveloperFreeReason(); if (text.Length > 0) { return CommandResult.Fail(text); } UnitDef unitDef = C.UnitDef(unitId ?? ""); if (unitDef == null) { return CommandResult.Fail("Unknown unit."); } if (count <= 0) { return CommandResult.Fail("Choose how many to add."); } Party playerParty = State.PlayerParty; int val = 1000 - playerParty.Troops.TotalTroops; count = Math.Min(count, val); if (count <= 0) { return CommandResult.Fail("Your party already has " + 1000 + " troops, the developer limit."); } playerParty.Troops.Add(unitDef.Id, count); return C.DeveloperDone("Developer: " + count + " " + unitDef.Name + ((count == 1) ? "" : " troops") + " joined your party."); } public CommandResult DeveloperClearTroops() { string text = DeveloperFreeReason(); if (text.Length > 0) { return CommandResult.Fail(text); } Party playerParty = State.PlayerParty; int totalTroops = playerParty.Troops.TotalTroops; if (totalTroops == 0) { return CommandResult.Fail("Your party has no troops."); } playerParty.Troops.Stacks.Clear(); return C.DeveloperDone("Developer: removed all " + totalTroops + " troops from your party."); } public string DeveloperTimeReason() { string text = DeveloperCampaignReason(); if (text.Length > 0) { return text; } if (C.AwaitingHeir) { return "Choose your heir first."; } if (C.LineEnded) { return "Your line has ended."; } if (State.Player.Activity == PlayerActivity.InEncounter || !string.IsNullOrEmpty(State.Player.PendingEncounterId) || !string.IsNullOrEmpty(State.PlayerParty.EncounterId) || C.MilitaryPartyReserved(State.PlayerPartyId)) { return "Resolve the current encounter first."; } return ""; } public DeveloperSkipResult DeveloperSkipTime(int minutes, int maxSteps) { DeveloperSkipResult developerSkipResult = new DeveloperSkipResult(); string text = DeveloperTimeReason(); if (text.Length > 0) { developerSkipResult.Stopped = text; return developerSkipResult; } minutes = Math.Max(0, Math.Min(120960, minutes)); int num = Math.Min(Math.Max(0, maxSteps), (minutes + Rules.StepMinutes - 1) / Rules.StepMinutes); for (int i = 0; i < num; i++) { C.Step(); developerSkipResult.Minutes += Rules.StepMinutes; string text2 = DeveloperTimeReason(); if (text2.Length > 0) { developerSkipResult.Stopped = text2; break; } } State.Clock.PendingMinutes = 0.0; State.Touch(); return developerSkipResult; } public void DeveloperSkipFinished(int minutes, string stopped) { if (minutes > 0) { State.AddLog(LogCategory.Info, "Developer: skipped " + FormatDuration(minutes) + (string.IsNullOrEmpty(stopped) ? "" : (" (stopped early: " + stopped + ")")) + "."); State.Touch(); } } public static string FormatDuration(int minutes) { int num = minutes / 1440; int num2 = minutes % 1440 / 60; if (num <= 0) { return Math.Max(0, minutes) / 60 + " h" + ((minutes % 60 > 0) ? (" " + minutes % 60 + " min") : ""); } return num + ((num == 1) ? " day" : " days") + ((num2 > 0) ? (" " + num2 + " h") : ""); } public CommandResult DeveloperTeleport(string settlementId) { string text = DeveloperFreeReason(); if (text.Length > 0) { return CommandResult.Fail(text); } Settlement settlement = State.Settlements.Get(settlementId ?? ""); if (settlement == null) { return CommandResult.Fail("Unknown settlement."); } Party playerParty = State.PlayerParty; if (C.PlayerSiege != null) { return CommandResult.Fail("Lift your siege first."); } if (playerParty.ActiveRaid != null) { return CommandResult.Fail("Stop your raid first."); } if (playerParty.State == PartyState.InSettlement && playerParty.CurrentSettlementId == settlement.Id) { return CommandResult.Fail("You are already in " + settlement.Name + "."); } C.LeaveSettlementInternal(playerParty); C.ClearOrder(playerParty); playerParty.WaitUntilMinute = 0L; State.Player.WaitUntilMinute = 0L; playerParty.Position = settlement.Position; bool flag = C.CanEnter(playerParty, settlement); if (flag) { C.TryEnterSettlement(playerParty, settlement); } C.UpdatePlayerTimeStates(); C.UpdateVisibility(); return C.DeveloperDone("Developer: your party " + (flag ? ("is now in " + settlement.Name) : ("stands outside " + settlement.Name + ", which will not let you in")) + ".", settlement.Id); } public List DeveloperKingdoms() { string faction = State.FactionOf(State.PlayerClan); return State.Kingdoms.Where((Kingdom k) => !k.IsEliminated && k.Id != faction).OrderBy((Kingdom k) => k.Name, StringComparer.Ordinal).ToList(); } public CommandResult DeveloperSetWar(string kingdomId, bool war) { string text = DeveloperFreeReason(); if (text.Length > 0) { return CommandResult.Fail(text); } Kingdom kingdom = State.Kingdoms.Get(kingdomId ?? ""); string faction = State.FactionOf(State.PlayerClan); if (kingdom == null || kingdom.IsEliminated) { return CommandResult.Fail("Choose a living kingdom."); } if (kingdom.Id == faction) { return CommandResult.Fail("That is your own kingdom."); } if (State.AtWar(faction, kingdom.Id) == war) { return CommandResult.Fail((war ? "You are already at war with " : "You are already at peace with ") + kingdom.Name + "."); } if (C.DiplomacyFactionReserved(faction) || C.DiplomacyFactionReserved(kingdom.Id)) { return CommandResult.Fail("Resolve the involved factions' encounters first."); } if (State.Diplomacy?.Truces != null) { State.Diplomacy.Truces.RemoveAll((DiplomaticTruce t) => (t.A == faction && t.B == kingdom.Id) || (t.A == kingdom.Id && t.B == faction)); } State.SetStance(faction, kingdom.Id, war ? Stance.War : Stance.Peace); string text2 = "Developer: " + C.DiplomacyFactionName(faction) + (war ? " is now at war with " : " made peace with ") + kingdom.Name + "."; C.FinishDiplomacyChange(faction, kingdom.Id, text2); return CommandResult.Success(text2); } public CommandResult DeveloperAddCrime(string settlementId, double amount) { string text = DeveloperCampaignReason(); if (text.Length > 0) { return CommandResult.Fail(text); } Settlement settlement = State.Settlements.Get(settlementId ?? ""); if (settlement == null || settlement.OwnerClanId == State.PlayerClanId) { return CommandResult.Fail("Choose a settlement of another realm."); } string faction = C.CrimeFactionOf(settlement); C.AddCrime(faction, amount, "developer tools", settlement.Id); return CommandResult.Success("Developer: criminal rating with " + C.CrimeFactionName(faction) + " is now " + C.CrimeRating(faction).ToString("0") + " (" + Campaign.CrimeTierName(Campaign.CrimeTierOf(C.CrimeRating(faction))) + ")."); } public CommandResult DeveloperRuleKingdom(string kingdomId) { string text = DeveloperCampaignReason(); if (text.Length > 0) { return CommandResult.Fail(text); } Kingdom kingdom = State.Kingdoms.Get(kingdomId); if (kingdom == null || kingdom.IsEliminated) { return CommandResult.Fail("Choose a living kingdom."); } if (State.Kingdoms.Any((Kingdom k) => k.Id != kingdomId && !k.IsEliminated && k.RulerClanId == State.PlayerClanId)) { return CommandResult.Fail("You already rule another kingdom."); } if (C.DiplomacyFactionReserved(kingdomId) || C.DiplomacyFactionReserved(State.FactionOf(State.PlayerClan))) { return CommandResult.Fail("Wait for the battles to finish."); } Clan clan = State.PlayerClan; if (clan.KingdomId != kingdomId) { State.Stances.RemoveAll((StanceRecord s) => s.A == clan.Id || s.B == clan.Id); clan.KingdomId = kingdomId; } kingdom.RulerClanId = clan.Id; ClanServiceState clanService = State.ClanService; clanService.Kind = ClanServiceKind.Ruler; clanService.KingdomId = kingdomId; clanService.StartedDay = State.Clock.Day; clanService.LastPaidDay = State.Clock.Day; clanService.EndsDay = -1L; clan.Influence = Math.Max(clan.Influence, 100.0); C.OnDiplomacyChanged(); State.Touch(); return CommandResult.Success("Developer: you rule " + kingdom.Name + "."); } public CommandResult DeveloperCaptureLord() { string text = DeveloperCampaignReason(); if (text.Length > 0) { return CommandResult.Fail(text); } Party party = State.PlayerParty; if (party == null || party.State == PartyState.Destroyed || party.State == PartyState.Disbanded) { return CommandResult.Fail("You have no party."); } Hero hero = (from h in State.Heroes.Where(delegate(Hero h) { if (h.Occupation == HeroOccupation.Lord && h.State == HeroState.Active && h.ClanId != State.PlayerClanId && C.IsGrown(h)) { Clan clan = State.Clans.Get(h.ClanId); if (clan != null && !clan.IsBandit) { return !State.Parties.Any((Party p) => p.LeaderHeroId == h.Id && p.State != PartyState.Destroyed && p.State != PartyState.Disbanded); } } return false; }) orderby party.Prisoners.Heroes.Count + h.Name.Length * 7 % 13 select h).ThenBy((Hero h) => h.Name, StringComparer.Ordinal).FirstOrDefault(); if (hero == null) { return CommandResult.Fail("No free lord or lady to take."); } foreach (Party party2 in State.Parties) { party2.Troops.Heroes.Remove(hero.Id); } C.ClearHeroRoleAssignments(hero.Id); hero.PartyId = ""; hero.SettlementId = ""; hero.State = HeroState.Captive; hero.CaptorPartyId = party.Id; hero.CaptorSettlementId = ""; hero.CaptiveSinceMinute = State.Clock.Minute; if (!party.Prisoners.Heroes.Contains(hero.Id)) { party.Prisoners.Heroes.Add(hero.Id); } State.Touch(); return CommandResult.Success("Developer: " + hero.Name + " of " + (State.Clans.Get(hero.ClanId)?.Name ?? "no clan") + " is now your prisoner."); } public CommandResult DeveloperJailLord(string settlementId) { string text = DeveloperCampaignReason(); if (text.Length > 0) { return CommandResult.Fail(text); } Settlement s = State.Settlements.Get(settlementId ?? ""); if (s == null || (s.Type != SettlementType.Town && s.Type != SettlementType.Castle)) { return CommandResult.Fail("Choose a town or castle."); } Hero hero = State.Heroes.Where(delegate(Hero h) { if (h.Occupation == HeroOccupation.Lord && h.State == HeroState.Active && h.ClanId != State.PlayerClanId && h.ClanId != s.OwnerClanId && C.IsGrown(h)) { Clan clan = State.Clans.Get(h.ClanId); if (clan != null && !clan.IsBandit) { return !State.Parties.Any((Party p) => p.LeaderHeroId == h.Id && p.State != PartyState.Destroyed && p.State != PartyState.Disbanded); } } return false; }).OrderBy((Hero h) => h.Name, StringComparer.Ordinal).FirstOrDefault(); if (hero == null) { return CommandResult.Fail("No free lord or lady to jail."); } foreach (Party party in State.Parties) { party.Troops.Heroes.Remove(hero.Id); } C.ClearHeroRoleAssignments(hero.Id); hero.PartyId = ""; hero.SettlementId = ""; hero.State = HeroState.Captive; hero.CaptorPartyId = ""; hero.CaptorSettlementId = s.Id; hero.CaptiveSinceMinute = State.Clock.Minute; if (!s.Prisoners.Heroes.Contains(hero.Id)) { s.Prisoners.Heroes.Add(hero.Id); } State.Touch(); return CommandResult.Success("Developer: " + hero.Name + " is now held in " + s.Name + "'s dungeon."); } public List DeveloperClans() { return State.Clans.Where((Clan c) => c.Id != State.PlayerClanId && C.LivingPoliticalClan(c)).OrderBy((Clan c) => c.Name, StringComparer.Ordinal).ToList(); } public CommandResult DeveloperAdjustRelation(string clanId, int delta) { string text = DeveloperCampaignReason(); if (text.Length > 0) { return CommandResult.Fail(text); } Clan clan = State.Clans.Get(clanId ?? ""); if (clan == null || clan.Id == State.PlayerClanId || !C.LivingPoliticalClan(clan)) { return CommandResult.Fail("Choose another living noble clan."); } if (State.Politics?.Relations == null) { return CommandResult.Fail("Clan relations are unavailable."); } int num = C.ClanRelation(State.PlayerClanId, clan.Id); C.AdjustClanRelation(State.PlayerClanId, clan.Id, delta); int num2 = C.ClanRelation(State.PlayerClanId, clan.Id); if (num2 == num) { return CommandResult.Fail("Your relation with " + clan.Name + " is already " + num2 + "."); } return C.DeveloperDone("Developer: your relation with " + clan.Name + " is now " + num2 + ".", clan.Id); } } internal sealed class DiplomacyConsequencesSystem { private readonly Campaign C; private CampaignState State => C.State; internal DiplomacyConsequencesSystem(Campaign host) { C = host; } public void OnDiplomacyChanged() { C.ReconcileCouncil(); C.UpdateSieges(advanceProgress: false); C.CleanupGovernors(); foreach (Party item in State.ActiveParties.ToList()) { if (C.MilitaryPartyReserved(item.Id) || !string.IsNullOrEmpty(item.EncounterId)) { continue; } Settlement settlement = State.Settlements.Get(item.CurrentSettlementId); if (item.State == PartyState.InSettlement && settlement != null && !C.CanEnter(item, settlement)) { C.LeaveSettlementInternal(item); C.ClearOrder(item); item.WaitUntilMinute = 0L; if (item.Id == State.PlayerPartyId) { State.Player.WaitUntilMinute = 0L; C.Raise(CampaignEventKind.Warning, "War closes the gates of " + settlement.Name + ".", true, settlement.Id); } } Party party = State.Parties.Get((item.Order.Kind == OrderKind.Flee) ? item.Order.ThreatId : item.Order.TargetId); Settlement settlement2 = State.Settlements.Get(item.Order.TargetId); bool flag = party == null || party.State == PartyState.Destroyed || party.State == PartyState.Disbanded; if (((item.Order.Kind == OrderKind.Engage || item.Order.Kind == OrderKind.Flee) && (flag || !State.AreHostile(item, party))) || (item.Order.Kind == OrderKind.GoToSettlement && (settlement2 == null || !C.CanEnter(item, settlement2)))) { C.ClearOrder(item); } string text = item.ActiveRaid?.SettlementId ?? ((item.Order.Kind == OrderKind.Raid) ? item.Order.TargetId : ""); if (!string.IsNullOrEmpty(text)) { Settlement settlement3 = State.Settlements.Get(text); if (settlement3 == null || !State.AreHostile(State.Clans.Get(item.ClanId), State.Clans.Get(settlement3.OwnerClanId))) { C.CancelRaid(item, "peace ended the raid"); } } item.NextThinkMinute = Math.Min(item.NextThinkMinute, State.Clock.Minute); } foreach (WorkshopState workshop in State.Workshops) { Settlement settlement4 = State.Settlements.Get(workshop.SettlementId); Clan clan = State.Clans.Get(workshop.OwnerClanId); Clan clan2 = ((settlement4 == null) ? null : State.Clans.Get(settlement4.OwnerClanId)); if (settlement4 == null || clan == null || clan2 == null || WorkshopTypes.Get(workshop.TypeId) == null || settlement4.OwnerClanId != workshop.SettlementOwnerClanId || State.AreHostile(clan, clan2) || C.IsSettlementBesieged(settlement4)) { workshop.Status = "Suspended"; } else if (workshop.Status == "Suspended") { workshop.Status = (workshop.Enabled ? "Ready" : "Paused"); } } C.DailyContracts(); C.ReconcileMilitaryParties(); C.UpdatePlayerTimeStates(); State.Touch(); } } internal sealed class DiplomacySystem { private readonly Campaign C; private CampaignState State => C.State; private WorldDef World => C.World; internal DiplomacySystem(Campaign host) { C = host; } public void EnsureDiplomacyFields() { bool changed = false; if (State.Diplomacy == null) { State.Diplomacy = new DiplomacyState(); changed = true; } if (State.Diplomacy.Truces == null) { State.Diplomacy.Truces = new List(); changed = true; } C.EnsurePactFields(ref changed); if (!State.Diplomacy.Initialized) { State.Diplomacy.Initialized = true; State.Diplomacy.LastAiDay = State.Clock.Day; changed = true; } if (changed) { State.Touch(); } } public long TruceDaysRemaining(string a, string b) { if (string.IsNullOrEmpty(a) || string.IsNullOrEmpty(b) || a == b || State.Diplomacy?.Truces == null) { return 0L; } return (from t in State.Diplomacy.Truces where t != null && ((t.A == a && t.B == b) || (t.A == b && t.B == a)) select Math.Max(0L, t.EndsDay - State.Clock.Day)).DefaultIfEmpty(0L).Max(); } internal bool DiplomacyFactionReserved(string factionId) { if (string.IsNullOrEmpty(factionId)) { return false; } if (!State.Parties.Any((Party p) => State.FactionOfParty(p) == factionId && (p.State == PartyState.Engaged || !string.IsNullOrEmpty(p.EncounterId)))) { return State.Encounters.Any((Encounter e) => e.Phase != EncounterPhase.Committed && e.Phase != EncounterPhase.Cancelled && (FactionOfDiplomacyParty(e.InitiatorPartyId) == factionId || e.AllParties.Any((string id) => FactionOfDiplomacyParty(id) == factionId))); } return true; } internal string FactionOfDiplomacyParty(string partyId) { Party party = State.Parties.Get(partyId); if (party != null) { return State.FactionOfParty(party); } return ""; } internal bool KnownDiplomacyFaction(string factionId) { Kingdom kingdom = State.Kingdoms.Get(factionId); if (kingdom != null) { return !kingdom.IsEliminated; } Clan clan = State.Clans.Get(factionId); if (clan != null && !clan.IsEliminated && !clan.IsBandit) { return string.IsNullOrEmpty(clan.KingdomId); } return false; } internal bool InactiveDiplomacyFaction(string factionId) { Kingdom kingdom = State.Kingdoms.Get(factionId); if (kingdom != null) { return kingdom.IsEliminated; } Clan clan = State.Clans.Get(factionId); if (clan != null && !clan.IsEliminated) { return !string.IsNullOrEmpty(clan.KingdomId); } return true; } internal bool HasIndependentDiplomacyObligations() { if (State.PlayerClan == null || !string.IsNullOrEmpty(State.PlayerClan.KingdomId)) { return false; } string id = State.PlayerClanId; if (!State.Stances.Any((StanceRecord s) => s.Stance == Stance.War && ((s.A == id && KnownDiplomacyFaction(s.B)) || (s.B == id && KnownDiplomacyFaction(s.A))))) { return State.Diplomacy?.Truces?.Any((DiplomaticTruce t) => t.EndsDay > State.Clock.Day && (t.A == id || t.B == id)) == true; } return true; } internal Clan LivingDiplomacyRuler(string kingdomId) { Clan clan = C.ServiceRuler(kingdomId); Hero hero = ((clan == null) ? null : State.Heroes.Get(clan.LeaderHeroId)); if (hero != null && hero.State != HeroState.Dead && hero.State != HeroState.Inactive && !(hero.ClanId != clan.Id)) { return clan; } return null; } internal string PlayerDiplomacyReason(string targetKingdomId) { if (State.PlayerParty == null) { return "Your party is unavailable."; } string text = C.CargoCommandReason(); if (text.Length > 0) { return text; } Clan playerClan = State.PlayerClan; ClanServiceState clanService = State.ClanService; if (playerClan.IsBandit || playerClan.IsEliminated || playerClan.LeaderHeroId != State.PlayerHeroId || State.PlayerHero.ClanId != playerClan.Id) { return "Only your clan leader can negotiate, and they have to be free and here."; } if (clanService == null || !clanService.Initialized || State.Diplomacy == null || !State.Diplomacy.Initialized) { return "Diplomacy is unavailable."; } bool num = clanService.Kind == ClanServiceKind.Independent && string.IsNullOrEmpty(playerClan.KingdomId) && string.IsNullOrEmpty(clanService.KingdomId); bool flag = clanService.Kind == ClanServiceKind.Ruler && clanService.KingdomId == playerClan.KingdomId && LivingDiplomacyRuler(playerClan.KingdomId)?.Id == playerClan.Id; if (!num && !flag) { return "Your ruler decides war and peace."; } if (LivingDiplomacyRuler(targetKingdomId) == null) { return "This kingdom has no living ruler."; } string text2 = State.FactionOf(playerClan); if (text2 == targetKingdomId) { return "You can't negotiate against your own kingdom."; } if (!string.IsNullOrEmpty(State.Player.PendingEncounterId) || DiplomacyFactionReserved(text2) || DiplomacyFactionReserved(targetKingdomId)) { return "Wait for the fighting involving these factions to finish."; } return ""; } public string DeclareKingdomWarReason(string targetKingdomId) { string text = PlayerDiplomacyReason(targetKingdomId); if (text.Length > 0) { return text; } string text2 = State.FactionOf(State.PlayerClan); if (State.AtWar(text2, targetKingdomId)) { return "You are already at war with this kingdom."; } if (C.Allied(text2, targetKingdomId)) { return "You're allies. End the alliance before going to war."; } long num = TruceDaysRemaining(text2, targetKingdomId); if (num <= 0) { return ""; } return "The truce lasts another " + num + " days."; } public CommandResult DeclareKingdomWar(string targetKingdomId) { string text = DeclareKingdomWarReason(targetKingdomId); if (text.Length > 0) { return CommandResult.Fail(text); } string text2 = State.FactionOf(State.PlayerClan); RemoveExpiredPairTruces(text2, targetKingdomId); State.SetStance(text2, targetKingdomId, Stance.War); string text3 = DiplomacyFactionName(text2) + " declared war on " + DiplomacyFactionName(targetKingdomId) + "."; FinishDiplomacyChange(text2, targetKingdomId, text3); C.TrainDiplomacy(60.0); return CommandResult.Success(text3); } public TradeQuote QuoteKingdomPeace(string targetKingdomId) { TradeQuote tradeQuote = new TradeQuote { Total = 1000L, Reason = PlayerDiplomacyReason(targetKingdomId) }; if (!tradeQuote.Ok) { return tradeQuote; } if (!State.AtWar(State.FactionOf(State.PlayerClan), targetKingdomId)) { tradeQuote.Reason = "You are already at peace with this kingdom."; } else if (State.PlayerClan.Gold < 1000) { tradeQuote.Reason = "Your clan needs " + 1000L + " denars to secure peace."; } else { Clan clan = LivingDiplomacyRuler(targetKingdomId); if (clan.Gold < 0 || clan.Gold > 9223372036854774807L) { tradeQuote.Reason = "Their ruler can't take the payment."; } else if (State.Clock.Day > 9223372036854775800L) { tradeQuote.Reason = "A truce cannot be recorded at this date."; } } return tradeQuote; } public CommandResult MakeKingdomPeace(string targetKingdomId) { TradeQuote tradeQuote = QuoteKingdomPeace(targetKingdomId); if (!tradeQuote.Ok) { return CommandResult.Fail(tradeQuote.Reason); } Clan clan = LivingDiplomacyRuler(targetKingdomId); string text = State.FactionOf(State.PlayerClan); string text2 = DiplomacyFactionName(text) + " paid " + 1000L + " denars to " + clan.Name + " for peace with " + DiplomacyFactionName(targetKingdomId) + "; a " + 7 + "-day truce was signed."; State.Transact(State.PlayerClan, -1000L, LedgerAccount.Other, text2); State.Transact(clan, 1000L, LedgerAccount.Other, text2); State.SetStance(text, targetKingdomId, Stance.Peace); AddDiplomacyTruce(text, targetKingdomId, State.PlayerClanId, clan.Id, 1000L); FinishDiplomacyChange(text, targetKingdomId, text2); C.TrainDiplomacy(80.0); return CommandResult.Success(text2); } internal void AddDiplomacyTruce(string a, string b, string payer = "", string recipient = "", long payment = 0L) { State.Diplomacy.Truces.RemoveAll((DiplomaticTruce t) => (t.A == a && t.B == b) || (t.A == b && t.B == a)); State.Diplomacy.Truces.Add(new DiplomaticTruce { A = ((string.CompareOrdinal(a, b) < 0) ? a : b), B = ((string.CompareOrdinal(a, b) < 0) ? b : a), SignedDay = State.Clock.Day, EndsDay = State.Clock.Day + 7, PayerClanId = payer, RecipientClanId = recipient, Payment = payment }); SortDiplomacyTruces(); } internal void SortDiplomacyTruces() { State.Diplomacy.Truces.Sort((DiplomaticTruce a, DiplomaticTruce b) => (string.CompareOrdinal(a.A, b.A) == 0) ? string.CompareOrdinal(a.B, b.B) : string.CompareOrdinal(a.A, b.A)); } internal string DiplomacyFactionName(string id) { return State.Kingdoms.Get(id)?.Name ?? State.Clans.Get(id)?.Name ?? id; } internal void FinishDiplomacyChange(string a, string b, string message) { State.AddLog(LogCategory.Politics, message, a, b); C.OnDiplomacyChanged(); string text = State.FactionOf(State.PlayerClan); C.Raise((text == a || text == b) ? CampaignEventKind.Warning : CampaignEventKind.Info, message, text == a || text == b, a, b); State.Touch(); } internal void RemoveExpiredPairTruces(string a, string b) { foreach (DiplomaticTruce item in State.Diplomacy.Truces.Where((DiplomaticTruce t) => t.EndsDay <= State.Clock.Day && ((t.A == a && t.B == b) || (t.A == b && t.B == a))).ToList()) { State.Diplomacy.Truces.Remove(item); State.AddLog(LogCategory.Politics, "The truce between " + DiplomacyFactionName(item.A) + " and " + DiplomacyFactionName(item.B) + " expired. Peace continues until war is declared.", item.A, item.B); } } internal void MigrateIndependentDiplomacy(string oldFactionId, string newFactionId) { foreach (StanceRecord item in State.Stances.Where((StanceRecord s) => s.A == oldFactionId || s.B == oldFactionId).ToList()) { string text = ((item.A == oldFactionId) ? item.B : item.A); State.Stances.Remove(item); if (!(text == newFactionId)) { StanceRecord stanceRecord = State.FindStance(newFactionId, text); if (stanceRecord != null) { State.Stances.Remove(stanceRecord); } StanceRecord stanceRecord2 = ((stanceRecord != null && ((stanceRecord.Stance == Stance.War && item.Stance != Stance.War) || (stanceRecord.Stance == item.Stance && stanceRecord.SinceMinute < item.SinceMinute))) ? stanceRecord : item); stanceRecord2.A = ((string.CompareOrdinal(newFactionId, text) < 0) ? newFactionId : text); stanceRecord2.B = ((string.CompareOrdinal(newFactionId, text) < 0) ? text : newFactionId); State.Stances.Add(stanceRecord2); } } foreach (DiplomaticTruce item2 in State.Diplomacy.Truces.Where((DiplomaticTruce t) => t.A == oldFactionId || t.B == oldFactionId).ToList()) { string text2 = ((item2.A == oldFactionId) ? item2.B : item2.A); if (text2 == newFactionId) { State.Diplomacy.Truces.Remove(item2); continue; } item2.A = ((string.CompareOrdinal(newFactionId, text2) < 0) ? newFactionId : text2); item2.B = ((string.CompareOrdinal(newFactionId, text2) < 0) ? text2 : newFactionId); } SortDiplomacyTruces(); } public double KingdomMilitaryStrength(string kingdomId) { if (C.ServiceRuler(kingdomId) == null) { return 0.0; } double num = State.ActiveParties.Where(delegate(Party p) { if ((p.Kind == PartyKind.Lord || p.Kind == PartyKind.Player) && State.FactionOfParty(p) == kingdomId) { Clan clan = State.Clans.Get(p.ClanId); if (clan == null) { return false; } return !clan.IsEliminated; } return false; }).Sum((Func)C.PartyStrength); foreach (Settlement item in State.Settlements.Where(delegate(Settlement s) { if ((s.Type == SettlementType.Town || s.Type == SettlementType.Castle) && State.Clans.Get(s.OwnerClanId)?.KingdomId == kingdomId) { Clan clan = State.Clans.Get(s.OwnerClanId); if (clan == null) { return false; } return !clan.IsEliminated; } return false; })) { num += item.Garrison.Stacks.Sum((TroopStack s) => (double)s.Healthy * C.UnitPower(s.UnitId)); num += item.Garrison.Heroes.Sum((string id) => C.HeroPower(State.Heroes.Get(id))); } return Math.Max(0.0, num); } internal bool DiplomacyFrontier(string a, string b) { HashSet known = new HashSet(World.Locations.Select((LocationDef l) => l.Id), StringComparer.Ordinal); List holdings = State.Settlements.Where(delegate(Settlement s) { if (known.Contains(s.Id) && (s.Type == SettlementType.Town || s.Type == SettlementType.Castle)) { Clan clan = State.Clans.Get(s.OwnerClanId); if (clan == null) { return false; } return !clan.IsEliminated; } return false; }).ToList(); return holdings.Where((Settlement s) => State.Clans.Get(s.OwnerClanId)?.KingdomId == a).Any((Settlement left) => holdings.Any((Settlement right) => State.Clans.Get(right.OwnerClanId)?.KingdomId == b && Vec2.Distance(left.Position, right.Position) <= C.StrategicRange(20.0))); } public void DailyDiplomacy() { if (State.Diplomacy == null || !State.Diplomacy.Initialized) { return; } bool flag = false; foreach (DiplomaticTruce item in State.Diplomacy.Truces.ToList()) { if (!DiplomacyFactionReserved(item.A) && !DiplomacyFactionReserved(item.B)) { if (!KnownDiplomacyFaction(item.A) || !KnownDiplomacyFaction(item.B)) { State.Diplomacy.Truces.Remove(item); State.AddLog(LogCategory.Politics, "The agreement between " + DiplomacyFactionName(item.A) + " and " + DiplomacyFactionName(item.B) + " ended: a faction is gone.", item.A, item.B); flag = true; } else if (item.EndsDay <= State.Clock.Day) { RemoveExpiredPairTruces(item.A, item.B); flag = true; } } } foreach (StanceRecord item2 in State.Stances.Where((StanceRecord s) => s.Stance == Stance.War && (InactiveDiplomacyFaction(s.A) || InactiveDiplomacyFaction(s.B))).ToList()) { if (!DiplomacyFactionReserved(item2.A) && !DiplomacyFactionReserved(item2.B)) { State.SetStance(item2.A, item2.B, Stance.Peace); FinishDiplomacyChange(item2.A, item2.B, "The war between " + DiplomacyFactionName(item2.A) + " and " + DiplomacyFactionName(item2.B) + " ended: a faction is gone."); } } if (flag) { State.Touch(); } C.DailyPacts(); C.DailyElections(); if (State.Clock.Day - State.Diplomacy.LastAiDay < 7) { return; } State.Diplomacy.LastAiDay = State.Clock.Day; State.Touch(); List list = State.Kingdoms.Where((Kingdom k) => LivingDiplomacyRuler(k.Id) != null && k.RulerClanId != State.PlayerClanId).OrderBy((Kingdom k) => k.Id, StringComparer.Ordinal).ToList(); for (int num = 0; num < list.Count; num++) { for (int num2 = num + 1; num2 < list.Count; num2++) { string id = list[num].Id; string id2 = list[num2].Id; StanceRecord stanceRecord = State.FindStance(id, id2); if (stanceRecord != null && stanceRecord.Stance == Stance.War && State.Clock.Minute - stanceRecord.SinceMinute >= 30240 && !DiplomacyFactionReserved(id) && !DiplomacyFactionReserved(id2) && !C.CouncilDiplomacyPending(id, id2)) { double num3 = C.WarAdvantage(id, id2); if (Math.Abs(num3) >= 0.25) { C.MakeNegotiatedPeace(id, id2, (num3 > 0.0) ? id2 : id, C.TributeFor(num3)); return; } State.SetStance(id, id2, Stance.Peace); AddDiplomacyTruce(id, id2, "", "", 0L); FinishDiplomacyChange(id, id2, list[num].Name + " and " + list[num2].Name + " agreed to white peace after a long war; a " + 7 + "-day truce was signed. No payment changed hands."); return; } } } for (int num4 = 0; num4 < list.Count; num4++) { for (int num5 = num4 + 1; num5 < list.Count; num5++) { string id3 = list[num4].Id; string id4 = list[num5].Id; StanceRecord stanceRecord2 = State.FindStance(id3, id4); if ((stanceRecord2 == null || stanceRecord2.Stance != Stance.War) && State.Clock.Minute - (stanceRecord2?.SinceMinute ?? 0) >= 20160 && TruceDaysRemaining(id3, id4) <= 0 && !DiplomacyFactionReserved(id3) && !DiplomacyFactionReserved(id4) && !C.CouncilDiplomacyPending(id3, id4) && DiplomacyFrontier(id3, id4) && !C.Allied(id3, id4) && C.TributeBetween(id3, id4) == null) { double num6 = KingdomMilitaryStrength(id3); double num7 = KingdomMilitaryStrength(id4); if (!(num6 <= 0.0) && !(num7 <= 0.0) && !(Math.Max(num6, num7) < Math.Min(num6, num7) * 1.25)) { string id5 = ((num6 >= num7) ? id3 : id4); string id6 = ((num6 >= num7) ? id4 : id3); State.SetStance(id3, id4, Stance.War); FinishDiplomacyChange(id3, id4, DiplomacyFactionName(id5) + " declared war on " + DiplomacyFactionName(id6) + " after building a military advantage along their frontier."); return; } } } } } } internal sealed class DiscoveriesSystem { private readonly Campaign C; private NavGrid Nav => C.Nav; private static string[][] SiteNames => Campaign.SiteNames; private static string[] SiteSights => Campaign.SiteSights; private CampaignState State => C.State; public string SiteHereId => SiteHere()?.Id ?? ""; internal DiscoveriesSystem(Campaign host) { C = host; } internal void PlaceDiscoverySites() { List sites = State.Quests.Sites; if (sites.Any((DiscoverySite s) => string.IsNullOrEmpty(s.QuestId))) { return; } List list = State.Settlements.Where((Settlement s) => s.Type != SettlementType.Hideout).ToList(); if (list.Count == 0 || Nav == null) { return; } RandomStream randomStream = new RandomStream("discoveries.place", State.Random.Seed); int num = Math.Max(4, Math.Min(18, list.Count / 8)); HashSet used = new HashSet(StringComparer.Ordinal); double gap = Math.Max(10.0, Math.Sqrt(Nav.WorldWidth * Nav.WorldHeight / ((double)num * 3.0))); int num2 = 0; int num3 = 0; while (num2 < num && num3 < num * 200) { Vec2 p = new Vec2(1.0 + randomStream.NextDouble() * (Nav.WorldWidth - 2.0), 1.0 + randomStream.NextDouble() * (Nav.WorldHeight - 2.0)); if (Nav.IsPassable(p)) { Settlement settlement = list.OrderBy((Settlement s) => Vec2.Distance(s.Position, p)).ThenBy((Settlement s) => s.Id, StringComparer.Ordinal).First(); double num4 = Vec2.Distance(settlement.Position, p); if (!(num4 < 4.0) && !(num4 > gap * 1.5) && Nav.SameComponent(p, settlement.Position) && !sites.Any((DiscoverySite s) => Vec2.Distance(s.Position, p) < gap)) { SiteKind siteKind = (SiteKind)randomStream.Range(0, SiteNames.Length); List list2 = SiteNames[(int)siteKind].Where((string x) => !used.Contains(x)).ToList(); string text = ((list2.Count > 0) ? list2[randomStream.Range(0, list2.Count)] : (SiteNames[(int)siteKind][0] + " near " + settlement.Name)); used.Add(text); DiscoverySite discoverySite = new DiscoverySite(); int num5 = ++num2; discoverySite.Id = "site." + num5.ToString(CultureInfo.InvariantCulture); discoverySite.Kind = siteKind; discoverySite.Name = Campaign.Cap(text); discoverySite.Position = p; discoverySite.RegionSettlementId = settlement.Id; sites.Add(discoverySite); } } num3++; } } public static string SiteKindName(SiteKind kind) { return kind switch { SiteKind.Ruins => "Ruins", SiteKind.Battlefield => "Old battlefield", SiteKind.Shrine => "Shrine", SiteKind.Wreck => "Wreck", SiteKind.Cave => "Cave", SiteKind.Camp => "Abandoned camp", SiteKind.Barrow => "Barrow", _ => "Tower", }; } public List KnownSites() { return (State.Quests?.Sites ?? new List()).Where((DiscoverySite s) => s.Found && (string.IsNullOrEmpty(s.QuestId) || QuestSiteLive(s))).OrderBy((DiscoverySite s) => s.Id, StringComparer.Ordinal).ToList(); } internal bool QuestSiteLive(DiscoverySite s) { QuestState questState = C.Quest(s.QuestId); if (questState != null) { if (questState.Status != QuestStatus.Active) { return s.Explored; } return true; } return false; } public DiscoverySite Site(string id) { return State.Quests?.Sites?.FirstOrDefault((DiscoverySite s) => s.Id == id); } internal DiscoverySite SiteHere() { Party p = State.PlayerParty; if (p == null || p.State != PartyState.Active || State.Quests?.Sites == null) { return null; } return (from s in State.Quests.Sites where s.Found && Vec2.Distance(s.Position, p.Position) <= 1.6 && (string.IsNullOrEmpty(s.QuestId) || QuestSiteLive(s)) orderby Vec2.Distance(s.Position, p.Position) select s).ThenBy((DiscoverySite s) => s.Id, StringComparer.Ordinal).FirstOrDefault(); } internal void HourlyDiscoveries() { Party p = State.PlayerParty; if (p == null || p.State != PartyState.Active || State.Player.Activity == PlayerActivity.Captive) { return; } List list = State.Quests.Sites.Where((DiscoverySite s) => !s.Found && string.IsNullOrEmpty(s.QuestId)).ToList(); if (list.Count == 0) { return; } double reach = Math.Max(2.0, C.SightRange(p) * 0.6); int num = Math.Max(C.Skill("scouting"), (int)Math.Round((double)C.RoleSkill(p, PartyRole.Scout))); foreach (DiscoverySite item in list.Where((DiscoverySite x) => Vec2.Distance(x.Position, p.Position) <= reach).OrderBy((DiscoverySite x) => x.Id, StringComparer.Ordinal)) { if (State.Random.Get("discoveries").Chance(Math.Min(0.9, 0.3 + (double)num / 300.0))) { item.Found = true; item.FoundMinute = State.Clock.Minute; C.GrantSkillExperience(State.PlayerHero, "scouting", 15.0); string text = "Your scouts found " + item.Name + " (" + SiteKindName(item.Kind).ToLowerInvariant() + "). It is marked on your map."; State.AddLog(LogCategory.Travel, text, item.RegionSettlementId); C.Raise(CampaignEventKind.Info, text, false, "site:" + item.Id); State.Touch(); } } } internal int BestScout() { return Math.Max(C.Skill("scouting"), (int)Math.Round((double)C.RoleSkill(State.PlayerParty, PartyRole.Scout))); } public StoryPrompt SitePrompt(string siteId) { DiscoverySite discoverySite = Site(siteId); if (discoverySite == null || !discoverySite.Found) { return null; } if (!string.IsNullOrEmpty(discoverySite.LegendPlace)) { return C.LegendSitePrompt(discoverySite); } if (!string.IsNullOrEmpty(discoverySite.QuestId)) { QuestState questState = C.Quest(discoverySite.QuestId); if (questState != null && questState.Status == QuestStatus.Active && !(SiteHere()?.Id != discoverySite.Id)) { return C.QuestPrompt(questState.Id); } return null; } StoryPrompt storyPrompt = new StoryPrompt { Kind = "site", SubjectId = discoverySite.Id, Title = discoverySite.Name, SpeakerRole = SiteKindName(discoverySite.Kind) }; if (discoverySite.Explored) { storyPrompt.Lines.Add("You have been here before. " + discoverySite.Outcome); storyPrompt.Options.Add(new StoryOption { Id = "leave", Text = "Move on." }); return storyPrompt; } storyPrompt.Lines.Add(SiteSights[(int)discoverySite.Kind]); string text = ((SiteHere()?.Id == discoverySite.Id) ? "" : ("Travel to " + discoverySite.Name + " first.")); string text2 = ((text.Length > 0) ? text : C.QuestActionReason()); storyPrompt.Options.Add(new StoryOption { Id = "search", Text = "Search it carefully. (6 hours)", Reason = text2, Hint = "Your party waits here while you search." }); storyPrompt.Options.Add(new StoryOption { Id = "scouts", Text = "Send scouts in first. (3 hours)", Reason = ((text2.Length > 0) ? text2 : ((BestScout() < 30) ? "You need someone with 30 Scouting (you or your scout)." : "")), Hint = "Quicker and safer; Scouting finds more." }); storyPrompt.Options.Add(new StoryOption { Id = "leave", Text = "Leave it be." }); return storyPrompt; } public CommandResult ExploreSite(string siteId, string option) { DiscoverySite discoverySite = Site(siteId); StoryPrompt storyPrompt = SitePrompt(siteId); if (discoverySite == null || storyPrompt == null) { return CommandResult.Fail("There is nothing to explore here."); } if (!string.IsNullOrEmpty(discoverySite.QuestId)) { return C.ChooseQuestOption(discoverySite.QuestId, option); } if (!string.IsNullOrEmpty(discoverySite.LegendPlace)) { return C.ChooseLegendSite(discoverySite, storyPrompt, option); } StoryOption storyOption = storyPrompt.Options.FirstOrDefault((StoryOption x) => x.Id == option); if (storyOption == null) { return CommandResult.Fail("That choice is not open."); } if (!storyOption.Enabled) { return CommandResult.Fail(storyOption.Reason); } if (option == "leave") { return CommandResult.Success(); } bool flag = option == "scouts"; CommandResult commandResult = C.Wait(flag ? 3 : 6); if (!commandResult.Ok) { return commandResult; } RandomStream rng = new RandomStream("site|" + discoverySite.Id, State.Random.Seed); string text = ExploreOutcome(discoverySite, flag, rng); discoverySite.Explored = true; discoverySite.ExploredMinute = State.Clock.Minute; discoverySite.Outcome = text; State.AddLog(LogCategory.Travel, discoverySite.Name + ": " + text, discoverySite.RegionSettlementId); State.Touch(); return CommandResult.Success(text); } internal string ExploreOutcome(DiscoverySite s, bool scouts, RandomStream rng) { Party playerParty = State.PlayerParty; int num = BestScout(); double probability = (scouts ? 0.06 : 0.18); C.GrantSkillExperience(State.PlayerHero, "scouting", scouts ? 40 : 25); if (rng.Chance(probability)) { string[] array = new string[5] { "Tomb robbers", "Wreckers", "Cave trolls (bandits in big hats)", "Squatters", "Grave wardens" }; Party party = C.SpawnQuestBand(s.Position, array[rng.Range(0, array.Length)] + " of " + s.Name, rng.Range(7, 12), null, rng); if (party != null) { party.Position = C.QuestSpotNear(playerParty.Position, 0.6, 1.2, rng); party.NextThinkMinute = State.Clock.Minute; C.Raise(CampaignEventKind.Warning, party.Name + " burst out of " + s.Name + "!", true, party.Id); return "An ambush! " + party.Name + " were waiting."; } } double num2 = rng.NextDouble() - (double)num / 1000.0; Settlement settlement = State.Settlements.Get(s.RegionSettlementId); bool flag = s.Kind == SiteKind.Battlefield || s.Kind == SiteKind.Camp || s.Kind == SiteKind.Barrow || s.Kind == SiteKind.Tower; if (num2 < 0.08) { string[] array2 = new string[5] { "the Rusty Wonder", "Old Faithful", "the Ancestor's Edge", "the Stonebiter", "the Lucky Blade" }; string text = C.GiveRelicWeapon(array2[rng.Range(0, array2.Length)], rng); State.PlayerClan.Renown += 3.0; return "Wrapped in oilcloth in the deepest corner: " + text + ". It is in your bag."; } if (flag && num2 < 0.2) { UnitDef unitDef = C.CultureSoldier(settlement?.CultureId ?? "", 5, rare: true) ?? C.CultureSoldier(settlement?.CultureId ?? "", 5, rare: false); int num3 = ((unitDef != null) ? C.JoinPlayer(unitDef.Id, rng.Range(2, 4)) : 0); if (num3 > 0) { return num3 + " " + unitDef.Name + ((num3 == 1) ? "" : "s") + " living rough among the ruins ask to join you. They do."; } } if (num2 < 0.45) { long amount = Campaign.Round10(150 + rng.Range(0, 350) + num); State.Transact(State.PlayerClan, amount, LedgerAccount.Discovery, "Found at " + s.Name); return "A buried pot of old coins: " + amount + " denars."; } if (num2 < 0.65) { string[] array3 = new string[5] { "good.silver", "good.ore", "good.velvet", "good.jewelry", "good.wine" }; TradeGoodDef tradeGoodDef = TradeGoods.Get(array3[rng.Range(0, array3.Length)]) ?? TradeGoods.Get("good.silver"); int val = rng.Range(2, 6); int val2 = (int)Math.Floor((C.CargoCapacity(playerParty) - C.CargoWeight(playerParty)) / Math.Max(0.1, tradeGoodDef.Weight)); int num4 = Math.Min(val, val2); if (num4 <= 0) { return "A cache of " + tradeGoodDef.Name.ToLowerInvariant() + ", but you have no room to carry any."; } playerParty.Cargo[tradeGoodDef.Id] = C.CargoCount(playerParty, tradeGoodDef.Id) + num4; return "A forgotten cache: " + num4 + " " + tradeGoodDef.Name.ToLowerInvariant() + ". It is in your cargo."; } if (num2 < 0.9) { string text2 = ((s.Kind == SiteKind.Battlefield) ? "tactics" : ((s.Kind == SiteKind.Tower || s.Kind == SiteKind.Ruins) ? "engineering" : ((s.Kind == SiteKind.Shrine) ? "medicine" : "scouting"))); C.GrantSkillExperience(State.PlayerHero, text2, 100.0); State.PlayerClan.Renown += 2.0; string[] array4 = new string[4] { "Old carvings tell of a great battle; you learn much from them.", "Scratched notes on the walls, by someone who knew their trade.", "A faded mural of a siege, in loving detail.", "A hermit's journal, mostly about soup, partly about war." }; return array4[rng.Range(0, array4.Length)] + " (" + Campaign.Cap(text2) + " experience, renown +2)"; } return "Dust, cobwebs and an angry badger. Nothing else."; } } internal sealed class EconomySystem { private readonly Campaign C; public const double MinimumTradeSpread = 0.04; private CampaignState State => C.State; internal EconomySystem(Campaign host) { C = host; } public void EnsureEconomyFields() { bool flag = false; foreach (Party party in State.Parties) { if (party.Cargo == null) { party.Cargo = new SortedDictionary(StringComparer.Ordinal); flag = true; } } foreach (Settlement settlement in State.Settlements) { if (settlement.Market == null) { settlement.Market = new MarketState(); flag = true; } if (settlement.Market.Stock == null) { settlement.Market.Stock = new SortedDictionary(StringComparer.Ordinal); flag = true; } if (settlement.Type == SettlementType.Hideout) { continue; } if (settlement.Market.Initialized) { if (!settlement.Market.ExpandedGoods) { StockExpandedGoods(settlement); settlement.Market.ExpandedGoods = true; flag = true; } continue; } settlement.Market.Initialized = true; settlement.Market.ExpandedGoods = true; settlement.Market.LastDay = State.Clock.Day; settlement.Market.Gold = ((settlement.Type == SettlementType.Town) ? 2500 : ((settlement.Type == SettlementType.Village) ? 1200 : 500)); foreach (TradeGoodDef item in TabsBannerlord.Core.Content.TradeGoods.All.Where((TradeGoodDef g) => TabsBannerlord.Core.Content.TradeGoods.IsOriginal(g.Id))) { bool flag2 = item.Id == "good.timber" || item.Id == "good.ore" || item.Id == "good.wool"; settlement.Market.Stock[item.Id] = ((settlement.Type == SettlementType.Village) ? ((item.Id == PrimaryVillageGood(settlement)) ? 80 : (flag2 ? 12 : 8)) : ((settlement.Type == SettlementType.Town) ? (flag2 ? 30 : 24) : 8)); } StockExpandedGoods(settlement); flag = true; } if (C.EnsureSettlementFood()) { flag = true; } if (flag) { State.Touch(); } } internal void StockExpandedGoods(Settlement s) { HashSet hashSet = ((s.Type == SettlementType.Town) ? new HashSet(C.BoundVillages(s).Select(PrimaryVillageGood), StringComparer.Ordinal) : null); foreach (TradeGoodDef item in TabsBannerlord.Core.Content.TradeGoods.All.Where((TradeGoodDef g) => !TabsBannerlord.Core.Content.TradeGoods.IsOriginal(g.Id))) { int num = ((s.Type != SettlementType.Village) ? ((s.Type == SettlementType.Town) ? (hashSet.Contains(item.Id) ? 20 : 4) : 0) : ((item.Id == PrimaryVillageGood(s)) ? 80 : 0)); if (num > 0 && MarketStock(s, item.Id) < num) { s.Market.Stock[item.Id] = num; } } } public string PrimaryVillageGood(Settlement s) { if (!string.IsNullOrEmpty(s?.Product) && VillageProducts.Get(s.Product) != null) { return s.Product; } return (new string[3] { "good.timber", "good.ore", "good.wool" })[(uint)(StableHash.Fnv1a64(s?.Id ?? "") % 3)]; } public int CargoCount(Party p, string goodId) { if (p?.Cargo == null || goodId == null || !p.Cargo.TryGetValue(goodId, out var value)) { return 0; } return Math.Max(0, value); } public double CargoWeight(Party p) { return TabsBannerlord.Core.Content.TradeGoods.All.Sum((TradeGoodDef g) => (double)CargoCount(p, g.Id) * g.Weight) + C.EquipmentWeight(p); } public double CargoCapacity(Party p) { if (p != null) { return (((p.Id == State.PlayerPartyId) ? 50.0 : 40.0) + 2.0 * (double)p.Troops.TotalTroops + 10.0 * (double)p.Troops.Heroes.Count + C.HorseCargoCapacity(p)) * (1.0 + Math.Max(0.0, C.PartyPerk(p, PerkEffect.Cargo))); } return 0.0; } public int MarketStock(Settlement s, string goodId) { if (s?.Market?.Stock == null || goodId == null || !s.Market.Stock.TryGetValue(goodId, out var value)) { return 0; } return Math.Max(0, value); } public static double TradeRate(bool buying, int tradeSkill, double haggle = 0.0) { double num = (double)Math.Max(0, Math.Min(300, tradeSkill)) / 300.0; double num2 = 1.1 - 0.08 * num; double num3 = 0.8 + 0.12 * num; haggle = (double.IsNaN(haggle) ? 0.0 : Math.Max(0.0, Math.Min(0.25, haggle))); if (haggle > 0.0) { double num4 = num2 - haggle; double num5 = num3 + haggle; if (num4 - num5 < 0.04) { double num6 = (num2 + num3) / 2.0; num4 = num6 + 0.02; num5 = num6 - 0.02; } num2 = Math.Max(num2 - haggle, Math.Min(num2, num4)); num3 = Math.Min(num3 + haggle, Math.Max(num3, num5)); } if (!buying) { return num3; } return num2; } public double PlayerHaggle() { return Math.Max(0.0, Math.Min(0.25, C.PersonalPerk(State.PlayerHero, PerkEffect.TradePrices))); } public int PlayerTradeSkill() { return Math.Max(0, Math.Min(300, State.PlayerHero?.Skill("trade") ?? 0)); } internal long TakePlayerCargoCost(string goodId, int count, int held) { SortedDictionary playerCargoCosts = State.PlayerCargoCosts; if (playerCargoCosts == null || !playerCargoCosts.TryGetValue(goodId, out var value)) { return 0L; } value = Math.Max(0L, value); long num = ((count >= held) ? value : ((long)decimal.Floor((decimal)value * (decimal)count / (decimal)Math.Max(1, held)))); if (count >= held || value - num <= 0) { playerCargoCosts.Remove(goodId); } else { playerCargoCosts[goodId] = value - num; } return num; } internal void AddPlayerCargoCost(string goodId, int heldBefore, long paid) { if (State.PlayerCargoCosts == null) { State.PlayerCargoCosts = new SortedDictionary(StringComparer.Ordinal); } SortedDictionary playerCargoCosts = State.PlayerCargoCosts; long value; long num = ((heldBefore > 0 && playerCargoCosts.TryGetValue(goodId, out value)) ? Math.Max(0L, value) : 0); playerCargoCosts[goodId] = ((num > long.MaxValue - paid) ? long.MaxValue : (num + paid)); } public long CommodityPrice(Settlement s, string goodId, bool buying, int stock, int tradeSkill = 0, double haggle = 0.0) { TradeGoodDef tradeGoodDef = TabsBannerlord.Core.Content.TradeGoods.All.FirstOrDefault((TradeGoodDef g) => g.Id == goodId); if (s == null || tradeGoodDef == null) { return 0L; } bool flag = s.Type == SettlementType.Village && goodId == PrimaryVillageGood(s); double num = (flag ? 50 : 40); double num2 = Math.Max(0.55, Math.Min(2.5, num / Math.Max(10.0, stock))); double num3 = (double)tradeGoodDef.BasePrice * num2 * (flag ? 0.85 : 1.0) * TradeRate(buying, tradeSkill, haggle); return Math.Max(1L, (long)(buying ? Math.Ceiling(num3) : Math.Floor(num3))); } internal string CargoCommandReason() { CommandResult commandResult = C.RequireFree(); if (!commandResult.Ok) { return commandResult.Message; } Party playerParty = State.PlayerParty; Hero playerHero = State.PlayerHero; if (playerParty.State != PartyState.Active && playerParty.State != PartyState.InSettlement) { return "Can't manage cargo right now."; } if (State.PlayerClan == null || playerParty.ClanId != State.PlayerClanId) { return "Your party has no valid clan."; } if (playerHero == null || playerHero.State != HeroState.Active || !Campaign.IsPresentPartyHero(playerParty, playerHero)) { return "You have to be with the party to manage cargo."; } return ""; } public string MarketAccessReason() { string text = C.DisguiseBlockReason(); if (text.Length > 0) { return text; } string text2 = CargoCommandReason(); if (text2.Length > 0) { return text2; } Party playerParty = State.PlayerParty; Settlement settlement = C.CurrentSettlement(); if (settlement == null || (settlement.Type != SettlementType.Town && settlement.Type != SettlementType.Village) || Vec2.Distance(playerParty.Position, settlement.Position) > 0.01 || !C.CanEnter(playerParty, settlement)) { return "Find a friendly town or village market."; } if (settlement.Market == null || !settlement.Market.Initialized || settlement.Market.Stock == null || playerParty.Cargo == null) { return "This market is unavailable."; } return ""; } public TradeQuote QuoteTrade(string goodId, int count, bool buying) { TradeQuote tradeQuote = new TradeQuote { Reason = MarketAccessReason() }; if (!tradeQuote.Ok) { return tradeQuote; } if (count < 1 || count > 1000) { tradeQuote.Reason = "Choose between 1 and 1000 goods."; return tradeQuote; } TradeGoodDef tradeGoodDef = TabsBannerlord.Core.Content.TradeGoods.All.FirstOrDefault((TradeGoodDef g) => g.Id == goodId); if (tradeGoodDef == null) { tradeQuote.Reason = "Unknown trade good."; return tradeQuote; } Settlement settlement = C.CurrentSettlement(); Party playerParty = State.PlayerParty; int num = MarketStock(settlement, goodId); if (buying && num < count) { tradeQuote.Reason = "Not that many in stock."; return tradeQuote; } if (!buying && CargoCount(playerParty, goodId) < count) { tradeQuote.Reason = "You're not carrying that many."; return tradeQuote; } if (!buying && count > 500 - num) { tradeQuote.Reason = "The market can't store any more of that."; return tradeQuote; } if (buying && CargoWeight(playerParty) + tradeGoodDef.Weight * (double)count > CargoCapacity(playerParty) + 1E-09) { tradeQuote.Reason = "No room for that."; return tradeQuote; } int tradeSkill = PlayerTradeSkill(); double haggle = PlayerHaggle(); for (int num2 = 0; num2 < count; num2++) { tradeQuote.Total += CommodityPrice(settlement, goodId, buying, buying ? (num - num2) : (num + num2 + 1), tradeSkill, haggle); } if (buying && State.PlayerClan.Gold < tradeQuote.Total) { tradeQuote.Reason = "Not enough denars."; } else if (!buying && settlement.Market.Gold < tradeQuote.Total) { tradeQuote.Reason = "The merchant can't afford it."; } else if (buying && settlement.Market.Gold > long.MaxValue - tradeQuote.Total) { tradeQuote.Reason = "The merchant can't hold any more money."; } else if (!buying && State.PlayerClan.Gold > long.MaxValue - tradeQuote.Total) { tradeQuote.Reason = "Your treasury's full."; } return tradeQuote; } public CommandResult TradeGoods(string goodId, int count, bool buying) { TradeQuote tradeQuote = QuoteTrade(goodId, count, buying); if (!tradeQuote.Ok) { return CommandResult.Fail(tradeQuote.Reason); } Settlement settlement = C.CurrentSettlement(); Party playerParty = State.PlayerParty; int num = CargoCount(playerParty, goodId); int num2 = num + (buying ? count : (-count)); long num3 = 0L; if (buying) { AddPlayerCargoCost(goodId, num, tradeQuote.Total); } else { num3 = tradeQuote.Total - TakePlayerCargoCost(goodId, count, num); } if (num2 == 0) { playerParty.Cargo.Remove(goodId); } else { playerParty.Cargo[goodId] = num2; } settlement.Market.Stock[goodId] = MarketStock(settlement, goodId) + (buying ? (-count) : count); settlement.Market.Gold += (buying ? tradeQuote.Total : (-tradeQuote.Total)); string name = TabsBannerlord.Core.Content.TradeGoods.All.First((TradeGoodDef g) => g.Id == goodId).Name; string text = string.Format("{0} {1} {2} for {3} denars at {4}.", buying ? "Bought" : "Sold", count, name, tradeQuote.Total, settlement.Name); State.Transact(State.PlayerClan, buying ? (-tradeQuote.Total) : tradeQuote.Total, LedgerAccount.Trade, text); State.AddLog(LogCategory.Economy, text, settlement.Id); if (num3 > 0) { C.GrantDailySkillExperience(State.PlayerHero, "trade", (double)num3 * 0.1, 100.0); } State.Touch(); return CommandResult.Success(text); } public ShoppingQuote QuoteShoppingList(IEnumerable> list) { ShoppingQuote shoppingQuote = new ShoppingQuote { Reason = MarketAccessReason() }; Party playerParty = State.PlayerParty; foreach (KeyValuePair entry in (list ?? Enumerable.Empty>()).Where((KeyValuePair e) => e.Value > 0).OrderBy, string>((KeyValuePair e) => e.Key, StringComparer.Ordinal)) { TradeGoodDef tradeGoodDef = TabsBannerlord.Core.Content.TradeGoods.All.FirstOrDefault((TradeGoodDef g) => g.Id == entry.Key); ShoppingLine shoppingLine = new ShoppingLine { GoodId = entry.Key, Name = (tradeGoodDef?.Name ?? entry.Key), Count = entry.Value, Weight = (tradeGoodDef?.Weight ?? 0.0) * (double)entry.Value }; if (tradeGoodDef == null) { shoppingLine.Reason = "Unknown trade good."; } else if (shoppingQuote.Reason.Length == 0) { TradeQuote tradeQuote = QuoteTrade(entry.Key, entry.Value, buying: true); shoppingLine.Total = tradeQuote.Total; shoppingLine.Reason = ((tradeQuote.Reason == "Not enough denars." || tradeQuote.Reason == "No room for that.") ? "" : tradeQuote.Reason); } shoppingQuote.Lines.Add(shoppingLine); shoppingQuote.Total = ((shoppingQuote.Total > long.MaxValue - shoppingLine.Total) ? long.MaxValue : (shoppingQuote.Total + shoppingLine.Total)); shoppingQuote.Weight += shoppingLine.Weight; } if (shoppingQuote.Reason.Length > 0) { return shoppingQuote; } if (shoppingQuote.Lines.Count == 0) { shoppingQuote.Reason = "The shopping list is empty."; return shoppingQuote; } ShoppingLine shoppingLine2 = shoppingQuote.Lines.FirstOrDefault((ShoppingLine l) => l.Reason.Length > 0); if (shoppingLine2 != null) { shoppingQuote.Reason = shoppingLine2.Name + ": " + shoppingLine2.Reason; } else if (State.PlayerClan.Gold < shoppingQuote.Total) { shoppingQuote.Reason = $"Not enough denars: the list costs {shoppingQuote.Total:N0}."; } else if (CargoWeight(playerParty) + shoppingQuote.Weight > CargoCapacity(playerParty) + 1E-09) { shoppingQuote.Reason = "No room for everything on the list."; } else if (C.CurrentSettlement().Market.Gold > long.MaxValue - shoppingQuote.Total) { shoppingQuote.Reason = "The merchant can't hold any more money."; } return shoppingQuote; } public CommandResult BuyShoppingList(IEnumerable> list) { ShoppingQuote shoppingQuote = QuoteShoppingList(list); if (!shoppingQuote.Ok) { return CommandResult.Fail((shoppingQuote.Reason.Length > 0) ? shoppingQuote.Reason : "The shopping list is empty."); } foreach (ShoppingLine line in shoppingQuote.Lines) { CommandResult commandResult = TradeGoods(line.GoodId, line.Count, buying: true); if (!commandResult.Ok) { return CommandResult.Fail("Stopped at " + line.Name + ": " + commandResult.Message); } } string arg = string.Join(", ", shoppingQuote.Lines.Select((ShoppingLine l) => l.Count + " " + l.Name)); return CommandResult.Success($"Bought {arg} for {shoppingQuote.Total:N0} denars."); } public string CargoDropReason(string goodId, int count) { string text = CargoCommandReason(); if (text.Length > 0) { return text; } if (TabsBannerlord.Core.Content.TradeGoods.All.FirstOrDefault((TradeGoodDef g) => g.Id == goodId) == null) { return "Unknown trade good."; } if (count < 1 || count > 1000) { return "Choose between 1 and 1000 goods."; } if (CargoCount(State.PlayerParty, goodId) < count) { return "You're not carrying that many."; } return ""; } public CommandResult DropCargo(string goodId, int count) { string text = CargoDropReason(goodId, count); if (text.Length > 0) { return CommandResult.Fail(text); } TradeGoodDef tradeGoodDef = TabsBannerlord.Core.Content.TradeGoods.All.First((TradeGoodDef g) => g.Id == goodId); Party playerParty = State.PlayerParty; int num = CargoCount(playerParty, goodId); int num2 = num - count; TakePlayerCargoCost(goodId, count, num); if (num2 == 0) { playerParty.Cargo.Remove(goodId); } else { playerParty.Cargo[goodId] = num2; } string text2 = $"Discarded {count} {tradeGoodDef.Name}."; State.AddLog(LogCategory.Economy, text2, playerParty.Id); State.Touch(); return CommandResult.Success(text2); } public void DailyMarkets() { bool flag = false; foreach (Settlement s in State.Settlements) { MarketState market = s.Market; if (s.Type == SettlementType.Hideout || market == null || !market.Initialized || market.LastDay >= State.Clock.Day) { continue; } market.LastDay = State.Clock.Day; flag = true; if (C.IsSettlementBesieged(s)) { continue; } long num = 0L; if (s.Type == SettlementType.Village) { double num2 = 200.0 - C.SettlementFood(s); if (num2 > 0.0) { C.AddSettlementFood(s, C.VillageFoodGood(s), Math.Min(num2, 6.0 * C.VillageOutputFactor(s))); } string text = PrimaryVillageGood(s); int baseUnits = VillageProducts.Get(text)?.GoodsPerDay ?? 6; market.Stock[text] = Math.Min(500, MarketStock(s, text) + C.VillageProductionAmount(s, text, baseUnits)); } else if (s.Type == SettlementType.Town) { if (MarketStock(s, "good.timber") >= 2 && MarketStock(s, "good.ore") >= 1 && MarketStock(s, "good.tools") < 500) { market.Stock["good.timber"] -= 2; market.Stock["good.ore"]--; market.Stock["good.tools"] = MarketStock(s, "good.tools") + 1; } if (MarketStock(s, "good.wool") >= 2 && MarketStock(s, "good.cloth") < 500) { market.Stock["good.wool"] -= 2; market.Stock["good.cloth"] = MarketStock(s, "good.cloth") + 1; } foreach (WorkshopTypeDef item in WorkshopTypes.All.Where((WorkshopTypeDef t) => !TabsBannerlord.Core.Content.TradeGoods.IsOriginal(t.OutputGoodId))) { if (item.Inputs.Any((KeyValuePair input) => MarketStock(s, input.Key) < input.Value) || MarketStock(s, item.OutputGoodId) >= 500) { continue; } foreach (KeyValuePair input in item.Inputs) { market.Stock[input.Key] = MarketStock(s, input.Key) - input.Value; } market.Stock[item.OutputGoodId] = MarketStock(s, item.OutputGoodId) + 1; } } if (s.Type == SettlementType.Village || s.Type == SettlementType.Town) { foreach (TradeGoodDef item2 in TabsBannerlord.Core.Content.TradeGoods.All.Where((TradeGoodDef g) => g.Id == "good.tools" || g.Id == "good.cloth" || (s.Type == SettlementType.Town && g.TownDemand > 0))) { for (int num3 = 0; num3 < Math.Max(1, item2.TownDemand); num3++) { int num4 = MarketStock(s, item2.Id); if (num4 <= 0) { break; } num += CommodityPrice(s, item2.Id, buying: true, num4); market.Stock[item2.Id] = num4 - 1; } } } if (market.Gold < 5000) { market.Gold += Math.Min(num, 5000 - market.Gold); } } if (flag) { State.Touch(); } } public void VillageTradeArrival(Party p, Settlement s) { if (p == null || s == null || p.Kind != PartyKind.Villager || State.Parties.Get(p.Id) != p || p.State != PartyState.InSettlement || p.CurrentSettlementId != s.Id || Vec2.Distance(p.Position, s.Position) > 0.01 || !C.CanEnter(p, s) || p.Cargo == null || s.Market?.Stock == null || !s.Market.Initialized) { return; } Settlement settlement = State.Settlements.Get(p.HomeSettlementId); if (settlement == null || settlement.Type != SettlementType.Village) { return; } bool flag = false; if (s.Id == settlement.Id) { if (C.VillageRecruitmentReason(s).Length > 0) { return; } double num = C.TakeSettlementFood(s, Math.Max(0.0, 4.0 - p.Food)); if (num > 0.0) { p.Food += num; flag = true; } string raw = PrimaryVillageGood(s); double weight = TabsBannerlord.Core.Content.TradeGoods.All.First((TradeGoodDef g) => g.Id == raw).Weight; int num2 = Math.Min((int)Math.Max(0.0, Math.Floor((CargoCapacity(p) - CargoWeight(p)) / weight)), Math.Min(Math.Max(0, 6 - CargoCount(p, raw)), MarketStock(s, raw))); if (num2 > 0) { p.Cargo[raw] = CargoCount(p, raw) + num2; s.Market.Stock[raw] -= num2; flag = true; } } else if (s.Id == settlement.BoundTo && (s.Type == SettlementType.Town || s.Type == SettlementType.Castle)) { double num3 = Math.Min(Math.Max(0.0, p.Food), Math.Max(0.0, C.FoodCapacity(s) - C.SettlementFood(s))); if (num3 > 0.0) { num3 = C.AddSettlementFood(s, C.VillageFoodGood(settlement), num3); p.Food = Math.Max(0.0, p.Food - num3); flag = num3 > 0.0 || flag; } foreach (TradeGoodDef item in TabsBannerlord.Core.Content.TradeGoods.All) { int num4 = CargoCount(p, item.Id); int num5 = Math.Min(num4, Math.Max(0, 500 - MarketStock(s, item.Id))); if (item.Category == GoodCategory.Food) { num5 = (int)Math.Min(num5, Math.Max(0.0, Math.Floor(C.FoodCapacity(s) - C.SettlementFood(s)))); } if (num5 > 0) { s.Market.Stock[item.Id] = MarketStock(s, item.Id) + num5; if (num5 == num4) { p.Cargo.Remove(item.Id); } else { p.Cargo[item.Id] = num4 - num5; } flag = true; } } } if (flag) { State.Touch(); } } } internal sealed class ElectionsSystem { private readonly Campaign C; private CampaignState State => C.State; internal ElectionsSystem(Campaign host) { C = host; } public double ClaimScore(Clan clan) { if (clan == null) { return 0.0; } int num = State.Settlements.Count((Settlement s) => s.OwnerClanId == clan.Id && (s.Type == SettlementType.Town || s.Type == SettlementType.Castle)); double num2 = State.ActiveParties.Where((Party p) => p.ClanId == clan.Id && (p.Kind == PartyKind.Lord || p.Kind == PartyKind.Player)).Sum((Func)C.PartyStrength); return clan.Renown + (double)(num * 150) + num2 / 5.0; } internal void NoteRulerDeath(Hero h) { Clan clan = State.Clans.Get(h?.ClanId ?? ""); if (clan == null || clan.LeaderHeroId != h.Id || State.Diplomacy?.PendingElections == null) { return; } foreach (Kingdom item in State.Kingdoms.Where((Kingdom k) => !k.IsEliminated && k.RulerClanId == clan.Id)) { if (!State.Diplomacy.PendingElections.Contains(item.Id)) { State.Diplomacy.PendingElections.Add(item.Id); } } State.Touch(); } internal bool ElectionLive(string kingdomId) { PoliticsState politics = State.Politics; if (politics == null) { return false; } return politics.Decisions?.Any((KingdomDecision d) => d.KingdomId == kingdomId && d.Kind == KingdomDecisionKind.RulerElection && Campaign.CouncilIsLive(d)) == true; } internal void DailyElections() { List list = State.Diplomacy?.PendingElections; if (list == null || list.Count == 0 || State.Politics == null || !State.Politics.Initialized) { return; } foreach (string kingdomId in list.ToList()) { Clan ruler = C.ServiceRuler(kingdomId); if (ruler != null) { Kingdom kingdom = State.Kingdoms.Get(kingdomId); if (kingdom != null && !kingdom.IsEliminated) { if (C.LivingDiplomacyRuler(kingdomId) == null || ElectionLive(kingdomId) || C.DiplomacyFactionReserved(kingdomId)) { continue; } list.Remove(kingdomId); State.Touch(); Clan clan = (from c in C.CouncilMembers(kingdomId) where c.Id != ruler.Id select c).OrderByDescending(ClaimScore).ThenBy((Clan c) => c.Id, StringComparer.Ordinal).FirstOrDefault(); if (clan != null && C.CouncilMember(kingdomId, ruler.Id)) { KingdomDecision decision = C.NewCouncilDecision(kingdomId, ruler.Id, KingdomDecisionKind.RulerElection); decision.CandidateClanId = clan.Id; decision.RivalClanId = ruler.Id; State.Politics.Decisions.Add(decision); if (State.Politics.Decisions.Any((KingdomDecision d) => d != decision && d.KingdomId == kingdomId && d.Status == KingdomDecisionStatus.Voting)) { State.AddLog(LogCategory.Politics, State.Kingdoms.Require(kingdomId).Name + " will elect its ruler once the council's current vote is done.", kingdomId, decision.Id); } else { C.OpenCouncilDecision(decision); } } continue; } } list.Remove(kingdomId); State.Touch(); } } public string AbdicateReason() { string text = C.PlayerCouncilReason(); if (text.Length > 0) { return text; } string kingdomId = State.PlayerClan.KingdomId; if (C.ServiceRuler(kingdomId)?.Id != State.PlayerClanId) { return "Only the ruler can abdicate."; } if (C.CouncilMembers(kingdomId).Count((Clan c) => c.Id != State.PlayerClanId) == 0) { return "Nobody else on the council could take the crown."; } if (State.Politics.Decisions.Any((KingdomDecision d) => Campaign.CouncilIsLive(d) && d.KingdomId == kingdomId)) { return "Wait for the council's current vote to end."; } if (State.Clock.Minute <= 9223372036854772927L) { return ""; } return "A vote cannot be recorded at this date."; } public CommandResult Abdicate() { string text = AbdicateReason(); if (text.Length > 0) { return CommandResult.Fail(text); } string kingdomId = State.PlayerClan.KingdomId; List list = (from c in C.CouncilMembers(kingdomId) where c.Id != State.PlayerClanId select c).OrderByDescending(ClaimScore).ThenBy((Clan c) => c.Id, StringComparer.Ordinal).Take(2) .ToList(); if (list.Count == 1) { TransferCrown(kingdomId, list[0]); return CommandResult.Success("You abdicated. " + list[0].Name + " now rules " + State.Kingdoms.Require(kingdomId).Name + "."); } KingdomDecision kingdomDecision = C.NewCouncilDecision(kingdomId, State.PlayerClanId, KingdomDecisionKind.RulerElection); kingdomDecision.CandidateClanId = list[1].Id; kingdomDecision.RivalClanId = list[0].Id; kingdomDecision.Abdication = true; State.Politics.Decisions.Add(kingdomDecision); C.OpenCouncilDecision(kingdomDecision); State.Touch(); return CommandResult.Success("You will abdicate. The council chooses between " + list[0].Name + " and " + list[1].Name + " over two days; you still rule until then."); } internal string ElectionStaleReason(KingdomDecision decision) { if (!C.CouncilMember(decision.KingdomId, decision.CandidateClanId) || !C.CouncilMember(decision.KingdomId, decision.RivalClanId)) { return "A claimant no longer sits on the council."; } if (!(decision.CandidateClanId == decision.RivalClanId)) { return ""; } return "There is only one claimant."; } internal bool CouncilElectionPreference(KingdomDecision decision, Clan clan, out string reason) { if (clan.Id == decision.CandidateClanId) { reason = "Votes for itself."; return true; } if (clan.Id == decision.RivalClanId) { reason = "Votes for itself."; return false; } Clan clan2 = State.Clans.Get(decision.CandidateClanId); Clan clan3 = State.Clans.Get(decision.RivalClanId); double num = (double)(C.ClanRelation(clan.Id, decision.CandidateClanId) - C.ClanRelation(clan.Id, decision.RivalClanId)) / 20.0; double num2 = (ClaimScore(clan2) - ClaimScore(clan3)) / 300.0; bool num3 = num + num2 - (decision.Abdication ? 0.0 : 0.5) > 0.0; string text = ((!num3) ? clan3?.Name : clan2?.Name); reason = ((Math.Abs(num) >= Math.Abs(num2) && Math.Abs(num) > 0.25) ? ("Favours " + text + ", its friends.") : ((Math.Abs(num2) > 0.25) ? ("Thinks " + text + " has the stronger claim.") : (decision.Abdication ? ("Leans to " + text + ".") : "Loyal to the ruling clan."))); return num3; } internal void ApplyElection(KingdomDecision decision, out string effect) { Clan clan = State.Clans.Get(decision.Passed ? decision.CandidateClanId : decision.RivalClanId); Kingdom kingdom = State.Kingdoms.Require(decision.KingdomId); if (clan == null) { effect = "Nobody could take the crown."; return; } if (clan.Id == kingdom.RulerClanId) { effect = "The crown stays with " + clan.Name + "."; return; } foreach (CouncilBallot item in decision.Ballots.Where((CouncilBallot b) => b != null)) { C.AdjustClanRelation(clan.Id, item.ClanId, (item.Support == decision.Passed) ? 5 : (-5)); } TransferCrown(decision.KingdomId, clan); effect = clan.Name + " now rules " + kingdom.Name + "."; } internal void TransferCrown(string kingdomId, Clan winner) { Kingdom kingdom = State.Kingdoms.Require(kingdomId); string rulerClanId = kingdom.RulerClanId; kingdom.RulerClanId = winner.Id; ClanServiceState clanService = State.ClanService; if (clanService != null && clanService.Initialized) { if (winner.Id == State.PlayerClanId) { clanService.Kind = ClanServiceKind.Ruler; clanService.KingdomId = kingdomId; clanService.StartedDay = State.Clock.Day; clanService.EndsDay = -1L; clanService.LastPaidDay = State.Clock.Day; } else if (rulerClanId == State.PlayerClanId && clanService.Kind == ClanServiceKind.Ruler && clanService.KingdomId == kingdomId) { clanService.Kind = ClanServiceKind.Vassal; clanService.StartedDay = State.Clock.Day; clanService.EndsDay = -1L; clanService.LastPaidDay = State.Clock.Day; } } string text = winner.Name + " takes the crown of " + kingdom.Name + (string.IsNullOrEmpty(rulerClanId) ? "." : (" from " + (State.Clans.Get(rulerClanId)?.Name ?? "its last rulers") + ".")); State.AddLog(LogCategory.Politics, text, kingdomId, winner.Id); C.Raise((winner.Id == State.PlayerClanId || rulerClanId == State.PlayerClanId) ? CampaignEventKind.Warning : CampaignEventKind.Info, text, winner.Id == State.PlayerClanId || rulerClanId == State.PlayerClanId, kingdomId, winner.Id); C.OnDiplomacyChanged(); State.Touch(); } } internal sealed class EncountersSystem { private readonly Campaign C; private NavGrid Nav => C.Nav; private CampaignRules Rules => C.Rules; private CampaignState State => C.State; public Encounter PendingPlayerEncounter => State.Encounters.Get(State.Player.PendingEncounterId); internal EncountersSystem(Campaign host) { C = host; } public static double ClosestApproach(Vec2 a0, Vec2 a1, Vec2 b0, Vec2 b1, out double t) { Vec2 vec = a0 - b0; Vec2 vec2 = a1 - a0 - (b1 - b0); double num = Vec2.Dot(vec2, vec2); t = ((num < 1E-12) ? 0.0 : Math.Max(0.0, Math.Min(1.0, (0.0 - Vec2.Dot(vec, vec2)) / num))); return (vec + vec2 * t).Length; } internal Vec2 ContactPoint(MoveSegment seg, double t) { Vec2 vec = Vec2.Lerp(seg.From, seg.To, t); if (Nav.IsPassable(vec)) { return vec; } if (!(t >= 0.5) || !Nav.IsPassable(seg.To)) { if (!Nav.IsPassable(seg.From)) { return seg.To; } return seg.From; } return seg.To; } public bool IsInterceptable(Party p) { if (p != null && p.State == PartyState.Active && string.IsNullOrEmpty(p.EncounterId)) { if (p.Id == State.PlayerPartyId) { return State.Player.Activity != PlayerActivity.Captive; } return true; } return false; } internal void DetectEncounters(List moves) { Dictionary dictionary = new Dictionary(StringComparer.Ordinal); foreach (MoveSegment move in moves) { dictionary[move.PartyId] = move; } List list = new List(); long minute = State.Clock.Minute; foreach (Party party4 in State.Parties) { if (party4.Order.Kind != OrderKind.Engage || !IsInterceptable(party4)) { continue; } Party party = C.ArmyHead(State.Parties.Get(party4.Order.TargetId)); if (party != null && IsInterceptable(party) && State.AreHostile(party4, party) && party.DisengagedUntilMinute <= minute) { MoveSegment value; MoveSegment seg = (dictionary.TryGetValue(party4.Id, out value) ? value : new MoveSegment { PartyId = party4.Id, From = party4.Position, To = party4.Position }); MoveSegment value2; MoveSegment seg2 = (dictionary.TryGetValue(party.Id, out value2) ? value2 : new MoveSegment { PartyId = party.Id, From = party.Position, To = party.Position }); if (!(ClosestApproach(seg.From, seg.To, seg2.From, seg2.To, out var t) > Rules.ContactRadius)) { list.Add(new Campaign.ContactCandidate { T = t, Initiator = party4.Id, Target = party.Id, InitiatorPos = ContactPoint(seg, t), TargetPos = ContactPoint(seg2, t) }); } } } list.Sort(delegate(Campaign.ContactCandidate a, Campaign.ContactCandidate b) { int num = a.T.CompareTo(b.T); if (num != 0) { return num; } num = string.CompareOrdinal(a.Initiator, b.Initiator); return (num == 0) ? string.CompareOrdinal(a.Target, b.Target) : num; }); foreach (Campaign.ContactCandidate item in list) { Party party2 = State.Parties.Get(item.Initiator); Party party3 = State.Parties.Get(item.Target); if (IsInterceptable(party2) && IsInterceptable(party3)) { party2.Position = item.InitiatorPos; party3.Position = item.TargetPos; StartEncounter(party2, party3); } } } public Encounter StartEncounter(Party initiator, Party target) { Encounter encounter = new Encounter { Id = State.Ids.Allocate("enc"), CreatedAtMinute = State.Clock.Minute, Position = Vec2.Lerp(initiator.Position, target.Position, 0.5), InitiatorPartyId = initiator.Id, Biome = Nav.TerrainAt(target.Position).Biome }; Clan clan = State.Clans.Get(initiator.ClanId); bool flag = (clan != null && clan.IsBandit) || (State.Clans.Get(target.ClanId)?.IsBandit ?? false); encounter.Kind = (flag ? EncounterKind.BanditAmbush : EncounterKind.FieldBattle); if (initiator.Id == State.PlayerPartyId && !flag && (target.Kind == PartyKind.Villager || target.Kind == PartyKind.Caravan)) { C.AddCrime(State.FactionOfParty(target), 8.0, "attacking " + target.Name, target.Id); } encounter.AttackerParties.Add(initiator.Id); encounter.DefenderParties.Add(target.Id); foreach (Party item in State.Parties.OrderBy((Party x) => x.Id, StringComparer.Ordinal)) { if (!(item.Id == initiator.Id) && !(item.Id == target.Id) && (!(item.Id == State.PlayerPartyId) || C.ClanArmyContains(initiator.Id) || C.ClanArmyContains(target.Id) || C.PlayerMarchesWith(initiator) || C.PlayerMarchesWith(target)) && IsInterceptable(item) && item.DisengagedUntilMinute <= State.Clock.Minute && !(Vec2.Distance(item.Position, encounter.Position) > Rules.JoinBattleRadius) && C.PartyCombatants(item) != 0) { if (State.AreAllied(item, initiator) && State.AreHostile(item, target)) { encounter.AttackerParties.Add(item.Id); } else if (State.AreAllied(item, target) && State.AreHostile(item, initiator)) { encounter.DefenderParties.Add(item.Id); } } } State.Encounters.Add(encounter); foreach (string allParty in encounter.AllParties) { Party party = State.Parties.Get(allParty); C.CancelRaid(party, "intercepted by another warband", notify: false); C.EndPartySiege(party, "intercepted by another warband"); party.State = PartyState.Engaged; party.EncounterId = encounter.Id; } encounter.PlayerInvolved = encounter.AllParties.Contains(State.PlayerPartyId); if (encounter.PlayerInvolved) { encounter.PlayerSide = encounter.SideOf(State.PlayerPartyId); State.Player.PendingEncounterId = encounter.Id; State.Player.Activity = PlayerActivity.InEncounter; C.NoteHeroesMet(); Party party2 = ((encounter.PlayerSide == BattleSide.Attacker) ? target : initiator); string text = ((encounter.PlayerSide == BattleSide.Attacker) ? ("You have caught up with " + party2.Name + ".") : (initiator.Name + " has intercepted you!")); C.Raise(CampaignEventKind.EncounterStarted, text, true, encounter.Id, party2.Id); } else { ResolveAiEncounter(encounter); } return encounter; } internal void ResolveAiEncounter(Encounter enc) { BattleManifest battleManifest = ManifestBuilder.Build(C, enc, 0); enc.AttemptCounter++; enc.CurrentAttemptId = enc.Id + "#" + enc.AttemptCounter; battleManifest.AttemptId = enc.CurrentAttemptId; enc.Manifest = battleManifest; enc.ExpectedRevision = State.Revision; enc.Phase = EncounterPhase.InBattle; BattleResult result = AutoResolver.Resolve(C, enc, battleManifest); CommitResult commitResult = OutcomeCommitter.Commit(C, result); if (!commitResult.Success) { throw new InvalidOperationException("AI battle commit failed: " + commitResult.Error); } } public void CancelEncounter(Encounter enc, string reason, string disengageParty = null) { enc.Phase = EncounterPhase.Cancelled; enc.ResultSummary = reason; foreach (string allParty in enc.AllParties) { Party party = State.Parties.Get(allParty); if (party == null) { continue; } if (party.EncounterId == enc.Id) { party.EncounterId = ""; if (party.State == PartyState.Engaged) { party.State = PartyState.Active; } } if (party.Order.Kind == OrderKind.Engage && enc.AllParties.Contains(party.Order.TargetId)) { C.ClearOrder(party); } } if (disengageParty != null) { Party party2 = State.Parties.Get(disengageParty); if (party2 != null) { party2.DisengagedUntilMinute = State.Clock.Minute + (long)(Rules.DisengageHours * 60.0); } } if (State.Player.PendingEncounterId == enc.Id) { State.Player.PendingEncounterId = ""; if (State.Player.Activity == PlayerActivity.InEncounter || State.Player.Activity == PlayerActivity.InBattle) { State.Player.Activity = PlayerActivity.Idle; } C.UpdatePlayerTimeStates(); } if (!string.IsNullOrEmpty(enc.SiegeId)) { C.CancelSiegeBattle(enc); } if (!string.IsNullOrEmpty(enc.SortieSiegeId)) { C.CancelSiegeSortie(enc); } C.CancelHideoutEncounter(enc); PruneEncounters(); State.Touch(); } internal void PruneEncounters() { foreach (Encounter item in State.Encounters.ToList()) { if ((item.Phase == EncounterPhase.Committed || item.Phase == EncounterPhase.Cancelled) && State.Player.PendingEncounterId != item.Id) { State.Encounters.Remove(item.Id); } } } } internal sealed class EncyclopediaSystem { private readonly Campaign C; private ContentDatabase Content => C.Content; private static IReadOnlyList EncyclopediaCategories => Campaign.EncyclopediaCategories; private static CultureInfo Inv => Campaign.Inv; private CampaignState State => C.State; private WorldDef World => C.World; public IReadOnlyList EncyclopediaBookmarks => State.EncyclopediaBookmarks ?? (State.EncyclopediaBookmarks = new List()); internal EncyclopediaSystem(Campaign host) { C = host; } public static IReadOnlyList EncyclopediaSorts(EncyclopediaCategory category) { return category switch { EncyclopediaCategory.Heroes => new string[2] { "Name", "Level" }.Concat(SkillIds.All.Select(Campaign.SkillName)).ToArray(), EncyclopediaCategory.Clans => new string[6] { "Name", "Tier", "Renown", "Members", "Fiefs", "Relation" }, EncyclopediaCategory.Kingdoms => new string[4] { "Name", "Clans", "Fiefs", "Wars" }, EncyclopediaCategory.Settlements => new string[6] { "Name", "Prosperity", "Loyalty", "Security", "Militia", "Food" }, EncyclopediaCategory.Units => new string[7] { "Name", "Tier", "Recruit cost", "Wage", "Attack", "Defense", "Health" }, _ => new string[1] { "Name" }, }; } public List EncyclopediaEntries(EncyclopediaCategory category) { return category switch { EncyclopediaCategory.Heroes => State.Heroes.Select(EncyclopediaHeroEntry).Concat((State.Notables ?? new List()).Select(EncyclopediaNotableEntry)).ToList(), EncyclopediaCategory.Clans => State.Clans.Select(EncyclopediaClanEntry).ToList(), EncyclopediaCategory.Kingdoms => State.Kingdoms.Select(EncyclopediaKingdomEntry).ToList(), EncyclopediaCategory.Settlements => State.Settlements.Where(C.HideoutKnown).Select(EncyclopediaSettlementEntry).ToList(), EncyclopediaCategory.Units => Content.Units.Select(EncyclopediaUnitEntry).ToList(), _ => EncyclopediaConcepts.All.Select(EncyclopediaConceptEntry).ToList(), }; } public static List EncyclopediaFilter(IEnumerable entries, EncyclopediaQuery query) { query = query ?? new EncyclopediaQuery(); string search = (query.Search ?? "").Trim(); double value; IEnumerable source = entries.Where((EncyclopediaEntry e) => (search.Length == 0 || Contains(e.Title, search) || Contains(e.Subtitle, search)) && query.Filters.All((KeyValuePair> f) => f.Value.Count == 0 || (e.Facets.TryGetValue(f.Key, out value) && f.Value.Contains(value)))); IOrderedEnumerable source2; if (query.Sort == "Name" || string.IsNullOrEmpty(query.Sort)) { source2 = (query.Descending ? source.OrderByDescending((EncyclopediaEntry e) => e.Title, StringComparer.OrdinalIgnoreCase) : source.OrderBy((EncyclopediaEntry e) => e.Title, StringComparer.OrdinalIgnoreCase)); } else { Func keySelector = (EncyclopediaEntry e) => (!e.Numbers.TryGetValue(query.Sort, out value)) ? double.NegativeInfinity : value; source2 = (query.Descending ? source.OrderByDescending(keySelector) : source.OrderBy(keySelector)); source2 = source2.ThenBy((EncyclopediaEntry e) => e.Title, StringComparer.OrdinalIgnoreCase); } return source2.ThenBy((EncyclopediaEntry e) => e.Link, StringComparer.Ordinal).ToList(); } public static SortedDictionary> EncyclopediaFacets(IEnumerable entries) { SortedDictionary> sortedDictionary = new SortedDictionary>(StringComparer.Ordinal); foreach (EncyclopediaEntry entry in entries) { foreach (KeyValuePair facet in entry.Facets) { if (!sortedDictionary.TryGetValue(facet.Key, out var value)) { value = (sortedDictionary[facet.Key] = new SortedSet(StringComparer.Ordinal)); } value.Add(facet.Value); } } SortedDictionary> sortedDictionary2 = new SortedDictionary>(StringComparer.Ordinal); foreach (KeyValuePair> item in sortedDictionary) { sortedDictionary2[item.Key] = item.Value.ToList(); } return sortedDictionary2; } public List EncyclopediaSearch(string text, int max = 40) { text = (text ?? "").Trim(); if (text.Length == 0) { return new List(); } return (from e in EncyclopediaCategories.SelectMany(EncyclopediaEntries) where Contains(e.Title, text) orderby (!e.Title.StartsWith(text, StringComparison.OrdinalIgnoreCase)) ? 1 : 0 select e).ThenBy((EncyclopediaEntry e) => e.Title, StringComparer.OrdinalIgnoreCase).ThenBy((EncyclopediaEntry e) => e.Link, StringComparer.Ordinal).Take(Math.Max(1, max)) .ToList(); } internal static bool Contains(string text, string part) { return (text ?? "").IndexOf(part, StringComparison.OrdinalIgnoreCase) >= 0; } internal EncyclopediaEntry EncyclopediaHeroEntry(Hero h) { Clan clan = State.Clans.Get(h.ClanId); EncyclopediaEntry encyclopediaEntry = new EncyclopediaEntry { Category = EncyclopediaCategory.Heroes, Link = EncyclopediaLinks.For(EncyclopediaCategory.Heroes, h.Id), Title = h.Name, Subtitle = HeroDescription(h, clan), Color = (clan?.Color ?? ""), Symbol = (clan?.Symbol ?? ""), Yours = (clan != null && clan.Id == State.PlayerClanId) }; encyclopediaEntry.Facets["Status"] = HeroStatusName(h); encyclopediaEntry.Facets["Occupation"] = HeroOccupationName(h, clan); encyclopediaEntry.Facets["Culture"] = CultureName(h.CultureId); encyclopediaEntry.Facets["Standing"] = Standing(clan); encyclopediaEntry.Numbers["Level"] = h.Level; if (h.Sex != HeroSex.Unspecified) { encyclopediaEntry.Numbers["Age"] = C.HeroYears(h); } if (KnowsHero(h)) { string[] all = SkillIds.All; foreach (string text in all) { encyclopediaEntry.Numbers[Campaign.SkillName(text)] = h.Skill(text); } } return encyclopediaEntry; } internal EncyclopediaEntry EncyclopediaNotableEntry(NotableState n) { Settlement settlement = State.Settlements.Get(n.SettlementId); Clan clan = State.Clans.Get(settlement?.OwnerClanId ?? ""); EncyclopediaEntry encyclopediaEntry = new EncyclopediaEntry(); encyclopediaEntry.Category = EncyclopediaCategory.Heroes; encyclopediaEntry.Link = EncyclopediaLinks.For(EncyclopediaCategory.Heroes, n.Id); encyclopediaEntry.Title = n.Name; encyclopediaEntry.Subtitle = n.Occupation + ((settlement == null) ? "" : (" of " + settlement.Name)); encyclopediaEntry.Color = clan?.Color ?? ""; encyclopediaEntry.Symbol = clan?.Symbol ?? ""; encyclopediaEntry.Facets["Status"] = (n.IsAlive ? "Alive" : "Dead"); encyclopediaEntry.Facets["Occupation"] = "Notable"; encyclopediaEntry.Facets["Culture"] = CultureName(n.CultureId); encyclopediaEntry.Facets["Standing"] = ((clan == null) ? "Unaffiliated" : Standing(clan)); encyclopediaEntry.Numbers["Level"] = 0.0; return encyclopediaEntry; } internal EncyclopediaEntry EncyclopediaClanEntry(Clan clan) { Kingdom kingdom = State.Kingdoms.Get(clan.KingdomId); EncyclopediaEntry encyclopediaEntry = new EncyclopediaEntry(); encyclopediaEntry.Category = EncyclopediaCategory.Clans; encyclopediaEntry.Link = EncyclopediaLinks.For(EncyclopediaCategory.Clans, clan.Id); encyclopediaEntry.Title = clan.Name; encyclopediaEntry.Subtitle = (clan.IsBandit ? "Outlaws" : ((kingdom != null) ? kingdom.Name : "Independent clan")); encyclopediaEntry.Color = clan.Color; encyclopediaEntry.Symbol = clan.Symbol; encyclopediaEntry.EmblemColor = clan.EmblemColor ?? ""; encyclopediaEntry.Yours = clan.Id == State.PlayerClanId; encyclopediaEntry.Facets["Status"] = (clan.IsEliminated ? "Eliminated" : "Active"); encyclopediaEntry.Facets["Kind"] = (clan.IsBandit ? "Outlaws" : "Noble clan"); encyclopediaEntry.Facets["Kingdom"] = (clan.IsBandit ? "Outlaws" : (kingdom?.Name ?? "Independent")); encyclopediaEntry.Facets["Culture"] = CultureName(clan.CultureId); encyclopediaEntry.Facets["Standing"] = Standing(clan); encyclopediaEntry.Numbers["Tier"] = ((!clan.IsBandit) ? Campaign.ClanTier(clan) : 0); encyclopediaEntry.Numbers["Renown"] = clan.Renown; encyclopediaEntry.Numbers["Members"] = ClanMembers(clan).Count((Hero h) => h.State != HeroState.Dead); encyclopediaEntry.Numbers["Fiefs"] = State.Settlements.Count((Settlement s) => s.OwnerClanId == clan.Id && s.Type != SettlementType.Hideout); encyclopediaEntry.Numbers["Relation"] = ((clan.Id == State.PlayerClanId) ? double.NegativeInfinity : ((double)C.ClanRelation(State.PlayerClanId, clan.Id))); return encyclopediaEntry; } internal EncyclopediaEntry EncyclopediaKingdomEntry(Kingdom k) { EncyclopediaEntry encyclopediaEntry = new EncyclopediaEntry { Category = EncyclopediaCategory.Kingdoms, Link = EncyclopediaLinks.For(EncyclopediaCategory.Kingdoms, k.Id), Title = k.Name, Subtitle = CultureName(k.CultureId) + " kingdom", Color = k.Color, Symbol = k.Symbol, Yours = (State.PlayerClan?.KingdomId == k.Id) }; encyclopediaEntry.Facets["Status"] = (k.IsEliminated ? "Eliminated" : "Active"); encyclopediaEntry.Facets["Standing"] = (encyclopediaEntry.Yours ? "Your kingdom" : (State.AtWar(State.FactionOf(State.PlayerClan), k.Id) ? "At war with you" : "At peace")); encyclopediaEntry.Facets["Culture"] = CultureName(k.CultureId); encyclopediaEntry.Numbers["Clans"] = KingdomClans(k).Count(); encyclopediaEntry.Numbers["Fiefs"] = State.Settlements.Count((Settlement s) => s.Type != SettlementType.Hideout && State.Clans.Get(s.OwnerClanId)?.KingdomId == k.Id); encyclopediaEntry.Numbers["Wars"] = WarsOf(k.Id).Count(); return encyclopediaEntry; } internal EncyclopediaEntry EncyclopediaSettlementEntry(Settlement s) { Clan clan = State.Clans.Get(s.OwnerClanId); Kingdom kingdom = State.Kingdoms.Get(clan?.KingdomId ?? ""); EncyclopediaEntry encyclopediaEntry = new EncyclopediaEntry { Category = EncyclopediaCategory.Settlements, Link = EncyclopediaLinks.For(EncyclopediaCategory.Settlements, s.Id), Title = s.Name, Subtitle = SettlementTypeName(s.Type) + ((clan == null) ? "" : (" · " + clan.Name)), Color = (clan?.Color ?? ""), Symbol = (clan?.Symbol ?? ""), Yours = (clan != null && clan.Id == State.PlayerClanId) }; encyclopediaEntry.Facets["Type"] = SettlementTypeName(s.Type); encyclopediaEntry.Facets["Culture"] = CultureName(s.CultureId); encyclopediaEntry.Facets["Standing"] = ((s.Type == SettlementType.Hideout) ? "Outlaws" : Standing(clan)); encyclopediaEntry.Facets["Kingdom"] = ((s.Type == SettlementType.Hideout) ? "Outlaws" : (kingdom?.Name ?? ((clan == null) ? "Unowned" : "Independent"))); if (s.Type != SettlementType.Hideout) { encyclopediaEntry.Numbers["Prosperity"] = s.Prosperity; encyclopediaEntry.Numbers["Loyalty"] = s.Loyalty; encyclopediaEntry.Numbers["Security"] = s.Security; encyclopediaEntry.Numbers["Militia"] = s.Militia; encyclopediaEntry.Numbers["Food"] = C.SettlementFood(s); } return encyclopediaEntry; } internal EncyclopediaEntry EncyclopediaUnitEntry(UnitDef u) { EncyclopediaEntry encyclopediaEntry = new EncyclopediaEntry(); encyclopediaEntry.Category = EncyclopediaCategory.Units; encyclopediaEntry.Link = EncyclopediaLinks.For(EncyclopediaCategory.Units, u.Id); encyclopediaEntry.Title = u.Name; encyclopediaEntry.Subtitle = "Tier " + u.Tier + " " + RoleName(u.Role).ToLowerInvariant() + " · " + CultureName(u.Culture); encyclopediaEntry.Color = Content.Cultures.Get(u.Culture)?.Color ?? ""; encyclopediaEntry.Symbol = Content.Cultures.Get(u.Culture)?.Symbol ?? ""; encyclopediaEntry.Facets["Culture"] = CultureName(u.Culture); encyclopediaEntry.Facets["Tier"] = "Tier " + u.Tier; encyclopediaEntry.Facets["Role"] = RoleName(u.Role); encyclopediaEntry.Facets["Mount"] = (u.Mounted ? "Mounted" : "On foot"); encyclopediaEntry.Numbers["Tier"] = u.Tier; encyclopediaEntry.Numbers["Recruit cost"] = u.RecruitCost; encyclopediaEntry.Numbers["Wage"] = u.DailyWage; encyclopediaEntry.Numbers["Attack"] = u.Attack; encyclopediaEntry.Numbers["Defense"] = u.Defense; encyclopediaEntry.Numbers["Health"] = u.Health; return encyclopediaEntry; } internal static EncyclopediaEntry EncyclopediaConceptEntry(EncyclopediaConceptDef c) { EncyclopediaEntry encyclopediaEntry = new EncyclopediaEntry(); encyclopediaEntry.Category = EncyclopediaCategory.Concepts; encyclopediaEntry.Link = EncyclopediaLinks.For(EncyclopediaCategory.Concepts, c.Id); encyclopediaEntry.Title = c.Title; encyclopediaEntry.Subtitle = c.Topic; encyclopediaEntry.Facets["Topic"] = c.Topic; return encyclopediaEntry; } public EncyclopediaPage EncyclopediaPage(string link) { if (!EncyclopediaLinks.TryParse(link, out var category, out var id)) { return null; } switch (category) { case EncyclopediaCategory.Heroes: { Hero hero = State.Heroes.Get(id); if (hero != null) { return HeroPage(hero); } NotableState notableState = State.Notables?.FirstOrDefault((NotableState x) => x.Id == id); if (notableState != null) { return NotablePage(notableState); } return null; } case EncyclopediaCategory.Clans: { Clan clan = State.Clans.Get(id); if (clan != null) { return ClanPage(clan); } return null; } case EncyclopediaCategory.Kingdoms: { Kingdom kingdom = State.Kingdoms.Get(id); if (kingdom != null) { return KingdomPage(kingdom); } return null; } case EncyclopediaCategory.Settlements: { Settlement settlement = State.Settlements.Get(id); if (settlement != null) { return SettlementPage(settlement); } return null; } case EncyclopediaCategory.Units: { UnitDef unitDef = Content.Units.Get(id); if (unitDef != null) { return UnitPage(unitDef); } return null; } default: { EncyclopediaConceptDef encyclopediaConceptDef = EncyclopediaConcepts.Get(id); if (encyclopediaConceptDef != null) { return ConceptPage(encyclopediaConceptDef); } return null; } } } internal EncyclopediaPage NewPage(EncyclopediaCategory category, string id, string title, string subtitle, string color = "", string symbol = "") { return new EncyclopediaPage { Category = category, Link = EncyclopediaLinks.For(category, id), Title = (title ?? ""), Subtitle = (subtitle ?? ""), Color = (color ?? ""), Symbol = (symbol ?? "") }; } internal EncyclopediaPage HeroPage(Hero h) { Clan clan = State.Clans.Get(h.ClanId); Kingdom kingdom = State.Kingdoms.Get(clan?.KingdomId ?? ""); EncyclopediaPage encyclopediaPage = NewPage(EncyclopediaCategory.Heroes, h.Id, h.Name, HeroDescription(h, clan), clan?.Color, clan?.Symbol); string mapTarget; string value = HeroWhereabouts(h, out mapTarget); encyclopediaPage.MapTarget = mapTarget; EncyclopediaSection encyclopediaSection = encyclopediaPage.Section("Information"); if (clan != null) { encyclopediaSection.Row("Clan", clan.Name, ClanLink(clan)); } if (clan != null && !clan.IsBandit) { encyclopediaSection.Row("Kingdom", kingdom?.Name ?? "Independent", (kingdom == null) ? "" : KingdomLink(kingdom)); } encyclopediaSection.Row("Culture", CultureName(h.CultureId)); if (h.Sex != HeroSex.Unspecified) { encyclopediaSection.Row("Age", (h.State == HeroState.Dead) ? ("Died at " + C.HeroYears(h) + (string.IsNullOrEmpty(h.DeathCause) ? "" : (" (" + h.DeathCause + ")")) + ((h.DeathDay >= 0) ? (", day " + (h.DeathDay + 1).ToString(Inv)) : "")) : (C.HeroYears(h).ToString(Inv) + (C.IsChild(h) ? " (a child)" : "")), "", "A year is " + 84 + " days; children come of age at " + 18 + "."); } encyclopediaSection.Row("Occupation", HeroOccupationName(h, clan)); encyclopediaSection.Row("Level", h.Level.ToString(Inv)); encyclopediaSection.Row("Status", HeroStatusName(h) + ((h.State == HeroState.Active && h.Health < 0.999) ? $" · {h.Health * 100.0:0}% health" : "")); encyclopediaSection.Row("Whereabouts", value, "", "What you know: parties out of sight show where you last saw them, and lords inside settlements only where you can see in."); Party party = State.Parties.Get(h.PartyId); if (party != null && party.LeaderHeroId == h.Id && party.State != PartyState.Destroyed && party.State != PartyState.Disbanded && h.State == HeroState.Active) { encyclopediaSection.Row("Leads", party.Name + " · " + PartyStrengthText(party), "", "Fighters: exact for your own parties, otherwise the estimate from your last sighting."); } Settlement settlement = State.Settlements.FirstOrDefault((Settlement s) => s.Management?.GovernorHeroId == h.Id && s.OwnerClanId == State.PlayerClanId); if (settlement != null) { encyclopediaSection.Row("Governor of", settlement.Name, SettlementLink(settlement)); } if (clan != null && !clan.IsBandit && clan.Id != State.PlayerClanId && h.State != HeroState.Dead) { encyclopediaSection.Row("Relation", Signed(C.ClanRelation(State.PlayerClanId, clan.Id)), "", "Relation between your clan and theirs."); } HorseState horseState = C.LordHorse(h); if (horseState != null && KnowsHero(h)) { encyclopediaSection.Row("Horse", horseState.Name + ", " + Campaign.HorseQuality(horseState).ToLowerInvariant() + " " + C.BreedName(horseState).ToLowerInvariant() + ((horseState.Injury != HorseInjury.None) ? (" (" + Horses.InjuryName(horseState.Injury).ToLowerInvariant() + ")") : ""), "", "The horse " + h.Name + " rides into battle. Capture them and it is yours."); } QuestState questState = C.DelegatedQuestOf(h.Id); if (questState != null && h.ClanId == State.PlayerClanId) { encyclopediaSection.Row("Away on", questState.Title, "", "Back about day " + (questState.DelegateDueMinute / 1440 + 1) + "."); } FamilySection(encyclopediaPage, h); bool flag = KnowsHero(h); EncyclopediaSection encyclopediaSection2 = encyclopediaPage.Section("Skills", flag ? "" : ("You have not met " + h.Name + ". Meet them to learn their skills: in the same settlement, when your parties meet, or with them in your party or your cells.")); string[] all = SkillIds.All; foreach (string text in all) { encyclopediaSection2.Row(Campaign.SkillName(text), flag ? h.Skill(text).ToString(Inv) : "N/A", "", flag ? "" : "Unknown until you meet them."); } AbilityDef value2; List list = (h.Abilities ?? new List()).Select((string a) => (State.Abilities?.Known == null || !State.Abilities.Known.TryGetValue(a, out value2)) ? a : value2.Name).ToList(); if (list.Count > 0) { EncyclopediaSection encyclopediaSection3 = encyclopediaPage.Section("Special abilities"); foreach (string item in list) { encyclopediaSection3.Row("", item); } } if (!string.IsNullOrWhiteSpace(h.Description)) { encyclopediaPage.Summary = h.Description; } return encyclopediaPage; } internal EncyclopediaPage NotablePage(NotableState n) { Settlement settlement = State.Settlements.Get(n.SettlementId); Clan clan = State.Clans.Get(settlement?.OwnerClanId ?? ""); EncyclopediaPage encyclopediaPage = NewPage(EncyclopediaCategory.Heroes, n.Id, n.Name, n.Occupation + ((settlement == null) ? "" : (" of " + settlement.Name)), clan?.Color, clan?.Symbol); encyclopediaPage.Summary = "A notable of " + (settlement?.Name ?? "a settlement") + ", who offers its volunteers and work."; EncyclopediaSection encyclopediaSection = encyclopediaPage.Section("Information"); encyclopediaSection.Row("Occupation", n.Occupation, "concept:notables"); if (settlement != null) { encyclopediaSection.Row("Home", settlement.Name, SettlementLink(settlement)); } encyclopediaSection.Row("Culture", CultureName(n.CultureId)); encyclopediaSection.Row("Status", n.IsAlive ? "Alive" : "Dead"); if (n.IsAlive) { encyclopediaSection.Row("Relation", Signed(n.PlayerRelation), "concept:notables", "Get on with them and more volunteers come, at 0, 10 and 20."); } if (n.IsAlive && settlement != null) { int num = settlement.Recruits.Count((RecruitSlot r) => r.ProviderId == n.Id); if (num > 0) { encyclopediaSection.Row("Volunteer places", num.ToString(Inv), "concept:notables"); } encyclopediaPage.MapTarget = settlement.Id; } NotableState notableState = State.Notables?.FirstOrDefault((NotableState x) => x.Id == n.PredecessorId); NotableState notableState2 = State.Notables?.FirstOrDefault((NotableState x) => x.PredecessorId == n.Id); if (notableState != null) { encyclopediaSection.Row("Succeeded", notableState.Name, EncyclopediaLinks.For(EncyclopediaCategory.Heroes, notableState.Id)); } if (notableState2 != null) { encyclopediaSection.Row("Succeeded by", notableState2.Name, EncyclopediaLinks.For(EncyclopediaCategory.Heroes, notableState2.Id)); } return encyclopediaPage; } internal EncyclopediaPage ClanPage(Clan clan) { Kingdom kingdom = State.Kingdoms.Get(clan.KingdomId); Hero hero = State.Heroes.Get(clan.LeaderHeroId); bool mine = clan.Id == State.PlayerClanId; EncyclopediaPage encyclopediaPage = NewPage(EncyclopediaCategory.Clans, clan.Id, clan.Name, clan.IsBandit ? "Outlaws" : (clan.IsEliminated ? "A clan that is no more" : ((kingdom != null) ? ("A clan of " + kingdom.Name) : "An independent clan")), clan.Color, clan.Symbol); encyclopediaPage.EmblemColor = clan.EmblemColor ?? ""; EncyclopediaSection encyclopediaSection = encyclopediaPage.Section("Information"); if (hero != null) { encyclopediaSection.Row("Leader", hero.Name, HeroLink(hero)); } if (!clan.IsBandit) { encyclopediaSection.Row("Kingdom", kingdom?.Name ?? "Independent", (kingdom == null) ? "" : KingdomLink(kingdom)); encyclopediaSection.Row("Culture", CultureName(clan.CultureId)); encyclopediaSection.Row("Tier", Campaign.ClanTier(clan).ToString(Inv), "", "Clan tiers come from renown; see Clans, renown and tiers."); encyclopediaSection.Row("Renown", clan.Renown.ToString("0", Inv)); if (!mine) { encyclopediaSection.Row("Relation", Signed(C.ClanRelation(State.PlayerClanId, clan.Id)), "", "Relation between your clan and this one."); } } else { encyclopediaSection.Row("Culture", CultureName(clan.CultureId)); } if (mine) { encyclopediaSection.Row("Treasury", clan.Gold.ToString("N0", Inv) + " denars"); encyclopediaSection.Row("Influence", clan.Influence.ToString("0", Inv)); } if (clan.IsEliminated) { encyclopediaSection.Row("Status", "Eliminated"); } List list = (from h in ClanMembers(clan) orderby (!(h.Id == clan.LeaderHeroId)) ? 1 : 0, (h.State == HeroState.Dead) ? 1 : 0 select h).ThenBy((Hero h) => h.Name, StringComparer.OrdinalIgnoreCase).ToList(); if (list.Count > 0) { EncyclopediaSection encyclopediaSection2 = encyclopediaPage.Section("Members"); foreach (Hero item in list) { encyclopediaSection2.Row((item.Id == clan.LeaderHeroId) ? "Leader" : ((HeroStatusName(item) == "Alive") ? HeroOccupationName(item, clan) : HeroStatusName(item)), item.Name, HeroLink(item)); } } List list2 = (from s in State.Settlements where s.OwnerClanId == clan.Id && s.Type != SettlementType.Hideout orderby (s.Type != SettlementType.Town) ? ((s.Type == SettlementType.Castle) ? 1 : 2) : 0 select s).ThenBy((Settlement s) => s.Name, StringComparer.OrdinalIgnoreCase).ToList(); if (list2.Count > 0) { EncyclopediaSection encyclopediaSection3 = encyclopediaPage.Section("Fiefs"); foreach (Settlement item2 in list2) { encyclopediaSection3.Row(SettlementTypeName(item2.Type), item2.Name, SettlementLink(item2)); } } if (clan.IsBandit) { List list3 = State.Settlements.Where((Settlement s) => s.Type == SettlementType.Hideout && C.HideoutKnown(s) && (s.BanditClanId == clan.Id || s.OwnerClanId == clan.Id)).OrderBy((Settlement s) => s.Name, StringComparer.OrdinalIgnoreCase).ToList(); if (list3.Count > 0) { EncyclopediaSection encyclopediaSection4 = encyclopediaPage.Section("Hideouts"); foreach (Settlement item3 in list3) { encyclopediaSection4.Row(item3.HideoutActive ? "Hideout" : "Abandoned hideout", item3.Name, SettlementLink(item3)); } } } List list4 = (from p in State.Parties where p.ClanId == clan.Id && p.Kind != PartyKind.SiegeDefender && p.Kind != PartyKind.Villager && p.State != PartyState.Destroyed && p.State != PartyState.Disbanded where mine || C.IsKnownToPlayer(p) || State.PlayerSightings.ContainsKey(p.Id) || (p.Kind == PartyKind.Lord && !string.IsNullOrEmpty(p.LeaderHeroId)) select p).OrderBy((Party p) => p.Name, StringComparer.OrdinalIgnoreCase).ThenBy((Party p) => p.Id, StringComparer.Ordinal).ToList(); if (list4.Count > 0) { EncyclopediaSection encyclopediaSection5 = encyclopediaPage.Section("Parties"); foreach (Party item4 in list4) { Hero hero2 = State.Heroes.Get(item4.LeaderHeroId); encyclopediaSection5.Row(PartyStrengthText(item4), item4.Name, (hero2 == null) ? "" : HeroLink(hero2), "Fighters: exact for your own parties, otherwise the estimate from your last sighting."); } } AddWars(encyclopediaPage, State.FactionOf(clan)); return encyclopediaPage; } internal EncyclopediaPage KingdomPage(Kingdom k) { Clan clan = State.Clans.Get(k.RulerClanId); Hero hero = State.Heroes.Get(clan?.LeaderHeroId ?? ""); EncyclopediaPage encyclopediaPage = NewPage(EncyclopediaCategory.Kingdoms, k.Id, k.Name, k.IsEliminated ? "A fallen kingdom" : (CultureName(k.CultureId) + " kingdom"), k.Color, k.Symbol); EncyclopediaSection encyclopediaSection = encyclopediaPage.Section("Information"); if (hero != null) { encyclopediaSection.Row("Ruler", hero.Name, HeroLink(hero)); } if (clan != null) { encyclopediaSection.Row("Ruling clan", clan.Name, ClanLink(clan)); } encyclopediaSection.Row("Culture", CultureName(k.CultureId)); RealmPolicy valueOrDefault = (State.Politics?.KingdomPolicies?.FirstOrDefault((KingdomPolicyState x) => x.KingdomId == k.Id)?.Policy).GetValueOrDefault(); encyclopediaSection.Row("Policy", PolicyName(valueOrDefault), "concept:council"); if (k.IsEliminated) { encyclopediaSection.Row("Status", "Eliminated"); } else { encyclopediaSection.Row("Standing", (State.PlayerClan?.KingdomId == k.Id) ? "Your kingdom" : (State.AtWar(State.FactionOf(State.PlayerClan), k.Id) ? "At war with you" : "At peace with you")); } List list = C.LawsInForce(k.Id); if (list.Count > 0) { EncyclopediaSection encyclopediaSection2 = encyclopediaPage.Section("Policies in force"); foreach (KingdomLaw item in list) { encyclopediaSection2.Row(KingdomLaws.Get(item)?.Group ?? "", KingdomLaws.Name(item), "concept:council"); } } List list2 = (from c in KingdomClans(k) orderby (!(c.Id == k.RulerClanId)) ? 1 : 0, c.Renown descending select c).ThenBy((Clan c) => c.Name, StringComparer.OrdinalIgnoreCase).ToList(); if (list2.Count > 0) { EncyclopediaSection encyclopediaSection3 = encyclopediaPage.Section("Clans"); foreach (Clan item2 in list2) { encyclopediaSection3.Row((item2.Id == k.RulerClanId) ? "Ruling clan" : ("Tier " + Campaign.ClanTier(item2)), item2.Name, ClanLink(item2)); } } List list3 = State.Settlements.Where((Settlement s) => s.Type != SettlementType.Hideout && State.Clans.Get(s.OwnerClanId)?.KingdomId == k.Id).ToList(); if (list3.Count > 0) { EncyclopediaSection encyclopediaSection4 = encyclopediaPage.Section("Fiefs"); foreach (Settlement item3 in (from s in list3 where s.Type != SettlementType.Village orderby (s.Type != SettlementType.Town) ? 1 : 0 select s).ThenBy((Settlement s) => s.Name, StringComparer.OrdinalIgnoreCase)) { encyclopediaSection4.Row(SettlementTypeName(item3.Type), item3.Name, SettlementLink(item3)); } int num = list3.Count((Settlement s) => s.Type == SettlementType.Village); if (num > 0) { encyclopediaSection4.Row("Villages", num.ToString(Inv)); } } AddWars(encyclopediaPage, k.Id); return encyclopediaPage; } internal void AddWars(EncyclopediaPage page, string faction) { if (string.IsNullOrEmpty(faction)) { return; } List list = WarsOf(faction).ToList(); EncyclopediaSection encyclopediaSection = page.Section("Wars", (list.Count == 0) ? "At peace with everyone." : ""); foreach (Campaign.WarRecord item in list) { encyclopediaSection.Row("Since " + DayText(item.SinceMinute), FactionName(item.Other), FactionLink(item.Other)); } List list2 = State.Diplomacy?.Truces?.Where((DiplomaticTruce t) => (t.A == faction || t.B == faction) && t.EndsDay > State.Clock.Day).ToList() ?? new List(); if (list2.Count <= 0) { return; } EncyclopediaSection encyclopediaSection2 = page.Section("Truces"); foreach (DiplomaticTruce item2 in list2) { string id = ((item2.A == faction) ? item2.B : item2.A); long num = item2.EndsDay - State.Clock.Day; encyclopediaSection2.Row(num + ((num == 1) ? " day left" : " days left"), FactionName(id), FactionLink(id)); } } internal EncyclopediaPage SettlementPage(Settlement s) { Clan clan = State.Clans.Get(s.OwnerClanId); Kingdom kingdom = State.Kingdoms.Get(clan?.KingdomId ?? ""); bool flag = s.Type == SettlementType.Village; bool flag2 = s.Type == SettlementType.Town || s.Type == SettlementType.Castle; bool flag3 = s.Type == SettlementType.Hideout; EncyclopediaPage encyclopediaPage = NewPage(EncyclopediaCategory.Settlements, s.Id, s.Name, SettlementTypeName(s.Type) + ((clan == null || flag3) ? "" : (" of " + clan.Name)), clan?.Color, clan?.Symbol); encyclopediaPage.MapTarget = s.Id; string text = World?.Locations?.FirstOrDefault((LocationDef l) => l.Id == s.Id)?.Description ?? ""; encyclopediaPage.Summary = ((text.Length > 0) ? text : (flag3 ? "A refuge where outlaws shelter between raids." : "")); EncyclopediaSection encyclopediaSection = encyclopediaPage.Section("Information"); encyclopediaSection.Row("Type", SettlementTypeName(s.Type)); if (!flag3 && clan != null) { encyclopediaSection.Row("Owner", clan.Name, ClanLink(clan)); } if (!flag3) { encyclopediaSection.Row("Kingdom", kingdom?.Name ?? ((clan == null) ? "Unowned" : "Independent"), (kingdom == null) ? "" : KingdomLink(kingdom)); } if (flag3) { Clan clan2 = State.Clans.Get(string.IsNullOrEmpty(s.BanditClanId) ? s.OwnerClanId : s.BanditClanId); if (clan2 != null) { encyclopediaSection.Row("Outlaws", clan2.Name, ClanLink(clan2)); } encyclopediaSection.Row("Status", s.HideoutActive ? "Occupied" : "Abandoned"); HideoutRecord hideoutRecord = C.Hideout(s.Id); if (s.HideoutActive && hideoutRecord != null) { encyclopediaSection.Row("Gang", C.HideoutGangEstimate(s.Id), "concept:hideouts"); } if (hideoutRecord != null && hideoutRecord.TimesCleared > 0) { encyclopediaSection.Row("Cleared", hideoutRecord.TimesCleared + ((hideoutRecord.TimesCleared == 1) ? " time" : " times")); } } encyclopediaSection.Row("Culture", CultureName(s.CultureId)); if (flag) { VillageProductDef villageProductDef = C.VillageProduct(s); if (villageProductDef != null) { encyclopediaSection.Row("Produces", villageProductDef.Name); } Settlement settlement = State.Settlements.Get(s.BoundTo); if (settlement != null) { encyclopediaSection.Row("Bound to", settlement.Name, SettlementLink(settlement)); } } if (flag2) { encyclopediaSection.Row("Walls", "Level " + Math.Max(1, s.WallLevel), "concept:sieges"); } if (!flag3) { EncyclopediaSection encyclopediaSection2 = encyclopediaPage.Section("Statistics"); encyclopediaSection2.Row(flag ? "Hearths" : "Prosperity", s.Prosperity.ToString("0", Inv), "concept:settlements"); encyclopediaSection2.Row("Loyalty", s.Loyalty.ToString("0", Inv), "concept:settlements"); encyclopediaSection2.Row("Security", s.Security.ToString("0", Inv), "concept:settlements"); encyclopediaSection2.Row("Militia", s.Militia.ToString(Inv), "concept:settlements"); if (flag2) { encyclopediaSection2.Row("Defenders", C.SiegeDefenders(s).ToString(Inv), "", "Fit garrison, militia and defending parties inside."); } else { encyclopediaSection2.Row("Defenders", C.RaidDefenders(s).ToString(Inv), "", "Fit militia and garrison who'd fight off a raid."); } encyclopediaSection2.Row("Food", C.SettlementFood(s).ToString("0", Inv), "concept:food"); if (s.Type == SettlementType.Town && s.Management != null) { encyclopediaSection2.Row("Hardship", Campaign.HardshipTier(s.Management.Hardship) + " (" + s.Management.Hardship.ToString("0", Inv) + ")", "concept:settlements", Campaign.HardshipEffects(s.Management.Hardship)); } if (flag && (s.VillageRecovery?.Damage ?? 0) > 0) { encyclopediaSection2.Row("Raid damage", s.VillageRecovery.Damage.ToString(Inv), "concept:raids"); } } if (flag2) { List list = State.Settlements.Where((Settlement v) => v.Type == SettlementType.Village && v.BoundTo == s.Id).OrderBy((Settlement v) => v.Name, StringComparer.OrdinalIgnoreCase).ToList(); if (list.Count > 0) { EncyclopediaSection encyclopediaSection3 = encyclopediaPage.Section("Villages"); foreach (Settlement item in list) { encyclopediaSection3.Row(C.VillageProduct(item)?.Name ?? "Village", item.Name, SettlementLink(item)); } } } List list2 = (State.Notables ?? new List()).Where((NotableState n) => n.IsAlive && n.SettlementId == s.Id).OrderBy((NotableState n) => n.Name, StringComparer.OrdinalIgnoreCase).ToList(); if (list2.Count > 0) { EncyclopediaSection encyclopediaSection4 = encyclopediaPage.Section("Notables"); foreach (NotableState item2 in list2) { encyclopediaSection4.Row(item2.Occupation, item2.Name, EncyclopediaLinks.For(EncyclopediaCategory.Heroes, item2.Id), "Their relation with you: " + Signed(item2.PlayerRelation) + "."); } } Hero hero = ((s.OwnerClanId == State.PlayerClanId) ? State.Heroes.Get(s.Management?.GovernorHeroId ?? "") : null); if (hero != null) { encyclopediaSection.Row("Governor", hero.Name, HeroLink(hero)); } SiegeState siegeState = C.SiegeForSettlement(s.Id); TournamentState tournamentState = ((s.Type == SettlementType.Town) ? C.TournamentAt(s.Id) : null); if (siegeState != null || tournamentState != null) { EncyclopediaSection encyclopediaSection5 = encyclopediaPage.Section("Now"); if (siegeState != null) { Party party = State.Parties.Get(siegeState.BesiegerPartyId); Clan clan3 = State.Clans.Get(party?.ClanId ?? ""); encyclopediaSection5.Row("Under siege", clan3?.Name ?? party?.Name ?? "Besieged", (clan3 == null) ? "concept:sieges" : ClanLink(clan3)); } if (tournamentState != null) { encyclopediaSection5.Row("Tournament", "Prize: " + (tournamentState.Prize?.Name ?? "a prize") + " · ends " + DayText(tournamentState.EndMinute), "concept:tournaments"); } } return encyclopediaPage; } internal EncyclopediaPage UnitPage(UnitDef u) { CultureDef cultureDef = Content.Cultures.Get(u.Culture); EncyclopediaPage encyclopediaPage = NewPage(EncyclopediaCategory.Units, u.Id, u.Name, "Tier " + u.Tier + " " + RoleName(u.Role).ToLowerInvariant() + " · " + CultureName(u.Culture), cultureDef?.Color, cultureDef?.Symbol); EncyclopediaSection encyclopediaSection = encyclopediaPage.Section("Information"); encyclopediaSection.Row("Culture", CultureName(u.Culture)); encyclopediaSection.Row("Tier", u.Tier.ToString(Inv)); encyclopediaSection.Row("Role", RoleName(u.Role)); encyclopediaSection.Row("Rarity", u.Rarity.ToString()); encyclopediaSection.Row("Mount", u.Mounted ? "Mounted" : "On foot"); if (!string.IsNullOrEmpty(u.TabsFaction)) { encyclopediaSection.Row("TABS faction", u.TabsFaction); } if (u.Slots > 1) { encyclopediaSection.Row("Battle places", u.Slots.ToString(Inv), "concept:battles", "This troop takes up several places on the field."); } EncyclopediaSection encyclopediaSection2 = encyclopediaPage.Section("Upkeep"); encyclopediaSection2.Row("Recruit cost", u.RecruitCost.ToString(Inv) + " denars"); encyclopediaSection2.Row("Daily wage", u.DailyWage.ToString("0.#", Inv) + " denars"); encyclopediaSection2.Row("Food a day", u.FoodUse.ToString("0.##", Inv)); encyclopediaSection2.Row("Map speed", "×" + u.MapSpeed.ToString("0.##", Inv)); EncyclopediaSection encyclopediaSection3 = encyclopediaPage.Section("Battle ratings", "For auto-resolve and judging strength on the map. In a played battle it's just its TABS unit."); encyclopediaSection3.Row("Attack", u.Attack.ToString("0.##", Inv)); encyclopediaSection3.Row("Defense", u.Defense.ToString("0.##", Inv)); encyclopediaSection3.Row("Health", u.Health.ToString("0.##", Inv)); if (u.Ranged > 0.0) { encyclopediaSection3.Row("Ranged", u.Ranged.ToString("0.##", Inv)); } EncyclopediaSection encyclopediaSection4 = encyclopediaPage.Section("How to get"); List list = Content.Cultures.Where((CultureDef c) => c.VillageRecruits.Any((WeightedUnit w) => w.Unit == u.Id)).OrderBy((CultureDef c) => c.Name, StringComparer.OrdinalIgnoreCase).ToList(); List list2 = Content.Cultures.Where((CultureDef c) => c.TownRecruits.Any((WeightedUnit w) => w.Unit == u.Id)).OrderBy((CultureDef c) => c.Name, StringComparer.OrdinalIgnoreCase).ToList(); foreach (AccessKind item in u.Access.Distinct()) { if (item == AccessKind.VillageRecruit && list.Count > 0) { foreach (CultureDef item2 in list) { encyclopediaSection4.Row("Village volunteers", item2.Name + " villages", "concept:notables"); } } else if (item == AccessKind.TownRecruit && list2.Count > 0) { foreach (CultureDef item3 in list2) { encyclopediaSection4.Row("Town volunteers", item3.Name + " towns", "concept:notables"); } } else { encyclopediaSection4.Row("", AccessName(item)); } } if (!u.Access.Contains(AccessKind.VillageRecruit)) { foreach (CultureDef item4 in list) { encyclopediaSection4.Row("Village volunteers", item4.Name + " villages", "concept:notables"); } } if (!u.Access.Contains(AccessKind.TownRecruit)) { foreach (CultureDef item5 in list2) { encyclopediaSection4.Row("Town volunteers", item5.Name + " towns", "concept:notables"); } } if (encyclopediaSection4.Rows.Count == 0) { encyclopediaPage.Sections.Remove(encyclopediaSection4); } if (u.Upgrades.Count > 0) { EncyclopediaSection encyclopediaSection5 = encyclopediaPage.Section("Upgrades to"); foreach (UpgradeDef upgrade in u.Upgrades) { UnitDef unitDef = Content.Units.Get(upgrade.To); if (unitDef != null) { string text = (string.IsNullOrEmpty(upgrade.RequiresSettlement) ? "" : (" · at a " + upgrade.RequiresSettlement)); encyclopediaSection5.Row(upgrade.Xp + " XP · " + upgrade.Gold + " denars" + text, unitDef.Name, UnitLink(unitDef)); } } } List list3 = UpgradeSources(u.Id); if (list3.Count > 0) { EncyclopediaSection encyclopediaSection6 = encyclopediaPage.Section("Upgraded from"); foreach (UnitDef item6 in list3) { encyclopediaSection6.Row("Tier " + item6.Tier, item6.Name, UnitLink(item6)); } } EncyclopediaSection encyclopediaSection7 = encyclopediaPage.Section("Troop tree"); HashSet seen = new HashSet(StringComparer.Ordinal); foreach (UnitDef item7 in TreeRoots(u)) { AddTree(encyclopediaSection7, item7, 0, seen); } if (encyclopediaSection7.Rows.Count <= 1) { encyclopediaPage.Sections.Remove(encyclopediaSection7); } return encyclopediaPage; } internal EncyclopediaPage ConceptPage(EncyclopediaConceptDef c) { EncyclopediaPage encyclopediaPage = NewPage(EncyclopediaCategory.Concepts, c.Id, c.Title, c.Topic); encyclopediaPage.Section("", c.Text); List list = (from x in c.See.Select(EncyclopediaConcepts.Get) where x != null select x).ToList(); if (list.Count > 0) { EncyclopediaSection encyclopediaSection = encyclopediaPage.Section("See also"); foreach (EncyclopediaConceptDef item in list) { encyclopediaSection.Row(item.Topic, item.Title, EncyclopediaLinks.For(EncyclopediaCategory.Concepts, item.Id)); } } return encyclopediaPage; } internal List UpgradeSources(string unitId) { return (from x in Content.Units where x.Upgrades.Any((UpgradeDef up) => up.To == unitId) orderby x.Tier select x).ThenBy((UnitDef x) => x.Name, StringComparer.OrdinalIgnoreCase).ToList(); } internal List TreeRoots(UnitDef unit) { List list = new List(); HashSet hashSet = new HashSet(StringComparer.Ordinal); Stack stack = new Stack(); stack.Push(unit); while (stack.Count > 0) { UnitDef unitDef = stack.Pop(); if (!hashSet.Add(unitDef.Id)) { continue; } List list2 = UpgradeSources(unitDef.Id); if (list2.Count == 0) { if (!list.Contains(unitDef)) { list.Add(unitDef); } continue; } foreach (UnitDef item in list2) { stack.Push(item); } } return list.OrderBy((UnitDef r) => r.Tier).ThenBy((UnitDef r) => r.Name, StringComparer.OrdinalIgnoreCase).ToList(); } internal void AddTree(EncyclopediaSection tree, UnitDef u, int depth, HashSet seen) { if (depth > 8) { return; } bool flag = !seen.Add(u.Id); tree.Row("Tier " + u.Tier, u.Name + (flag ? " (above)" : ""), UnitLink(u), "", depth); if (flag) { return; } foreach (UpgradeDef upgrade in u.Upgrades) { UnitDef unitDef = Content.Units.Get(upgrade.To); if (unitDef != null) { AddTree(tree, unitDef, depth + 1, seen); } } } public string HeroWhereabouts(Hero h, out string mapTarget) { mapTarget = ""; if (h == null) { return "Unknown"; } if (h.State == HeroState.Dead) { return "Dead"; } if (h.State == HeroState.Inactive) { Settlement settlement = State.Settlements.Get(h.SettlementId); if (settlement != null && (h.ClanId == State.PlayerClanId || CanSeeInto(settlement))) { mapTarget = settlement.Id; return "Growing up in " + settlement.Name; } if (!C.IsChild(h)) { return "Away"; } return "Growing up at home"; } bool flag = h.ClanId == State.PlayerClanId; if (h.State == HeroState.Captive) { Party party = State.Parties.Get(h.CaptorPartyId); Settlement settlement2 = State.Settlements.Get(h.CaptorSettlementId); if (party != null && party.Id == State.PlayerPartyId) { mapTarget = party.Id; return "Your prisoner"; } if (party != null && party.ClanId == State.PlayerClanId) { mapTarget = party.Id; return "Prisoner of " + party.Name; } if (settlement2 != null && CanSeeInto(settlement2)) { mapTarget = settlement2.Id; return "Prisoner in " + settlement2.Name; } return "Held prisoner; where, you do not know"; } Party party2 = State.Parties.Get(h.PartyId); if (party2 != null && party2.State != PartyState.Destroyed && party2.State != PartyState.Disbanded) { if (party2.Id == State.PlayerPartyId) { mapTarget = party2.Id; if (!flag || !h.IsPlayer) { return "In your party"; } return "Leading your party"; } Settlement settlement3 = ((party2.State == PartyState.InSettlement) ? State.Settlements.Get(party2.CurrentSettlementId) : null); bool flag2 = flag || C.IsPlayerCaravan(party2) || C.IsPlayerMilitaryParty(party2) || C.IsKingdomArmyParty(party2); if (settlement3 != null) { if (flag2 || CanSeeInto(settlement3)) { mapTarget = settlement3.Id; return "In " + settlement3.Name; } return LastSeen(party2, out mapTarget); } if (flag2) { mapTarget = party2.Id; return "With " + party2.Name + " near " + NearestPlaceName(party2.Position); } return LastSeen(party2, out mapTarget); } WandererPlan wandererPlan = (C.IsWanderer(h) ? C.WandererPlan(h.Id) : null); if (wandererPlan != null && wandererPlan.Travelling) { Settlement settlement4 = State.Settlements.Get(wandererPlan.FromId); Settlement settlement5 = State.Settlements.Get(wandererPlan.DestinationId); return "On the road " + ((settlement4 == null) ? "" : ("from " + settlement4.Name + " ")) + "to " + (settlement5?.Name ?? "another town"); } Settlement settlement6 = State.Settlements.Get(h.SettlementId); if (settlement6 != null) { if (h.Occupation == HeroOccupation.Companion && string.IsNullOrEmpty(h.ClanId)) { mapTarget = settlement6.Id; return "In the tavern at " + settlement6.Name; } if (flag || CanSeeInto(settlement6)) { mapTarget = settlement6.Id; return "In " + settlement6.Name; } } return "Whereabouts unknown"; } internal string LastSeen(Party party, out string mapTarget) { mapTarget = ""; if (!State.PlayerSightings.TryGetValue(party.Id, out var value)) { return "Whereabouts unknown"; } mapTarget = party.Id; if (value.CurrentlyVisible) { return "With " + party.Name + " near " + NearestPlaceName(value.Position) + " (in sight)"; } return "Last seen near " + NearestPlaceName(value.Position) + ", " + AgoText(value.SeenAtMinute); } public bool KnowsHero(Hero h) { if (h != null) { if (!h.IsPlayer && (string.IsNullOrEmpty(h.ClanId) || !(h.ClanId == State.PlayerClanId)) && !State.Settings.FullInformation) { return State.MetHeroes?.Contains(h.Id) ?? false; } return true; } return false; } internal void NoteHeroesMet() { if (State.MetHeroes == null) { State.MetHeroes = new SortedSet(StringComparer.Ordinal); } SortedSet met = State.MetHeroes; Party playerParty = State.PlayerParty; if (playerParty != null) { MeetParty(playerParty); foreach (string hero in playerParty.Prisoners.Heroes) { Meet(hero); } } Encounter encounter = State.Encounters.Get(State.Player.PendingEncounterId); if (encounter != null) { foreach (string allParty in encounter.AllParties) { MeetParty(State.Parties.Get(allParty)); } } if (State.Player.Activity == PlayerActivity.Captive) { MeetParty(State.Parties.Get(State.Player.CaptorPartyId)); } if (playerParty == null || playerParty.State != PartyState.InSettlement || string.IsNullOrEmpty(playerParty.CurrentSettlementId)) { return; } string currentSettlementId = playerParty.CurrentSettlementId; foreach (Party party2 in State.Parties) { if (party2.State == PartyState.InSettlement && party2.CurrentSettlementId == currentSettlementId) { MeetParty(party2); } } foreach (Hero hero2 in State.Heroes) { if (hero2.State == HeroState.Active && !(hero2.SettlementId != currentSettlementId)) { Party party = State.Parties.Get(hero2.PartyId); if (party == null || party.State == PartyState.Destroyed || party.State == PartyState.Disbanded) { met.Add(hero2.Id); } } } void Meet(string id) { if (!string.IsNullOrEmpty(id) && State.Heroes.Contains(id)) { met.Add(id); } } void MeetParty(Party p) { if (p == null || p.State == PartyState.Destroyed || p.State == PartyState.Disbanded) { return; } Meet(p.LeaderHeroId); foreach (string hero3 in p.Troops.Heroes) { Meet(hero3); } } } internal bool CanSeeInto(Settlement s) { if (s == null) { return false; } if (State.PlayerParty?.CurrentSettlementId == s.Id && State.PlayerParty.State == PartyState.InSettlement) { return true; } Clan clan = State.Clans.Get(s.OwnerClanId); if (clan != null && State.PlayerClan != null) { return State.FactionOf(clan) == State.FactionOf(State.PlayerClan); } return false; } public string PartyStrengthText(Party p) { if (p == null) { return ""; } if (p.Id == State.PlayerPartyId || p.ClanId == State.PlayerClanId || C.IsPlayerCaravan(p) || C.IsPlayerMilitaryParty(p) || C.IsKingdomArmyParty(p)) { return C.PartyCombatants(p) + " fighters"; } if (State.PlayerSightings.TryGetValue(p.Id, out var value)) { return "~" + value.EstimatedStrength + " fighters"; } return "strength unknown"; } internal string NearestPlaceName(Vec2 position) { Settlement settlement = null; double num = double.MaxValue; foreach (Settlement settlement2 in State.Settlements) { if (settlement2.Type != SettlementType.Hideout) { double num2 = Vec2.Distance(settlement2.Position, position); if (num2 < num) { num = num2; settlement = settlement2; } } } return settlement?.Name ?? "the wilds"; } internal string AgoText(long minute) { long num = Math.Max(0L, State.Clock.Minute - minute); if (num < 60) { return "just now"; } if (num < 1440) { long num2 = num / 60; return num2 + ((num2 == 1) ? " hour ago" : " hours ago"); } long num3 = num / 1440; return num3 + ((num3 == 1) ? " day ago" : " days ago"); } internal static string DayText(long minute) { return "day " + (minute / 1440 + 1).ToString(Inv); } public bool IsEncyclopediaBookmark(string link) { return State.EncyclopediaBookmarks?.Contains(link) ?? false; } public CommandResult ToggleEncyclopediaBookmark(string link) { if (State.EncyclopediaBookmarks == null) { State.EncyclopediaBookmarks = new List(); } List encyclopediaBookmarks = State.EncyclopediaBookmarks; if (encyclopediaBookmarks.Remove(link)) { State.Touch(); return CommandResult.Success("Bookmark removed."); } if (EncyclopediaPage(link) == null) { return CommandResult.Fail("That page isn't in the encyclopedia."); } if (encyclopediaBookmarks.Count >= 60) { return CommandResult.Fail("You can keep up to " + 60 + " bookmarks. Remove one first."); } encyclopediaBookmarks.Add(link); State.Touch(); return CommandResult.Success("Bookmarked."); } internal IEnumerable ClanMembers(Clan clan) { return State.Heroes.Where((Hero h) => h.ClanId == clan.Id); } internal IEnumerable KingdomClans(Kingdom k) { return State.Clans.Where((Clan c) => c.KingdomId == k.Id && !c.IsEliminated && !c.IsBandit); } internal IEnumerable WarsOf(string faction) { return (from s in State.Stances where s.Stance == Stance.War && (s.A == faction || s.B == faction) select new Campaign.WarRecord { Other = ((s.A == faction) ? s.B : s.A), SinceMinute = s.SinceMinute } into w where FactionExists(w.Other) select w).OrderBy((Campaign.WarRecord w) => FactionName(w.Other), StringComparer.OrdinalIgnoreCase); } internal bool FactionExists(string id) { Kingdom kingdom = State.Kingdoms.Get(id); if (kingdom != null) { return !kingdom.IsEliminated; } Clan clan = State.Clans.Get(id); if (clan != null) { return !clan.IsEliminated; } return false; } internal string FactionName(string id) { return State.Kingdoms.Get(id)?.Name ?? State.Clans.Get(id)?.Name ?? id; } internal string FactionLink(string id) { if (!State.Kingdoms.Contains(id)) { if (!State.Clans.Contains(id)) { return ""; } return EncyclopediaLinks.For(EncyclopediaCategory.Clans, id); } return EncyclopediaLinks.For(EncyclopediaCategory.Kingdoms, id); } internal string Standing(Clan clan) { if (clan == null) { return "Unaffiliated"; } if (clan.Id == State.PlayerClanId) { return "Your clan"; } if (clan.IsBandit) { return "Outlaws"; } Clan playerClan = State.PlayerClan; if (playerClan != null && State.FactionOf(clan) == State.FactionOf(playerClan)) { return "Your kingdom"; } if (playerClan != null && State.AreHostile(playerClan, clan)) { return "At war with you"; } return "At peace"; } internal string HeroStatusName(Hero h) { if (h.State != HeroState.Dead) { if (h.State != HeroState.Captive) { if (h.State != HeroState.Inactive) { return "Alive"; } if (!C.IsChild(h)) { return "Inactive"; } return "Child"; } return "Prisoner"; } return "Dead"; } internal void FamilySection(EncyclopediaPage page, Hero h) { EncyclopediaSection encyclopediaSection = page.Section("Family"); Hero hero = State.Heroes.Get(h.SpouseId); if (hero != null && (C.SpouseOf(h) != null || h.State == HeroState.Dead)) { encyclopediaSection.Row(Families.Noun(hero.Sex, "Husband", "Wife", "Spouse"), Who(hero), HeroLink(hero)); } foreach (Hero item in from id in h.FormerSpouseIds ?? new List() select State.Heroes.Get(id) into x where x != null select x) { List divorcedIds = h.DivorcedIds; encyclopediaSection.Row(((divorcedIds != null && divorcedIds.Contains(item.Id)) ? "Former " : "Late ") + Families.Noun(item.Sex, "husband", "wife", "spouse"), Who(item), HeroLink(item)); } foreach (Hero item2 in C.ParentsOf(h)) { encyclopediaSection.Row((item2.Id == h.FatherId) ? "Father" : "Mother", Who(item2), HeroLink(item2)); } foreach (Hero item3 in (from c in C.ChildrenOf(h) orderby c.BornDay select c).ThenBy((Hero c) => c.Id, StringComparer.Ordinal)) { encyclopediaSection.Row(Families.Noun(item3.Sex, "Son", "Daughter", "Child"), Who(item3), HeroLink(item3)); } foreach (Hero item4 in (from c in C.SiblingsOf(h) orderby c.BornDay select c).ThenBy((Hero c) => c.Id, StringComparer.Ordinal)) { encyclopediaSection.Row(Families.Noun(item4.Sex, "Brother", "Sister", "Sibling"), Who(item4), HeroLink(item4)); } if (h.ChildDueDay >= 0 && h.State != HeroState.Dead && (h.ClanId == State.PlayerClanId || KnowsHero(h))) { encyclopediaSection.Row("Expecting", "A child, due in " + Math.Max(0L, h.ChildDueDay - State.Clock.Day) + " days"); } if (encyclopediaSection.Rows.Count == 0) { encyclopediaSection.Text = "No family known."; } string Who(Hero k) { return k.Name + ((k.State == HeroState.Dead) ? (" (died at " + C.HeroYears(k) + ")") : (C.IsChild(k) ? (" (" + C.HeroYears(k) + ")") : "")); } } internal string HeroOccupationName(Hero h, Clan clan) { if (h.IsPlayer) { return "You"; } switch (h.Occupation) { case HeroOccupation.Companion: if (clan != null) { if (!h.IsFamily) { return "Companion"; } return "Family"; } return "Wanderer"; case HeroOccupation.Notable: return "Notable"; case HeroOccupation.BanditBoss: return "Outlaw leader"; default: if (h.Sex != HeroSex.Female) { return "Lord"; } return "Lady"; } } internal string HeroDescription(Hero h, Clan clan) { if (h.IsPlayer) { return "You" + ((clan == null) ? "" : (", leader of " + clan.Name)); } Kingdom kingdom = State.Kingdoms.Get(clan?.KingdomId ?? ""); if (clan != null && kingdom != null && kingdom.RulerClanId == clan.Id && clan.LeaderHeroId == h.Id && !kingdom.IsEliminated) { return "Ruler of " + kingdom.Name; } if (clan != null && clan.LeaderHeroId == h.Id) { return (clan.IsBandit ? "Chief of " : "Leader of ") + clan.Name; } string text = HeroOccupationName(h, clan); if (text == "Wanderer") { return "Wanderer"; } if (clan == null) { return text; } if (clan.Id == State.PlayerClanId && text == "Family") { if (!C.IsChild(h)) { return "Your family"; } return "Your family (a child)"; } if (h.State == HeroState.Dead && h.Occupation == HeroOccupation.Player) { return "Former head of " + clan.Name; } if (!(text == "Companion") || !(clan.Id == State.PlayerClanId)) { return text + " of " + clan.Name; } return "Your companion"; } internal string CultureName(string id) { object obj; if (!string.IsNullOrEmpty(id)) { obj = Content.Cultures.Get(id)?.Name; if (obj == null) { return id; } } else { obj = "None"; } return (string)obj; } internal static string SettlementTypeName(SettlementType t) { return t.ToString(); } internal static string RoleName(TroopRole role) { return role.ToString(); } internal static string PolicyName(RealmPolicy p) { return p switch { RealmPolicy.WarLevy => "War Levy", RealmPolicy.LocalCharters => "Local Charters", _ => "Balanced", }; } internal static string AccessName(AccessKind a) { return a switch { AccessKind.VillageRecruit => "Volunteers in villages", AccessKind.TownRecruit => "Volunteers in towns", AccessKind.Upgrade => "Upgrading another troop", AccessKind.Mercenary => "Hired as a mercenary", AccessKind.Bandit => "Found among outlaws", AccessKind.Discovery => "Found on the map", AccessKind.Quest => "A quest reward", AccessKind.LordOnly => "Only in lords' parties", _ => "Not yet available to you", }; } internal static string Signed(int value) { if (value <= 0) { return value.ToString(Inv); } return "+" + value.ToString(Inv); } internal static string HeroLink(Hero h) { return EncyclopediaLinks.For(EncyclopediaCategory.Heroes, h.Id); } internal static string ClanLink(Clan c) { return EncyclopediaLinks.For(EncyclopediaCategory.Clans, c.Id); } internal static string KingdomLink(Kingdom k) { return EncyclopediaLinks.For(EncyclopediaCategory.Kingdoms, k.Id); } internal static string SettlementLink(Settlement s) { return EncyclopediaLinks.For(EncyclopediaCategory.Settlements, s.Id); } internal static string UnitLink(UnitDef u) { return EncyclopediaLinks.For(EncyclopediaCategory.Units, u.Id); } } internal sealed class EnterprisesSystem { private readonly Campaign C; private CampaignState State => C.State; internal EnterprisesSystem(Campaign host) { C = host; } public void EnsureEnterpriseFields() { if (State.Workshops == null) { State.Workshops = new List(); State.Touch(); } } public string BuyWorkshopReason(string typeId) { string text = C.DisguiseBlockReason(); if (text.Length > 0) { return text; } string text2 = C.CargoCommandReason(); if (text2.Length > 0) { return text2; } Settlement town = C.CompanionMeetingSettlement(townOnly: true); if (town == null) { return "Workshops are bought in friendly towns."; } WorkshopTypeDef workshopTypeDef = WorkshopTypes.Get(typeId); if (workshopTypeDef == null) { return "Unknown workshop type."; } if (State.Clans.Get(town.OwnerClanId) == null) { return "Nobody here is selling a workshop."; } if (State.Workshops.Count((WorkshopState x) => x.OwnerClanId == State.PlayerClanId) >= 3) { return "Three workshops is the limit."; } if (State.Workshops.Any((WorkshopState x) => x.SettlementId == town.Id && x.TypeId == typeId)) { return "You already have that workshop here."; } if (State.PlayerClan.Gold < workshopTypeDef.Cost) { return "You need " + workshopTypeDef.Cost + " denars."; } if (town.Market.Gold > long.MaxValue - (workshopTypeDef.Cost - 200)) { return "The seller cannot receive payment."; } return ""; } public CommandResult BuyWorkshop(string typeId) { string text = BuyWorkshopReason(typeId); if (text.Length > 0) { return CommandResult.Fail(text); } Settlement settlement = C.CompanionMeetingSettlement(townOnly: true); WorkshopTypeDef workshopTypeDef = WorkshopTypes.Get(typeId); State.Transact(State.PlayerClan, -workshopTypeDef.Cost, LedgerAccount.Trade, "Bought " + workshopTypeDef.Name); settlement.Market.Gold += workshopTypeDef.Cost - 200; WorkshopState item = new WorkshopState { Id = "workshop." + State.Ids.AllocateNumber("workshop"), OwnerClanId = State.PlayerClanId, SettlementId = settlement.Id, SettlementOwnerClanId = settlement.OwnerClanId, TypeId = workshopTypeDef.Id, PurchasePrice = workshopTypeDef.Cost, Capital = 200L, LastDay = State.Clock.Day }; State.Workshops.Add(item); State.AddLog(LogCategory.Economy, "Bought a " + workshopTypeDef.Name + " in " + settlement.Name + "; 200 denars stay in as capital.", settlement.Id); State.Touch(); return CommandResult.Success(workshopTypeDef.Name + " purchased."); } public string WorkshopActionReason(string id, string action, long amount = 0L) { string text = C.CargoCommandReason(); if (text.Length > 0) { return text; } WorkshopState workshopState = State.Workshops.FirstOrDefault((WorkshopState x) => x.Id == id); if (workshopState == null || workshopState.OwnerClanId != State.PlayerClanId) { return "This is not your workshop."; } Settlement settlement = C.CompanionMeetingSettlement(townOnly: true); if (settlement == null || settlement.Id != workshopState.SettlementId) { return "Go to its town to manage it."; } if (settlement.OwnerClanId != workshopState.SettlementOwnerClanId) { return "The town changed hands, so the workshop's shut."; } switch (action) { case "enable": case "disable": return ""; case "fund": if (amount <= 0) { return "Choose a positive amount."; } if (State.PlayerClan.Gold < amount) { return "You can't afford that."; } if (workshopState.Capital > long.MaxValue - amount) { return "The workshop cannot hold this deposit."; } return ""; case "withdraw": if (amount <= 0) { return "Choose a positive amount."; } if (workshopState.Capital < amount) { return "The workshop hasn't got that much."; } if (State.PlayerClan.Gold > long.MaxValue - amount) { return "Your treasury's full."; } return ""; case "sell": { if (workshopState.Capital > 9223372036854775057L) { return "The sale amount is too large."; } long num = 750 + workshopState.Capital; if (settlement.Market.Gold < 750) { return "The merchants here can't afford it."; } if (State.PlayerClan.Gold > long.MaxValue - num) { return "Your treasury can't take that much."; } return ""; } default: return "Unknown workshop action."; } } public CommandResult SetWorkshopEnabled(string id, bool enabled) { string text = WorkshopActionReason(id, enabled ? "enable" : "disable", 0L); if (text.Length > 0) { return CommandResult.Fail(text); } WorkshopState workshopState = State.Workshops.First((WorkshopState x) => x.Id == id); if (workshopState.Enabled == enabled) { return CommandResult.Success(enabled ? "Already enabled." : "Already paused."); } workshopState.Enabled = enabled; workshopState.Status = (enabled ? "Ready" : "Paused"); State.Touch(); return CommandResult.Success(workshopState.Status); } public CommandResult FundWorkshop(string id, long amount) { string text = WorkshopActionReason(id, "fund", amount); if (text.Length > 0) { return CommandResult.Fail(text); } WorkshopState workshopState = State.Workshops.First((WorkshopState x) => x.Id == id); State.Transact(State.PlayerClan, -amount, LedgerAccount.Trade, "Workshop operating capital"); workshopState.Capital += amount; State.Touch(); return CommandResult.Success("Operating capital added."); } public CommandResult WithdrawWorkshop(string id, long amount) { string text = WorkshopActionReason(id, "withdraw", amount); if (text.Length > 0) { return CommandResult.Fail(text); } State.Workshops.First((WorkshopState x) => x.Id == id).Capital -= amount; State.Transact(State.PlayerClan, amount, LedgerAccount.Trade, "Workshop withdrawal"); State.Touch(); return CommandResult.Success("Capital withdrawn."); } public CommandResult SellWorkshop(string id) { string text = WorkshopActionReason(id, "sell", 0L); if (text.Length > 0) { return CommandResult.Fail(text); } WorkshopState workshopState = State.Workshops.First((WorkshopState x) => x.Id == id); Settlement settlement = State.Settlements.Require(workshopState.SettlementId); long amount = 750 + workshopState.Capital; settlement.Market.Gold -= 750L; workshopState.Capital = 0L; State.Transact(State.PlayerClan, amount, LedgerAccount.Trade, "Sold workshop at " + settlement.Name); State.Workshops.Remove(workshopState); State.AddLog(LogCategory.Economy, "Sold a workshop at " + settlement.Name + " for " + amount + " denars including capital.", settlement.Id); State.Touch(); return CommandResult.Success("Workshop sold."); } public string AbandonWorkshopReason(string id) { string text = C.CargoCommandReason(); if (text.Length > 0) { return text; } WorkshopState workshopState = State.Workshops.FirstOrDefault((WorkshopState x) => x.Id == id); if (workshopState == null || workshopState.OwnerClanId != State.PlayerClanId) { return "This is not your workshop."; } Settlement settlement = State.Settlements.Get(workshopState.SettlementId); if (settlement == null || settlement.OwnerClanId != workshopState.SettlementOwnerClanId || State.AreHostile(State.PlayerClan, State.Clans.Get(settlement.OwnerClanId))) { return ""; } return "You can only walk away from a workshop shut by war or a lost charter. Otherwise sell it in its town."; } public CommandResult AbandonWorkshop(string id) { string text = AbandonWorkshopReason(id); if (text.Length > 0) { return CommandResult.Fail(text); } WorkshopState workshopState = State.Workshops.First((WorkshopState x) => x.Id == id); Settlement settlement = State.Settlements.Get(workshopState.SettlementId); long capital = workshopState.Capital; workshopState.Capital = 0L; State.Workshops.Remove(workshopState); State.AddLog(LogCategory.Economy, "Abandoned a workshop at " + (settlement?.Name ?? "a lost settlement") + "; its assets and " + capital + " denars of operating capital were lost.", workshopState.SettlementId); State.Touch(); return CommandResult.Success("Workshop abandoned. Its assets and " + capital + " denars of capital were lost."); } public string RecharterWorkshopReason(string id) { string text = C.CargoCommandReason(); if (text.Length > 0) { return text; } WorkshopState workshopState = State.Workshops.FirstOrDefault((WorkshopState x) => x.Id == id); if (workshopState == null || workshopState.OwnerClanId != State.PlayerClanId) { return "This is not your workshop."; } Settlement settlement = C.CompanionMeetingSettlement(townOnly: true); if (settlement == null || settlement.Id != workshopState.SettlementId) { return "Renew the charter in its town (it has to be friendly)."; } if (settlement.OwnerClanId == workshopState.SettlementOwnerClanId) { return "The charter's still good."; } if (State.Clans.Get(settlement.OwnerClanId) == null) { return "This town can't renew it."; } if (State.PlayerClan.Gold < 250) { return "Renewing the charter costs " + 250L + " denars."; } if (settlement.Market.Gold > 9223372036854775557L) { return "The town's merchants cannot receive the charter fee."; } return ""; } public CommandResult RecharterWorkshop(string id) { string text = RecharterWorkshopReason(id); if (text.Length > 0) { return CommandResult.Fail(text); } WorkshopState workshopState = State.Workshops.First((WorkshopState x) => x.Id == id); Settlement settlement = State.Settlements.Require(workshopState.SettlementId); State.Transact(State.PlayerClan, -250L, LedgerAccount.Trade, "Renewed workshop charter at " + settlement.Name); settlement.Market.Gold += 250L; workshopState.SettlementOwnerClanId = settlement.OwnerClanId; workshopState.Enabled = true; workshopState.Status = "Ready"; workshopState.LastProfit = 0L; workshopState.LastDay = State.Clock.Day; State.AddLog(LogCategory.Economy, "Renewed a workshop charter at " + settlement.Name + " for " + 250L + " denars.", settlement.Id); State.Touch(); return CommandResult.Success("Workshop charter renewed."); } public void DailyEnterprises() { bool flag = false; foreach (WorkshopState item in State.Workshops.OrderBy((WorkshopState x) => x.Id, StringComparer.Ordinal)) { if (item.LastDay >= State.Clock.Day) { continue; } item.LastDay = State.Clock.Day; item.LastProfit = 0L; flag = true; Settlement town = State.Settlements.Get(item.SettlementId); Clan clan = State.Clans.Get(item.OwnerClanId); Clan clan2 = ((town == null) ? null : State.Clans.Get(town.OwnerClanId)); WorkshopTypeDef workshopTypeDef = WorkshopTypes.Get(item.TypeId); if (town == null || clan == null || clan2 == null || workshopTypeDef == null || town.OwnerClanId != item.SettlementOwnerClanId || State.AreHostile(clan, clan2) || C.IsSettlementBesieged(town)) { item.Status = "Suspended"; continue; } if (!item.Enabled) { item.Status = "Paused"; continue; } if (workshopTypeDef.Inputs.Any((KeyValuePair x) => C.MarketStock(town, x.Key) < x.Value)) { item.Status = "Needs materials"; continue; } if (C.MarketStock(town, workshopTypeDef.OutputGoodId) >= 500) { item.Status = "Market full"; continue; } long num = 0L; foreach (KeyValuePair input in workshopTypeDef.Inputs) { for (int num2 = 0; num2 < input.Value; num2++) { num += C.CommodityPrice(town, input.Key, buying: true, C.MarketStock(town, input.Key) - num2); } } long num3 = C.CommodityPrice(town, workshopTypeDef.OutputGoodId, buying: false, C.MarketStock(town, workshopTypeDef.OutputGoodId) + 1); long num4 = num + workshopTypeDef.OperatingCost; if (item.Capital < num4) { item.Status = "Needs capital"; continue; } if (town.Market.Gold > long.MaxValue - num || town.Market.Gold + num < num3) { item.Status = "Merchant short of cash"; continue; } long num5 = num3 - num4; if ((num5 > 0 && (item.Capital > long.MaxValue - num5 || item.TotalProfit > long.MaxValue - num5)) || (num5 < 0 && item.TotalProfit < long.MinValue - num5) || clan2.Gold > long.MaxValue - workshopTypeDef.OperatingCost) { item.Status = "Treasury full"; continue; } foreach (KeyValuePair input2 in workshopTypeDef.Inputs) { town.Market.Stock[input2.Key] = C.MarketStock(town, input2.Key) - input2.Value; } town.Market.Stock[workshopTypeDef.OutputGoodId] = C.MarketStock(town, workshopTypeDef.OutputGoodId) + 1; town.Market.Gold += num - num3; item.Capital += num5; item.LastProfit = num5; item.TotalProfit += num5; State.Transact(clan2, workshopTypeDef.OperatingCost, LedgerAccount.Trade, workshopTypeDef.Name + " operating fees at " + town.Name); item.Status = "Produced"; } if (flag) { State.Touch(); } } } internal sealed class EquipmentBattlesSystem { private readonly Campaign C; private CampaignState State => C.State; internal EquipmentBattlesSystem(Campaign host) { C = host; } public EquipmentCombatStats HeroEquipmentStats(Hero hero, HeroEquipmentState loadout = null) { return LoadoutCombatStats(State, (string id) => C.UnitDef(id), C.UnitDef(hero?.UnitId ?? ""), loadout ?? hero?.Loadout); } public static EquipmentCombatStats LoadoutCombatStats(CampaignState state, Func unitDef, UnitDef basis, HeroEquipmentState selected) { CraftedWeaponState craftedWeaponState = Crafted(selected?.WeaponId ?? ""); double attack; double defense; double ranged; if (craftedWeaponState != null) { Smithing.CombatRatings(basis, craftedWeaponState.Class, craftedWeaponState.TierScore, craftedWeaponState.Quality, out attack, out defense, out ranged); } else { EquipmentDef equipmentDef = EquipmentCatalog.Find(selected?.WeaponId ?? ""); UnitDef obj = ((equipmentDef == null) ? basis : unitDef(equipmentDef.SourceUnitId)); attack = obj?.Attack ?? 1.0; defense = obj?.Defense ?? 1.0; ranged = obj?.Ranged ?? 0.0; if (equipmentDef != null && equipmentDef.Hand == EquipmentHand.Main) { defense = basis?.Defense ?? 1.0; } } Smithing.OffhandRatings(Crafted(selected?.ShieldId ?? ""), Crafted(selected?.AmmoId ?? ""), ref defense, ref ranged); CraftedWeaponState craftedWeaponState2 = Crafted(selected?.ShieldId ?? ""); EquipmentDef equipmentDef2 = EquipmentCatalog.Find(selected?.ShieldId ?? ""); double attack2 = -1.0; if (craftedWeaponState2 != null && Smithing.ClassDef(craftedWeaponState2.Class).OffHand) { Smithing.CombatRatings(basis, craftedWeaponState2.Class, craftedWeaponState2.TierScore, craftedWeaponState2.Quality, out attack2, out var _, out var _); } else if (EquipmentCatalog.OffHandKit(equipmentDef2)) { attack2 = unitDef(equipmentDef2.SourceUnitId)?.Attack ?? 1.0; } if (attack2 >= 0.0) { attack = Math.Round(Math.Max(attack, attack2) + 0.3 * Math.Min(attack, attack2), 4); } EquipmentDef equipmentDef3 = EquipmentCatalog.Find(selected?.ShieldId ?? ""); if (equipmentDef3 != null && equipmentDef3.Slot == EquipmentSlot.Shield) { defense = Math.Round(defense * (1.0 + equipmentDef3.ShieldDefense), 4); } return new EquipmentCombatStats { Attack = attack, Defense = defense, Health = (basis?.Health ?? 1.0), Ranged = ranged, Role = (basis?.Role ?? TroopRole.Infantry) }; CraftedWeaponState Crafted(string id) { if (!Smithing.IsCraftedId(id) || state?.Smithing?.Weapons == null || !state.Smithing.Weapons.TryGetValue(id, out var value)) { return null; } return value; } } public static HeroEquipmentState CopyHeroLoadout(HeroEquipmentState loadout) { return loadout?.Copy(); } internal string EquipmentReunionReason(Party source, Party target) { foreach (KeyValuePair item in source.Equipment ?? new SortedDictionary(StringComparer.Ordinal)) { OwnedItemInfo ownedItemInfo = C.ItemInfo(item.Key); if (ownedItemInfo == null || item.Value < 0 || (long)item.Value + (long)C.EquipmentCount(target, item.Key) > ownedItemInfo.Limit) { return "Your party cannot hold this equipment quantity."; } } return ""; } internal void ReuniteEquipment(Party source, Party target) { if (source.Equipment == null || source.Equipment.Count == 0) { return; } if (target.Equipment == null) { target.Equipment = new SortedDictionary(StringComparer.Ordinal); } foreach (KeyValuePair item in source.Equipment) { if (item.Value > 0) { target.Equipment[item.Key] = C.EquipmentCount(target, item.Key) + item.Value; } } source.Equipment.Clear(); } internal string SeizeEquipment(Party source, Party captor) { if (source?.Equipment == null || source.Equipment.Count == 0 || source == captor) { return ""; } int num = 0; int num2 = 0; bool flag = captor != null && captor.State != PartyState.Destroyed && captor.State != PartyState.Disbanded; if (flag && captor.Equipment == null) { captor.Equipment = new SortedDictionary(StringComparer.Ordinal); } foreach (OwnedItemInfo item in (from x in source.Equipment.Keys.OrderBy((string x) => x, StringComparer.Ordinal).Select(C.ItemInfo) where x != null select x).ToList()) { int num3 = C.EquipmentCount(source, item.Id); int num4 = (flag ? ((item.Weight <= 0.0) ? int.MaxValue : ((int)Math.Max(0.0, Math.Min(2147483647.0, Math.Floor((C.CargoCapacity(captor) - C.CargoWeight(captor)) / item.Weight))))) : 0); if (flag) { num4 = Math.Min(num4, Math.Max(0, item.Limit - C.EquipmentCount(captor, item.Id))); } int num5 = Math.Min(num3, num4); if (num5 > 0) { captor.Equipment[item.Id] = C.EquipmentCount(captor, item.Id) + num5; } num += num5; num2 += num3 - num5; } source.Equipment.Clear(); if (num + num2 == 0) { return ""; } string text = source.Name + " lost loose equipment: " + num + " taken" + ((num > 0) ? (" by " + captor.Name) : "") + ((num2 > 0) ? (", " + num2 + " abandoned") : "") + "."; State.AddLog(LogCategory.Economy, text, source.Id); return text; } } internal sealed class EquipmentSystem { private readonly Campaign C; private CampaignState State => C.State; internal EquipmentSystem(Campaign host) { C = host; } public void EnsureEquipmentFields() { bool flag = false; foreach (Party party in State.Parties) { if (party.Equipment == null) { party.Equipment = new SortedDictionary(StringComparer.Ordinal); flag = true; } } foreach (Settlement settlement in State.Settlements) { MarketState market = settlement.Market; if (market == null || market.EquipmentInitialized) { continue; } SortedDictionary equipmentStock = market.EquipmentStock; if (equipmentStock != null && equipmentStock.Count > 0) { continue; } if (market.EquipmentStock == null) { market.EquipmentStock = new SortedDictionary(StringComparer.Ordinal); } if (settlement.Type == SettlementType.Town) { foreach (EquipmentDef item in EquipmentCatalog.All) { market.EquipmentStock[item.Id] = 2; } } market.EquipmentInitialized = true; flag = true; } if (State.EquipmentIntroduced == null) { State.EquipmentIntroduced = new SortedSet(StringComparer.Ordinal); } if (State.EquipmentIntroduced.Count == 0) { foreach (EquipmentDef item2 in EquipmentCatalog.All.Where((EquipmentDef i) => EquipmentCatalog.FirstStock.Contains(i.Id) || (State.EquipmentPiecesStocked && i.Hand != EquipmentHand.Both))) { State.EquipmentIntroduced.Add(item2.Id); } } foreach (EquipmentDef item3 in EquipmentCatalog.All.Where((EquipmentDef i) => !State.EquipmentIntroduced.Contains(i.Id)).ToList()) { foreach (Settlement item4 in State.Settlements.Where(delegate(Settlement s) { if (s.Type == SettlementType.Town) { MarketState market2 = s.Market; if (market2 != null && market2.EquipmentInitialized) { return s.Market.EquipmentStock != null; } } return false; })) { if (!item4.Market.EquipmentStock.ContainsKey(item3.Id)) { item4.Market.EquipmentStock[item3.Id] = 2; } } State.EquipmentIntroduced.Add(item3.Id); flag = true; } if (!State.EquipmentPiecesStocked) { State.EquipmentPiecesStocked = true; flag = true; } if (flag) { State.Touch(); } } public int EquipmentCount(Party party, string itemId) { if (party?.Equipment == null || itemId == null || !party.Equipment.TryGetValue(itemId, out var value)) { return 0; } return Math.Max(0, value); } public int EquipmentStock(Settlement settlement, string itemId) { if (settlement?.Market?.EquipmentStock == null || itemId == null || !settlement.Market.EquipmentStock.TryGetValue(itemId, out var value)) { return 0; } return Math.Max(0, value); } public double EquipmentWeight(Party party) { return OwnedItems.Weight(State, party?.Equipment); } public OwnedItemInfo ItemInfo(string id) { return OwnedItems.Resolve(State, id); } internal string EquipmentCommandReason() { string text = C.CargoCommandReason(); if (text.Length > 0) { return text; } Party playerParty = State.PlayerParty; if (!string.IsNullOrEmpty(State.Player.PendingEncounterId) || !string.IsNullOrEmpty(playerParty.EncounterId) || C.MilitaryPartyReserved(playerParty.Id)) { return "Deal with the encounter first."; } if (playerParty.Equipment == null) { return "Your equipment inventory is unavailable."; } List list = new List(); EquipmentValidation.CheckInventory(State, playerParty.Equipment, "Your inventory", list); return list.FirstOrDefault() ?? ""; } public string EquipmentHeroReason(string heroId) { string text = EquipmentCommandReason(); if (text.Length > 0) { return text; } Hero hero = State.Heroes.Get(heroId ?? ""); if (hero == null || hero.ClanId != State.PlayerClanId || (hero.Id != State.PlayerHeroId && !C.IsOwnedCompanion(hero))) { return "Pick yourself or a companion."; } if (hero.State != HeroState.Active || !Campaign.IsPresentPartyHero(State.PlayerParty, hero)) { return "They have to be in your party for that."; } if (!EquipmentCatalog.SupportsArchetype(C.UnitDef(hero.UnitId))) { return "This archetype can't use modular gear yet."; } List list = new List(); EquipmentValidation.CheckLoadout(State, hero.Loadout, "This hero", list); if (list.Count > 0) { return list[0]; } EquipmentDef equipmentDef = EquipmentCatalog.Find(hero.Loadout?.OutfitId); if (equipmentDef != null && C.UnitDef(equipmentDef.SourceUnitId) == null) { return "This hero's outfit source content is unavailable."; } TroopRole? troopRole = WeaponRole(hero.Loadout?.WeaponId); if (troopRole.HasValue) { TroopRole valueOrDefault = troopRole.GetValueOrDefault(); if (valueOrDefault != C.UnitDef(hero.UnitId).Role) { return "That weapon doesn't suit how this hero fights."; } } return ""; } public TroopRole? WeaponRole(string itemId) { OwnedItemInfo ownedItemInfo = ItemInfo(itemId); if (ownedItemInfo != null && ownedItemInfo.Kind == OwnedItemKind.CraftedWeapon) { return Smithing.ClassDef(ownedItemInfo.Crafted.Class).Role; } if (ownedItemInfo != null && ownedItemInfo.Kind == OwnedItemKind.WeaponKit) { return C.UnitDef(ownedItemInfo.Kit.SourceUnitId)?.Role; } return null; } internal static EquipmentSlot? SlotOf(OwnedItemInfo info) { if (info != null) { if (info.Kind != OwnedItemKind.CraftedWeapon) { if (info.Kind != OwnedItemKind.WeaponKit) { if (info.Kind != OwnedItemKind.Shield) { if (info.Kind != OwnedItemKind.Outfit) { return null; } return EquipmentSlot.Outfit; } return EquipmentSlot.Shield; } return EquipmentSlot.Weapon; } return Smithing.ClassDef(info.Crafted.Class).Slot; } return null; } public EquipmentSlot? EquipmentSlotOf(string itemId) { return SlotOf(ItemInfo(itemId)); } public bool IsOffHandWeapon(string itemId) { OwnedItemInfo ownedItemInfo = ItemInfo(itemId); if (ownedItemInfo != null && ownedItemInfo.Kind == OwnedItemKind.CraftedWeapon) { return Smithing.ClassDef(ownedItemInfo.Crafted.Class).OffHand; } if (ownedItemInfo != null && ownedItemInfo.Kind == OwnedItemKind.WeaponKit) { if (EquipmentCatalog.OffHandKit(ownedItemInfo.Kit)) { UnitDef unitDef = C.UnitDef(ownedItemInfo.Kit.SourceUnitId); if (unitDef == null) { return false; } return unitDef.Role == TroopRole.Infantry; } return false; } return false; } public bool DualWields(Hero hero) { if (!string.IsNullOrEmpty(hero?.Loadout?.ShieldId)) { return IsOffHandWeapon(hero.Loadout.ShieldId); } return false; } internal WeaponClassDef CraftedClass(string itemId) { CraftedWeaponState craftedWeaponState = ItemInfo(itemId)?.Crafted; if (craftedWeaponState != null) { return Smithing.ClassDef(craftedWeaponState.Class); } return null; } internal string ShieldHandReason(Hero hero, string weaponId) { return ShieldHandReason(C.UnitDef(hero.UnitId)?.Role ?? TroopRole.Infantry, weaponId); } private string ShieldHandReason(TroopRole role, string weaponId) { WeaponClassDef weaponClassDef = CraftedClass(weaponId); if (weaponClassDef != null && weaponClassDef.BothHands) { return "A " + weaponClassDef.Name.ToLowerInvariant() + " needs both hands: take off the shield first."; } switch (role) { case TroopRole.Ranged: if ((weaponClassDef == null || !weaponClassDef.Thrown) && !(weaponId == "eq.weapon.javelin")) { return "A ranged hero can only carry a shield with throwing weapons."; } break; default: return "Only foot soldiers and throwers carry shields."; case TroopRole.Infantry: break; } return ""; } public List HeroArchetypes(string heroId) { Hero hero = State.Heroes.Get(heroId ?? ""); if (hero == null || string.IsNullOrEmpty(hero.CultureId)) { return new List(); } int tier = Math.Max(2, Math.Max(C.UnitDef(hero.UnitId ?? "")?.Tier ?? 0, C.UnitDef(hero.Creation?.ArchetypeId ?? "")?.Tier ?? 0)); return (from unit in C.Content.Units where unit.Culture == hero.CultureId && unit.Tier >= 1 && unit.Tier <= tier && Campaign.SupportsWardrobe(unit) orderby unit.Role, unit.Tier select unit).ThenBy((UnitDef unit) => unit.Id, StringComparer.Ordinal).ToList(); } public List ArchetypeReturns(string heroId, string unitId) { List list = new List(); Hero hero = State.Heroes.Get(heroId ?? ""); UnitDef unitDef = C.UnitDef(unitId ?? ""); HeroEquipmentState heroEquipmentState = hero?.Loadout; if (heroEquipmentState == null || unitDef == null) { return list; } bool flag = EquipmentCatalog.SupportsArchetype(unitDef); string text = heroEquipmentState.WeaponId ?? ""; if (text.Length > 0 && (!flag || WeaponRole(text) != unitDef.Role)) { list.Add(EquipmentSlot.Weapon); text = ""; } string text2 = heroEquipmentState.ShieldId ?? ""; if (text2.Length > 0 && (IsOffHandWeapon(text2) ? ((byte)unitDef.Role != 0) : (ShieldHandReason(unitDef.Role, text).Length > 0))) { list.Add(EquipmentSlot.Shield); } if (!string.IsNullOrEmpty(heroEquipmentState.AmmoId) && (CraftedClass(heroEquipmentState.AmmoId) == null || AmmoReason(text, heroEquipmentState.AmmoId).Length > 0)) { list.Add(EquipmentSlot.Ammo); } if (!string.IsNullOrEmpty(heroEquipmentState.OutfitId) && !flag) { list.Add(EquipmentSlot.Outfit); } return list; } public string ArchetypeChangeReason(string heroId, string unitId) { string text = EquipmentCommandReason(); if (text.Length > 0) { return text; } if (C.TournamentBusyReason().Length > 0) { return C.TournamentBusyReason(); } Hero hero = State.Heroes.Get(heroId ?? ""); if (hero == null || hero.Id != State.PlayerHeroId) { return "Only your own character can change how they fight."; } if (hero.State != HeroState.Active) { return "You can't do that now."; } UnitDef unit = C.UnitDef(unitId ?? ""); if (unit == null || !HeroArchetypes(hero.Id).Any((UnitDef u) => u.Id == unit.Id)) { return "Choose one of your culture's foot troops."; } if (unit.Id == hero.UnitId) { return "You already fight as " + unit.Name + "."; } Party playerParty = State.PlayerParty; double num = 0.0; foreach (EquipmentSlot item in ArchetypeReturns(hero.Id, unit.Id)) { OwnedItemInfo ownedItemInfo = ItemInfo(hero.Loadout.ItemId(item)); if (ownedItemInfo != null) { if (EquipmentCount(playerParty, ownedItemInfo.Id) >= ownedItemInfo.Limit) { return "Your bag cannot hold another " + ownedItemInfo.Name + ", which " + unit.Name + " can't use."; } num += ownedItemInfo.Weight; } } if (num > 0.0 && C.CargoWeight(playerParty) + num > C.CargoCapacity(playerParty) + 1E-09) { return "No room in the bag for the gear " + unit.Name + " can't use."; } return ""; } public CommandResult ChangeHeroArchetype(string heroId, string unitId) { string text = ArchetypeChangeReason(heroId, unitId); if (text.Length > 0) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Require(heroId); UnitDef unitDef = C.UnitDef(unitId); List list = new List(); foreach (EquipmentSlot item in ArchetypeReturns(hero.Id, unitDef.Id)) { OwnedItemInfo ownedItemInfo = ItemInfo(hero.Loadout.ItemId(item)); if (ownedItemInfo != null) { SetEquipmentCount(State.PlayerParty.Equipment, ownedItemInfo.Id, EquipmentCount(State.PlayerParty, ownedItemInfo.Id) + 1); list.Add(ownedItemInfo.Name); } hero.Loadout.SetItem(item, ""); } hero.UnitId = unitDef.Id; string text2 = hero.Name + " now fights as " + Article(unitDef.Name) + " (" + RoleName(unitDef.Role) + ")" + ((list.Count > 0) ? ("; " + string.Join(", ", list.ToArray()) + " went back to the bag.") : "."); State.AddLog(LogCategory.Info, text2, hero.Id); State.Touch(); return CommandResult.Success(text2); } public static string RoleName(TroopRole role) { return role switch { TroopRole.Infantry => "melee", TroopRole.Support => "support", TroopRole.Ranged => "ranged", _ => role.ToString().ToLowerInvariant(), }; } private static string Article(string name) { return ((name.Length > 0 && "AEIOUaeiou".IndexOf(name[0]) >= 0) ? "an " : "a ") + name; } internal string AmmoReason(string weaponId, string ammoId) { WeaponClassDef weaponClassDef = CraftedClass(ammoId); if (weaponClassDef == null) { return ""; } WeaponClassDef weaponClassDef2 = CraftedClass(weaponId); if (weaponClassDef.Class == WeaponClass.Arrows && (weaponClassDef2 == null || weaponClassDef2.Family != WeaponFamily.Bow)) { return "Forged arrows need a forged bow."; } if (weaponClassDef.Class == WeaponClass.Bolts && (weaponClassDef2 == null || weaponClassDef2.Family != WeaponFamily.Crossbow)) { return "Forged bolts need a forged crossbow."; } return ""; } public string EquipmentEquipReason(string heroId, string itemId, bool offHand = false) { string text = EquipmentHeroReason(heroId); if (text.Length > 0) { return text; } OwnedItemInfo ownedItemInfo = ItemInfo(itemId); EquipmentSlot? equipmentSlot = SlotOf(ownedItemInfo); if (ownedItemInfo == null || !equipmentSlot.HasValue) { return "Unknown equipment item."; } if (offHand) { if (!IsOffHandWeapon(ownedItemInfo.Id)) { return "Only a one-handed melee weapon goes in the off hand."; } UnitDef unitDef = C.UnitDef(State.Heroes.Require(heroId).UnitId); if (unitDef == null || unitDef.Role != TroopRole.Infantry) { return "Only foot soldiers can fight with a weapon in each hand."; } if (!Campaign.SupportsWardrobe(unitDef)) { return "This archetype can't carry a second weapon."; } equipmentSlot = EquipmentSlot.Shield; } if (ownedItemInfo.Kit != null && C.UnitDef(ownedItemInfo.Kit.SourceUnitId) == null) { return "This item's source content is unavailable."; } Hero hero = State.Heroes.Require(heroId); if (equipmentSlot == EquipmentSlot.Weapon && WeaponRole(ownedItemInfo.Id) != C.UnitDef(hero.UnitId).Role) { return "Choose a weapon for this hero's " + ((C.UnitDef(hero.UnitId).Role == TroopRole.Ranged) ? "ranged" : "melee") + " combat role."; } if (!Campaign.SupportsWardrobe(C.UnitDef(hero.UnitId)) && (equipmentSlot == EquipmentSlot.Shield || equipmentSlot == EquipmentSlot.Ammo)) { return "This archetype can't carry shields or forged ammunition."; } string text2 = hero.Loadout?.ShieldId ?? ""; string text3 = hero.Loadout?.AmmoId ?? ""; if (equipmentSlot == EquipmentSlot.Weapon) { if (text2.Length > 0) { string text4 = ShieldHandReason(hero, ownedItemInfo.Id); if (text4.Length > 0) { if (!DualWields(hero)) { return text4; } return text4.Replace("take off the shield first", "take off the off-hand weapon first"); } if (DualWields(hero)) { EquipmentDef kit = ownedItemInfo.Kit; if (kit != null && kit.Hand == EquipmentHand.Both) { return "The " + ownedItemInfo.Name + " fills both hands: take off the off-hand weapon first."; } } } if (text3.Length > 0) { string text5 = AmmoReason(ownedItemInfo.Id, text3); if (text5.Length > 0) { return "Take off the " + (ItemInfo(text3)?.Name ?? "ammunition") + " first. " + text5; } } } if (equipmentSlot == EquipmentSlot.Shield) { string text6 = ShieldHandReason(hero, hero.Loadout?.WeaponId ?? ""); if (text6.Length > 0) { return text6.Replace(": take off the shield first.", "."); } if (offHand && !string.IsNullOrEmpty(hero.Loadout?.WeaponId) && !IsOffHandWeapon(hero.Loadout.WeaponId)) { OwnedItemInfo ownedItemInfo2 = ItemInfo(hero.Loadout.WeaponId); if (ownedItemInfo2 != null && ownedItemInfo2.Kit?.Hand == EquipmentHand.Both) { return "The " + ItemInfo(hero.Loadout.WeaponId).Name + " already fills both hands. Equip a single weapon first."; } } } if (equipmentSlot == EquipmentSlot.Ammo) { string text7 = AmmoReason(hero.Loadout?.WeaponId ?? "", ownedItemInfo.Id); if (text7.Length > 0) { return text7; } } string text8 = hero.Loadout?.ItemId(equipmentSlot.Value); if (text8 == ownedItemInfo.Id) { return "Already equipped."; } Party playerParty = State.PlayerParty; if (EquipmentCount(playerParty, ownedItemInfo.Id) < 1) { return "Your party doesn't own that."; } OwnedItemInfo ownedItemInfo3 = ItemInfo(text8); if (ownedItemInfo3 != null && EquipmentCount(playerParty, ownedItemInfo3.Id) >= ownedItemInfo3.Limit) { return "Your bag cannot hold another " + ownedItemInfo3.Name + "."; } double num = (ownedItemInfo3?.Weight ?? 0.0) - ownedItemInfo.Weight; if (num > 0.0 && C.CargoWeight(playerParty) + num > C.CargoCapacity(playerParty) + 1E-09) { return "No room for the item you're taking off."; } return ""; } public CommandResult EquipHeroItem(string heroId, string itemId, bool offHand = false) { string text = EquipmentEquipReason(heroId, itemId, offHand); if (text.Length > 0) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Require(heroId); OwnedItemInfo ownedItemInfo = ItemInfo(itemId); EquipmentSlot slot = (offHand ? EquipmentSlot.Shield : SlotOf(ownedItemInfo).Value); OwnedItemInfo ownedItemInfo2 = ItemInfo(hero.Loadout?.ItemId(slot)); SortedDictionary equipment = State.PlayerParty.Equipment; SetEquipmentCount(equipment, ownedItemInfo.Id, EquipmentCount(State.PlayerParty, ownedItemInfo.Id) - 1); if (ownedItemInfo2 != null) { SetEquipmentCount(equipment, ownedItemInfo2.Id, EquipmentCount(State.PlayerParty, ownedItemInfo2.Id) + 1); } if (hero.Loadout == null) { hero.Loadout = new HeroEquipmentState(); } hero.Loadout.SetItem(slot, ownedItemInfo.Id); string text2 = hero.Name + " equipped " + ownedItemInfo.Name + (offHand ? " in the off hand." : "."); State.AddLog(LogCategory.Info, text2, hero.Id); State.Touch(); return CommandResult.Success(text2); } public string EquipmentUnequipReason(string heroId, EquipmentSlot slot) { string text = EquipmentHeroReason(heroId); if (text.Length > 0) { return text; } if (!Enum.IsDefined(typeof(EquipmentSlot), slot)) { return "Unknown equipment slot."; } Hero hero = State.Heroes.Require(heroId); OwnedItemInfo ownedItemInfo = ItemInfo(hero.Loadout?.ItemId(slot)); if (ownedItemInfo == null) { return "This slot is the archetype's own gear; there's nothing to take off."; } if (slot == EquipmentSlot.Weapon && !string.IsNullOrEmpty(hero.Loadout.AmmoId)) { return "Take off the " + (ItemInfo(hero.Loadout.AmmoId)?.Name ?? "ammunition") + " first: it needs this weapon."; } if (slot == EquipmentSlot.Weapon && !string.IsNullOrEmpty(hero.Loadout.ShieldId) && ShieldHandReason(hero, "").Length > 0) { return "Take off the " + (DualWields(hero) ? "off-hand weapon" : "shield") + " first: the hero's own weapon has no hand free for it."; } Party playerParty = State.PlayerParty; if (EquipmentCount(playerParty, ownedItemInfo.Id) >= ownedItemInfo.Limit) { return "Your bag cannot hold another " + ownedItemInfo.Name + "."; } if (C.CargoWeight(playerParty) + ownedItemInfo.Weight > C.CargoCapacity(playerParty) + 1E-09) { return "No room for the item you're taking off."; } return ""; } public CommandResult UnequipHeroItem(string heroId, EquipmentSlot slot) { string text = EquipmentUnequipReason(heroId, slot); if (text.Length > 0) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Require(heroId); OwnedItemInfo ownedItemInfo = ItemInfo(hero.Loadout.ItemId(slot)); SetEquipmentCount(State.PlayerParty.Equipment, ownedItemInfo.Id, EquipmentCount(State.PlayerParty, ownedItemInfo.Id) + 1); hero.Loadout.SetItem(slot, ""); string text2 = hero.Name + " returned " + ownedItemInfo.Name + " to the party's bag."; State.AddLog(LogCategory.Info, text2, hero.Id); State.Touch(); return CommandResult.Success(text2); } public EquipmentTradeQuote QuoteEquipmentTrade(string itemId, bool buying) { OwnedItemInfo ownedItemInfo = ItemInfo(itemId); EquipmentTradeQuote equipmentTradeQuote = new EquipmentTradeQuote { Total = ((ownedItemInfo == null) ? 0 : (buying ? ownedItemInfo.Price : SalePrice(ownedItemInfo))), Reason = EquipmentCommandReason() }; if (!equipmentTradeQuote.Ok) { return equipmentTradeQuote; } if (ownedItemInfo == null) { equipmentTradeQuote.Reason = "Unknown equipment item."; return equipmentTradeQuote; } if (buying && ownedItemInfo.Kind == OwnedItemKind.Material) { equipmentTradeQuote.Reason = "The outfitter doesn't sell smithing stock."; return equipmentTradeQuote; } if (buying && ownedItemInfo.Kind == OwnedItemKind.CraftedWeapon) { equipmentTradeQuote.Reason = "No forged weapons sold here."; return equipmentTradeQuote; } Settlement settlement = C.CurrentSettlement(); Party playerParty = State.PlayerParty; if (settlement == null || settlement.Type != SettlementType.Town || !C.CanEnter(playerParty, settlement) || !(Vec2.Distance(playerParty.Position, settlement.Position) <= 0.01)) { equipmentTradeQuote.Reason = "Find a friendly town's outfitter."; return equipmentTradeQuote; } MarketState market = settlement.Market; if (market == null || !market.Initialized || !market.EquipmentInitialized || market.EquipmentStock == null) { equipmentTradeQuote.Reason = "This outfitter is unavailable."; return equipmentTradeQuote; } List list = new List(); EquipmentValidation.CheckInventory(State, market.EquipmentStock, "This outfitter", list); if (list.Count > 0) { equipmentTradeQuote.Reason = list[0]; return equipmentTradeQuote; } bool flag = ownedItemInfo.Kind != OwnedItemKind.CraftedWeapon && ownedItemInfo.Kind != OwnedItemKind.Material; if (ownedItemInfo.Kit != null && C.UnitDef(ownedItemInfo.Kit.SourceUnitId) == null) { equipmentTradeQuote.Reason = "This item's source content is unavailable."; } else if (ownedItemInfo.Kind == OwnedItemKind.Clothing && !market.ClothingInitialized && buying) { equipmentTradeQuote.Reason = "This outfitter has no clothing yet."; } else if (market.Gold < 0 || State.PlayerClan.Gold < 0) { equipmentTradeQuote.Reason = "The trading accounts are invalid."; } else if (buying && EquipmentStock(settlement, ownedItemInfo.Id) < 1) { equipmentTradeQuote.Reason = "Sold out."; } else if (!buying && EquipmentCount(playerParty, ownedItemInfo.Id) < 1) { equipmentTradeQuote.Reason = "You can only sell what's in the bag."; } else if (buying && EquipmentCount(playerParty, ownedItemInfo.Id) >= ownedItemInfo.Limit) { equipmentTradeQuote.Reason = "No room in the bag for another."; } else if (!buying && flag && EquipmentStock(settlement, ownedItemInfo.Id) >= ownedItemInfo.Limit) { equipmentTradeQuote.Reason = "The outfitter has no room for it."; } else if (buying && C.CargoWeight(playerParty) + ownedItemInfo.Weight > C.CargoCapacity(playerParty) + 1E-09) { equipmentTradeQuote.Reason = "No room for that."; } else if (buying && State.PlayerClan.Gold < equipmentTradeQuote.Total) { equipmentTradeQuote.Reason = "Not enough denars."; } else if (!buying && market.Gold < equipmentTradeQuote.Total) { equipmentTradeQuote.Reason = "The outfitter can't afford it."; } else if (buying && market.Gold > long.MaxValue - equipmentTradeQuote.Total) { equipmentTradeQuote.Reason = "The outfitter can't hold any more money."; } else if (!buying && State.PlayerClan.Gold > long.MaxValue - equipmentTradeQuote.Total) { equipmentTradeQuote.Reason = "Your treasury's full."; } return equipmentTradeQuote; } public CommandResult TradeEquipment(string itemId, bool buying) { EquipmentTradeQuote equipmentTradeQuote = QuoteEquipmentTrade(itemId, buying); if (!equipmentTradeQuote.Ok) { return CommandResult.Fail(equipmentTradeQuote.Reason); } OwnedItemInfo ownedItemInfo = ItemInfo(itemId); Settlement settlement = C.CurrentSettlement(); Party playerParty = State.PlayerParty; SetEquipmentCount(playerParty.Equipment, ownedItemInfo.Id, EquipmentCount(playerParty, ownedItemInfo.Id) + (buying ? 1 : (-1))); if (ownedItemInfo.Kind == OwnedItemKind.CraftedWeapon) { State.Smithing.Weapons.Remove(ownedItemInfo.Id); } else if (ownedItemInfo.Kind != OwnedItemKind.Material) { SetEquipmentCount(settlement.Market.EquipmentStock, ownedItemInfo.Id, EquipmentStock(settlement, ownedItemInfo.Id) + ((!buying) ? 1 : (-1))); } settlement.Market.Gold += (buying ? equipmentTradeQuote.Total : (-equipmentTradeQuote.Total)); string text = (buying ? "Bought " : "Sold ") + ownedItemInfo.Name + " for " + equipmentTradeQuote.Total + " denars at " + settlement.Name + "."; State.Transact(State.PlayerClan, buying ? (-equipmentTradeQuote.Total) : equipmentTradeQuote.Total, LedgerAccount.EquipmentTrade, text); State.AddLog(LogCategory.Economy, text, settlement.Id); State.Touch(); return CommandResult.Success(text); } public string EquipmentDropReason(string itemId, int count) { string text = EquipmentCommandReason(); if (text.Length > 0) { return text; } if (ItemInfo(itemId) == null) { return "Unknown equipment item."; } if (count < 1 || count > 1000) { return "Choose between 1 and 1000."; } if (EquipmentCount(State.PlayerParty, itemId) < count) { return "You're not carrying that many."; } return ""; } public CommandResult DropEquipment(string itemId, int count) { string text = EquipmentDropReason(itemId, count); if (text.Length > 0) { return CommandResult.Fail(text); } OwnedItemInfo ownedItemInfo = ItemInfo(itemId); Party playerParty = State.PlayerParty; int num = EquipmentCount(playerParty, ownedItemInfo.Id) - count; SetEquipmentCount(playerParty.Equipment, ownedItemInfo.Id, num); if (ownedItemInfo.Kind == OwnedItemKind.CraftedWeapon && num == 0) { State.Smithing.Weapons.Remove(ownedItemInfo.Id); } string text2 = "Discarded " + ((count == 1) ? ownedItemInfo.Name : (count + " " + ownedItemInfo.Name)) + "."; State.AddLog(LogCategory.Economy, text2, playerParty.Id); State.Touch(); return CommandResult.Success(text2); } public long SalePrice(OwnedItemInfo item) { if (item == null) { return 0L; } if (item.Kind != OwnedItemKind.CraftedWeapon) { return item.Price / 2; } _ = State.PlayerHero; double num = (C.PartySmiths().Any((Hero h) => C.HasHeroPerk(h, "perk.smith.artisan")) ? 0.65 : 0.3); return Math.Max(1L, (long)Math.Round((double)item.Price * num)); } internal static void SetEquipmentCount(SortedDictionary inventory, string id, int count) { if (count == 0) { inventory.Remove(id); } else { inventory[id] = count; } } } internal sealed class FamiliesSystem { private readonly Campaign C; private ContentDatabase Content => C.Content; private CampaignState State => C.State; public CampaignSettings Settings => State.Settings ?? (State.Settings = new CampaignSettings()); internal FamiliesSystem(Campaign host) { C = host; } public double HeroAge(Hero h) { if (h == null) { return 0.0; } long num = ((h.State == HeroState.Dead && h.DeathDay >= 0) ? h.DeathDay : State.Clock.Day); return Math.Max(0.0, (double)(num - h.BornDay) / 84.0); } public int HeroYears(Hero h) { return (int)Math.Floor(HeroAge(h) + 1E-09); } public bool IsChild(Hero h) { if (h != null && h.Sex != HeroSex.Unspecified) { return HeroAge(h) < 18.0; } return false; } public bool IsGrown(Hero h) { if (h != null) { return !IsChild(h); } return false; } public bool IsAlive(Hero h) { if (h != null) { return h.State != HeroState.Dead; } return false; } public Hero SpouseOf(Hero h) { Hero hero = ((h == null || string.IsNullOrEmpty(h.SpouseId)) ? null : State.Heroes.Get(h.SpouseId)); if (hero == null || hero.State == HeroState.Dead || h.State == HeroState.Dead || !(hero.SpouseId == h.Id)) { return null; } return hero; } public IEnumerable ChildrenOf(Hero h) { if (h != null) { return State.Heroes.Where((Hero c) => c.FatherId == h.Id || c.MotherId == h.Id); } return Enumerable.Empty(); } public IEnumerable ParentsOf(Hero h) { if (h != null) { Hero hero = State.Heroes.Get(h.FatherId); Hero mother = State.Heroes.Get(h.MotherId); if (hero != null) { yield return hero; } if (mother != null) { yield return mother; } } } public IEnumerable SiblingsOf(Hero h) { if (h != null) { return State.Heroes.Where((Hero o) => o.Id != h.Id && ((!string.IsNullOrEmpty(h.FatherId) && o.FatherId == h.FatherId) || (!string.IsNullOrEmpty(h.MotherId) && o.MotherId == h.MotherId))); } return Enumerable.Empty(); } internal void AddAncestors(Hero h, int generations, HashSet into) { if (h == null || generations <= 0) { return; } foreach (Hero item in ParentsOf(h)) { if (into.Add(item.Id)) { AddAncestors(item, generations - 1, into); } } } public bool AreCloseKin(Hero a, Hero b) { if (a == null || b == null) { return false; } HashSet hashSet = new HashSet(StringComparer.Ordinal) { a.Id }; HashSet hashSet2 = new HashSet(StringComparer.Ordinal) { b.Id }; AddAncestors(a, 2, hashSet); AddAncestors(b, 2, hashSet2); return hashSet.Overlaps(hashSet2); } public bool IsNoble(Hero h) { if (h != null) { if (h.Occupation != HeroOccupation.Lord && h.Occupation != HeroOccupation.Player) { if (h.Occupation == HeroOccupation.Companion) { return h.IsFamily; } return false; } return true; } return false; } public string MarriageReason(Hero a, Hero b) { if (a == null || b == null || a.Id == b.Id) { return "Choose two different people."; } Hero[] array = new Hero[2] { a, b }; foreach (Hero hero in array) { if (hero.State == HeroState.Dead) { return hero.Name + " has died."; } if (IsChild(hero)) { return hero.Name + " is too young to marry."; } if (hero.State != HeroState.Active) { return hero.Name + " is not free to marry."; } if (!IsNoble(hero)) { return hero.Name + " is not of a noble family."; } if (SpouseOf(hero) != null) { return hero.Name + " is already married."; } if (hero.Sex == HeroSex.Unspecified) { return hero.Name + "'s family is not yet known."; } } if (a.Sex == b.Sex) { return "A marriage needs a man and a woman."; } if (AreCloseKin(a, b)) { return a.Name + " and " + b.Name + " are too closely related."; } return ""; } public int LordPartyLimit(Clan clan) { if (clan == null || State.Families?.LordParties == null || !State.Families.LordParties.TryGetValue(clan.Id, out var value)) { return 2; } return value; } public Settlement ClanHome(Clan clan) { if (clan == null) { return null; } return (from s in State.Settlements where s.OwnerClanId == clan.Id && s.Type != SettlementType.Hideout orderby (s.Type == SettlementType.Village) ? 1 : 0 select s).ThenBy((Settlement s) => s.Id, StringComparer.Ordinal).FirstOrDefault(); } public string ClanSurname(Clan clan) { if (clan == null) { return ""; } FamiliesState families = State.Families; if (families.ClanSurnames.TryGetValue(clan.Id, out var value) && !string.IsNullOrEmpty(value)) { return value; } value = ((clan.Id == State.PlayerClanId) ? Families.SurnameOf(State.PlayerHero?.Name) : ""); if (string.IsNullOrEmpty(value)) { value = Wanderers.Surname(clan.CultureId, StableHash.Fnv1a64("surname|" + clan.Id)); } families.ClanSurnames[clan.Id] = value; return value; } public List LivingClanMembers(Clan clan) { if (clan != null) { return State.Heroes.Where((Hero h) => h.ClanId == clan.Id && h.State != HeroState.Dead && h.Occupation != HeroOccupation.Notable).ToList(); } return new List(); } public List ClanFamily(Clan clan) { return LivingClanMembers(clan).Where(IsNoble).ToList(); } public void EnsureFamilyFields() { bool flag = false; if (State.Families == null) { State.Families = new FamiliesState(); flag = true; } FamiliesState families = State.Families; if (families.ClanSurnames == null) { families.ClanSurnames = new SortedDictionary(StringComparer.Ordinal); flag = true; } if (families.Courtships == null) { families.Courtships = new List(); flag = true; } if (families.RelativeDueDay == null) { families.RelativeDueDay = new SortedDictionary(StringComparer.Ordinal); flag = true; } if (families.LordParties == null) { families.LordParties = new SortedDictionary(StringComparer.Ordinal); flag = true; } foreach (Hero hero in State.Heroes) { if (hero.FormerSpouseIds == null) { hero.FormerSpouseIds = new List(); flag = true; } if (hero.DivorcedIds == null) { hero.DivorcedIds = new List(); flag = true; } if (hero.BirthClanId == null) { hero.BirthClanId = ""; flag = true; } if (hero.Education == null) { hero.Education = new SortedDictionary(StringComparer.Ordinal); flag = true; } } if (!families.Started && State.Heroes.Any((Hero h) => h.Occupation == HeroOccupation.Lord)) { Hero playerHero = State.PlayerHero; if (playerHero != null && playerHero.Sex == HeroSex.Unspecified) { families.PlayerSexChosen = false; } StartFamilies(); flag = true; } if (flag) { State.Touch(); } } public void StartFamilies() { FamiliesState families = State.Families; if (families.Started) { return; } RandomStream rng = State.Random.Get("families"); foreach (Hero item in State.Heroes.ToList()) { GiveIdentity(item); } HashSet taken = new HashSet(State.Heroes.Select((Hero h) => h.Name), StringComparer.Ordinal); foreach (Clan clan in State.Clans.Where((Clan c) => !c.IsBandit && !c.IsEliminated && c.Id != State.PlayerClanId).ToList()) { int val = State.Heroes.Count((Hero h) => h.ClanId == clan.Id && h.Occupation == HeroOccupation.Lord && h.State != HeroState.Dead); families.LordParties[clan.Id] = Math.Max(1, Math.Min(2, val)); FoundClanFamily(clan, rng, taken); } if (State.PlayerClan != null) { ClanSurname(State.PlayerClan); } families.Started = true; families.LastDay = State.Clock.Day; State.Touch(); } internal bool GiveIdentity(Hero h) { if (h == null || h.Sex != HeroSex.Unspecified) { return false; } ulong num = StableHash.Fnv1a64("identity|" + h.Id); HeroSex heroSex = Families.SexOfName(h.Name); if (heroSex == HeroSex.Unspecified) { heroSex = ((num % 100 < (ulong)((h.Occupation == HeroOccupation.Lord) ? 60 : 50)) ? HeroSex.Male : HeroSex.Female); } h.Sex = heroSex; Clan clan = State.Clans.Get(h.ClanId); int num2 = (h.IsPlayer ? ((h.Creation != null && h.Creation.Age > 0) ? h.Creation.Age : 30) : ((h.Occupation == HeroOccupation.Lord) ? ((clan != null && clan.LeaderHeroId == h.Id) ? (38 + (int)(num / 7 % 23)) : (20 + (int)(num / 7 % 25))) : ((h.Occupation != HeroOccupation.Companion) ? (25 + (int)(num / 7 % 26)) : (20 + (int)(num / 7 % 26))))); long num3 = (h.IsPlayer ? 0 : State.Clock.Day); h.BornDay = num3 - (long)num2 * 84L - (long)(h.IsPlayer ? 0 : (num / 1009 % 84)); if (h.Occupation == HeroOccupation.Lord) { h.IsFamily = true; } if (h.FormerSpouseIds == null) { h.FormerSpouseIds = new List(); } if (h.Education == null) { h.Education = new SortedDictionary(StringComparer.Ordinal); } return true; } internal void FoundClanFamily(Clan clan, RandomStream rng, HashSet taken) { List list = (from hero3 in State.Heroes where hero3.ClanId == clan.Id && hero3.Occupation == HeroOccupation.Lord && hero3.State != HeroState.Dead orderby (!(hero3.Id == clan.LeaderHeroId)) ? 1 : 0 select hero3).ToList(); if (list.Count == 0) { return; } Hero hero = list[0]; double num = HeroAge(hero); foreach (Hero item in list.Skip(1)) { if (num - HeroAge(item) >= 20.0 && string.IsNullOrEmpty(item.FatherId) && string.IsNullOrEmpty(item.MotherId)) { SetParent(item, hero); } } if (SpouseOf(hero) != null || num < 22.0 || hero.Sex == HeroSex.Unspecified) { return; } Settlement home = ClanHome(clan); HeroSex sex = ((hero.Sex != HeroSex.Male) ? HeroSex.Male : HeroSex.Female); int num2 = Math.Max(20, Math.Min(70, (int)num + rng.Range(-6, 5))); Hero hero2 = NewKin(clan, sex, num2, home, rng, taken, grown: true); hero2.SpouseId = hero.Id; hero.SpouseId = hero2.Id; foreach (Hero item2 in ChildrenOf(hero).ToList()) { if (HeroAge(hero2) - HeroAge(item2) >= 18.0) { SetParent(item2, hero2); } } Hero h = ((hero.Sex == HeroSex.Female) ? hero : hero2); int num3 = Math.Max(1, (int)Math.Ceiling(HeroAge(h)) - 44); int num4 = Math.Min(17, (int)HeroAge(h) - 19); if (num4 < num3) { return; } int num5 = rng.Range(0, 3); for (int num6 = 0; num6 < num5; num6++) { Hero child = NewKin(clan, rng.Chance(0.5) ? HeroSex.Male : HeroSex.Female, rng.Range(num3, num4 + 1), home, rng, taken, grown: false); SetParent(child, hero); SetParent(child, hero2); foreach (EducationStageDef item3 in Families.EducationStages.Where((EducationStageDef s) => HeroAge(child) >= (double)s.Age)) { child.Education[item3.StageId] = rng.Pick(Families.EducationStage(item3.StageId).Choices).Id; } } } internal static void SetParent(Hero child, Hero parent) { if (parent.Sex == HeroSex.Female) { child.MotherId = parent.Id; } else { child.FatherId = parent.Id; } } internal Hero NewKin(Clan clan, HeroSex sex, double age, Settlement home, RandomStream rng, ICollection taken, bool grown, string cultureId = null) { string cultureId2 = (string.IsNullOrEmpty(cultureId) ? clan.CultureId : cultureId); bool flag = clan.Id == State.PlayerClanId; Hero hero = new Hero { Id = State.Ids.Allocate("hero.kin"), Name = Families.Name(cultureId2, sex, ClanSurname(clan), rng, taken), ClanId = clan.Id, CultureId = cultureId2, UnitId = KinUnit(clan, cultureId2), Occupation = ((!flag) ? HeroOccupation.Lord : HeroOccupation.Companion), IsFamily = true, Sex = sex, BornDay = State.Clock.Day - (long)Math.Round(age * 84.0), State = ((!grown) ? HeroState.Inactive : HeroState.Active), SettlementId = (home?.Id ?? ""), Level = ((!grown) ? 1 : 5) }; if (grown) { string[] original = SkillIds.Original; foreach (string text in original) { hero.Skills[text] = ((text == "smithing" || text == "riding") ? 10 : (10 + rng.Range(0, 30))); } } string text2 = Campaign.LordUnitFor(Content, cultureId2, hero.Id); if (!string.IsNullOrEmpty(text2) && Content.Units.Get(text2) != null) { hero.UnitId = text2; } State.Heroes.Add(hero); C.HeroDevelopmentSystem.InitialiseHero(hero); taken.Add(hero.Name); return hero; } internal string KinUnit(Clan clan, string cultureId) { string text = Content.Cultures.Get(cultureId ?? "")?.HeroUnit; if (!string.IsNullOrEmpty(text) && Content.Units.Get(text) != null) { return text; } text = Content.Cultures.Get(clan?.CultureId ?? "")?.HeroUnit; if (string.IsNullOrEmpty(text) || Content.Units.Get(text) == null) { return State.Heroes.Get(clan?.LeaderHeroId ?? "")?.UnitId ?? State.PlayerHero?.UnitId ?? ""; } return text; } internal void DailyFamilies() { FamiliesState families = State.Families; if (families == null || !families.Started || families.AwaitingHeir || families.LineEnded) { return; } long day = State.Clock.Day; if (families.LastDay >= day) { return; } families.LastDay = day; RandomStream rng = State.Random.Get("families"); foreach (Hero item in State.Heroes.ToList()) { GiveIdentity(item); } if (!Settings.PeopleAge) { foreach (Hero hero in State.Heroes) { if (hero.State != HeroState.Dead && hero.Sex != HeroSex.Unspecified) { hero.BornDay++; } } } GrowChildren(rng); DeliverChildren(rng); if (Settings.Births) { ConceiveChildren(rng); } if (Settings.LordsMarry) { MatchLords(rng); } if (Settings.OldAgeDeaths) { DeathsOfOldAge(rng); } if (!families.AwaitingHeir && !families.LineEnded) { KeepFamiliesAtHome(); RepairClanLeaders(); C.InheritExtinctClans(); SendRelatives(rng); } } internal void GrowChildren(RandomStream rng) { EducationStageDef[] educationStages = Families.EducationStages; foreach (Hero item in State.Heroes.Where((Hero h) => h.State == HeroState.Inactive && h.Sex != HeroSex.Unspecified).ToList()) { double num = HeroAge(item); bool flag = item.ClanId == State.PlayerClanId; for (int num2 = 0; num2 < educationStages.Length; num2++) { EducationStageDef educationStageDef = educationStages[num2]; if (num < (double)educationStageDef.Age || item.Education.ContainsKey(educationStageDef.StageId)) { continue; } double num3 = ((num2 + 1 < educationStages.Length) ? educationStages[num2 + 1].Age : 18); if (flag && num < num3) { if (num - (double)educationStageDef.Age < 1.0 / 84.0) { C.Raise(CampaignEventKind.Family, $"{item.Name} is {educationStageDef.Age}: choose their upbringing in the family screen.", false, item.Id); } } else { item.Education[educationStageDef.StageId] = rng.Pick(Families.EducationStage(educationStageDef.StageId).Choices).Id; } } if (num >= 18.0) { ComeOfAge(item, rng); } } } internal void ComeOfAge(Hero child, RandomStream rng) { foreach (EducationStageDef item in Families.EducationStages.Where((EducationStageDef s) => !child.Education.ContainsKey(s.StageId))) { child.Education[item.StageId] = rng.Pick(Families.EducationStage(item.StageId).Choices).Id; } child.Skills = Families.GrownSkills(child.Education, rng); C.HeroDevelopmentSystem.InitialiseHero(child); child.Level = 1; child.Health = 1.0; child.State = HeroState.Active; Clan clan = State.Clans.Get(child.ClanId); Settlement settlement = State.Settlements.Get(child.SettlementId); if (settlement == null) { settlement = ClanHome(clan) ?? NearestTown(State.PlayerParty?.Position ?? Vec2.Zero, clan); child.SettlementId = settlement?.Id ?? ""; } if (child.ClanId == State.PlayerClanId) { string text = child.Name + " has come of age" + ((settlement != null) ? (" and waits for you at " + settlement.Name + ": meet them there to bring them into your party.") : "."); State.AddLog(LogCategory.Info, text, child.Id, settlement?.Id ?? ""); C.Raise(CampaignEventKind.Family, text, false, child.Id, settlement?.Id ?? ""); } else { State.AddLog(LogCategory.Politics, child.Name + " of " + (clan?.Name ?? "no clan") + " has come of age.", child.Id, clan?.Id ?? ""); } } public string EducationReason(string childId, string stageId, string choiceId) { Hero hero = State.Heroes.Get(childId); if (hero == null || hero.ClanId != State.PlayerClanId || hero.State != HeroState.Inactive) { return "You can only raise your own clan's children."; } EducationStageDef educationStageDef = Families.EducationStages.FirstOrDefault((EducationStageDef s) => s.StageId == stageId); if (educationStageDef == null) { return "Unknown step of their upbringing."; } if (HeroAge(hero) < (double)educationStageDef.Age) { return $"{hero.Name} is too young for this yet (at {educationStageDef.Age})."; } if (hero.Education.ContainsKey(stageId)) { return "That's already decided."; } if (CharacterCreation.LifeStageChoice(stageId, choiceId) == null) { return "Pick one of the paths on offer."; } return ""; } public CommandResult ChooseEducation(string childId, string stageId, string choiceId) { string text = EducationReason(childId, stageId, choiceId); if (text.Length > 0) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Require(childId); CharacterChoiceDef characterChoiceDef = CharacterCreation.LifeStageChoice(stageId, choiceId); hero.Education[stageId] = choiceId; State.AddLog(LogCategory.Info, hero.Name + "'s upbringing: " + characterChoiceDef.Name + ".", hero.Id); State.Touch(); return CommandResult.Success(hero.Name + ": " + characterChoiceDef.Name + "."); } public List<(Hero child, EducationStageDef stage)> EducationDue() { return State.Heroes.Where((Hero h) => h.ClanId == State.PlayerClanId && h.State == HeroState.Inactive && h.Sex != HeroSex.Unspecified).SelectMany((Hero h) => from s in Families.EducationStages where HeroAge(h) >= (double)s.Age && !h.Education.ContainsKey(s.StageId) select (h: h, s: s)).ToList(); } internal bool Together(Hero a, Hero b) { if (a == null || b == null) { return false; } if (!string.IsNullOrEmpty(a.PartyId) && a.PartyId == b.PartyId) { return true; } string text = Place(a); string text2 = Place(b); if (text.Length > 0) { return text == text2; } return false; string Place(Hero h) { Party party = State.Parties.Get(h.PartyId); if (party != null) { if (party.State != PartyState.InSettlement) { return ""; } return party.CurrentSettlementId; } return h.SettlementId ?? ""; } } internal void ConceiveChildren(RandomStream rng) { Dictionary dictionary = new Dictionary(StringComparer.Ordinal); foreach (Hero hero in State.Heroes) { if (hero.State != HeroState.Dead && !string.IsNullOrEmpty(hero.ClanId)) { dictionary[hero.ClanId] = (dictionary.TryGetValue(hero.ClanId, out var value) ? value : 0) + 1; } } foreach (Hero item in State.Heroes.Where((Hero h) => h.Sex == HeroSex.Female && h.State == HeroState.Active && h.ChildDueDay < 0).ToList()) { Hero husband = SpouseOf(item); if (husband == null || husband.State != HeroState.Active) { continue; } double num = Families.YearlyChildChance(HeroAge(item)); if (num <= 0.0) { continue; } bool flag = item.ClanId == State.PlayerClanId || husband.ClanId == State.PlayerClanId; if ((flag && !Together(item, husband)) || ChildrenOf(item).Count((Hero c) => c.State != HeroState.Dead && (c.FatherId == husband.Id || c.MotherId == husband.Id)) >= 5) { continue; } int value2; double num2 = Families.CrowdingFactor(dictionary.TryGetValue(item.ClanId ?? "", out value2) ? value2 : 0); if (!(num2 <= 0.0) && rng.Chance(Families.DailyChance(num) * num2)) { item.ChildDueDay = State.Clock.Day + 36; item.ChildFatherId = husband.Id; if (flag) { string text = $"{item.Name} is expecting a child, due in {36} days."; State.AddLog(LogCategory.Info, text, item.Id); C.Raise(CampaignEventKind.Family, text, false, item.Id); } } } } internal void DeliverChildren(RandomStream rng) { foreach (Hero item in State.Heroes.Where((Hero h) => h.ChildDueDay >= 0 && h.ChildDueDay <= State.Clock.Day).ToList()) { if (item.State == HeroState.Dead) { item.ChildDueDay = -1L; item.ChildFatherId = ""; } else { BearChild(item, rng); } } } internal Hero BearChild(Hero mother, RandomStream rng) { Hero hero = State.Heroes.Get(mother.ChildFatherId); Clan clan = ((mother.ClanId == State.PlayerClanId || hero?.ClanId == State.PlayerClanId) ? State.PlayerClan : (State.Clans.Get(hero?.ClanId ?? "") ?? State.Clans.Get(mother.ClanId))); mother.ChildDueDay = -1L; mother.ChildFatherId = ""; if (clan == null) { return null; } HashSet taken = new HashSet(State.Heroes.Select((Hero h) => h.Name), StringComparer.Ordinal); Settlement settlement = BirthPlace(mother, clan); HeroSex heroSex = (rng.Chance(0.5) ? HeroSex.Male : HeroSex.Female); string cultureId = (hero ?? mother).CultureId; Hero hero2 = NewKin(clan, heroSex, 0.0, settlement, rng, taken, grown: false, cultureId); hero2.BornDay = State.Clock.Day; hero2.MotherId = mother.Id; hero2.FatherId = hero?.Id ?? ""; Hero hero3 = new Hero[2] { mother, hero }.FirstOrDefault((Hero p) => p != null && p.ClanId == clan.Id && Content.Units.Get(p.UnitId) != null); if (clan.Id == State.PlayerClanId && hero3 != null) { hero2.UnitId = hero3.UnitId; } string text = ((settlement == null) ? "" : (" at " + settlement.Name)); string text2 = mother.Name + ((hero != null) ? (" and " + hero.Name + " have") : " has") + " a " + ((heroSex == HeroSex.Female) ? "daughter" : "son") + ", " + hero2.Name + ((text.Length > 0) ? ("," + text) : "") + "."; if (clan.Id == State.PlayerClanId) { State.AddLog(LogCategory.Info, text2, hero2.Id, settlement?.Id ?? ""); C.Raise(CampaignEventKind.Family, text2, false, hero2.Id, settlement?.Id ?? ""); } else { State.AddLog(LogCategory.Politics, text2, hero2.Id, clan.Id); } return hero2; } internal Settlement BirthPlace(Hero mother, Clan clan) { Party party = State.Parties.Get(mother.PartyId); Settlement settlement = ((party == null) ? State.Settlements.Get(mother.SettlementId) : ((party.State == PartyState.InSettlement) ? State.Settlements.Get(party.CurrentSettlementId) : null)); if (settlement != null && settlement.Type != SettlementType.Hideout && !State.AreHostile(clan, State.Clans.Get(settlement.OwnerClanId)) && clan.Id == State.PlayerClanId) { return settlement; } Settlement settlement2 = ClanHome(clan); if (settlement2 != null) { return settlement2; } if (settlement != null && settlement.Type != SettlementType.Hideout && !State.AreHostile(clan, State.Clans.Get(settlement.OwnerClanId))) { return settlement; } Vec2 vec = party?.Position ?? State.Settlements.Get(mother.SettlementId)?.Position ?? State.PlayerParty?.Position ?? Vec2.Zero; return NearestTown(vec, clan); } internal Settlement NearestTown(Vec2 from, Clan clan) { List list = State.Settlements.Where((Settlement s) => s.Type == SettlementType.Town).ToList(); List list2 = list.Where((Settlement s) => !State.AreHostile(clan, State.Clans.Get(s.OwnerClanId))).ToList(); return ((list2.Count > 0) ? list2 : list).OrderBy((Settlement s) => Vec2.Distance(from, s.Position)).ThenBy((Settlement s) => s.Id, StringComparer.Ordinal).FirstOrDefault(); } internal Hero MarriageMover(Hero a, Hero b) { Hero hero = ((a.Sex == HeroSex.Female) ? a : b); Hero hero2 = ((hero == a) ? b : a); bool num = State.Clans.Get(hero.ClanId)?.LeaderHeroId == hero.Id; bool flag = State.Clans.Get(hero2.ClanId)?.LeaderHeroId == hero2.Id; if (!num) { return hero; } if (!flag) { return hero2; } return null; } internal bool AiNoble(Hero h) { Clan clan = State.Clans.Get(h.ClanId); if (h.Occupation == HeroOccupation.Lord && clan != null && !clan.IsBandit && !clan.IsEliminated) { return clan.Id != State.PlayerClanId; } return false; } internal void MatchLords(RandomStream rng) { List list = State.Heroes.Where((Hero h) => AiNoble(h) && h.State == HeroState.Active && h.Sex != HeroSex.Unspecified && IsGrown(h) && HeroAge(h) <= 55.0 && SpouseOf(h) == null).ToList(); foreach (Hero item in list) { Hero seeker = item; if (SpouseOf(seeker) == null && seeker.State == HeroState.Active && rng.Chance(0.005) && !HeroBusy(seeker)) { Clan clan = State.Clans.Get(seeker.ClanId); double age = HeroAge(seeker); List list2 = (from o in list where o.ClanId != seeker.ClanId && o.Sex != seeker.Sex && SpouseOf(o) == null && o.State == HeroState.Active && Math.Abs(HeroAge(o) - age) <= 12.0 && MarriageReason(seeker, o).Length == 0 && !State.AreHostile(clan, State.Clans.Get(o.ClanId)) && Room(o) && !HeroBusy(o) orderby (!(State.Clans.Get(o.ClanId)?.KingdomId == clan.KingdomId) || string.IsNullOrEmpty(clan.KingdomId)) ? 1 : 0, (!(o.CultureId == seeker.CultureId)) ? 1 : 0, Math.Abs(HeroAge(o) - age) select o).ThenBy((Hero o) => o.Id, StringComparer.Ordinal).Take(3).ToList(); if (list2.Count != 0) { Hero b = rng.Pick(list2); Marry(seeker, b, MarriageMover(seeker, b)); } } bool Room(Hero o) { Hero hero = MarriageMover(seeker, o); if (hero == null) { return false; } Clan clan2 = State.Clans.Get((hero == seeker) ? o.ClanId : seeker.ClanId); return LivingClanMembers(clan2).Count < 12; } } } internal void Marry(Hero a, Hero b, Hero mover) { a.SpouseId = b.Id; b.SpouseId = a.Id; Hero hero = ((mover == a) ? b : a); Clan clan = State.Clans.Get(mover.ClanId); if (clan != null && string.IsNullOrEmpty(mover.BirthClanId)) { mover.BirthClanId = clan.Id; } Clan clan2 = State.Clans.Get(hero.ClanId); if (clan2 != null && mover.ClanId != clan2.Id) { MoveToClan(mover, clan2); } State.Families.Courtships.RemoveAll((CourtshipState c) => c.HeroId == a.Id || c.HeroId == b.Id || c.SuitorId == a.Id || c.SuitorId == b.Id); if (clan != null && clan2 != null && clan.Id != clan2.Id) { C.AdjustClanRelation(clan.Id, clan2.Id, 15); } string text = a.Name + " and " + b.Name + " are married." + ((clan != null && clan2 != null && clan.Id != clan2.Id) ? (" " + mover.Name + " joins " + clan2.Name + ".") : ""); bool flag = a.ClanId == State.PlayerClanId || b.ClanId == State.PlayerClanId || clan?.Id == State.PlayerClanId; State.AddLog((!flag) ? LogCategory.Politics : LogCategory.Info, text, a.Id, b.Id); if (flag) { C.Raise(CampaignEventKind.Family, text, false, a.Id, b.Id); } } internal void MoveToClan(Hero h, Clan to) { Clan clan = State.Clans.Get(h.ClanId); C.ClearHeroRoleAssignments(h.Id); C.ClearHeroGovernorAssignments(h.Id); Party party = State.Parties.Get(h.PartyId); if (party != null) { party.Troops.Heroes.Remove(h.Id); h.PartyId = ""; if (party.LeaderHeroId == h.Id && party.Kind == PartyKind.Lord && party.Id != State.PlayerPartyId && C.MilitaryPartyFor(party) == null && party.State != PartyState.Destroyed && party.State != PartyState.Disbanded) { DisbandLordParty(party, h.Name + " married into " + to.Name); } } if (clan?.Id == State.PlayerClanId) { ReturnGearToBag(h); h.MountId = ""; h.Dismounted = false; } h.ClanId = to.Id; h.IsFamily = true; if (to.Id == State.PlayerClanId) { C.BringLordHorseIntoClan(h); h.Occupation = HeroOccupation.Companion; h.DailyWage = 0; h.HireCost = 0L; h.SettlementId = ""; } else { h.Occupation = HeroOccupation.Lord; h.SettlementId = (ClanHome(to) ?? NearestTown(State.Settlements.Get(h.SettlementId)?.Position ?? party?.Position ?? Vec2.Zero, to))?.Id ?? ""; } if (clan != null && clan.LeaderHeroId == h.Id) { ChooseClanLeader(clan, h); } C.ReconcileCaravans(); C.ReconcileMilitaryParties(); } internal void DisbandLordParty(Party p, string reason) { Settlement settlement = State.Settlements.Get(p.HomeSettlementId); if (settlement == null || settlement.OwnerClanId != p.ClanId) { settlement = ClanHome(State.Clans.Get(p.ClanId)); } int num = 0; int num2 = 0; foreach (TroopStack stack in p.Troops.Stacks) { if (settlement != null && settlement.Type != SettlementType.Hideout) { settlement.Garrison.Add(stack.UnitId, stack.Healthy, stack.Wounded); num += stack.Total; } else { num2 += stack.Total; } } if (settlement != null && settlement.Type != SettlementType.Hideout) { foreach (TroopStack stack2 in p.Prisoners.Stacks) { settlement.Prisoners.Add(stack2.UnitId, stack2.Healthy, stack2.Wounded); } } p.Troops.Stacks.Clear(); p.Prisoners.Stacks.Clear(); OutcomeCommitter.DestroyParty(C, p, reason + ((num > 0) ? $"; {num} troops went to {settlement.Name}" : "") + ((num2 > 0) ? $"; {num2} troops scattered" : "")); } internal void ReturnGearToBag(Hero h) { HeroEquipmentState loadout = h.Loadout; h.Loadout = null; if (loadout == null) { return; } Party playerParty = State.PlayerParty; bool flag = playerParty != null && playerParty.State != PartyState.Destroyed && playerParty.State != PartyState.Disbanded; List list = loadout.SlotItems().ToList(); if (loadout.Clothing != null) { list.AddRange(from w in loadout.Clothing.Values where w != null && !w.Bare select w.PieceId); } foreach (string item in list.Where((string i) => !string.IsNullOrEmpty(i))) { if (flag) { if (playerParty.Equipment == null) { playerParty.Equipment = new SortedDictionary(StringComparer.Ordinal); } playerParty.Equipment[item] = C.EquipmentCount(playerParty, item) + 1; } else if (Smithing.IsCraftedId(item)) { State.Smithing?.Weapons?.Remove(item); } } } internal bool HeroBusy(Hero h) { if (h == null) { return false; } if (h.IsPlayer) { PlayerActivity activity = State.Player.Activity; if (activity == PlayerActivity.InEncounter || activity == PlayerActivity.InBattle || activity == PlayerActivity.Raiding || activity == PlayerActivity.Besieging) { return true; } if (C.PlayerTournament != null || C.PlayerSiege != null) { return true; } } if (C.NamedCustodyReserved(h)) { return true; } TournamentState playerTournament = C.PlayerTournament; if (playerTournament != null && playerTournament.Run?.Fighters?.Any((TournamentFighterState x) => x.HeroId == h.Id) == true) { return true; } Party party = State.Parties.Get(h.PartyId); if (party == null || party.State == PartyState.Destroyed || party.State == PartyState.Disbanded) { return false; } if (party.State == PartyState.Engaged || !string.IsNullOrEmpty(party.EncounterId) || C.MilitaryPartyReserved(party.Id)) { return true; } if (party.ActiveRaid != null || party.Order.Kind == OrderKind.Besiege || party.Order.Kind == OrderKind.Raid || C.ClanArmyContains(party.Id)) { return true; } if (State.Sieges != null && State.Sieges.Any((SiegeState s) => s.Stage != SiegeStage.Ended && s.BesiegerPartyId == party.Id)) { return true; } if (party.State == PartyState.InSettlement && C.IsSettlementBesieged(State.Settlements.Get(party.CurrentSettlementId))) { return true; } return false; } internal void DeathsOfOldAge(RandomStream rng) { foreach (Hero item in State.Heroes.Where((Hero x) => x.State != HeroState.Dead && x.Sex != HeroSex.Unspecified && x.Occupation != HeroOccupation.Notable).ToList()) { double num = HeroAge(item); if (!(num < 50.0) && item.State != HeroState.Dead && rng.Chance(Families.DailyChance(Families.YearlyDeathChance(num))) && !HeroBusy(item)) { HeroDies(item, "old age"); if (State.Families.AwaitingHeir || State.Families.LineEnded) { break; } } } } public void HeroDies(Hero h, string cause) { if (h == null || h.State == HeroState.Dead) { return; } bool isPlayer = h.IsPlayer; if (h.State == HeroState.Captive) { State.Parties.Get(h.CaptorPartyId)?.Prisoners.Heroes.Remove(h.Id); State.Settlements.Get(h.CaptorSettlementId)?.Prisoners.Heroes.Remove(h.Id); h.CaptorPartyId = ""; h.CaptorSettlementId = ""; } C.ClearHeroRoleAssignments(h.Id); C.ClearHeroGovernorAssignments(h.Id); if (h.ClanId == State.PlayerClanId) { ReturnGearToBag(h); } else { foreach (string item in h.Loadout?.SlotItems().ToList() ?? new List()) { if (Smithing.IsCraftedId(item)) { State.Smithing?.Weapons?.Remove(item); } } h.Loadout = null; } h.MountId = ""; C.ForgetLordHorse(h); Party party = State.Parties.Get(h.PartyId); bool flag = party != null && party.LeaderHeroId == h.Id && party.State != PartyState.Destroyed && party.State != PartyState.Disbanded; party?.Troops.Heroes.Remove(h.Id); foreach (Party party2 in State.Parties) { party2.Troops.Heroes.Remove(h.Id); } h.PartyId = ""; h.SettlementId = ""; h.State = HeroState.Dead; if (flag && party.Kind == PartyKind.Lord && party.Id != State.PlayerPartyId && C.MilitaryPartyFor(party) == null) { DisbandLordParty(party, h.Name + " died"); } Clan clan = State.Clans.Get(h.ClanId); string text = h.Name + ((clan != null && !clan.IsBandit) ? (" of " + clan.Name) : "") + $" has died of {cause} at {HeroYears(h)}."; text = ((cause == "old age") ? text : text.Replace("died of " + cause, "died " + cause)); bool flag2 = h.ClanId == State.PlayerClanId; if (!isPlayer) { State.AddLog(flag2 ? LogCategory.Warning : LogCategory.Politics, text, h.Id); if (flag2) { C.Raise(CampaignEventKind.Family, text, false, h.Id); } } AfterHeroDeath(h, cause); C.ReconcileCaravans(); C.ReconcileMilitaryParties(); } internal void AfterHeroDeath(Hero h, string cause) { if (h.DeathDay < 0) { h.DeathDay = State.Clock.Day; } if (string.IsNullOrEmpty(h.DeathCause)) { h.DeathCause = cause ?? ""; } h.ChildDueDay = -1L; h.ChildFatherId = ""; Hero hero = (string.IsNullOrEmpty(h.SpouseId) ? null : State.Heroes.Get(h.SpouseId)); if (hero != null && hero.SpouseId == h.Id) { hero.SpouseId = ""; if (hero.FormerSpouseIds == null) { hero.FormerSpouseIds = new List(); } hero.FormerSpouseIds.Add(h.Id); } State.Families?.Courtships?.RemoveAll((CourtshipState c) => c.HeroId == h.Id || c.SuitorId == h.Id); State.Wanderers?.Plans?.Remove(h.Id); C.NoteRulerDeath(h); if (h.IsPlayer) { C.BeginSuccession(h); return; } Clan clan = State.Clans.Get(h.ClanId); if (clan != null && clan.LeaderHeroId == h.Id && clan.Id != State.PlayerClanId) { ChooseClanLeader(clan, h); } } internal void ChooseClanLeader(Clan clan, Hero previous) { Hero hero = (from h in (from h in LivingClanMembers(clan) where h.Id != previous?.Id && IsGrown(h) && (h.State == HeroState.Active || h.State == HeroState.Captive) && (h.Occupation == HeroOccupation.Lord || h.IsFamily || h.Occupation == HeroOccupation.Player) select h).ToList() orderby (h.State != HeroState.Active) ? 1 : 0 select h).ThenBy(Rank).ThenByDescending((Hero h) => HeroAge(h)).ThenBy((Hero h) => h.Id, StringComparer.Ordinal) .FirstOrDefault(); clan.LeaderHeroId = hero?.Id ?? ""; State.AddLog(LogCategory.Politics, (hero != null) ? (hero.Name + " now leads " + clan.Name + ".") : (clan.Name + " has no grown member to lead it."), clan.Id, hero?.Id ?? ""); int Rank(Hero h) { if (previous != null && (h.FatherId == previous.Id || h.MotherId == previous.Id)) { return 0; } if (previous != null && h.Id == previous.SpouseId) { return 1; } if (previous != null && SiblingsOf(previous).Any((Hero s) => s.Id == h.Id)) { return 2; } return 3; } } internal void RepairClanLeaders() { foreach (Clan item in State.Clans.Where((Clan c) => !c.IsBandit && !c.IsEliminated && c.Id != State.PlayerClanId)) { Hero leader = State.Heroes.Get(item.LeaderHeroId); if ((leader == null || !(leader.ClanId == item.Id) || leader.State == HeroState.Dead || !IsGrown(leader)) && LivingClanMembers(item).Any((Hero h) => h.Id != leader?.Id && IsGrown(h) && (h.State == HeroState.Active || h.State == HeroState.Captive))) { ChooseClanLeader(item, leader); } } } internal void SendRelatives(RandomStream rng) { FamiliesState families = State.Families; HashSet hashSet = null; foreach (Clan item in State.Clans.Where((Clan c) => !c.IsBandit && !c.IsEliminated && c.Id != State.PlayerClanId).ToList()) { Settlement settlement = ClanHome(item); if (settlement == null || LivingClanMembers(item).Count((Hero h) => IsGrown(h) && IsNoble(h) && (h.State == HeroState.Active || h.State == HeroState.Captive)) >= 2 || (families.RelativeDueDay.TryGetValue(item.Id, out var value) && State.Clock.Day < value)) { continue; } if (hashSet == null) { hashSet = new HashSet(State.Heroes.Select((Hero h) => h.Name), StringComparer.Ordinal); } Hero hero = NewKin(item, rng.Chance(0.6) ? HeroSex.Male : HeroSex.Female, rng.Range(20, 35), settlement, rng, hashSet, grown: true); families.RelativeDueDay[item.Id] = State.Clock.Day + 28; State.AddLog(LogCategory.Politics, hero.Name + ", a cousin, has come to " + settlement.Name + " to serve " + item.Name + ".", hero.Id, item.Id); if (!string.IsNullOrEmpty(item.LeaderHeroId)) { Hero hero2 = State.Heroes.Get(item.LeaderHeroId); if (hero2 == null || hero2.State != HeroState.Dead) { continue; } } ChooseClanLeader(item, null); } } internal void KeepFamiliesAtHome() { foreach (Hero item in State.Heroes.Where((Hero x) => (x.State == HeroState.Active || x.State == HeroState.Inactive) && x.IsFamily && string.IsNullOrEmpty(x.PartyId)).ToList()) { Clan clan = State.Clans.Get(item.ClanId); if (clan == null) { continue; } Settlement settlement = State.Settlements.Get(item.SettlementId); if (settlement == null || settlement.Type == SettlementType.Hideout || State.AreHostile(clan, State.Clans.Get(settlement.OwnerClanId))) { Settlement settlement2 = ((clan.Id == State.PlayerClanId) ? null : ClanHome(clan)); if (settlement2 != null && State.AreHostile(clan, State.Clans.Get(settlement2.OwnerClanId))) { settlement2 = null; } settlement2 = settlement2 ?? NearestTown(settlement?.Position ?? State.PlayerParty?.Position ?? Vec2.Zero, clan); if (settlement2 != null && !(settlement2.Id == item.SettlementId)) { item.SettlementId = settlement2.Id; State.AddLog(LogCategory.Info, item.Name + " has moved to " + settlement2.Name + ".", item.Id, settlement2.Id); } } } } public bool IsKin(Hero h) { return h?.IsFamily ?? false; } } internal sealed class FamilyLawSystem { private readonly Campaign C; private CampaignState State => C.State; internal FamilyLawSystem(Campaign host) { C = host; } private bool LivingClan(Clan clan) { if (clan != null && !clan.IsBandit) { return !clan.IsEliminated; } return false; } private bool AiClan(Clan clan) { if (LivingClan(clan)) { return clan.Id != State.PlayerClanId; } return false; } internal bool LineEnded(Clan clan) { if (AiClan(clan)) { return !State.Heroes.Any((Hero h) => h.ClanId == clan.Id && h.State != HeroState.Dead && C.IsGrown(h) && C.IsNoble(h) && (h.State == HeroState.Active || h.State == HeroState.Captive)); } return false; } internal bool RulesAKingdom(Clan clan) { return State.Kingdoms.Any((Kingdom k) => !k.IsEliminated && k.RulerClanId == clan.Id); } internal Hero LastOfLine(Clan clan) { Hero hero = State.Heroes.Get(clan.LeaderHeroId); if (hero != null && hero.ClanId == clan.Id) { return hero; } return (from h in State.Heroes where h.ClanId == clan.Id && h.State == HeroState.Dead && (C.IsNoble(h) || h.Occupation == HeroOccupation.Lord) orderby h.DeathDay descending select h).ThenBy((Hero h) => h.Id, StringComparer.Ordinal).FirstOrDefault(); } internal int KinRank(Hero last, Clan clan, Hero h) { if (last != null) { if (h.FatherId == last.Id || h.MotherId == last.Id) { return 0; } if (h.Id == last.SpouseId) { goto IL_00ce; } List formerSpouseIds = last.FormerSpouseIds; if (formerSpouseIds != null && formerSpouseIds.Contains(h.Id)) { List divorcedIds = last.DivorcedIds; if (divorcedIds == null || !divorcedIds.Contains(h.Id)) { goto IL_00ce; } } if (C.SiblingsOf(last).Any((Hero x) => x.Id == h.Id)) { return 2; } if (last.FatherId == h.Id || last.MotherId == h.Id) { return 3; } if (C.ParentsOf(h).Any((Hero p) => p.FatherId == last.Id || p.MotherId == last.Id)) { return 4; } if (C.ParentsOf(h).Any((Hero p) => C.SiblingsOf(last).Any((Hero x) => x.Id == p.Id))) { return 5; } } if (C.ParentsOf(h).Any((Hero p) => p.ClanId == clan.Id || p.BirthClanId == clan.Id) || h.BirthClanId == clan.Id) { return 6; } return -1; IL_00ce: return 1; } public Hero ClanHeir(Clan clan) { if (!AiClan(clan)) { return null; } Hero last = LastOfLine(clan); return (from x in (from h in State.Heroes where h.State != HeroState.Dead && h.ClanId != clan.Id && C.IsGrown(h) && (C.IsNoble(h) || h.IsPlayer) && LivingClan(State.Clans.Get(h.ClanId)) select new { Hero = h, Rank = KinRank(last, clan, h) } into x where x.Rank >= 0 orderby x.Rank, (!x.Hero.IsPlayer) ? 1 : 0, C.HeroAge(x.Hero) descending select x).ThenBy(x => x.Hero.Id, StringComparer.Ordinal) select x.Hero).FirstOrDefault(); } internal void InheritExtinctClans() { foreach (Clan item in State.Clans.Where(AiClan).OrderBy((Clan c) => c.Id, StringComparer.Ordinal).ToList()) { if (LineEnded(item) && !RulesAKingdom(item)) { Hero hero = ClanHeir(item); if (hero != null) { Inherit(item, State.Clans.Require(hero.ClanId), hero); } } } } internal void Inherit(Clan clan, Clan to, Hero heir) { Hero hero = LastOfLine(clan); bool flag = to.Id == State.PlayerClanId; foreach (Party item in State.Parties.Where((Party p) => p.ClanId == clan.Id && p.State != PartyState.Destroyed && p.State != PartyState.Disbanded && string.IsNullOrEmpty(p.EncounterId) && p.State != PartyState.Engaged).ToList()) { CaravanState caravanState = C.CaravanFor(item); if (caravanState != null && caravanState.ClanCaravan && !flag) { caravanState.OwnerClanId = to.Id; item.ClanId = to.Id; item.Name = to.Name + " caravan"; } else if (caravanState != null) { if (item.Gold > 0) { State.Transact(to, item.Gold, LedgerAccount.Trade, "Inherited from " + item.Name); } item.Gold = 0L; item.Cargo.Clear(); item.Troops.Stacks.Clear(); caravanState.Status = "Disbanded"; caravanState.CargoCosts.Clear(); OutcomeCommitter.DestroyParty(C, item, "its clan's line ended"); } else if (item.Kind == PartyKind.Lord) { C.DisbandLordParty(item, "the line of " + clan.Name + " ended"); } } List list = State.Settlements.Where((Settlement s) => s.OwnerClanId == clan.Id && s.Type != SettlementType.Hideout).OrderBy((Settlement s) => s.Id, StringComparer.Ordinal).ToList(); foreach (Settlement item2 in list) { C.ChangeSettlementOwner(item2, to.Id); } long num = Math.Max(0L, clan.Gold); if (num > 0) { State.Transact(clan, -num, LedgerAccount.Other, "Inheritance passed to " + to.Name); State.Transact(to, num, LedgerAccount.Other, "Inheritance from " + clan.Name); } List list2 = State.Heroes.Where((Hero h) => h.ClanId == clan.Id && h.State != HeroState.Dead).OrderBy((Hero h) => h.Id, StringComparer.Ordinal).ToList(); foreach (Hero item3 in list2) { C.MoveHeroToClan(item3, to); } clan.IsEliminated = true; clan.LeaderHeroId = ""; C.ClearClanIndependentDiplomacy(clan.Id); string text = ((list.Count > 0) ? string.Join(", ", list.Select((Settlement s) => s.Name).ToArray()) : "no fiefs") + ((num > 0) ? (" and " + num.ToString("N0") + " denars") : "") + ((list2.Count > 0) ? ("; " + list2.Count + ((list2.Count == 1) ? " child goes" : " children go") + " with them as wards") : ""); string text2 = "The line of " + clan.Name + " has ended" + ((hero != null) ? (" with " + hero.Name) : "") + ". " + heir.Name + ((flag && heir.IsPlayer) ? ", you, " : (" of " + to.Name + ", ")) + "the nearest kin, inherits " + text + "."; State.AddLog((!flag) ? LogCategory.Politics : LogCategory.Info, text2, clan.Id, to.Id, heir.Id); if (flag) { C.Raise(CampaignEventKind.Family, (heir.IsPlayer ? "You inherit" : (to.Name + " inherits")) + " from " + clan.Name + ": " + text + ".", true, clan.Id, heir.Id); } C.OnDiplomacyChanged(); State.Touch(); } internal Clan DivorceDestination(Hero spouse) { if (spouse == null) { return null; } Clan clan = State.Clans.Get(spouse.BirthClanId ?? ""); if (AiClan(clan)) { return clan; } foreach (Hero item in C.ParentsOf(spouse)) { Clan clan2 = State.Clans.Get(item.ClanId); if (AiClan(clan2)) { return clan2; } } foreach (Hero item2 in C.SiblingsOf(spouse).OrderBy((Hero x) => x.Id, StringComparer.Ordinal)) { Clan clan3 = State.Clans.Get(item2.ClanId); if (AiClan(clan3)) { return clan3; } } List list = State.Clans.Where(AiClan).ToList(); List list2 = list.Where((Clan c) => c.CultureId == spouse.CultureId).ToList(); return ((list2.Count > 0) ? list2 : list).OrderBy((Clan c) => C.LivingClanMembers(c).Count).ThenBy((Clan c) => c.Id, StringComparer.Ordinal).FirstOrDefault(); } public string DivorceReason() { Hero playerHero = State.PlayerHero; if (playerHero == null || playerHero.State != HeroState.Active) { return "You are not free to do that."; } if (C.AwaitingHeir || C.LineEnded) { return "Choose your heir first."; } switch (State.Player.Activity) { case PlayerActivity.Captive: return "You are a prisoner."; case PlayerActivity.InEncounter: case PlayerActivity.InBattle: return "Finish the encounter first."; default: { Hero spouse = C.SpouseOf(playerHero); if (spouse == null) { return "You are not married."; } if (spouse.ClanId != State.PlayerClanId) { return spouse.Name + " is not of your clan."; } if (spouse.State != HeroState.Active) { return spouse.Name + " must be free first."; } if (playerHero.ChildDueDay >= 0 || spouse.ChildDueDay >= 0) { return "Wait until the child is born."; } if (C.GovernorAssignedSettlement(spouse.Id) != null) { return "Recall " + spouse.Name + " from governing first."; } if (State.Parties.Any((Party p) => p.LeaderHeroId == spouse.Id && p.State != PartyState.Destroyed && p.State != PartyState.Disbanded)) { return spouse.Name + " leads a party of their own: bring them back first."; } if (C.HeroBusy(spouse)) { return spouse.Name + " is busy."; } if (DivorceDestination(spouse) == null) { return "There is nowhere for " + spouse.Name + " to go."; } return ""; } } } public CommandResult Divorce() { string text = DivorceReason(); if (text.Length > 0) { return CommandResult.Fail(text); } Hero playerHero = State.PlayerHero; Hero spouse = C.SpouseOf(playerHero); Clan clan = DivorceDestination(spouse); playerHero.SpouseId = ""; spouse.SpouseId = ""; if (playerHero.FormerSpouseIds == null) { playerHero.FormerSpouseIds = new List(); } if (spouse.FormerSpouseIds == null) { spouse.FormerSpouseIds = new List(); } if (playerHero.DivorcedIds == null) { playerHero.DivorcedIds = new List(); } if (spouse.DivorcedIds == null) { spouse.DivorcedIds = new List(); } playerHero.FormerSpouseIds.Add(spouse.Id); spouse.FormerSpouseIds.Add(playerHero.Id); playerHero.DivorcedIds.Add(spouse.Id); spouse.DivorcedIds.Add(playerHero.Id); State.Families?.Courtships?.RemoveAll((CourtshipState c) => c.HeroId == spouse.Id || c.SuitorId == spouse.Id); C.MoveHeroToClan(spouse, clan); C.AdjustClanRelation(State.PlayerClanId, clan.Id, -20); string text2 = "You and " + spouse.Name + " are divorced. " + spouse.Name + " returns to " + clan.Name + "; your children stay with you."; State.AddLog(LogCategory.Info, text2, playerHero.Id, spouse.Id, clan.Id); C.Raise(CampaignEventKind.Family, text2, false, playerHero.Id, spouse.Id); State.Touch(); return CommandResult.Success(text2); } } internal sealed class GarrisonsSystem { private readonly Campaign C; private CampaignState State => C.State; private CampaignRules Rules => C.Rules; internal GarrisonsSystem(Campaign host) { C = host; } public void EnsureGarrisonFields() { bool flag = false; if (State.GarrisonParties == null) { State.GarrisonParties = new List(); flag = true; } foreach (Settlement settlement in State.Settlements) { if (settlement.Management != null) { if (settlement.Management.GarrisonOrders == null) { settlement.Management.GarrisonOrders = new GarrisonOrdersState(); flag = true; } GarrisonOrdersState garrisonOrders = settlement.Management.GarrisonOrders; if (garrisonOrders.UpgradePaths == null) { garrisonOrders.UpgradePaths = new SortedDictionary(StringComparer.Ordinal); flag = true; } if (garrisonOrders.Target < 0) { garrisonOrders.Target = 0; flag = true; } if (garrisonOrders.TierCap < 0) { garrisonOrders.TierCap = 0; flag = true; } } } if (flag | Reconcile()) { State.Touch(); } } public GarrisonPartyState RecordFor(Party p) { if (p != null && p.Kind == PartyKind.Garrison) { return State.GarrisonParties?.FirstOrDefault((GarrisonPartyState r) => r.PartyId == p.Id); } return null; } public GarrisonPartyState Record(string id) { return State.GarrisonParties?.FirstOrDefault((GarrisonPartyState r) => r.Id == id); } internal string SiegeCall(Party p, Settlement s) { GarrisonPartyState garrisonPartyState = RecordFor(p); if (garrisonPartyState == null || garrisonPartyState.Role != GarrisonPartyRole.Guards || garrisonPartyState.Order == GarrisonPartyOrder.Return || s == null) { return ""; } if (p.State != PartyState.Active || !string.IsNullOrEmpty(p.EncounterId) || C.MilitaryPartyReserved(p.Id) || p.DisengagedUntilMinute > State.Clock.Minute || C.PartyCombatants(p) == 0) { return ""; } if (Vec2.Distance(p.Position, s.Position) > Rules.PatrolRadius) { return ""; } switch (garrisonPartyState.Order) { case GarrisonPartyOrder.Guard: if (!(garrisonPartyState.TargetId == s.Id)) { return ""; } return "defend"; case GarrisonPartyOrder.Patrol: if (!(garrisonPartyState.HomeSettlementId == s.Id)) { return ""; } return "defend"; case GarrisonPartyOrder.Escort: return garrisonPartyState.TargetId ?? ""; case GarrisonPartyOrder.Follow: return State.PlayerPartyId; default: return ""; } } internal void BringToSiege(Party p, Settlement s) { p.Position = s.Position; C.ClearOrder(p); } public bool IsPlayerGarrisonParty(Party p) { if (p != null && p.Kind == PartyKind.Garrison && p.ClanId == State.PlayerClanId && p.State != PartyState.Destroyed) { return p.State != PartyState.Disbanded; } return false; } public IEnumerable<(GarrisonPartyState record, Party party)> PartiesOf(string clanId) { return from r in State.GarrisonParties ?? new List() where r.OwnerClanId == clanId select (r: r, State.Parties.Get(r.PartyId)) into x where x.Item2 != null && x.Item2.State != PartyState.Destroyed && x.Item2.State != PartyState.Disbanded select x; } public IEnumerable<(GarrisonPartyState record, Party party)> PartiesFrom(Settlement s) { return from x in PartiesOf(s.OwnerClanId) where x.record.HomeSettlementId == s.Id select x; } internal bool Reconcile() { bool result = false; foreach (GarrisonPartyState item in State.GarrisonParties.ToList()) { Party party = State.Parties.Get(item.PartyId); if (party == null || party.State == PartyState.Destroyed || party.State == PartyState.Disbanded || party.Kind != PartyKind.Garrison) { State.GarrisonParties.Remove(item); if (party != null && (party.State == PartyState.Destroyed || party.State == PartyState.Disbanded) && string.IsNullOrEmpty(party.EncounterId)) { State.Parties.Remove(party.Id); } result = true; } else { if (!string.IsNullOrEmpty(party.EncounterId)) { continue; } Settlement settlement = State.Settlements.Get(item.HomeSettlementId); if (settlement == null || settlement.OwnerClanId != item.OwnerClanId) { Settlement settlement2 = NearestHolding(item.OwnerClanId, party.Position); if (settlement2 == null) { Dissolve(item, party, "had nowhere left to go and went home"); result = true; continue; } item.HomeSettlementId = settlement2.Id; party.HomeSettlementId = settlement2.Id; if (item.Role == GarrisonPartyRole.Guards) { item.Order = GarrisonPartyOrder.Return; } result = true; } if (item.Role != GarrisonPartyRole.Guards) { Settlement settlement3 = State.Settlements.Get(item.DestinationId); if (settlement3 == null || settlement3.OwnerClanId != item.OwnerClanId) { item.DestinationId = item.HomeSettlementId; result = true; } } } } return result; } private Settlement NearestHolding(string clanId, Vec2 from) { return (from s in State.Settlements where s.OwnerClanId == clanId && (s.Type == SettlementType.Town || s.Type == SettlementType.Castle) orderby Vec2.Distance(@from, s.Position) select s).ThenBy((Settlement s) => s.Id, StringComparer.Ordinal).FirstOrDefault(); } private void Dissolve(GarrisonPartyState r, Party p, string why) { State.GarrisonParties.Remove(r); p.Troops.Stacks.Clear(); p.Prisoners.Stacks.Clear(); p.State = PartyState.Disbanded; State.PlayerSightings.Remove(p.Id); State.Parties.Remove(p.Id); State.AddLog(LogCategory.Recruitment, p.Name + " " + why + ".", p.HomeSettlementId); } public bool Improves(Settlement s) { if (s == null || s.Management == null || (s.Type != SettlementType.Town && s.Type != SettlementType.Castle)) { return false; } Clan clan = State.Clans.Get(s.OwnerClanId); if (clan == null || clan.IsBandit || clan.IsEliminated) { return false; } if (!(s.OwnerClanId == State.PlayerClanId)) { return C.Settings.AiGarrisonsImprove; } return true; } public GarrisonOrdersState OrdersOf(Settlement s) { GarrisonOrdersState garrisonOrdersState = s.Management.GarrisonOrders ?? (s.Management.GarrisonOrders = new GarrisonOrdersState()); if (s.OwnerClanId != State.PlayerClanId && s.Management.OwnerClanId == s.OwnerClanId) { garrisonOrdersState.Training = true; garrisonOrdersState.AutoUpgrade = true; garrisonOrdersState.RecruitPrisoners = true; } return garrisonOrdersState; } internal void DailyGarrison(Settlement s) { if (Improves(s) && !(s.Management.OwnerClanId != s.OwnerClanId)) { GarrisonOrdersState o = OrdersOf(s); Drill(s, o); Promote(s, o); WinOverPrisoners(s, o); } } public int DrillXp(Settlement s) { return 5 + ((C.ProjectLevel(s, "project.watchtower") > 0) ? 1 : 0) + (int)Math.Round(Math.Max(0.0, C.SettlementPerk(s, PerkEffect.GarrisonXp))); } internal int Drill(Settlement s, GarrisonOrdersState o) { if (!o.Training) { return 0; } int num = 0; foreach (TroopStack stack in s.Garrison.Stacks) { UnitDef unitDef = C.UnitDef(stack.UnitId); if (unitDef != null && stack.Healthy > 0 && unitDef.Upgrades.Count != 0) { long num2 = (long)stack.Total * (long)unitDef.Upgrades.Max((UpgradeDef u) => Math.Max(1, u.Xp)); if (stack.Xp < num2) { int num3 = (int)Math.Min(num2 - stack.Xp, (long)stack.Healthy * (long)DrillXp(s)); stack.Xp += num3; num += num3; } } } return num; } public List PromotionsFor(Settlement s, string unitId) { UnitDef unitDef = C.UnitDef(unitId); GarrisonOrdersState o = OrdersOf(s); if (unitDef == null) { return new List(); } return unitDef.Upgrades.Where((UpgradeDef u) => C.UnitDef(u.To) != null && (o.TierCap <= 0 || C.UnitDef(u.To).Tier <= o.TierCap) && (string.IsNullOrEmpty(u.RequiresSettlement) || u.RequiresSettlement == s.Type.ToString())).ToList(); } public UpgradeDef PromotionFor(Settlement s, string unitId) { List list = PromotionsFor(s, unitId); if (list.Count == 0) { return null; } if (OrdersOf(s).UpgradePaths.TryGetValue(unitId, out var chosen)) { UpgradeDef upgradeDef = list.FirstOrDefault((UpgradeDef u) => u.To == chosen); if (upgradeDef != null) { return upgradeDef; } } return list.OrderBy((UpgradeDef u) => s.Garrison.Find(u.To)?.Total ?? 0).ThenBy((UpgradeDef u) => u.To, StringComparer.Ordinal).First(); } internal int Promote(Settlement s, GarrisonOrdersState o) { if (!o.AutoUpgrade) { return 0; } Clan clan = State.Clans.Get(s.OwnerClanId); if (clan == null) { return 0; } SettlementManagementState management = s.Management; int num = 0; long num2 = 0L; foreach (TroopStack item in s.Garrison.Stacks.OrderBy((TroopStack x) => C.UnitDef(x.UnitId)?.Tier ?? 0).ThenBy((TroopStack x) => x.UnitId, StringComparer.Ordinal).ToList()) { UpgradeDef upgradeDef = PromotionFor(s, item.UnitId); if (upgradeDef == null || item.Healthy <= 0) { continue; } int num3 = Math.Min(item.Healthy, item.Xp / Math.Max(1, upgradeDef.Xp)); if (upgradeDef.Gold > 0) { num3 = (int)Math.Min(num3, Math.Max(0L, clan.Gold) / upgradeDef.Gold); } if (management.GarrisonWageLimit > 0) { double num4 = C.GarrisonWagePerHead(s, upgradeDef.To) - C.GarrisonWagePerHead(s, item.UnitId); if (num4 > 0.0) { num3 = (int)Math.Min(num3, Math.Max(0.0, Math.Floor(((double)management.GarrisonWageLimit - C.GarrisonDailyWages(s)) / num4))); } } if (num3 > 0) { long num5 = (long)upgradeDef.Gold * (long)num3; if (num5 > 0) { State.Transact(clan, -num5, LedgerAccount.Upgrade, "Garrison of " + s.Name + ": " + num3 + " " + C.UnitDef(item.UnitId).Name + " promoted"); } string unitId = item.UnitId; int val = item.Xp - upgradeDef.Xp * num3; s.Garrison.RemoveHealthy(unitId, num3); TroopStack troopStack = s.Garrison.Find(unitId); if (troopStack != null) { troopStack.Xp = Math.Max(0, val); } s.Garrison.Add(upgradeDef.To, num3); num += num3; num2 += num5; } } if (num > 0) { State.AddLog(LogCategory.Recruitment, num + " soldiers of the garrison of " + s.Name + " were promoted" + ((num2 > 0) ? (" (" + num2 + " denars).") : "."), s.Id); State.Touch(); } return num; } internal int WinOverPrisoners(Settlement s, GarrisonOrdersState o) { foreach (TroopStack stack in s.Prisoners.Stacks) { if (C.UnitDef(stack.UnitId) != null && stack.Healthy > 0) { double num = (double)stack.Healthy / (C.PrisonerRecruitmentDays(stack.UnitId) * 2.0); stack.PrisonerRecruitment = Math.Min(stack.Total, PrisonersSystem.PrisonerProgress(stack) + num); } } if (!o.RecruitPrisoners) { return 0; } int num2 = 0; foreach (TroopStack item in s.Prisoners.Stacks.OrderByDescending((TroopStack x) => C.UnitDef(x.UnitId)?.Tier ?? 0).ThenBy((TroopStack x) => x.UnitId, StringComparer.Ordinal).ToList()) { int num3 = C.PrisonerReadyCount(item); if (num3 <= 0) { continue; } int num4 = Math.Min(num3, Room(s, item.UnitId)); if (num4 > 0) { double val = PrisonersSystem.PrisonerProgress(item) - (double)num4; string unitId = item.UnitId; s.Prisoners.RemoveHealthy(unitId, num4); TroopStack troopStack = s.Prisoners.Find(unitId); if (troopStack != null) { troopStack.PrisonerRecruitment = Math.Max(0.0, Math.Min(troopStack.Total, val)); } s.Garrison.Add(unitId, num4); num2 += num4; } } if (num2 > 0) { string text = num2 + " prisoner" + ((num2 == 1) ? "" : "s") + " in the dungeon of " + s.Name + " joined its garrison."; State.AddLog(LogCategory.Recruitment, text, s.Id); if (s.OwnerClanId == State.PlayerClanId) { C.Raise(CampaignEventKind.Info, text, false, s.Id); } State.Touch(); } return num2; } public int Incoming(Settlement s) { return (from x in PartiesOf(s.OwnerClanId) where x.record.Role != GarrisonPartyRole.Guards && x.record.DestinationId == s.Id select x).Sum(((GarrisonPartyState record, Party party) x) => x.party.Troops.TotalTroops); } public double IncomingWages(Settlement s) { return (from x in PartiesOf(s.OwnerClanId) where x.record.Role != GarrisonPartyRole.Guards && x.record.DestinationId == s.Id select x).Sum(((GarrisonPartyState record, Party party) x) => x.party.Troops.Stacks.Sum((TroopStack st) => (double)st.Total * C.GarrisonWagePerHead(s, st.UnitId))); } public int Room(Settlement s, string unitId) { SettlementManagementState management = s.Management; GarrisonOrdersState garrisonOrdersState = OrdersOf(s); long num = 2147483647L; if (garrisonOrdersState.Target > 0) { num = Math.Min(num, garrisonOrdersState.Target - s.Garrison.TotalTroops - Incoming(s)); } if (management.GarrisonWageLimit > 0 && s.OwnerClanId == management.OwnerClanId) { double num2 = C.GarrisonWagePerHead(s, unitId); if (num2 > 0.0) { num = Math.Min(num, (long)Math.Floor(((double)management.GarrisonWageLimit - C.GarrisonDailyWages(s) - IncomingWages(s)) / num2 + 1E-09)); } } return (int)Math.Max(0L, Math.Min(2147483647L, num)); } internal int AutoRecruit(Settlement s) { SettlementManagementState management = s.Management; GarrisonOrdersState garrisonOrdersState = OrdersOf(s); if (!management.GarrisonAutoRecruit || (management.GarrisonWageLimit <= 0 && garrisonOrdersState.Target <= 0) || management.OwnerClanId != s.OwnerClanId || C.IsSettlementBesieged(s)) { return 0; } Clan clan = State.Clans.Get(s.OwnerClanId); if (clan == null || clan.IsBandit) { return 0; } int num = 0; long num2 = 0L; foreach (RecruitSlot item in s.Recruits.Where((RecruitSlot x) => x.Available && C.UnitDef(x.UnitId) != null).ToList()) { if (num >= 4) { break; } UnitDef unitDef = C.UnitDef(item.UnitId); if (Room(s, unitDef.Id) > 0) { if (clan.Gold < unitDef.RecruitCost) { break; } State.Transact(clan, -unitDef.RecruitCost, LedgerAccount.Recruitment, "Garrison recruit at " + s.Name); s.Garrison.Add(unitDef.Id, 1); item.Available = false; num2 += unitDef.RecruitCost; num++; } } if (num > 0) { State.AddLog(LogCategory.Recruitment, "The garrison of " + s.Name + " took on " + num + " volunteer" + ((num == 1) ? "" : "s") + " (" + num2 + " denars).", s.Id); } foreach (Settlement item2 in (from v in C.BoundVillages(s) where v.OwnerClanId == s.OwnerClanId && !C.IsVillageBeingRaided(v) select v).OrderBy((Settlement v) => v.Id, StringComparer.Ordinal)) { TroopRoster troopRoster = new TroopRoster(); long num3 = 0L; List list = new List(); foreach (RecruitSlot item3 in item2.Recruits.Where((RecruitSlot x) => x.Available && C.UnitDef(x.UnitId) != null)) { UnitDef unitDef2 = C.UnitDef(item3.UnitId); if (Room(s, unitDef2.Id) - troopRoster.TotalTroops > 0 && clan.Gold - num3 >= unitDef2.RecruitCost) { troopRoster.Add(unitDef2.Id, 1); num3 += unitDef2.RecruitCost; list.Add(item3); } } if (troopRoster.TotalTroops < 5) { continue; } State.Transact(clan, -num3, LedgerAccount.Recruitment, "Garrison recruits at " + item2.Name + " for " + s.Name); foreach (RecruitSlot item4 in list) { item4.Available = false; } Party party = Spawn(s, item2, GarrisonPartyRole.Recruits, troopRoster, "Recruits for " + s.Name); Record(party).DestinationId = s.Id; State.AddLog(LogCategory.Recruitment, troopRoster.TotalTroops + " volunteers from " + item2.Name + " set out to join the garrison of " + s.Name + " (" + num3 + " denars).", s.Id, item2.Id, party.Id); num += troopRoster.TotalTroops; break; } return num; } private GarrisonPartyState Record(Party p) { return State.GarrisonParties.First((GarrisonPartyState r) => r.PartyId == p.Id); } private Party Spawn(Settlement home, Settlement from, GarrisonPartyRole role, TroopRoster troops, string name) { Party party = new Party { Id = State.Ids.Allocate("party"), Name = name, Kind = PartyKind.Garrison, ClanId = home.OwnerClanId, HomeSettlementId = home.Id, Position = from.Position, State = PartyState.InSettlement, CurrentSettlementId = from.Id, Morale = 60.0, CreatedAtMinute = State.Clock.Minute, NextThinkMinute = State.Clock.Minute }; foreach (TroopStack stack in troops.Stacks) { party.Troops.Add(stack.UnitId, stack.Healthy, stack.Wounded, stack.Xp); } State.Parties.Add(party); State.GarrisonParties.Add(new GarrisonPartyState { Id = State.Ids.Allocate("garrisonparty"), PartyId = party.Id, OwnerClanId = home.OwnerClanId, HomeSettlementId = home.Id, Role = role, Order = ((role != GarrisonPartyRole.Guards) ? GarrisonPartyOrder.Return : GarrisonPartyOrder.Patrol), StartedMinute = State.Clock.Minute }); State.Touch(); return party; } private TroopRoster Detach(TroopRoster garrison, int count) { TroopRoster troopRoster = new TroopRoster(); int healthy = garrison.TotalHealthy; if (count <= 0 || healthy <= 0) { return troopRoster; } count = Math.Min(count, healthy); var source = (from st in garrison.Stacks where st.Healthy > 0 select new { UnitId = st.UnitId, n = (int)Math.Floor((double)st.Healthy * (double)count / (double)healthy) }).ToList(); Dictionary want = Enumerable.ToDictionary(source, x => x.UnitId, x => x.n, StringComparer.Ordinal); int num = count - want.Values.Sum(); foreach (TroopStack item in (from st in garrison.Stacks where st.Healthy > 0 orderby st.Healthy - want[st.UnitId] descending select st).ThenBy((TroopStack st) => st.UnitId, StringComparer.Ordinal)) { if (num <= 0) { break; } if (want[item.UnitId] < item.Healthy) { want[item.UnitId]++; num--; } } foreach (KeyValuePair item2 in want.Where((KeyValuePair kv) => kv.Value > 0).OrderBy, string>((KeyValuePair kv) => kv.Key, StringComparer.Ordinal)) { MoveHealthy(garrison, troopRoster, item2.Key, item2.Value); } return troopRoster; } private static void MoveHealthy(TroopRoster from, TroopRoster to, string unitId, int n) { TroopStack troopStack = from.Find(unitId); if (troopStack != null) { n = Math.Min(n, troopStack.Healthy); if (n > 0) { int xp = (int)((troopStack.Total > 0) ? ((long)troopStack.Xp * (long)n / troopStack.Total) : 0); from.RemoveHealthy(unitId, n); to.Add(unitId, n, 0, xp); } } } internal string FiefReason() { CommandResult commandResult = C.RequireFree(); if (!commandResult.Ok) { return commandResult.Message; } Settlement settlement = C.CurrentSettlement(); if (settlement == null) { return "You're not in a settlement."; } if (settlement.OwnerClanId != State.PlayerClanId) { return "This isn't yours."; } if (settlement.Type != SettlementType.Town && settlement.Type != SettlementType.Castle) { return "Only towns and castles keep a garrison."; } if (!string.IsNullOrEmpty(State.PlayerParty?.EncounterId)) { return "Deal with the encounter first."; } return ""; } public CommandResult SetFlag(string which, bool on) { string text = FiefReason(); if (text.Length > 0) { return CommandResult.Fail(text); } Settlement settlement = C.CurrentSettlement(); C.SyncSettlementManagementOwner(settlement); GarrisonOrdersState garrisonOrdersState = OrdersOf(settlement); string msg; switch (which) { case "training": garrisonOrdersState.Training = on; msg = (on ? ("The garrison drills every day: each healthy soldier gains " + DrillXp(settlement) + " experience.") : "The garrison no longer drills."); break; case "upgrade": garrisonOrdersState.AutoUpgrade = on; msg = (on ? "Soldiers with enough experience are promoted at dawn, paid from your treasury." : "The garrison's soldiers are no longer promoted on their own."); break; case "prisoners": garrisonOrdersState.RecruitPrisoners = on; msg = (on ? "Prisoners in the dungeon who come round to serving join the garrison." : "Prisoners stay in the dungeon."); break; default: return CommandResult.Fail("Unknown order."); } State.Touch(); return CommandResult.Success(msg); } public CommandResult SetTierCap(int tier) { string text = FiefReason(); if (text.Length > 0) { return CommandResult.Fail(text); } if (tier < 0 || tier > 6) { return CommandResult.Fail("Choose a tier from 1 to 6, or none."); } Settlement settlement = C.CurrentSettlement(); C.SyncSettlementManagementOwner(settlement); OrdersOf(settlement).TierCap = tier; State.Touch(); return CommandResult.Success((tier == 0) ? "Soldiers are promoted as far as they can go." : ("Soldiers are promoted no higher than tier " + tier + ".")); } public CommandResult SetTarget(int size) { string text = FiefReason(); if (text.Length > 0) { return CommandResult.Fail(text); } if (size < 0) { return CommandResult.Fail("A size can't be negative."); } Settlement settlement = C.CurrentSettlement(); C.SyncSettlementManagementOwner(settlement); OrdersOf(settlement).Target = size; if (size == 0 && settlement.Management.GarrisonWageLimit <= 0) { settlement.Management.GarrisonAutoRecruit = false; } State.Touch(); return CommandResult.Success((size == 0) ? "No target size: the garrison recruits up to its wage limit only." : ("The garrison recruits up to " + size + " soldiers.")); } public CommandResult SetUpgradePath(string unitId, string toUnitId) { string text = FiefReason(); if (text.Length > 0) { return CommandResult.Fail(text); } UnitDef unitDef = C.UnitDef(unitId ?? ""); if (unitDef == null) { return CommandResult.Fail("Unknown troop."); } Settlement settlement = C.CurrentSettlement(); C.SyncSettlementManagementOwner(settlement); GarrisonOrdersState garrisonOrdersState = OrdersOf(settlement); if (string.IsNullOrEmpty(toUnitId)) { garrisonOrdersState.UpgradePaths.Remove(unitDef.Id); State.Touch(); return CommandResult.Success(unitDef.Name + " are promoted to whichever the garrison has fewer of."); } if (!unitDef.Upgrades.Any((UpgradeDef u) => u.To == toUnitId) || C.UnitDef(toUnitId) == null) { return CommandResult.Fail(unitDef.Name + " can't become that."); } garrisonOrdersState.UpgradePaths[unitDef.Id] = toUnitId; State.Touch(); return CommandResult.Success(unitDef.Name + " are promoted to " + C.UnitDef(toUnitId).Name + "."); } public string FormGuardsReason(int size) { string text = FiefReason(); if (text.Length > 0) { return text; } Settlement settlement = C.CurrentSettlement(); if (C.IsSettlementBesieged(settlement)) { return "Not while it's under siege."; } if (PartiesFrom(settlement).Count(((GarrisonPartyState record, Party party) x) => x.record.Role == GarrisonPartyRole.Guards) >= 2) { return "Its " + 2 + " guard parties are already out."; } if (size < 5) { return "Guards go out at least " + 5 + " strong."; } if (settlement.Garrison.TotalHealthy < size) { return "The garrison has only " + settlement.Garrison.TotalHealthy + " healthy soldiers."; } return ""; } public CommandResult FormGuards(int size) { string text = FormGuardsReason(size); if (text.Length > 0) { return CommandResult.Fail(text); } Settlement settlement = C.CurrentSettlement(); C.SyncSettlementManagementOwner(settlement); int num = PartiesFrom(settlement).Count(((GarrisonPartyState record, Party party) x) => x.record.Role == GarrisonPartyRole.Guards); TroopRoster troopRoster = Detach(settlement.Garrison, size); Party party = Spawn(settlement, settlement, GarrisonPartyRole.Guards, troopRoster, ((num == 0) ? "Guards of " : "Second guards of ") + settlement.Name); State.AddLog(LogCategory.Recruitment, party.Name + " went out " + troopRoster.TotalTroops + " strong to patrol the land round it.", settlement.Id, party.Id); return CommandResult.Success(party.Name + " are out, " + troopRoster.TotalTroops + " strong, patrolling round " + settlement.Name + "."); } public IEnumerable TransferDestinations(Settlement from) { return (from x in State.Settlements where x.Id != @from.Id && x.OwnerClanId == @from.OwnerClanId && (x.Type == SettlementType.Town || x.Type == SettlementType.Castle) && C.Nav.SameComponent(@from.Position, x.Position) orderby Vec2.Distance(@from.Position, x.Position) select x).ThenBy((Settlement x) => x.Id, StringComparer.Ordinal); } public string SendTroopsReason(string destinationId, string unitId, int count) { string text = FiefReason(); if (text.Length > 0) { return text; } Settlement settlement = C.CurrentSettlement(); if (C.IsSettlementBesieged(settlement)) { return "Not while it's under siege."; } Settlement dest = State.Settlements.Get(destinationId ?? ""); if (dest == null || !TransferDestinations(settlement).Any((Settlement x) => x.Id == dest.Id)) { return "Choose another town or castle of yours."; } if (count <= 0) { return "Choose how many."; } if ((settlement.Garrison.Find(unitId ?? "")?.Healthy ?? 0) < count) { return "Not enough healthy soldiers of that kind."; } return ""; } public CommandResult SendTroops(string destinationId, string unitId, int count) { string text = SendTroopsReason(destinationId, unitId, count); if (text.Length > 0) { return CommandResult.Fail(text); } Settlement s = C.CurrentSettlement(); Settlement dest = State.Settlements.Get(destinationId); TroopRoster troopRoster = new TroopRoster(); MoveHealthy(s.Garrison, troopRoster, unitId, count); (GarrisonPartyState, Party) tuple = PartiesFrom(s).FirstOrDefault(((GarrisonPartyState record, Party party) x) => x.record.Role == GarrisonPartyRole.Transfer && x.record.DestinationId == dest.Id && x.party.State == PartyState.InSettlement && x.party.CurrentSettlementId == s.Id); Party party; if (tuple.Item2 != null) { party = tuple.Item2; foreach (TroopStack stack in troopRoster.Stacks) { party.Troops.Add(stack.UnitId, stack.Healthy, stack.Wounded, stack.Xp); } } else { party = Spawn(s, s, GarrisonPartyRole.Transfer, troopRoster, "Soldiers bound for " + dest.Name); Record(party).DestinationId = dest.Id; } State.AddLog(LogCategory.Recruitment, count + " " + C.UnitDef(unitId).Name + " left " + s.Name + " for the garrison of " + dest.Name + ".", s.Id, dest.Id, party.Id); State.Touch(); return CommandResult.Success(count + " " + C.UnitDef(unitId).Name + " are marching to " + dest.Name + "."); } public string OrderReason(string recordId, GarrisonPartyOrder order, string targetId) { GarrisonPartyState garrisonPartyState = Record(recordId); Party party = State.Parties.Get(garrisonPartyState?.PartyId ?? ""); if (garrisonPartyState == null || party == null || garrisonPartyState.OwnerClanId != State.PlayerClanId || party.State == PartyState.Destroyed || party.State == PartyState.Disbanded) { return "Those soldiers are gone."; } if (garrisonPartyState.Role != GarrisonPartyRole.Guards) { return "They're on the march to a garrison."; } if (!string.IsNullOrEmpty(party.EncounterId)) { return "They're fighting."; } Clan clan = State.Clans.Get(State.PlayerClanId); switch (order) { case GarrisonPartyOrder.Guard: { Settlement settlement = State.Settlements.Get(targetId ?? ""); if (settlement == null || settlement.Type == SettlementType.Hideout) { return "Choose a village, castle or town to guard."; } if (State.FactionOf(State.Clans.Get(settlement.OwnerClanId)) != State.FactionOf(clan)) { return "Only your own realm's places."; } if (!C.Nav.SameComponent(party.Position, settlement.Position)) { return "They can't get there."; } break; } case GarrisonPartyOrder.Escort: { Party party2 = State.Parties.Get(targetId ?? ""); if (party2 == null || party2.ClanId != State.PlayerClanId || party2.Id == State.PlayerPartyId || party2.Id == party.Id || party2.State == PartyState.Destroyed || party2.State == PartyState.Disbanded) { return "Choose a party of your clan to escort."; } if (party2.Kind == PartyKind.Garrison) { GarrisonPartyState garrisonPartyState2 = RecordFor(party2); if (garrisonPartyState2 != null && garrisonPartyState2.Role == GarrisonPartyRole.Guards) { return "Guards don't escort guards."; } } break; } case GarrisonPartyOrder.Follow: if (State.Player.Activity == PlayerActivity.Captive || State.PlayerParty == null) { return "You can't lead them now."; } break; } return ""; } public CommandResult SetOrder(string recordId, GarrisonPartyOrder order, string targetId = "") { string text = OrderReason(recordId, order, targetId); if (text.Length > 0) { return CommandResult.Fail(text); } GarrisonPartyState garrisonPartyState = Record(recordId); Party party = State.Parties.Get(garrisonPartyState.PartyId); garrisonPartyState.Order = order; garrisonPartyState.TargetId = ((order == GarrisonPartyOrder.Guard || order == GarrisonPartyOrder.Escort) ? targetId : ""); party.NextThinkMinute = 0L; C.ClearOrder(party); State.Touch(); return CommandResult.Success(party.Name + ": " + Describe(garrisonPartyState) + "."); } public string Describe(GarrisonPartyState r) { if (r == null) { return ""; } if (r.Role == GarrisonPartyRole.Recruits) { return "volunteers marching to " + (State.Settlements.Get(r.DestinationId)?.Name ?? "the garrison"); } if (r.Role == GarrisonPartyRole.Transfer) { return "marching to the garrison of " + (State.Settlements.Get(r.DestinationId)?.Name ?? "another holding"); } string text = State.Settlements.Get(r.HomeSettlementId)?.Name ?? "their garrison"; return r.Order switch { GarrisonPartyOrder.Guard => "guarding " + (State.Settlements.Get(r.TargetId)?.Name ?? "a place"), GarrisonPartyOrder.Escort => "escorting " + (State.Parties.Get(r.TargetId)?.Name ?? "a party"), GarrisonPartyOrder.Follow => "following you", GarrisonPartyOrder.Return => "returning to " + text, _ => "patrolling round " + text, }; } internal void Options(Party p, double strength, List<(Party party, double strength, double dist)> hostiles, List options) { GarrisonPartyState r = RecordFor(p); if (r == null) { return; } Settlement settlement = State.Settlements.Get(r.HomeSettlementId); if (settlement == null) { return; } if (r.Role != GarrisonPartyRole.Guards || r.Order == GarrisonPartyOrder.Return) { Settlement dest = ((r.Role == GarrisonPartyRole.Guards) ? settlement : (State.Settlements.Get(r.DestinationId) ?? settlement)); if (p.State == PartyState.InSettlement && p.CurrentSettlementId == dest.Id) { options.Add(new Campaign.AiOption { Task = "Join the garrison", Score = 10.0, Detail = dest.Name, Apply = delegate { Merge(r, p, dest); } }); return; } C.AddFleeOrFight(p, strength, hostiles, options, canEngage: false); options.Add(new Campaign.AiOption { Task = "March to " + dest.Name, Score = 1.0, Detail = Describe(r), Apply = delegate { GoTo(p, dest); } }); return; } Vec2 anchor = settlement.Position; double radius = Rules.PatrolRadius; Settlement guarded = null; Party party = null; switch (r.Order) { case GarrisonPartyOrder.Guard: guarded = State.Settlements.Get(r.TargetId); if (guarded == null || State.FactionOf(State.Clans.Get(guarded.OwnerClanId)) != State.FactionOf(State.Clans.Get(r.OwnerClanId))) { r.Order = GarrisonPartyOrder.Return; r.TargetId = ""; return; } anchor = guarded.Position; radius = Rules.PatrolRadius * 0.6; break; case GarrisonPartyOrder.Escort: party = State.Parties.Get(r.TargetId); if (party == null || party.ClanId != r.OwnerClanId || party.State == PartyState.Destroyed || party.State == PartyState.Disbanded) { r.Order = GarrisonPartyOrder.Return; r.TargetId = ""; State.AddLog(LogCategory.Travel, p.Name + " have no one left to escort and are going home.", p.Id); return; } anchor = party.Position; radius = Rules.JoinBattleRadius * 2.0; break; case GarrisonPartyOrder.Follow: party = State.PlayerParty; if (party == null || State.Player.Activity == PlayerActivity.Captive || party.State == PartyState.Destroyed) { r.Order = GarrisonPartyOrder.Return; return; } anchor = party.Position; radius = Rules.JoinBattleRadius * 2.0; break; } List<(Party party, double strength, double dist)> near = hostiles.Where(((Party party, double strength, double dist) h) => Vec2.Distance(h.party.Position, anchor) <= radius).ToList(); C.AddFleeOrFight(p, strength, near, options, canEngage: true); C.AddFleeOrFight(p, strength, hostiles.Where(((Party party, double strength, double dist) h) => !near.Contains(h)).ToList(), options, canEngage: false); if (guarded != null) { foreach (var item in near.Where(((Party party, double strength, double dist) h) => h.party.ActiveRaid?.SettlementId == guarded.Id || C.SiegeForSettlement(guarded.Id)?.BesiegerPartyId == h.party.Id)) { var (target, _, _) = item; if (!(strength / Math.Max(0.01, item.strength) < Rules.EngageStrengthRatio * 0.8)) { options.Add(new Campaign.AiOption { Task = "Drive off " + target.Name, Score = 4.0, Detail = "attacking " + guarded.Name, Apply = delegate { C.SetMoveOrder(p, OrderKind.Engage, target.Position, target.Id, "guard"); } }); } } } if (party != null) { Party follow = party; if (follow.State == PartyState.InSettlement) { Settlement place = State.Settlements.Get(follow.CurrentSettlementId); if (place != null && C.CanEnter(p, place)) { options.Add(new Campaign.AiOption { Task = "Wait at " + place.Name, Score = 0.8, Detail = Describe(r), Apply = delegate { GoTo(p, place); } }); } else { options.Add(new Campaign.AiOption { Task = "Wait outside", Score = 0.8, Detail = Describe(r), Apply = delegate { C.ClearOrder(p); } }); } return; } options.Add(new Campaign.AiOption { Task = ((r.Order == GarrisonPartyOrder.Follow) ? "Follow you" : ("Escort " + follow.Name)), Score = 0.8, Detail = Describe(r), Apply = delegate { if (p.Order.Kind != OrderKind.Follow || p.Order.TargetId != follow.Id) { C.SetMoveOrder(p, OrderKind.Follow, follow.Position, follow.Id, "escort"); } } }); return; } options.Add(new Campaign.AiOption { Task = ((guarded != null) ? ("Guard " + guarded.Name) : "Patrol"), Score = 0.7, Detail = Describe(r), Apply = delegate { if (p.Order.Kind != OrderKind.Patrol || !p.Order.HasPath || Vec2.Distance(p.Order.PathGoal, anchor) > radius * 1.5) { C.PatrolNear(p, anchor); } } }); } private void GoTo(Party p, Settlement s) { if (p.State == PartyState.InSettlement && p.CurrentSettlementId == s.Id) { C.ClearOrder(p); } else if (p.Order.Kind != OrderKind.GoToSettlement || p.Order.TargetId != s.Id) { C.SetMoveOrder(p, OrderKind.GoToSettlement, s.Position, s.Id, "garrison"); } } internal void Merge(GarrisonPartyState r, Party p, Settlement s) { foreach (TroopStack stack in p.Troops.Stacks) { s.Garrison.Add(stack.UnitId, stack.Healthy, stack.Wounded, stack.Xp); } foreach (TroopStack stack2 in p.Prisoners.Stacks) { s.Prisoners.Add(stack2.UnitId, stack2.Healthy, stack2.Wounded, stack2.Xp); } int totalTroops = p.Troops.TotalTroops; State.GarrisonParties.Remove(r); p.Troops.Stacks.Clear(); p.Prisoners.Stacks.Clear(); p.State = PartyState.Disbanded; State.PlayerSightings.Remove(p.Id); State.Parties.Remove(p.Id); string text = totalTroops + " soldiers joined the garrison of " + s.Name + ((r.Role == GarrisonPartyRole.Recruits) ? " from its villages." : "."); State.AddLog(LogCategory.Recruitment, text, s.Id); if (r.OwnerClanId == State.PlayerClanId && r.Role != GarrisonPartyRole.Recruits) { C.Raise(CampaignEventKind.Info, text, false, s.Id); } State.Touch(); } public double FieldWages(Party p) { Settlement home = State.Settlements.Get(p.HomeSettlementId); if (home != null) { return p.Troops.Stacks.Sum((TroopStack st) => (double)st.Total * C.GarrisonWagePerHead(home, st.UnitId)) * 1.5; } return 0.0; } public double FieldWagesOf(string clanId) { return PartiesOf(clanId).Sum(((GarrisonPartyState record, Party party) x) => FieldWages(x.party)); } internal void DailyParties() { if (Reconcile()) { State.Touch(); } foreach (var (garrisonPartyState, party) in PartiesOf(State.PlayerClanId).Concat(State.Clans.Where((Clan c) => c.Id != State.PlayerClanId).SelectMany((Clan c) => PartiesOf(c.Id))).ToList()) { if (party.State == PartyState.Engaged) { continue; } Clan clan = State.Clans.Get(garrisonPartyState.OwnerClanId); long num = (long)Math.Ceiling(FieldWages(party)); if (clan != null && num > 0 && -State.Transact(clan, -num, LedgerAccount.GarrisonWages, "Wages for " + party.Name, allowPartial: true) < num && garrisonPartyState.Role == GarrisonPartyRole.Guards && garrisonPartyState.Order != GarrisonPartyOrder.Return) { garrisonPartyState.Order = GarrisonPartyOrder.Return; party.NextThinkMinute = 0L; string text = party.Name + " weren't paid in full and are going back to " + (State.Settlements.Get(garrisonPartyState.HomeSettlementId)?.Name ?? "their garrison") + "."; State.AddLog(LogCategory.Warning, text, party.Id); if (garrisonPartyState.OwnerClanId == State.PlayerClanId) { C.Raise(CampaignEventKind.Warning, text, false, party.Id); } } } } } internal sealed class GovernanceSystem { private readonly Campaign C; private CampaignState State => C.State; internal GovernanceSystem(Campaign host) { C = host; } public void EnsureGovernanceFields() { bool flag = false; foreach (Settlement settlement in State.Settlements) { if (settlement.Management == null) { settlement.Management = new SettlementManagementState(); flag = true; } SettlementManagementState management = settlement.Management; if (!management.Initialized) { management.Initialized = true; management.OwnerClanId = settlement.OwnerClanId; management.LastDay = State.Clock.Day; flag = true; } } if (flag) { State.Touch(); } } public static bool IsSettlementProject(string id) { if (!(id == "project.granary") && !(id == "project.watchtower")) { return id == "project.walls"; } return true; } public string ProjectName(string id) { return id switch { "project.walls" => "Walls", "project.watchtower" => "Watchtower", "project.granary" => "Granary", _ => "Unknown project", }; } public long ProjectCost(string id) { return id switch { "project.walls" => 2000, "project.watchtower" => 400, "project.granary" => 300, _ => 0, }; } public int ProjectTimber(string id) { return id switch { "project.walls" => 10, "project.watchtower" => 3, "project.granary" => 5, _ => 0, }; } public int ProjectTools(string id) { return id switch { "project.walls" => 5, "project.watchtower" => 3, "project.granary" => 2, _ => 0, }; } public static int ProjectDays(string id) { if (!(id == "project.walls")) { return 3; } return 10; } public int ProjectLevel(Settlement settlement, string id) { return id switch { "project.walls" => C.WallLevel(settlement), "project.watchtower" => (settlement?.Management?.WatchtowerLevel).GetValueOrDefault(), "project.granary" => (settlement?.Management?.GranaryLevel).GetValueOrDefault(), _ => 0, }; } internal bool IsGovernedSettlement(Settlement settlement) { if (settlement != null) { if (settlement.Type != SettlementType.Town) { return settlement.Type == SettlementType.Castle; } return true; } return false; } internal TaxPolicy EffectiveSettlementPolicy(Settlement settlement) { if (!IsGovernedSettlement(settlement) || settlement.Management == null || !(settlement.Management.OwnerClanId == settlement.OwnerClanId)) { return TaxPolicy.Balanced; } return settlement.Management.Policy; } public double GovernanceTaxFactor(Settlement settlement) { return EffectiveSettlementPolicy(settlement) switch { TaxPolicy.Levy => 1.25, TaxPolicy.Relief => 0.75, _ => 1.0, } * C.GovernorTaxFactor(settlement) * C.RealmPolicyTaxFactor(settlement) * C.LawTaxFactor(settlement) * C.HardshipTaxFactor(settlement); } public double SettlementFoodConsumption(Settlement settlement, double baseConsumption) { int num = ((settlement != null && settlement.Type == SettlementType.Town) ? Math.Max(0, Math.Min(3, settlement.Management?.GranaryLevel ?? 0)) : 0); return Math.Max(0.0, baseConsumption) * (1.0 - 0.1 * (double)num); } public double SettlementSecurityChange(Settlement settlement) { if (settlement == null || settlement.Type == SettlementType.Hideout) { return 0.0; } double num = Math.Max(-0.5, Math.Min(0.5, 50.0 - settlement.Security)); double num2 = Math.Min(1.0, (double)Math.Max(0, settlement.Garrison?.TotalHealthy ?? 0) * 0.05); int num3 = (IsGovernedSettlement(settlement) ? Math.Max(0, Math.Min(3, settlement.Management?.WatchtowerLevel ?? 0)) : 0); return Math.Max(0.0, Math.Min(100.0, settlement.Security + num + num2 + (double)num3 * 0.5 + C.LawSecurity(settlement) + C.HardshipSecurity(settlement) + C.SettlementPerk(settlement, PerkEffect.Security))) - settlement.Security; } public double SettlementLoyaltyChange(Settlement settlement) { return SettlementLoyaltyForecast(settlement).Change; } public StatForecast SettlementLoyaltyForecast(Settlement settlement) { StatForecast statForecast = new StatForecast { Current = (settlement?.Loyalty ?? 0.0) }; if (settlement == null || settlement.Type == SettlementType.Hideout) { return statForecast; } statForecast.Add("Settling towards 50", Math.Max(-0.25, Math.Min(0.25, 50.0 - settlement.Loyalty))); switch (EffectiveSettlementPolicy(settlement)) { case TaxPolicy.Relief: statForecast.Add("Tax relief", 1.0); break; case TaxPolicy.Levy: statForecast.Add("Tax levy", -1.0); break; } if (C.SettlementFood(settlement) <= 0.0) { statForecast.Add("Hunger", -1.0); } if (settlement.Security < 25.0) { statForecast.Add("Lawlessness", -0.5); } statForecast.Add("Governor", C.GovernorLoyaltyBonus(settlement)); RealmPolicy realmPolicy = C.RealmPolicyAt(settlement); statForecast.Add((realmPolicy == RealmPolicy.LocalCharters) ? "Local charters" : "War levy", C.RealmPolicyLoyaltyChange(settlement)); C.AddLawLoyalty(statForecast, settlement); statForecast.Add("Hardship (" + Campaign.HardshipTier(settlement.Management?.Hardship ?? 0.0).ToLowerInvariant() + ")", C.HardshipLoyalty(settlement)); statForecast.Add("Perks", C.SettlementPerk(settlement, PerkEffect.Loyalty)); double num = Math.Max(0.0, Math.Min(100.0, settlement.Loyalty + statForecast.Change)); if (Math.Abs(num - (settlement.Loyalty + statForecast.Change)) > 1E-12) { statForecast.Add((num <= 0.0) ? "Lower limit" : "Upper limit", num - (settlement.Loyalty + statForecast.Change)); } return statForecast; } internal string SettlementManagementReason() { string text = C.CargoCommandReason(); if (text.Length > 0) { return text; } Settlement settlement = C.CurrentSettlement(); if (!IsGovernedSettlement(settlement) || Vec2.Distance(State.PlayerParty.Position, settlement.Position) > 0.01) { return "Go to the town or castle to manage it."; } if (settlement.OwnerClanId != State.PlayerClanId) { return "You don't own this place."; } if (!C.CanEnter(State.PlayerParty, settlement)) { return "You can't get in."; } if (settlement.Management == null || !settlement.Management.Initialized) { return "Settlement management is unavailable."; } return ""; } public string SettlementPolicyReason(TaxPolicy policy) { string text = SettlementManagementReason(); if (text.Length > 0) { return text; } if (!Enum.IsDefined(typeof(TaxPolicy), policy)) { return "Unknown tax policy."; } return ""; } public CommandResult SetSettlementPolicy(TaxPolicy policy) { string text = SettlementPolicyReason(policy); if (text.Length > 0) { return CommandResult.Fail(text); } Settlement settlement = C.CurrentSettlement(); bool flag = SyncSettlementManagementOwner(settlement); SettlementManagementState management = settlement.Management; if (management.Policy == policy) { if (flag) { State.Touch(); } return CommandResult.Success("Tax policy already set."); } management.Policy = policy; State.AddLog(LogCategory.Economy, settlement.Name + " adopted " + policy.ToString().ToLowerInvariant() + " taxes.", settlement.Id); State.Touch(); return CommandResult.Success("Tax policy changed."); } public string ProjectStartReason(string id) { string text = SettlementManagementReason(); if (text.Length > 0) { return text; } if (!IsSettlementProject(id)) { return "Unknown settlement project."; } Settlement settlement = C.CurrentSettlement(); SettlementManagementState management = settlement.Management; if (id == "project.granary" && settlement.Type != SettlementType.Town) { return "Granaries cut how much townsfolk eat. Towns only."; } if (management.OwnerClanId == settlement.OwnerClanId && !string.IsNullOrEmpty(management.ProjectId)) { return "Finish or cancel the current project first."; } if (ProjectLevel(settlement, id) >= 3) { return "Already at its highest level."; } if (State.PlayerClan.Gold < ProjectCost(id)) { return "You need " + ProjectCost(id) + " denars."; } if (C.CargoCount(State.PlayerParty, "good.timber") < ProjectTimber(id) || C.CargoCount(State.PlayerParty, "good.tools") < ProjectTools(id)) { return "Bring " + ProjectTimber(id) + " hardwood and " + ProjectTools(id) + " tools in your cargo."; } return ""; } public CommandResult StartSettlementProject(string id) { string text = ProjectStartReason(id); if (text.Length > 0) { return CommandResult.Fail(text); } Settlement settlement = C.CurrentSettlement(); SyncSettlementManagementOwner(settlement); SettlementManagementState management = settlement.Management; State.Transact(State.PlayerClan, -ProjectCost(id), LedgerAccount.Upgrade, "Construction: " + ProjectName(id) + " at " + settlement.Name); ConsumeProjectCargo("good.timber", ProjectTimber(id)); ConsumeProjectCargo("good.tools", ProjectTools(id)); management.ProjectId = id; management.ProjectRemainingDays = ProjectDays(id); management.ProjectOwnerClanId = settlement.OwnerClanId; management.LastDay = State.Clock.Day; State.AddLog(LogCategory.Economy, "Construction started: " + ProjectName(id) + " at " + settlement.Name + ". Materials and " + ProjectCost(id) + " denars paid.", settlement.Id); State.Touch(); return CommandResult.Success(ProjectName(id) + " started; ready in " + ProjectDays(id) + " days."); } internal void ConsumeProjectCargo(string goodId, int count) { int num = C.CargoCount(State.PlayerParty, goodId) - count; if (num == 0) { State.PlayerParty.Cargo.Remove(goodId); } else { State.PlayerParty.Cargo[goodId] = num; } } public string CancelSettlementProjectReason() { string text = SettlementManagementReason(); if (text.Length > 0) { return text; } Settlement settlement = C.CurrentSettlement(); SettlementManagementState management = settlement.Management; if (string.IsNullOrEmpty(management.ProjectId)) { return "There is no active project."; } if (management.ProjectOwnerClanId != State.PlayerClanId || management.OwnerClanId != settlement.OwnerClanId) { return "The last owner started this one."; } return ""; } public CommandResult CancelSettlementProject() { string text = CancelSettlementProjectReason(); if (text.Length > 0) { return CommandResult.Fail(text); } Settlement settlement = C.CurrentSettlement(); string text2 = ProjectName(settlement.Management.ProjectId); ClearSettlementProject(settlement.Management); State.AddLog(LogCategory.Economy, "Cancelled " + text2 + " at " + settlement.Name + "; the materials and money spent were lost.", settlement.Id); State.Touch(); return CommandResult.Success("Project cancelled. What you paid is gone."); } internal static void ClearSettlementProject(SettlementManagementState management) { management.ProjectId = ""; management.ProjectRemainingDays = 0; management.ProjectOwnerClanId = ""; } internal bool SyncSettlementManagementOwner(Settlement settlement) { SettlementManagementState management = settlement.Management; if (management.OwnerClanId == settlement.OwnerClanId) { return false; } if (!string.IsNullOrEmpty(management.ProjectId)) { State.AddLog(LogCategory.Economy, "Construction abandoned after " + settlement.Name + " changed hands; the materials and money spent were lost.", settlement.Id); ClearSettlementProject(management); } if (management.ProjectQueue != null && management.ProjectQueue.Count > 0) { State.AddLog(LogCategory.Economy, "The build queue at " + settlement.Name + " was dropped when it changed hands.", settlement.Id); management.ProjectQueue.Clear(); } management.QueueWaitingDay = -1L; management.GarrisonWageLimit = 0L; management.GarrisonAutoRecruit = false; management.GovernorBudget = 0L; management.Policy = TaxPolicy.Balanced; management.GarrisonOrders = new GarrisonOrdersState(); management.OwnerClanId = settlement.OwnerClanId; return true; } internal void ProgressProject(Settlement settlement) { SettlementManagementState management = settlement.Management; if (string.IsNullOrEmpty(management.ProjectId)) { return; } if (management.ProjectOwnerClanId != settlement.OwnerClanId) { State.AddLog(LogCategory.Economy, "An unfunded legacy project at " + settlement.Name + " was abandoned; construction costs were lost.", settlement.Id); ClearSettlementProject(management); return; } double num = Math.Max(0.0, Math.Min(1.0, C.SettlementPerk(settlement, PerkEffect.BuildSpeed))); int num2 = 1 + ((num > 0.0 && State.Random.Get("perks").Chance(num)) ? 1 : 0); management.ProjectRemainingDays = Math.Max(0, management.ProjectRemainingDays - num2); if (management.ProjectRemainingDays <= 0) { string projectId = management.ProjectId; switch (projectId) { case "project.granary": management.GranaryLevel = Math.Min(3, management.GranaryLevel + 1); break; case "project.watchtower": management.WatchtowerLevel = Math.Min(3, management.WatchtowerLevel + 1); break; case "project.walls": settlement.WallLevel = Math.Min(3, C.WallLevel(settlement) + 1); break; } ClearSettlementProject(management); State.AddLog(LogCategory.Economy, ProjectName(projectId) + " completed at " + settlement.Name + ".", settlement.Id); } } public void DailyGovernance() { bool flag = false; foreach (Settlement settlement in State.Settlements) { if (settlement.Type != SettlementType.Hideout && settlement.Management != null && settlement.Management.Initialized) { SettlementManagementState management = settlement.Management; flag |= SyncSettlementManagementOwner(settlement); if (management.LastDay < State.Clock.Day) { management.LastDay = State.Clock.Day; flag = true; double num = SettlementSecurityChange(settlement); double num2 = SettlementLoyaltyChange(settlement); settlement.Security += num; settlement.Loyalty += num2; ProgressProject(settlement); C.DailySettlementBudgets(settlement); } } } if (flag) { State.Touch(); } } } internal sealed class GovernorsSystem { private readonly Campaign C; private CampaignState State => C.State; internal GovernorsSystem(Campaign host) { C = host; } public Settlement GovernorAssignedSettlement(string heroId) { if (!string.IsNullOrEmpty(heroId)) { return State.Settlements.FirstOrDefault((Settlement s) => s.Management?.GovernorHeroId == heroId); } return null; } public Hero SettlementGovernor(Settlement settlement) { return State.Heroes.Get(settlement?.Management?.GovernorHeroId ?? ""); } public IEnumerable GovernorCandidates() { return State.Heroes.Where((Hero h) => C.IsOwnedCompanion(h) && h.CanFight && Campaign.IsPresentPartyHero(State.PlayerParty, h) && GovernorAssignedSettlement(h.Id) == null && !State.Parties.Any((Party p) => p.LeaderHeroId == h.Id && p.State != PartyState.Destroyed && p.State != PartyState.Disbanded)).OrderBy((Hero h) => h.Name, StringComparer.Ordinal).ThenBy((Hero h) => h.Id, StringComparer.Ordinal) .ToList(); } internal bool IsStationedGovernor(Settlement settlement, Hero hero) { if (!C.IsGovernedSettlement(settlement) || hero == null || hero.Occupation != HeroOccupation.Companion || hero.State != HeroState.Active || hero.ClanId != settlement.OwnerClanId || string.IsNullOrEmpty(hero.ClanId) || hero.SettlementId != settlement.Id || !string.IsNullOrEmpty(hero.PartyId) || !string.IsNullOrEmpty(hero.CaptorPartyId) || !string.IsNullOrEmpty(hero.CaptorSettlementId)) { return false; } if (State.Settlements.Count((Settlement s) => s.Management?.GovernorHeroId == hero.Id) != 1) { return false; } if (!State.Parties.Any((Party p) => p.Troops.Heroes.Contains(hero.Id) || p.Prisoners.Heroes.Contains(hero.Id) || (p.LeaderHeroId == hero.Id && p.State != PartyState.Destroyed && p.State != PartyState.Disbanded))) { return !State.Settlements.Any((Settlement s) => s.Garrison.Heroes.Contains(hero.Id) || s.Prisoners.Heroes.Contains(hero.Id)); } return false; } public bool GovernorActive(Settlement settlement) { Hero hero = SettlementGovernor(settlement); if (IsStationedGovernor(settlement, hero) && hero.CanFight) { return settlement.Management.GovernorPaidDay == State.Clock.Day; } return false; } public double GovernorTaxFactor(Settlement settlement) { if (!GovernorActive(settlement)) { return 1.0; } return 1.1; } public double GovernorLoyaltyBonus(Settlement settlement) { if (!GovernorActive(settlement)) { return 0.0; } return 0.5; } public double GovernorDailyWages(Settlement settlement) { Hero hero = SettlementGovernor(settlement); return IsStationedGovernor(settlement, hero) ? Math.Max(0, hero.DailyWage) : 0; } public string GovernorAssignmentReason(string heroId) { string text = C.SettlementManagementReason(); if (text.Length > 0) { return text; } if (!string.IsNullOrEmpty(C.CurrentSettlement().Management.GovernorHeroId)) { return "Recall the current governor first."; } Hero hero = State.Heroes.Get(heroId); if (!C.IsOwnedCompanion(hero) || !hero.CanFight || !Campaign.IsPresentPartyHero(State.PlayerParty, hero)) { return "Pick a healthy companion who's with you."; } if (GovernorAssignedSettlement(hero.Id) != null) { return "Already governing somewhere."; } if (State.Parties.Any((Party p) => p.LeaderHeroId == hero.Id && p.State != PartyState.Destroyed && p.State != PartyState.Disbanded)) { return "A party leader has to give up command first."; } return ""; } public CommandResult AssignGovernor(string heroId) { string text = GovernorAssignmentReason(heroId); if (text.Length > 0) { return CommandResult.Fail(text); } Settlement settlement = C.CurrentSettlement(); Hero hero = State.Heroes.Require(heroId); C.SyncSettlementManagementOwner(settlement); C.ClearHeroRoleAssignments(hero.Id); State.PlayerParty.Troops.Heroes.Remove(hero.Id); hero.PartyId = ""; hero.SettlementId = settlement.Id; settlement.Management.GovernorHeroId = hero.Id; settlement.Management.LastGovernorDay = State.Clock.Day; settlement.Management.GovernorPaidDay = -1L; State.AddLog(LogCategory.Economy, hero.Name + " now governs " + settlement.Name + ". Pay and duties start next dawn (" + Math.Max(0, hero.DailyWage) + " denars/day).", hero.Id, settlement.Id); State.Touch(); return CommandResult.Success(hero.Name + " stays on as governor. Duties start next dawn."); } public string GovernorRecallReason() { string text = C.CargoCommandReason(); if (text.Length > 0) { return text; } Settlement settlement = C.CurrentSettlement(); if (!C.IsGovernedSettlement(settlement) || Vec2.Distance(State.PlayerParty.Position, settlement.Position) > 0.01 || !C.CanEnter(State.PlayerParty, settlement)) { return "Meet the governor where they govern."; } Hero hero = SettlementGovernor(settlement); if (!C.IsOwnedCompanion(hero) || !IsStationedGovernor(settlement, hero)) { return "Your governor isn't here."; } return ""; } public CommandResult RecallGovernor() { string text = GovernorRecallReason(); if (text.Length > 0) { return CommandResult.Fail(text); } Settlement settlement = C.CurrentSettlement(); Hero hero = SettlementGovernor(settlement); settlement.Management.GovernorHeroId = ""; settlement.Management.GovernorPaidDay = -1L; C.JoinCompanionToPlayerParty(hero); State.AddLog(LogCategory.Economy, hero.Name + " left the governorship of " + settlement.Name + " and rejoined your party.", hero.Id, settlement.Id); State.Touch(); return CommandResult.Success(hero.Name + " rejoins your party. Nobody governs there now."); } public void ClearHeroGovernorAssignments(string heroId) { if (string.IsNullOrEmpty(heroId)) { return; } bool flag = false; foreach (Settlement item in State.Settlements.Where((Settlement s) => s.Management?.GovernorHeroId == heroId)) { item.Management.GovernorHeroId = ""; item.Management.GovernorPaidDay = -1L; flag = true; } if (flag) { State.Touch(); } } public void ReleaseSettlementGovernor(Settlement settlement, string reason) { if (settlement?.Management != null && !string.IsNullOrEmpty(settlement.Management.GovernorHeroId)) { Hero hero = SettlementGovernor(settlement); settlement.Management.GovernorHeroId = ""; settlement.Management.GovernorPaidDay = -1L; if (hero != null && hero.State == HeroState.Active && hero.SettlementId == settlement.Id && string.IsNullOrEmpty(hero.PartyId) && string.IsNullOrEmpty(hero.CaptorPartyId) && string.IsNullOrEmpty(hero.CaptorSettlementId) && !State.Parties.Any((Party p) => p.Troops.Heroes.Contains(hero.Id) || p.Prisoners.Heroes.Contains(hero.Id)) && !State.Settlements.Any((Settlement s) => s.Garrison.Heroes.Contains(hero.Id) || s.Prisoners.Heroes.Contains(hero.Id)) && hero.ClanId != settlement.OwnerClanId) { C.ShelterCompanion(hero, settlement.Position, reason); } else { State.AddLog(LogCategory.Economy, (hero?.Name ?? "The governor") + " no longer governs " + settlement.Name + " (" + reason + ").", hero?.Id ?? "", settlement.Id); } State.Touch(); } } public void CleanupGovernors() { foreach (Settlement settlement in State.Settlements) { if (!string.IsNullOrEmpty(settlement.Management?.GovernorHeroId)) { Hero hero = SettlementGovernor(settlement); if (!IsStationedGovernor(settlement, hero)) { ReleaseSettlementGovernor(settlement, (hero != null && hero.ClanId != settlement.OwnerClanId) ? "the settlement changed hands" : "the governor became unavailable"); } } } } public void DailyGovernors() { CleanupGovernors(); bool flag = false; foreach (Settlement settlement in State.Settlements) { Hero hero = SettlementGovernor(settlement); if (!IsStationedGovernor(settlement, hero)) { continue; } SettlementManagementState management = settlement.Management; if (management.LastGovernorDay >= State.Clock.Day) { continue; } management.LastGovernorDay = State.Clock.Day; management.GovernorPaidDay = -1L; flag = true; Clan clan = State.Clans.Get(hero.ClanId); long num = Math.Max(0, hero.DailyWage); if (clan == null || clan.Gold < num) { State.AddLog(LogCategory.Warning, "The salary for " + hero.Name + " at " + settlement.Name + " couldn't be paid; no governor bonuses today.", hero.Id, settlement.Id); } else { if (num > 0) { State.Transact(clan, -num, LedgerAccount.Wages, "Governor salary: " + hero.Name + " at " + settlement.Name); } management.GovernorPaidDay = State.Clock.Day; } } if (flag) { State.Touch(); } } } internal sealed class HeroBondsSystem { private readonly Campaign C; private ContentDatabase Content => C.Content; private static Dictionary DeedRemarks => Campaign.DeedRemarks; private CampaignState State => C.State; internal HeroBondsState Bonds => State.HeroBonds ?? (State.HeroBonds = new HeroBondsState()); internal HeroBondsSystem(Campaign host) { C = host; } public void RememberHero(Hero h, string kind, string detail = "") { if (h != null && !h.IsPlayer && h.State != HeroState.Dead && !string.IsNullOrEmpty(h.ClanId) && !(h.ClanId == State.PlayerClanId)) { if (!Bonds.Memories.TryGetValue(h.Id, out var value) || value == null) { value = (Bonds.Memories[h.Id] = new List()); } value.Add(new HeroMemoryState { Kind = kind, Day = State.Clock.Day, Detail = (detail ?? "") }); while (value.Count > 6) { value.RemoveAt(0); } State.Touch(); } } public IReadOnlyList MemoriesOf(string heroId) { if (heroId == null || State.HeroBonds?.Memories == null || !State.HeroBonds.Memories.TryGetValue(heroId, out var value) || value == null) { return new List(); } return value; } internal void RememberBattle(Encounter enc, List<(string partyId, BattleSide side, string heroId)> leaders, bool playerWon, bool decided) { if (enc == null || !enc.PlayerInvolved || !decided) { return; } HashSet hashSet = new HashSet(StringComparer.Ordinal); string detail = (from l in leaders where l.side != enc.PlayerSide select State.Parties.Get(l.partyId)?.Name ?? "" into n where n.Length > 0 select n).ToList().FirstOrDefault() ?? "the enemy"; foreach (var leader in leaders) { BattleSide item = leader.side; string item2 = leader.heroId; Hero hero = State.Heroes.Get(item2 ?? ""); if (hero == null || hero.IsPlayer || hero.ClanId == State.PlayerClanId) { continue; } if (item == enc.PlayerSide) { if (playerWon) { RememberHero(hero, "fought_beside", detail); if (hashSet.Add(hero.ClanId)) { C.AdjustClanRelation(State.PlayerClanId, hero.ClanId, 2); } } } else { RememberHero(hero, playerWon ? "defeated" : "beat_you", SettlementNear(enc)); } } } internal string SettlementNear(Encounter enc) { Party party = State.PlayerParty; if (party == null) { return ""; } return (from s in State.Settlements where s.Type != SettlementType.Hideout orderby Vec2.Distance(s.Position, party.Position) select s).FirstOrDefault()?.Name ?? ""; } internal string MemoryRemark(Hero h, Random r) { List list = (from x in MemoriesOf(h.Id) where State.Clock.Day - x.Day <= 365 select x).ToList(); if (list.Count == 0) { return ""; } HeroMemoryState? obj = list.LastOrDefault((HeroMemoryState x) => x.Kind == "executed_kin") ?? list.LastOrDefault((HeroMemoryState x) => x.Kind == "captured" || x.Kind == "released") ?? list[list.Count - 1]; Campaign.Personality personality = Campaign.PersonalityOf(h); string text = obj.Detail ?? ""; switch (obj.Kind) { case "executed_kin": return Campaign.Pick(r, "You put " + text + " to death. I have not forgotten, and I never will.", "My kin " + text + " died by your order. Do not think I forgive it."); case "captured": if (personality.Honor <= 0) { return Campaign.Pick(r, "You took me prisoner. I have not forgotten the chains.", "The last time we met, I was in your irons."); } return Campaign.Pick(r, "You held me prisoner once. You kept me fairly; I grant you that.", "I was your captive once. An honest captor, at least."); case "released": return Campaign.Pick(r, "You let me go when you could have asked a ransom. I remember that.", "I owe you my freedom. That is not a small thing."); case "ransomed": return Campaign.Pick(r, "My family paid you well for my freedom. I hope it was worth it.", "I cost my house a fortune in ransom, thanks to you."); case "defeated": if (personality.Valor <= 0) { return Campaign.Pick(r, "Fortune favoured you" + At(text) + ".", "You had the better of me" + At(text) + ". Do not expect it again."); } return Campaign.Pick(r, "You beat me fairly" + At(text) + ". Next time will be different.", "That was a fine fight" + At(text) + ". I lost, but it was a fine fight."); case "beat_you": return Campaign.Pick(r, "Last time we met" + At(text) + ", you were running. Have you recovered?", "You fought well" + At(text) + ", for the losing side."); case "fought_beside": return Campaign.Pick(r, "We stood together against " + ((text.Length > 0) ? text : "our enemies") + ". That counts for something.", "I have not forgotten how you fought beside me against " + ((text.Length > 0) ? text : "them") + "."); case "gift": return Campaign.Pick(r, "Your gift was most welcome.", "I still have your gift. A generous thought."); case "spar_won": return Campaign.Pick(r, "You owe me a rematch, and I mean to collect.", "My arm still remembers our bout."); case "spar_lost": return Campaign.Pick(r, "Ready to lose to me again?", "Have you been practising since our bout?"); case "lesson": return Campaign.Pick(r, "Have you been practising what I showed you?", "How goes the training?"); case "favour": return Campaign.Pick(r, "I hope my help served you well.", "Remember who helped you, when the time comes."); default: return ""; } } internal static string At(string place) { if (!string.IsNullOrEmpty(place)) { return " near " + place; } return ""; } internal string RenownRemark(Random r) { int num = Campaign.ClanTier(State.PlayerClan); if (num >= 5) { return Campaign.Pick(r, "Your name is spoken in every hall in the land.", "Even the kings watch what you do now."); } if (num >= 3) { return Campaign.Pick(r, "Your house's name is rising, I hear.", "They speak of your company in the taverns."); } if (num <= 0) { return Campaign.Pick(r, "I confess I had not heard of you before.", "Your name is new to me."); } return ""; } internal List OpinionLines(Hero h, Random r) { List list = new List(); int num = C.HeroRelation(h); list.Add((num <= -30) ? "Honestly? I do not trust you." : ((num < -10) ? "I have my doubts about you." : ((num <= 10) ? "I hardly know you yet." : ((num <= 40) ? "I think well of you." : "You are a true friend to my house.")))); foreach (HeroMemoryState item in MemoriesOf(h.Id).Reverse().Take(3)) { string text = item.Detail ?? ""; switch (item.Kind) { case "executed_kin": list.Add("You executed " + text + "."); break; case "captured": list.Add("You took me prisoner."); break; case "released": list.Add("You set me free without a ransom."); break; case "ransomed": list.Add("You ransomed me back to my family."); break; case "defeated": list.Add("You defeated me in battle" + At(text) + "."); break; case "beat_you": list.Add("I defeated you in battle" + At(text) + "."); break; case "fought_beside": list.Add("We fought side by side against " + ((text.Length > 0) ? text : "a common enemy") + "."); break; case "gift": list.Add("You gave me a gift."); break; case "spar_won": list.Add("You beat me in a friendly bout."); break; case "spar_lost": list.Add("I beat you in a friendly bout."); break; case "lesson": list.Add("I taught you a thing or two."); break; case "favour": list.Add("I did you a favour."); break; } } string text2 = RenownRemark(r); if (text2.Length > 0) { list.Add(text2); } return list; } internal static long DaySince(SortedDictionary days, string id, long today) { if (days == null || !days.TryGetValue(id, out var value)) { return long.MaxValue; } return today - value; } internal string LordInteractionReason(Hero h) { if (h == null || h.State == HeroState.Dead) { return "There is nobody to talk to."; } if (h.Occupation != HeroOccupation.Lord || string.IsNullOrEmpty(h.ClanId) || h.ClanId == State.PlayerClanId) { return "Only with lords and ladies of other clans."; } if (C.HeroIsEnemy(h)) { return Campaign.First(h) + " will not deal with an enemy."; } if (C.TalkReason(h.Id).Length > 0) { return C.TalkReason(h.Id); } return ""; } public long GiftCost(Hero h) { return 100 + 75L * (long)Campaign.ClanTier(State.Clans.Get(h?.ClanId ?? "")); } public string GiftReason(string heroId) { Hero hero = State.Heroes.Get(heroId ?? ""); string text = LordInteractionReason(hero); if (text.Length > 0) { return text; } long num = DaySince(Bonds.GiftDay, hero.Id, State.Clock.Day); if (num < 14) { return "You gave " + Campaign.First(hero) + " a gift recently. Wait " + (14 - num) + " more day" + ((14 - num == 1) ? "" : "s") + "."; } if (State.PlayerClan.Gold < GiftCost(hero)) { return "You cannot afford a fitting gift (" + GiftCost(hero).ToString("N0", CultureInfo.InvariantCulture) + " denars)."; } return ""; } public CommandResult GiveGift(string heroId) { string text = GiftReason(heroId); if (text.Length > 0) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Get(heroId); Clan clan = State.Clans.Get(hero.ClanId); long num = GiftCost(hero); Campaign.Personality personality = Campaign.PersonalityOf(hero); int delta = 3 + ((personality.Generosity < 0) ? 2 : 0) + ((personality.Calculating > 0) ? 1 : 0) - ((personality.Honor > 0 && personality.Generosity > 0) ? 1 : 0); State.Transact(State.PlayerClan, -num, LedgerAccount.Other, "A gift to " + hero.Name); State.Transact(clan, num, LedgerAccount.Other, "A gift from " + State.PlayerHero.Name); C.AdjustClanRelation(State.PlayerClanId, clan.Id, delta); Bonds.GiftDay[hero.Id] = State.Clock.Day; RememberHero(hero, "gift"); C.TrainDiplomacy(10.0); State.Touch(); return CommandResult.Success("You gave " + hero.Name + " a gift of " + num.ToString("N0", CultureInfo.InvariantCulture) + " denars. Relation with " + clan.Name + " +" + delta + "."); } public string FavourReason(string heroId) { Hero hero = State.Heroes.Get(heroId ?? ""); string text = LordInteractionReason(hero); if (text.Length > 0) { return text; } if (C.HeroRelation(hero) < 15) { return Campaign.First(hero) + " does not know you well enough to do you favours (relation " + 15 + " needed)."; } long num = DaySince(Bonds.FavourDay, hero.Id, State.Clock.Day); if (num < 20) { return Campaign.First(hero) + " helped you only " + num + " day" + ((num == 1) ? "" : "s") + " ago."; } return ""; } internal void SpendFavour(Hero h, int relationCost) { Bonds.FavourDay[h.Id] = State.Clock.Day; if (relationCost > 0) { C.AdjustClanRelation(State.PlayerClanId, h.ClanId, -relationCost); } RememberHero(h, "favour"); State.Touch(); } public int FavourTroopCount(Hero h) { return 3 + ((Campaign.PersonalityOf(h).Generosity > 0) ? 2 : 0); } public string FavourTroopsReason(string heroId) { string text = FavourReason(heroId); if (text.Length > 0) { return text; } Hero hero = State.Heroes.Get(heroId); Party playerParty = State.PlayerParty; string id = Content.Cultures.Get(hero.CultureId ?? "")?.BasicTroop ?? ""; if (C.UnitDef(id) == null) { return "They have no soldiers to spare."; } if (playerParty.Troops.TotalTroops + FavourTroopCount(hero) > C.PartySizeLimit(playerParty)) { return "No room for more soldiers."; } return ""; } public CommandResult AskFavourTroops(string heroId) { string text = FavourTroopsReason(heroId); if (text.Length > 0) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Get(heroId); string basicTroop = Content.Cultures.Get(hero.CultureId).BasicTroop; int healthy = FavourTroopCount(hero); State.PlayerParty.Troops.Add(basicTroop, healthy); SpendFavour(hero, 3); return CommandResult.Success(healthy + " " + (C.UnitDef(basicTroop)?.Name ?? basicTroop) + " join you, lent by " + hero.Name + "."); } public long FavourPurse(Hero h) { Clan clan = State.Clans.Get(h.ClanId); if (clan != null) { return Math.Min(Math.Max(0L, clan.Gold) / 10, 250 + 100L * (long)Campaign.ClanTier(clan)); } return 0L; } public string FavourPurseReason(string heroId) { string text = FavourReason(heroId); if (text.Length > 0) { return text; } Hero h = State.Heroes.Get(heroId); if (FavourPurse(h) < 100) { return Campaign.First(h) + "'s house has no coin to spare."; } return ""; } public CommandResult AskFavourPurse(string heroId) { string text = FavourPurseReason(heroId); if (text.Length > 0) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Get(heroId); Clan clan = State.Clans.Get(hero.ClanId); long num = FavourPurse(hero); State.Transact(clan, -num, LedgerAccount.Other, "A purse for " + State.PlayerHero.Name); State.Transact(State.PlayerClan, num, LedgerAccount.Other, "A purse from " + hero.Name); SpendFavour(hero, (Campaign.PersonalityOf(hero).Generosity > 0) ? 3 : 6); return CommandResult.Success(hero.Name + " gives you a purse of " + num.ToString("N0", CultureInfo.InvariantCulture) + " denars."); } public string FavourWordReason(string heroId) { string text = FavourReason(heroId); if (text.Length > 0) { return text; } Hero hero = State.Heroes.Get(heroId); string text2 = State.Clans.Get(hero.ClanId)?.KingdomId ?? ""; if (text2.Length == 0 || text2 != (State.PlayerClan.KingdomId ?? "")) { return "Only a lord of your own realm can speak for you at court."; } return ""; } public CommandResult AskFavourWord(string heroId) { string text = FavourWordReason(heroId); if (text.Length > 0) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Get(heroId); int num = ((State.Clans.Get(hero.ClanId)?.LeaderHeroId == hero.Id) ? 12 : 8); State.PlayerClan.Influence += num; SpendFavour(hero, 2); return CommandResult.Success(hero.Name + " speaks well of you at court. Influence +" + num + "."); } public string SparReason(string heroId) { Hero hero = State.Heroes.Get(heroId ?? ""); string text = LordInteractionReason(hero); if (text.Length > 0) { return text; } Hero playerHero = State.PlayerHero; if (!hero.CanFight) { return Campaign.First(hero) + " is in no state to fight."; } if (playerHero == null || !playerHero.CanFight) { return "You are in no state to fight."; } if (Campaign.PersonalityOf(hero).Valor < 0) { return Campaign.First(hero) + " sees no sense in trading blows for sport."; } if (DaySince(Bonds.SparDay, hero.Id, State.Clock.Day) < 1) { return "You have already sparred with " + Campaign.First(hero) + " today."; } return ""; } public CommandResult Spar(string heroId) { string text = SparReason(heroId); if (text.Length > 0) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Get(heroId); Hero playerHero = State.PlayerHero; double num = Math.Max(0.1, C.HeroPower(playerHero)); double num2 = Math.Max(0.1, C.HeroPower(hero)); bool flag = State.Random.Get("herobonds").NextDouble() < num / (num + num2); int num3 = ((Campaign.PersonalityOf(hero).Valor > 0) ? 2 : ((!flag) ? 1 : 0)); if (num3 > 0) { C.AdjustClanRelation(State.PlayerClanId, hero.ClanId, num3); } C.GrantHeroExperience(playerHero, flag ? 40 : 25); Bonds.SparDay[hero.Id] = State.Clock.Day; RememberHero(hero, flag ? "spar_won" : "spar_lost"); State.Touch(); return CommandResult.Success((flag ? "You won the bout with " : "You lost the bout with ") + hero.Name + ". +" + (flag ? 40 : 25) + " experience" + ((num3 > 0) ? (", relation +" + num3) : "") + "."); } public string LessonSkill(Hero h) { Hero me = State.PlayerHero; if (h?.Skills == null || me == null) { return ""; } return (from s in (from s in h.Skills where SkillIds.All.Contains(s.Key) && s.Value >= me.Skill(s.Key) + 25 && me.Skill(s.Key) < 300 orderby s.Value - me.Skill(s.Key) descending select s).ThenBy, string>((KeyValuePair s) => s.Key, StringComparer.Ordinal) select s.Key).FirstOrDefault() ?? ""; } public string LessonReason(string heroId) { Hero hero = State.Heroes.Get(heroId ?? ""); string text = LordInteractionReason(hero); if (text.Length > 0) { return text; } if (C.HeroRelation(hero) < 10) { return Campaign.First(hero) + " will teach only a friend (relation " + 10 + " needed)."; } long num = DaySince(Bonds.LessonDay, hero.Id, State.Clock.Day); if (num < 10) { return "Practise what " + Campaign.First(hero) + " showed you first (" + (10 - num) + " more day" + ((10 - num == 1) ? "" : "s") + ")."; } if (LessonSkill(hero).Length == 0) { return Campaign.First(hero) + " has nothing to teach you that you do not already know."; } return ""; } public CommandResult TakeLesson(string heroId) { string text = LessonReason(heroId); if (text.Length > 0) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Get(heroId); string text2 = LessonSkill(hero); C.GrantSkillExperience(State.PlayerHero, text2, 60.0); Bonds.LessonDay[hero.Id] = State.Clock.Day; RememberHero(hero, "lesson", text2); State.Touch(); return CommandResult.Success(hero.Name + " teaches you " + Campaign.SkillWord(text2) + ". +" + 60 + " " + Campaign.SkillWord(text2) + " practice."); } internal IEnumerable PresentCompanions() { return from id in State.PlayerParty?.Troops.Heroes ?? new List() select State.Heroes.Get(id) into h where h != null && C.IsOwnedCompanion(h) && !h.IsFamily && h.State == HeroState.Active && Campaign.IsPresentPartyHero(State.PlayerParty, h) select h; } public int Approval(Hero h) { if (h == null || State.HeroBonds?.Approval == null || !State.HeroBonds.Approval.TryGetValue(h.Id, out var value)) { return 0; } return value; } internal void SetApproval(Hero h, int value) { Bonds.Approval[h.Id] = Math.Max(-100, Math.Min(100, value)); } internal void CompanionsReact(string deed, Func delta, string context = "") { List list = PresentCompanions().ToList(); if (list.Count == 0) { return; } Hero hero = null; int num = 0; foreach (Hero item in list) { int num2 = delta(Campaign.PersonalityOf(item)); if (num2 != 0) { SetApproval(item, Approval(item) + num2); if (Math.Abs(num2) > Math.Abs(num) || (Math.Abs(num2) == Math.Abs(num) && hero != null && string.CompareOrdinal(item.Id, hero.Id) < 0)) { num = num2; hero = item; } } } State.Touch(); if (hero != null && DeedRemarks.TryGetValue(deed, out var value)) { string[] array = value[(num <= 0) ? 1u : 0u]; string text = array[State.Random.Get("herobonds").Range(0, array.Length)]; string text2 = hero.Name + ((num > 0) ? " nods" : " frowns") + ": \"" + text + "\""; Bonds.LastRemark[hero.Id] = text; State.AddLog(LogCategory.Info, text2 + ((context.Length > 0) ? (" (" + context + ")") : ""), hero.Id); C.Raise(CampaignEventKind.Info, text2, false, hero.Id); } } internal void CompanionsReactToBattle(bool won) { CompanionsReact(won ? "victory" : "defeat", (Campaign.Personality p) => (!won) ? ((p.Valor <= 0) ? ((p.Valor < 0) ? 1 : 0) : (-2)) : (1 + ((p.Valor > 0) ? 1 : 0))); } internal void CompanionsReactToRaid(Settlement village) { CompanionsReact("raid", (Campaign.Personality p) => ((p.Mercy > 0) ? (-5) : ((p.Mercy < 0) ? 2 : (-1))) + ((p.Honor > 0) ? (-2) : 0), village?.Name ?? ""); } internal void CompanionsReactToExecution(Hero victim) { CompanionsReact("execute", (Campaign.Personality p) => ((p.Mercy > 0) ? (-8) : ((p.Mercy < 0) ? 3 : (-2))) + ((p.Honor > 0) ? (-3) : 0), victim?.Name ?? ""); } internal void CompanionsReactToRelease(Hero freed) { CompanionsReact("release", (Campaign.Personality p) => ((p.Mercy > 0) ? 2 : 0) + ((p.Honor > 0) ? 1 : 0) - ((p.Calculating > 0) ? 2 : 0) - ((p.Generosity < 0) ? 1 : 0), freed?.Name ?? ""); } internal void CompanionsReactToHardship() { if (Bonds.HardshipDay != State.Clock.Day) { Bonds.HardshipDay = State.Clock.Day; CompanionsReact("hardship", (Campaign.Personality p) => (p.Generosity <= 0) ? (-3) : (-1)); } } public long CompanionGiftReasonDays(Hero h) { return Math.Max(0L, 14 - DaySince(Bonds.GiftDay, h?.Id ?? "", State.Clock.Day)); } public string CompanionGiftReason(string heroId) { Hero hero = State.Heroes.Get(heroId ?? ""); if (hero == null || !C.IsOwnedCompanion(hero)) { return "Only for your companions."; } if (C.TalkReason(hero.Id).Length > 0) { return C.TalkReason(hero.Id); } long num = CompanionGiftReasonDays(hero); if (num > 0) { return "You gave " + Campaign.First(hero) + " something recently. Wait " + num + " more day" + ((num == 1) ? "" : "s") + "."; } if (State.PlayerClan.Gold < 100) { return "You cannot spare " + 100 + " denars."; } return ""; } public CommandResult GiveCompanionGift(string heroId) { string text = CompanionGiftReason(heroId); if (text.Length > 0) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Get(heroId); int num = 5 + ((Campaign.PersonalityOf(hero).Generosity < 0) ? 3 : 0); State.Transact(State.PlayerClan, -100L, LedgerAccount.Wages, "A gift to " + hero.Name); SetApproval(hero, Approval(hero) + num); Bonds.GiftDay[hero.Id] = State.Clock.Day; State.Touch(); return CommandResult.Success(hero.Name + " pockets the coin with a grin. Approval +" + num + "."); } public CompanionRequestState CompanionRequest(Hero h) { if (h == null || State.HeroBonds?.Requests == null || !State.HeroBonds.Requests.TryGetValue(h.Id, out var value)) { return null; } return value; } public string DescribeRequest(CompanionRequestState q) { if (q == null) { return ""; } return q.Kind switch { "visit" => "I'd like to see " + (State.Settlements.Get(q.TargetId)?.Name ?? "home") + " again. Take the company there while I'm with you.", "weapon" => "This old blade of mine won't last. Get me a proper weapon and I'll do the rest.", "tournament" => "I want to test myself in a tournament. Enter one with me in the company.", _ => "", }; } internal CompanionRequestState NewRequest(Hero h) { RandomStream randomStream = State.Random.Get("herobonds"); List list = new List(); Settlement here = C.CurrentSettlement(); List list2 = State.Settlements.Where((Settlement s) => s.Type == SettlementType.Town && s.CultureId == h.CultureId && s.Id != here?.Id && C.CanEnter(State.PlayerParty, s)).ToList(); if (list2.Count > 0) { list.Add(new CompanionRequestState { Kind = "visit", TargetId = list2[randomStream.Range(0, list2.Count)].Id }); } if (string.IsNullOrEmpty(h.Loadout?.WeaponId) && EquipmentCatalog.SupportsArchetype(C.UnitDef(h.UnitId))) { list.Add(new CompanionRequestState { Kind = "weapon" }); } if (C.ActiveTournaments.Any() && Campaign.PersonalityOf(h).Valor >= 0) { list.Add(new CompanionRequestState { Kind = "tournament" }); } if (list.Count == 0) { return null; } CompanionRequestState companionRequestState = list[randomStream.Range(0, list.Count)]; companionRequestState.AskedDay = State.Clock.Day; return companionRequestState; } public string AskCompanionWants(Hero h) { CompanionRequestState companionRequestState = CompanionRequest(h); if (companionRequestState != null) { return "I haven't forgotten what I asked. " + DescribeRequest(companionRequestState); } companionRequestState = NewRequest(h); if (companionRequestState == null) { return "I have all I need, captain. For now."; } Bonds.Requests[h.Id] = companionRequestState; State.Touch(); return DescribeRequest(companionRequestState); } internal void FulfilRequest(Hero h, string how) { Bonds.Requests.Remove(h.Id); SetApproval(h, Approval(h) + 15); C.GrantHeroExperience(h, 100); string text = h.Name + " is pleased: " + how + " Approval +15."; State.AddLog(LogCategory.Info, text, h.Id); C.Raise(CampaignEventKind.Info, text, false, h.Id); State.Touch(); } internal void NoteCompanionTournament(IEnumerable heroIds) { foreach (string item in heroIds ?? Enumerable.Empty()) { Hero h = State.Heroes.Get(item ?? ""); if (CompanionRequest(h)?.Kind == "tournament") { FulfilRequest(h, "they fought in the tournament."); } } } internal void DailyHeroBonds() { List list = PresentCompanions().ToList(); Settlement settlement = C.CurrentSettlement(); foreach (Hero item in list) { CompanionRequestState companionRequestState = CompanionRequest(item); if (companionRequestState != null) { if (companionRequestState.Kind == "visit" && settlement != null && settlement.Id == companionRequestState.TargetId) { FulfilRequest(item, "you brought them to " + settlement.Name + "."); } else if (companionRequestState.Kind == "weapon" && !string.IsNullOrEmpty(item.Loadout?.WeaponId)) { FulfilRequest(item, "they have a weapon of their own."); } else if (State.Clock.Day - companionRequestState.AskedDay > 60) { Bonds.Requests.Remove(item.Id); SetApproval(item, Approval(item) - 3); State.AddLog(LogCategory.Info, item.Name + " has given up waiting for you to keep your word.", item.Id); } } int num = Approval(item); long value; bool flag = Bonds.LeaveWarned.TryGetValue(item.Id, out value) && value > 0; if (num <= -60 && !flag) { Bonds.LeaveWarned[item.Id] = State.Clock.Day; string text = item.Name + " takes you aside: \"I am not sure I can follow you much longer, captain.\""; State.AddLog(LogCategory.Info, text, item.Id); C.Raise(CampaignEventKind.Warning, text, false, item.Id); } else if (num > -60 && flag) { Bonds.LeaveWarned.Remove(item.Id); } else if (num <= -80 && flag && State.Clock.Day - value >= 3 && C.CompanionDismissalReason(item.Id).Length == 0 && C.DismissCompanion(item.Id).Ok) { Bonds.LeaveWarned.Remove(item.Id); Bonds.Requests.Remove(item.Id); string text2 = item.Name + " has had enough of your leadership and left the company."; C.Raise(CampaignEventKind.Warning, text2, true, item.Id); } } if (list.Count > 0 && State.Random.Get("herobonds").Chance(0.12)) { CampChat(list); } } internal void CampChat(List companions) { RandomStream randomStream = State.Random.Get("herobonds"); Hero a = companions[randomStream.Range(0, companions.Count)]; Party playerParty = State.PlayerParty; Campaign.Personality personality = Campaign.PersonalityOf(a); string text; if (companions.Count < 2 || !randomStream.Chance(0.5)) { text = ((C.FoodSupply(playerParty) < C.DailyFoodNeed(playerParty) * 2.0) ? (a.Name + " stares into an empty pot: \"We need to buy food, captain.\"") : ((playerParty.Troops.TotalWounded > playerParty.Troops.TotalTroops / 3) ? (a.Name + " looks over the wounded: \"We need rest before the next fight.\"") : ((personality.Valor > 0) ? (a.Name + " sharpens a blade by the fire: \"When do we fight next?\"") : ((personality.Generosity <= 0) ? (a.Name + " hums an old song from home by the fire.") : (a.Name + " shares out the last of their own bread among the men."))))); } else { Hero hero = companions.Where((Hero x) => x.Id != a.Id).ElementAt(randomStream.Range(0, companions.Count - 1)); Campaign.Personality personality2 = Campaign.PersonalityOf(hero); text = ((personality.Valor > 0 && personality2.Valor < 0) ? (a.Name + " teases " + hero.Name + " for always hanging back in a fight. " + Campaign.First(hero) + " says somebody has to stay alive to bury the brave.") : ((personality.Generosity < 0 && personality2.Generosity > 0) ? (a.Name + " grumbles that " + hero.Name + " gives away half their pay to beggars.") : ((personality.Honor > 0 && personality2.Honor < 0) ? (a.Name + " counts the purse twice after " + hero.Name + " has been near it.") : ((personality.Calculating > 0) ? (a.Name + " beats " + hero.Name + " at dice again and will not say how.") : (a.Name + " and " + hero.Name + " swap stories of old fights late into the night."))))); } State.AddLog(LogCategory.Info, text, a.Id); State.Touch(); } internal List CompanionOpinion(Hero h, Random r) { List list = new List(); int num = Approval(h); list.Add((num >= 50) ? Campaign.Pick(r, "I'd follow you anywhere, captain.", "Best captain I've ever served.") : ((num >= 15) ? Campaign.Pick(r, "You lead well enough. I'm glad I signed on.", "No complaints from me.") : ((num > -15) ? Campaign.Pick(r, "Can't complain. Can't say I'm cheering, either.", "You're the captain. I follow.") : ((num > -60) ? Campaign.Pick(r, "Some of what you do sits badly with me.", "I've had better captains, if I'm honest.") : Campaign.Pick(r, "I'm close to walking away, captain. Very close.", "I don't know how much more of this I can take."))))); if (State.HeroBonds?.LastRemark != null && State.HeroBonds.LastRemark.TryGetValue(h.Id, out var value) && !string.IsNullOrEmpty(value)) { list.Add("As I said before: \"" + value + "\""); } string text = Campaign.DescribePersonality(h); if (text.Length > 0) { list.Add("(" + Campaign.First(h) + " strikes you as " + text + ". Approval " + num.ToString("+0;-0;0", CultureInfo.InvariantCulture) + ".)"); } else { list.Add("(Approval " + num.ToString("+0;-0;0", CultureInfo.InvariantCulture) + ".)"); } return list; } } internal sealed class HeroDevelopmentSystem { private readonly Campaign C; private CampaignState State => C.State; internal HeroDevelopmentSystem(Campaign host) { C = host; } public static int HeroFocusPointsForLevel(int level) { return 2 + (Math.Max(1, Math.Min(50, level)) - 1); } public int HeroFocusBudget(Hero hero) { if (hero != null) { return HeroFocusPointsForLevel(C.HeroLevel(hero)) + ExtraFocus(hero); } return 0; } public static int ExtraFocus(Hero hero) { if (hero != null) { return Math.Max(0, Math.Min(100, hero.BonusFocus)) + Math.Max(0, Math.Min(CharacterCreation.MaximumOriginFocus, hero.OriginFocus)); } return 0; } public int HeroFocusAvailable(Hero hero) { if (hero == null || HeroFocusRecordsReason(hero).Length > 0) { return 0; } return HeroFocusBudget(hero) - (hero.SkillFocus?.Values.Sum() ?? 0); } public int HeroSkillFocus(Hero hero, string skill) { if (hero == null || !SkillIds.All.Contains(skill) || HeroFocusRecordsReason(hero).Length > 0 || hero.SkillFocus == null) { return 0; } if (!hero.SkillFocus.TryGetValue(skill, out var value)) { return 0; } return value; } public double HeroLearningRate(Hero hero, string skill) { if (hero == null) { return 1.0; } double num = (1.0 + 0.2 * (double)HeroSkillFocus(hero, skill)) * (1.0 + 0.1 * (double)(HeroAttribute(hero, Skills.AttributeOf(skill)) - 2)); int num2 = HeroLearningLimit(hero, skill); int num3 = hero.Skill(skill); if (num3 >= num2) { num *= Math.Max(0.1, 1.0 - (double)(num3 - num2) / 40.0); } return num; } public int HeroLearningLimit(Hero hero, string skill) { if (hero != null) { return 40 + 20 * (HeroAttribute(hero, Skills.AttributeOf(skill)) - 2) + 30 * HeroSkillFocus(hero, skill); } return 0; } public static int HeroAttribute(Hero hero, string attribute) { if (hero?.Attributes == null || string.IsNullOrEmpty(attribute)) { return 2; } if (!hero.Attributes.TryGetValue(attribute, out var value)) { return 2; } return Math.Max(2, Math.Min(10, value)); } public int HeroAttributeBudget(Hero hero) { if (hero != null) { return AttributeIds.All.Length * 2 + Math.Max(0, hero.OriginAttributes) + C.HeroLevel(hero) / 4; } return 0; } public int HeroAttributePointsAvailable(Hero hero) { if (hero != null) { return Math.Max(0, HeroAttributeBudget(hero) - AttributeIds.All.Sum((string a) => HeroAttribute(hero, a))); } return 0; } public string HeroAttributeChoiceReason(string heroId, string attribute) { string text = HeroDevelopmentReason(heroId); if (text.Length > 0) { return text; } if (!AttributeIds.All.Contains(attribute)) { return "Unknown attribute."; } Hero hero = State.Heroes.Require(heroId); if (HeroAttribute(hero, attribute) >= 10) { return 10 + " is the most."; } if (HeroAttributePointsAvailable(hero) <= 0) { return "An attribute point comes every " + 4 + " levels."; } return ""; } public CommandResult InvestHeroAttribute(string heroId, string attribute) { string text = HeroAttributeChoiceReason(heroId, attribute); if (text.Length > 0) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Require(heroId); if (hero.Attributes == null) { hero.Attributes = new SortedDictionary(StringComparer.Ordinal); } hero.Attributes[attribute] = HeroAttribute(hero, attribute) + 1; string text2 = $"{hero.Name}'s {Skills.Attribute(attribute).Name} rose to {hero.Attributes[attribute]}."; State.AddLog(LogCategory.Info, text2, hero.Id); State.Touch(); return CommandResult.Success(text2); } public void EnsureHeroAttributes() { bool flag = false; foreach (Hero hero in State.Heroes) { if (hero.Attributes == null) { hero.Attributes = new SortedDictionary(StringComparer.Ordinal); flag = true; } if (hero.Skills != null) { if (hero.Skills.Count > 0 && !hero.Skills.ContainsKey("athletics")) { SeedNewSkills(hero); flag = true; } if (hero.Attributes.Count == 0) { FitAttributes(hero); flag = true; } if (hero.OriginAttributes < 0) { hero.OriginAttributes = 0; flag = true; } } } if (flag) { State.Touch(); } } internal void InitialiseHero(Hero hero) { if (hero != null) { if (hero.Skills == null) { hero.Skills = new SortedDictionary(StringComparer.Ordinal); } if (hero.Attributes == null) { hero.Attributes = new SortedDictionary(StringComparer.Ordinal); } if (hero.Skills.Count > 0 && !hero.Skills.ContainsKey("athletics")) { SeedNewSkills(hero); } if (hero.Attributes.Count == 0 || (hero.Skills.Count > 0 && hero.OriginAttributes == 0 && AttributeIds.All.All((string a) => HeroAttribute(hero, a) == 2))) { FitAttributes(hero); } } } internal void SeedNewSkills(Hero hero) { int num = Math.Max(1, C.UnitDef(hero.UnitId ?? "")?.Tier ?? 1); int num2 = C.HeroLevel(hero); int num3 = Math.Min(200, 15 + 15 * num + 2 * num2); string text = MainWeaponSkill(hero); string[] all = SkillIds.All; foreach (string text2 in all) { if (hero.Skills.ContainsKey(text2) || SkillIds.Original.Contains(text2)) { continue; } int value; if (text2 == text) { value = num3; } else if (SkillIds.Weapons.Contains(text2)) { value = Math.Min(80, 5 + 3 * num + num2); } else { switch (text2) { case "athletics": value = Math.Min(150, 10 + 8 * num + num2); break; case "charm": value = Math.Max(5, (int)Math.Round(0.6 * (double)Math.Max(hero.Skill("diplomacy"), hero.Skill("leadership")))); break; case "roguery": { Clan clan = State.Clans.Get(hero.ClanId); value = ((clan != null && clan.IsBandit) ? (40 + 10 * num) : 5); break; } default: value = 5; break; } } hero.Skills[text2] = value; } } public string MainWeaponSkill(Hero hero) { OwnedItemInfo ownedItemInfo = C.ItemInfo(hero?.Loadout?.WeaponId ?? ""); if (ownedItemInfo?.Crafted != null) { return Skills.WeaponSkill(ownedItemInfo.Crafted.Class); } EquipmentDef equipmentDef = EquipmentCatalog.Find(hero?.Loadout?.WeaponId ?? ""); if (equipmentDef != null && equipmentDef.Class.HasValue) { return Skills.WeaponSkill(equipmentDef.Class.Value); } return UnitWeaponSkill(C.UnitDef(hero?.UnitId ?? "")); } public static string UnitWeaponSkill(UnitDef unit) { if (unit == null) { return "one_handed"; } if (unit.Role == TroopRole.Ranged) { if ((unit.TabsUnitId ?? "").IndexOf("cross", StringComparison.OrdinalIgnoreCase) < 0) { return "bow"; } return "crossbow"; } if (unit.Role == TroopRole.Cavalry) { return "polearm"; } string text = unit.TabsUnitId + " " + unit.Id; if (text.IndexOf("pike", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("spear", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("halberd", StringComparison.OrdinalIgnoreCase) >= 0) { return "polearm"; } if (text.IndexOf("great", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("berserker", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("samurai", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("executioner", StringComparison.OrdinalIgnoreCase) >= 0) { return "two_handed"; } if (text.IndexOf("javelin", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("throw", StringComparison.OrdinalIgnoreCase) >= 0) { return "throwing"; } return "one_handed"; } internal void FitAttributes(Hero hero) { hero.Attributes.Clear(); string[] all = AttributeIds.All; foreach (string text in all) { int num = 2; foreach (SkillDef item in Skills.Of(text)) { int value; int num2 = ((hero.SkillFocus != null && hero.SkillFocus.TryGetValue(item.Id, out value)) ? value : 0); int num3 = hero.Skill(item.Id) - 40 - 30 * num2; if (num3 > 0) { num = Math.Max(num, 2 + (num3 + 19) / 20); } } hero.Attributes[text] = Math.Min(10, num); } int num4 = AttributeIds.All.Sum((string a) => hero.Attributes[a]) - AttributeIds.All.Length * 2; hero.OriginAttributes = Math.Max(0, num4 - C.HeroLevel(hero) / 4); } internal string HeroFocusRecordsReason(Hero hero) { if (hero.SkillFocus == null) { return ""; } long num = 0L; foreach (KeyValuePair item in hero.SkillFocus) { if (!SkillIds.All.Contains(item.Key) || item.Value < 0 || item.Value > 5) { return "This hero's focus records are invalid."; } num += item.Value; } if (num <= HeroFocusBudget(hero)) { return ""; } return "This hero has spent more focus than their level allows."; } internal string HeroDevelopmentReason(string heroId) { string text = C.CompanionCommandReason(); if (text.Length > 0) { return text; } Party playerParty = State.PlayerParty; if (!string.IsNullOrEmpty(State.Player.PendingEncounterId) || !string.IsNullOrEmpty(playerParty.EncounterId) || C.MilitaryPartyReserved(playerParty.Id)) { return "Deal with the encounter first."; } Hero hero = State.Heroes.Get(heroId ?? ""); if (hero == null || hero.ClanId != State.PlayerClanId || (hero.Id != State.PlayerHeroId && !C.IsOwnedCompanion(hero))) { return "Pick yourself or a companion."; } if (hero.State != HeroState.Active || !Campaign.IsPresentPartyHero(playerParty, hero)) { return "They have to be in your party to train."; } return HeroFocusRecordsReason(hero); } public string HeroFocusChoiceReason(string heroId, string skill) { string text = HeroDevelopmentReason(heroId); if (text.Length > 0) { return text; } if (!SkillIds.All.Contains(skill)) { return "Unknown skill."; } Hero hero = State.Heroes.Require(heroId); if (skill == "diplomacy" && hero.Id != State.PlayerHeroId) { return "Only you learn Diplomacy: from council business, war and peace, service and ransoms."; } if (hero.Skill(skill) >= 300) { return "Already mastered."; } if (HeroSkillFocus(hero, skill) >= 5) { return "Five focus points is the most."; } if (HeroFocusAvailable(hero) <= 0) { return "Level up to earn another focus point."; } return ""; } public CommandResult InvestHeroFocus(string heroId, string skill) { string text = HeroFocusChoiceReason(heroId, skill); if (text.Length > 0) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Require(heroId); int value = HeroSkillFocus(hero, skill) + 1; if (hero.SkillFocus == null) { hero.SkillFocus = new SortedDictionary(StringComparer.Ordinal); } hero.SkillFocus[skill] = value; string text2 = hero.Name + " invested a focus point in " + Skills.Name(skill) + "."; State.AddLog(LogCategory.Info, text2, hero.Id); State.Touch(); return CommandResult.Success(text2); } public HeroRetrainingQuote QuoteHeroRetraining(string heroId) { HeroRetrainingQuote heroRetrainingQuote = new HeroRetrainingQuote { HeroId = (heroId ?? ""), Cost = 500L, ExpectedRevision = State.Revision, Reason = HeroDevelopmentReason(heroId) }; if (!heroRetrainingQuote.Allowed) { return heroRetrainingQuote; } Settlement settlement = C.CurrentSettlement(); if (settlement == null || settlement.Type != SettlementType.Town || !C.CanEnter(State.PlayerParty, settlement) || !(Vec2.Distance(State.PlayerParty.Position, settlement.Position) <= 0.01)) { heroRetrainingQuote.Reason = "Retrain in a friendly town."; return heroRetrainingQuote; } Hero hero = State.Heroes.Require(heroId); SortedDictionary skillFocus = hero.SkillFocus; if (skillFocus == null || !skillFocus.Any((KeyValuePair entry) => entry.Value > 0)) { List perks = hero.Perks; if (perks == null || !perks.Any()) { heroRetrainingQuote.Reason = "Nothing to reset."; goto IL_0147; } } if (State.PlayerClan.Gold < heroRetrainingQuote.Cost) { heroRetrainingQuote.Reason = $"You need {heroRetrainingQuote.Cost} denars to retrain."; } goto IL_0147; IL_0147: return heroRetrainingQuote; } public CommandResult RetrainHero(string heroId, long expectedRevision) { if (expectedRevision != State.Revision) { return CommandResult.Fail("Something changed. Check the retraining offer again."); } HeroRetrainingQuote heroRetrainingQuote = QuoteHeroRetraining(heroId); if (!heroRetrainingQuote.Allowed) { return CommandResult.Fail(heroRetrainingQuote.Reason); } Hero hero = State.Heroes.Require(heroId); Settlement settlement = C.CurrentSettlement(); string text = $"{hero.Name} retrained at {settlement.Name} for {heroRetrainingQuote.Cost} denars."; State.Transact(State.PlayerClan, -heroRetrainingQuote.Cost, LedgerAccount.HeroTraining, text); hero.SkillFocus?.Clear(); hero.Perks?.Clear(); State.AddLog(LogCategory.Info, text, hero.Id, settlement.Id); State.Touch(); return CommandResult.Success(text); } } internal sealed class HideoutsSystem { private readonly Campaign C; private NavGrid Nav => C.Nav; private static string[] OutlawChiefNames => Campaign.OutlawChiefNames; private CampaignState State => C.State; public string HideoutChiefPending { get { if (State.Hideouts == null || State.Player.Activity == PlayerActivity.InEncounter || State.Player.Activity == PlayerActivity.InBattle || State.Player.Activity == PlayerActivity.Captive) { return ""; } return State.Hideouts.Records.FirstOrDefault((HideoutRecord r) => r.Stage == "chief")?.SettlementId ?? ""; } } internal HideoutsSystem(Campaign host) { C = host; } public void EnsureHideoutFields() { bool flag = false; if (State.Hideouts == null) { State.Hideouts = new HideoutsState(); flag = true; } HideoutsState hideouts = State.Hideouts; if (hideouts.Records == null) { hideouts.Records = new List(); flag = true; } foreach (HideoutRecord record in hideouts.Records) { if (record.SquadTroops == null) { record.SquadTroops = new SortedDictionary(StringComparer.Ordinal); flag = true; } if (record.SquadHeroes == null) { record.SquadHeroes = new List(); flag = true; } } if (State.Legends == null) { State.Legends = new LegendsState(); flag = true; } if (State.Legends.Joined == null) { State.Legends.Joined = new SortedSet(StringComparer.Ordinal); flag = true; } if (!hideouts.Started) { hideouts.Started = true; foreach (Settlement s in State.Settlements.Where((Settlement x) => x.Type == SettlementType.Hideout).OrderBy((Settlement x) => x.Id, StringComparer.Ordinal)) { if (!hideouts.Records.Any((HideoutRecord r) => r.SettlementId == s.Id)) { HideoutRecord hideoutRecord = new HideoutRecord { SettlementId = s.Id }; hideouts.Records.Add(hideoutRecord); if (s.HideoutActive) { MoveInGang(hideoutRecord, s); } else { hideoutRecord.ResettleDay = State.Clock.Day + 28; } } } flag = true; } if (flag) { State.Touch(); } } public HideoutRecord Hideout(string settlementId) { return State.Hideouts?.Records?.FirstOrDefault((HideoutRecord r) => r.SettlementId == settlementId); } public bool HideoutKnown(Settlement s) { if (s == null || s.Type != SettlementType.Hideout) { return true; } if (State.Settings.FullInformation) { return true; } return Hideout(s.Id)?.Found ?? true; } public bool HideoutKnown(string settlementId) { return HideoutKnown(State.Settlements.Get(settlementId)); } internal void MoveInGang(HideoutRecord rec, Settlement s) { Clan clan = State.Clans.Get(s.BanditClanId); if (clan == null || clan.BanditTroops == null || clan.BanditTroops.Count == 0) { return; } rec.Generation++; RandomStream randomStream = new RandomStream("hideout|" + s.Id + "|" + rec.Generation.ToString(CultureInfo.InvariantCulture), State.Random.Seed); Party party = new Party { Id = State.Ids.Allocate("gang"), Name = "The gang of " + s.Name, Kind = PartyKind.Bandit, ClanId = clan.Id, HomeSettlementId = s.Id, Position = s.Position, State = PartyState.InSettlement, CurrentSettlementId = s.Id, Morale = 60.0, AiFrozen = true, HideoutGuardOf = s.Id, CreatedAtMinute = State.Clock.Minute }; int num = randomStream.Range(12, 23); List weights = clan.BanditTroops.Select((WeightedUnit w) => w.Weight).ToList(); for (int num2 = 0; num2 < num; num2++) { int num3 = randomStream.PickWeighted(weights); if (num3 >= 0) { party.Troops.Add(clan.BanditTroops[num3].Unit, 1); } } State.Parties.Add(party); rec.GuardPartyId = party.Id; rec.Stage = ""; rec.ResettleDay = -1L; rec.SquadTroops.Clear(); rec.SquadHeroes.Clear(); HashSet taken = new HashSet(from r in State.Hideouts.Records where r != rec && r.GuardPartyId.Length > 0 select r.ChiefUnitId, StringComparer.Ordinal); List list = Legends.Chiefs.Where((LegendDef l) => C.UnitDef(l.Unit) != null && !State.Legends.Joined.Contains(l.Unit) && !taken.Contains(l.Unit)).ToList(); if (list.Count > 0 && randomStream.Chance(0.55)) { LegendDef legendDef = list[randomStream.Range(0, list.Count)]; rec.ChiefUnitId = legendDef.Unit; rec.ChiefName = C.UnitDef(legendDef.Unit).Name; } else { UnitDef unitDef = (from w in clan.BanditTroops select C.UnitDef(w.Unit) into u where u != null orderby u.Tier descending, u.TabsCost descending select u).ThenBy((UnitDef u) => u.Id, StringComparer.Ordinal).FirstOrDefault(); rec.ChiefUnitId = unitDef?.Id ?? clan.BanditTroops[0].Unit; rec.ChiefName = OutlawChiefNames[randomStream.Range(0, OutlawChiefNames.Length)]; } s.HideoutActive = true; } internal LegendDef ChiefLegend(HideoutRecord rec) { LegendDef legendDef = Legends.For(rec?.ChiefUnitId ?? ""); if (legendDef == null || legendDef.Route != LegendRoute.Chief) { return null; } return legendDef; } public string HideoutChiefDescription(string settlementId) { HideoutRecord hideoutRecord = Hideout(settlementId); if (hideoutRecord == null || hideoutRecord.ChiefUnitId.Length == 0) { return ""; } LegendDef legendDef = ChiefLegend(hideoutRecord); if (legendDef == null) { return hideoutRecord.ChiefName + ", a " + (C.UnitDef(hideoutRecord.ChiefUnitId)?.Name ?? "bandit").ToLowerInvariant(); } return hideoutRecord.ChiefName + ", " + legendDef.Story; } internal void HourlyHideouts() { Party playerParty = State.PlayerParty; if (State.Hideouts == null || playerParty == null || playerParty.State != PartyState.Active || State.Player.Activity == PlayerActivity.Captive) { return; } List list = State.Hideouts.Records.Where((HideoutRecord r) => !r.Found).ToList(); if (list.Count == 0) { return; } double num = Math.Max(2.5, C.SightRange(playerParty) * 0.7); int num2 = C.BestScout(); foreach (HideoutRecord item in list.OrderBy((HideoutRecord r) => r.SettlementId, StringComparer.Ordinal)) { Settlement settlement = State.Settlements.Get(item.SettlementId); if (settlement != null && !(Vec2.Distance(settlement.Position, playerParty.Position) > num) && State.Random.Get("discoveries").Chance(Math.Min(0.95, 0.35 + (double)num2 / 250.0))) { item.Found = true; item.FoundMinute = State.Clock.Minute; C.GrantSkillExperience(State.PlayerHero, "scouting", 20.0); string text = (settlement.HideoutActive ? ("Your scouts found a bandit hideout: " + settlement.Name + ". It is marked on your map.") : ("Your scouts found an abandoned bandit camp: " + settlement.Name + ".")); State.AddLog(LogCategory.Travel, text, settlement.Id); C.Raise(CampaignEventKind.Info, text, false, settlement.Id); State.Touch(); } } } public CommandResult DeveloperRevealHideouts() { if (!State.DeveloperTools) { return CommandResult.Fail("Developer tools were not enabled when this campaign was created."); } if (State.Hideouts == null || !State.Hideouts.Started) { EnsureHideoutFields(); } int num = 0; foreach (HideoutRecord item in State.Hideouts.Records.Where((HideoutRecord x) => !x.Found)) { item.Found = true; item.FoundMinute = State.Clock.Minute; num++; } State.Touch(); return CommandResult.Success("Developer: " + num + " hideouts revealed."); } public int HideoutSquadLimit() { int num = Campaign.ClanTier(State.PlayerClan); return Math.Min(24, 8 + 2 * num + C.Skill("tactics") / 30); } public Settlement HideoutHere() { Party p = State.PlayerParty; if (p == null || p.State != PartyState.Active) { return null; } return (from s in State.Settlements where s.Type == SettlementType.Hideout && HideoutKnown(s) && Vec2.Distance(s.Position, p.Position) <= 2.0 orderby Vec2.Distance(s.Position, p.Position) select s).ThenBy((Settlement s) => s.Id, StringComparer.Ordinal).FirstOrDefault(); } public string HideoutAssaultReason(string settlementId) { Settlement settlement = State.Settlements.Get(settlementId); HideoutRecord hideoutRecord = Hideout(settlementId); if (settlement == null || hideoutRecord == null || settlement.Type != SettlementType.Hideout) { return "That is not a bandit camp."; } if (!HideoutKnown(settlement)) { return "You haven't found that camp."; } if (!settlement.HideoutActive) { return settlement.Name + " is abandoned. A new gang will move in before long."; } if (hideoutRecord.Stage == "chief") { return "The chief of " + settlement.Name + " waits for your answer."; } Party party = State.Parties.Get(hideoutRecord.GuardPartyId); if (party == null || party.State == PartyState.Destroyed || C.PartyCombatants(party) == 0) { return "Nobody is home at " + settlement.Name + " just now."; } if (!string.IsNullOrEmpty(party.EncounterId)) { return "The gang of " + settlement.Name + " is already fighting."; } string text = C.QuestActionReason(); if (text.Length > 0) { return text; } Party playerParty = State.PlayerParty; if (playerParty.State != PartyState.Active) { return "Leave the settlement first."; } if (C.ClanArmyContains(playerParty.Id) && State.ClanArmy?.LeaderPartyId != playerParty.Id) { return "You're marching with an army; its leader decides where it goes."; } if (Vec2.Distance(playerParty.Position, settlement.Position) > 2.0) { return "Travel to " + settlement.Name + " first."; } if (C.PartyCombatants(playerParty) == 0) { return "Nobody in your party is fit to fight."; } return ""; } public string HideoutGangEstimate(string settlementId) { HideoutRecord hideoutRecord = Hideout(settlementId); Party party = State.Parties.Get(hideoutRecord?.GuardPartyId ?? ""); if (party == null || party.State == PartyState.Destroyed) { return "Nobody is home."; } int num = C.PartyCombatants(party); int num2 = C.BestScout(); if (num2 >= 60) { return num + " outlaws, led by " + HideoutChiefDescription(settlementId) + "."; } int num3 = ((num2 >= 30) ? 3 : 6); int num4 = Math.Max(1, num - num3); int num5 = num + num3; return "Between " + num4 + " and " + num5 + " outlaws" + ((num2 >= 30) ? (", led by " + hideoutRecord.ChiefName) : "") + "."; } public void SuggestHideoutSquad(out SortedDictionary troops, out List heroes) { troops = new SortedDictionary(StringComparer.Ordinal); heroes = new List(); Party playerParty = State.PlayerParty; if (playerParty == null) { return; } int num = HideoutSquadLimit(); foreach (string item in playerParty.Troops.Heroes.OrderBy((string x) => (!(x == State.PlayerHeroId)) ? 1 : 0).ThenBy((string x) => x, StringComparer.Ordinal)) { Hero hero = State.Heroes.Get(item); if (hero != null && hero.CanFight && heroes.Count < num) { heroes.Add(item); } } int num2 = num - heroes.Count; foreach (TroopStack item2 in (from x in playerParty.Troops.Stacks where x.Healthy > 0 orderby C.UnitDef(x.UnitId)?.Tier ?? 1 descending, C.UnitDef(x.UnitId)?.TabsCost ?? 0 descending select x).ThenBy((TroopStack x) => x.UnitId, StringComparer.Ordinal)) { if (num2 <= 0) { break; } int num3 = Math.Min(num2, item2.Healthy); troops[item2.UnitId] = num3; num2 -= num3; } } public string HideoutSquadReason(IDictionary troops, IList heroes) { Party playerParty = State.PlayerParty; if (playerParty == null) { return "You have no party."; } int num = 0; foreach (KeyValuePair item in troops ?? new Dictionary()) { if (item.Value < 0) { return "A squad cannot hold fewer than none."; } if (item.Value != 0) { TroopStack troopStack = playerParty.Troops.Find(item.Key); if (troopStack == null || troopStack.Healthy < item.Value) { return "You do not have " + item.Value + " healthy " + (C.UnitDef(item.Key)?.Name ?? item.Key) + "."; } num += item.Value; } } foreach (string item2 in heroes ?? new List()) { Hero hero = State.Heroes.Get(item2); if (hero == null || !playerParty.Troops.Heroes.Contains(item2)) { return "That hero isn't in your party."; } if (!hero.CanFight) { return hero.Name + " is too hurt to fight."; } num++; } if (num == 0) { return "Choose who goes in."; } int num2 = HideoutSquadLimit(); if (num > num2) { return "At most " + num2 + " can go in (clan tier and Tactics raise this)."; } return ""; } public CommandResult StartHideoutAssault(string settlementId, IDictionary troops, IList heroes) { string text = HideoutAssaultReason(settlementId); if (text.Length == 0) { text = HideoutSquadReason(troops, heroes); } if (text.Length > 0) { return CommandResult.Fail(text); } Settlement settlement = State.Settlements.Get(settlementId); HideoutRecord hideoutRecord = Hideout(settlementId); Party defenders = State.Parties.Get(hideoutRecord.GuardPartyId); Encounter encounter = BeginHideoutEncounter(settlement, defenders, "gang", troops, heroes); C.Raise(CampaignEventKind.EncounterStarted, "Your squad creeps up on " + settlement.Name + ".", true, encounter.Id, settlement.Id); return CommandResult.Success(); } internal Encounter BeginHideoutEncounter(Settlement s, Party defenders, string stage, IDictionary troops, IList heroes) { Party playerParty = State.PlayerParty; Encounter encounter = new Encounter { Id = State.Ids.Allocate("enc"), CreatedAtMinute = State.Clock.Minute, Kind = EncounterKind.HideoutRaid, Position = s.Position, Biome = Nav.TerrainAt(s.Position).Biome, InitiatorPartyId = playerParty.Id, HideoutId = s.Id, HideoutStage = stage }; foreach (KeyValuePair item in troops ?? new Dictionary()) { if (item.Value > 0) { encounter.SquadTroops[item.Key] = item.Value; } } foreach (string item2 in heroes ?? new List()) { if (!encounter.SquadHeroes.Contains(item2)) { encounter.SquadHeroes.Add(item2); } } encounter.AttackerParties.Add(playerParty.Id); encounter.DefenderParties.Add(defenders.Id); State.Encounters.Add(encounter); C.ClearOrder(playerParty); Party[] array = new Party[2] { playerParty, defenders }; foreach (Party obj in array) { obj.State = PartyState.Engaged; obj.EncounterId = encounter.Id; } encounter.PlayerInvolved = true; encounter.PlayerSide = BattleSide.Attacker; State.Player.PendingEncounterId = encounter.Id; State.Player.Activity = PlayerActivity.InEncounter; C.UpdatePlayerTimeStates(); State.Touch(); return encounter; } internal void ReturnGangHome(Party p, Settlement s) { if (p != null && s != null && p.State != PartyState.Destroyed && p.State != PartyState.Disbanded) { p.State = PartyState.InSettlement; p.CurrentSettlementId = s.Id; p.Position = s.Position; p.EncounterId = ""; p.HideoutGuardOf = s.Id; p.HomeSettlementId = s.Id; p.AiFrozen = true; p.DisengagedUntilMinute = 0L; C.ClearOrder(p); } } internal void CancelHideoutEncounter(Encounter enc) { if (enc == null || enc.Kind != EncounterKind.HideoutRaid) { return; } Settlement settlement = State.Settlements.Get(enc.HideoutId); HideoutRecord hideoutRecord = Hideout(enc.HideoutId); Party party = enc.DefenderParties.Select((string id) => State.Parties.Get(id)).FirstOrDefault((Party p) => p != null); if (enc.HideoutStage == "chief") { if (party != null) { OutcomeCommitter.DestroyParty(C, party, "the chief fled"); } if (hideoutRecord != null && settlement != null) { ClearHideout(hideoutRecord, settlement, chiefBeaten: false, hideoutRecord.ChiefName + " slipped away while you hesitated."); } } else { ReturnGangHome(party, settlement); } } internal void CompleteHideoutRaid(Encounter enc, BattleResult result, BattleReport report) { if (enc == null || enc.Kind != EncounterKind.HideoutRaid || string.IsNullOrEmpty(enc.HideoutId)) { return; } Settlement settlement = State.Settlements.Get(enc.HideoutId); HideoutRecord hideoutRecord = Hideout(enc.HideoutId); if (settlement == null || hideoutRecord == null) { return; } bool flag = report?.PlayerWon ?? false; Party party = enc.DefenderParties.Select((string id) => State.Parties.Get(id)).FirstOrDefault((Party p) => p != null); if (enc.HideoutStage == "chief") { if (flag) { if (party != null && party.State != PartyState.Destroyed) { OutcomeCommitter.DestroyParty(C, party, "the chief was beaten"); } string item = WinOverChief(hideoutRecord); report?.Lines.Add(item); report?.Lines.Add(ClearHideout(hideoutRecord, settlement, chiefBeaten: true, "")); return; } hideoutRecord.Stage = ""; if (party != null && party.State != PartyState.Destroyed) { party.Troops.RemoveHealthy(hideoutRecord.ChiefUnitId, 1); ReturnGangHome(party, settlement); hideoutRecord.GuardPartyId = party.Id; } else { hideoutRecord.GuardPartyId = ""; } report?.Lines.Add(hideoutRecord.ChiefName + " holds " + settlement.Name + "."); } else if (flag) { if (party != null && party.State != PartyState.Destroyed) { OutcomeCommitter.DestroyParty(C, party, "the gang scattered"); } hideoutRecord.GuardPartyId = ""; hideoutRecord.Stage = "chief"; hideoutRecord.SquadTroops.Clear(); foreach (KeyValuePair squadTroop in enc.SquadTroops) { hideoutRecord.SquadTroops[squadTroop.Key] = squadTroop.Value; } hideoutRecord.SquadHeroes = enc.SquadHeroes.ToList(); report?.Lines.Add("The gang of " + settlement.Name + " is broken. Out of the biggest tent steps their chief: " + HideoutChiefDescription(settlement.Id) + "."); } else { if (party != null && party.State != PartyState.Destroyed) { ReturnGangHome(party, settlement); } else { hideoutRecord.GuardPartyId = ""; } report?.Lines.Add("The gang still holds " + settlement.Name + "."); } } internal string WinOverChief(HideoutRecord rec) { LegendDef legendDef = ChiefLegend(rec); UnitDef unitDef = C.UnitDef(rec.ChiefUnitId); if (legendDef != null && unitDef != null && !State.Legends.Joined.Contains(legendDef.Unit) && State.PlayerParty != null && State.PlayerParty.State != PartyState.Disbanded) { State.PlayerParty.Troops.Add(legendDef.Unit, 1); State.Legends.Joined.Add(legendDef.Unit); State.PlayerClan.Renown += 5.0; string text = rec.ChiefName + " picks themselves up, looks at you for a long moment, and offers you their " + ((unitDef.Role == TroopRole.Monster) ? "enormous hand" : "weapon") + ". " + unitDef.Name + " joins your party."; State.AddLog(LogCategory.Recruitment, text, rec.SettlementId); return text; } long amount = Campaign.Round10(150.0 + (double)(unitDef?.TabsCost ?? 100) / 2.0); State.Transact(State.PlayerClan, amount, LedgerAccount.Loot, "The purse of " + rec.ChiefName); State.PlayerClan.Renown += 2.0; return rec.ChiefName + " is beaten. Their purse holds " + amount + " denars."; } internal string ClearHideout(HideoutRecord rec, Settlement s, bool chiefBeaten, string lead) { RandomStream randomStream = new RandomStream("hideout.cleared|" + s.Id + "|" + rec.Generation.ToString(CultureInfo.InvariantCulture), State.Random.Seed); s.HideoutActive = false; rec.Stage = ""; rec.GuardPartyId = ""; rec.SquadTroops.Clear(); rec.SquadHeroes.Clear(); rec.ClearedMinute = State.Clock.Minute; rec.ResettleDay = State.Clock.Day + randomStream.Range(28, 43); rec.TimesCleared++; long amount = Campaign.Round10(250 + randomStream.Range(0, 350)); State.Transact(State.PlayerClan, amount, LedgerAccount.Loot, "The hoard of " + s.Name); State.PlayerClan.Renown += (chiefBeaten ? 6 : 4); C.GrantSkillExperience(State.PlayerHero, "tactics", 60.0); int num = 0; foreach (NotableState item in (State.Notables ?? new List()).Where((NotableState x) => x.IsAlive).OrderBy((NotableState x) => x.Id, StringComparer.Ordinal).ToList()) { Settlement settlement = State.Settlements.Get(item.SettlementId); if (settlement != null && settlement.Type != SettlementType.Hideout && !(Vec2.Distance(settlement.Position, s.Position) > 30.0)) { C.AdjustNotableRelation(item.Id, 3, "you cleared " + s.Name); num++; } } string text = ((lead.Length > 0) ? (lead + " ") : "") + s.Name + " is cleared: the gang's hoard of " + amount + " denars is yours" + ((num > 0) ? ", and the villages around are grateful" : "") + "."; State.AddLog(LogCategory.Battle, text, s.Id); C.Raise(CampaignEventKind.Info, text, false, s.Id); State.Touch(); return text; } internal SortedDictionary SurvivingSquad(HideoutRecord rec, out List heroes) { Party playerParty = State.PlayerParty; SortedDictionary sortedDictionary = new SortedDictionary(StringComparer.Ordinal); heroes = new List(); if (playerParty == null) { return sortedDictionary; } foreach (KeyValuePair squadTroop in rec.SquadTroops) { int num = Math.Min(squadTroop.Value, playerParty.Troops.Find(squadTroop.Key)?.Healthy ?? 0); if (num > 0) { sortedDictionary[squadTroop.Key] = num; } } foreach (string squadHero in rec.SquadHeroes) { if (playerParty.Troops.Heroes.Contains(squadHero)) { Hero hero = State.Heroes.Get(squadHero); if (hero != null && hero.CanFight) { heroes.Add(squadHero); } } } return sortedDictionary; } public StoryPrompt HideoutPrompt(string settlementId) { HideoutRecord hideoutRecord = Hideout(settlementId); Settlement settlement = State.Settlements.Get(settlementId); if (hideoutRecord == null || settlement == null || hideoutRecord.Stage != "chief") { return null; } LegendDef legendDef = ChiefLegend(hideoutRecord); StoryPrompt obj = new StoryPrompt { Kind = "hideout", SubjectId = settlement.Id, Title = settlement.Name, Speaker = hideoutRecord.ChiefName, SpeakerRole = "Bandit chief", Lines = { "Your squad stands among the smoking tents. " + HideoutChiefDescription(settlement.Id) + ", looks you over.", (legendDef != null) ? "\"Not bad. Beat me yourself and I might even work for you.\"" : "\"You'll not have my purse without a fight.\"" } }; Hero playerHero = State.PlayerHero; obj.Options.Add(new StoryOption { Id = "duel", Text = "Face " + hideoutRecord.ChiefName + " alone.", Reason = ((playerHero == null || !playerHero.CanFight) ? "You're too hurt to fight a duel." : ""), Hint = "You against the chief, one to one." + ((legendDef != null) ? " Win and they join you." : " Win and their purse is yours.") }); List heroes; int num = SurvivingSquad(hideoutRecord, out heroes).Values.Sum() + heroes.Count; obj.Options.Add(new StoryOption { Id = "fight", Text = "Fight on together. (" + num + " of your squad)", Reason = ((num == 0) ? "None of your squad can fight on." : ""), Hint = "Your survivors against the chief and a few bodyguards." }); obj.Options.Add(new StoryOption { Id = "release", Text = "Let them run.", Hint = "The camp is yours; the chief gets away." }); return obj; } public CommandResult ChooseHideoutOption(string settlementId, string option) { HideoutRecord hideoutRecord = Hideout(settlementId); Settlement settlement = State.Settlements.Get(settlementId); StoryPrompt storyPrompt = HideoutPrompt(settlementId); if (storyPrompt == null) { return CommandResult.Fail("Nothing to decide here."); } StoryOption storyOption = storyPrompt.Options.FirstOrDefault((StoryOption x) => x.Id == option); if (storyOption == null) { return CommandResult.Fail("That choice is not open."); } if (!storyOption.Enabled) { return CommandResult.Fail(storyOption.Reason); } if (option == "release") { return CommandResult.Success(ClearHideout(hideoutRecord, settlement, chiefBeaten: false, hideoutRecord.ChiefName + " runs for the woods.")); } Clan clan = State.Clans.Get(settlement.BanditClanId); Party party = new Party { Id = State.Ids.Allocate("gang"), Name = hideoutRecord.ChiefName, Kind = PartyKind.Bandit, ClanId = (clan?.Id ?? ""), HomeSettlementId = settlement.Id, Position = settlement.Position, State = PartyState.Active, Morale = 70.0, AiFrozen = true, HideoutGuardOf = settlement.Id, CreatedAtMinute = State.Clock.Minute }; party.Troops.Add(hideoutRecord.ChiefUnitId, 1); IDictionary troops; List heroes; if (option == "duel") { troops = new Dictionary(); heroes = new List { State.PlayerHeroId }; } else { troops = SurvivingSquad(hideoutRecord, out heroes); RandomStream randomStream = new RandomStream("hideout.guards|" + settlement.Id + "|" + hideoutRecord.Generation.ToString(CultureInfo.InvariantCulture), State.Random.Seed); if (clan != null && clan.BanditTroops?.Count > 0) { List weights = clan.BanditTroops.Select((WeightedUnit w) => w.Weight).ToList(); int num = 0; for (int num2 = randomStream.Range(2, 5); num < num2; num++) { int num3 = randomStream.PickWeighted(weights); if (num3 >= 0) { party.Troops.Add(clan.BanditTroops[num3].Unit, 1); } } } } State.Parties.Add(party); hideoutRecord.Stage = ""; Encounter encounter = BeginHideoutEncounter(settlement, party, "chief", troops, heroes); C.Raise(CampaignEventKind.EncounterStarted, (option == "duel") ? (hideoutRecord.ChiefName + " accepts your challenge.") : (hideoutRecord.ChiefName + " calls the last of the gang."), true, encounter.Id, settlement.Id); return CommandResult.Success(); } internal void DailyHideouts() { if (State.Hideouts == null || !State.Hideouts.Started) { return; } foreach (HideoutRecord item in State.Hideouts.Records.OrderBy((HideoutRecord r) => r.SettlementId, StringComparer.Ordinal)) { Settlement settlement = State.Settlements.Get(item.SettlementId); if (settlement == null || item.Stage == "chief") { continue; } if (!settlement.HideoutActive) { if (item.ResettleDay >= 0 && State.Clock.Day >= item.ResettleDay) { MoveInGang(item, settlement); if (item.Found) { string text = "A new gang has moved into " + settlement.Name + "."; State.AddLog(LogCategory.Info, text, settlement.Id); C.Raise(CampaignEventKind.Info, text, false, settlement.Id); } State.Touch(); } continue; } Party party = State.Parties.Get(item.GuardPartyId); if (party != null && !string.IsNullOrEmpty(party.EncounterId)) { continue; } Clan clan = State.Clans.Get(settlement.BanditClanId); if (clan?.BanditTroops == null || clan.BanditTroops.Count == 0) { continue; } if (party == null || party.State == PartyState.Destroyed || party.State == PartyState.Disbanded) { party = new Party { Id = State.Ids.Allocate("gang"), Name = "The gang of " + settlement.Name, Kind = PartyKind.Bandit, ClanId = clan.Id, HomeSettlementId = settlement.Id, Position = settlement.Position, State = PartyState.InSettlement, CurrentSettlementId = settlement.Id, Morale = 60.0, AiFrozen = true, HideoutGuardOf = settlement.Id, CreatedAtMinute = State.Clock.Minute }; party.Troops.Add(clan.BanditTroops[0].Unit, 4); State.Parties.Add(party); item.GuardPartyId = party.Id; State.Touch(); } else { if (State.Clock.Day % 2 != 0L || party.Troops.TotalTroops >= 22) { continue; } RandomStream randomStream = new RandomStream("hideout.grow|" + settlement.Id + "|" + State.Clock.Day.ToString(CultureInfo.InvariantCulture), State.Random.Seed); List weights = clan.BanditTroops.Select((WeightedUnit w) => w.Weight).ToList(); int num = randomStream.PickWeighted(weights); if (num >= 0) { party.Troops.Add(clan.BanditTroops[num].Unit, 1); } foreach (TroopStack item2 in party.Troops.Stacks.ToList()) { if (item2.Wounded > 0) { party.Troops.Heal(item2.UnitId, Math.Max(1, item2.Wounded / 3)); } } State.Touch(); } } } } internal sealed class HorseLifeSystem { private readonly Campaign C; private NavGrid Nav => C.Nav; private CampaignRules Rules => C.Rules; private CampaignState State => C.State; internal HorseLifeSystem(Campaign host) { C = host; } internal int Footmen(Party p) { int num = 0; foreach (TroopStack stack in p.Troops.Stacks) { if ((C.UnitDef(stack.UnitId)?.MapSpeed ?? 1.0) <= 1.0) { UnitDef unitDef = C.UnitDef(stack.UnitId); if (unitDef == null || !unitDef.Mounted) { num += stack.Healthy; } } } return num; } public HerdSummary Herd(Party p) { HerdSummary herdSummary = new HerdSummary(); if (p == null) { return herdSummary; } List list = C.PartyHorses(p).ToList(); herdSummary.Horses = list.Count; herdSummary.People = p.Troops.TotalTroops + p.Troops.Heroes.Count; if (list.Count == 0) { return herdSummary; } List riders = C.PresentClanHeroes(p).Where(C.HeroRides).ToList(); herdSummary.Riders = riders.Count; int num = p.Troops.Heroes.Select((string id) => State.Heroes.Get(id)).Count((Hero h) => h != null && h.State == HeroState.Active && Campaign.IsPresentPartyHero(p, h) && !riders.Contains(h)); herdSummary.Footmen = Footmen(p) + num; List list2 = (from h in list.Where(C.SpareRidingHorse) orderby C.HorseCurrentStats(h).Speed descending select h).ThenBy((HorseState h) => h.Id, StringComparer.Ordinal).ToList(); herdSummary.Remounted = Math.Min(list2.Count, herdSummary.Footmen); double num2 = 0.0; foreach (Hero item in riders) { HorseState horseState = C.HeroMount(item); num2 += Horses.MapSpeedFactor(C.HorseCurrentStats(horseState).Speed, horseState.Fatigue) - 1.0; } double num3 = 0.0; for (int num4 = 0; num4 < herdSummary.Remounted; num4++) { num3 += Horses.MapSpeedFactor(C.HorseCurrentStats(list2[num4]).Speed, list2[num4].Fatigue) - 1.0; } if (C.PartyHasRidingPerk(p, "perk.riding.remount")) { num3 *= 1.5; } num2 += num3; if (herdSummary.People > 0) { herdSummary.SpeedFactor = Math.Max(0.9, Math.Min(1.0 + Rules.MountedBonusMax, 1.0 + num2 / (double)herdSummary.People)); } if (riders.Count > 0 && riders.Any((Hero h) => C.HasHeroPerk(h, "perk.riding.trail_rider"))) { herdSummary.SpeedFactor *= 1.03; } herdSummary.Loose = Math.Max(0, list.Count - herdSummary.Riders - herdSummary.Remounted); herdSummary.HerdingFactor = Horses.HerdingFactor(herdSummary.Loose, herdSummary.People); foreach (HorseState item2 in list) { HorseBreedDef horseBreedDef = Campaign.BreedOf(item2); if (horseBreedDef != null) { bool num5 = item2.Injury == HorseInjury.None || item2.Injury == HorseInjury.Bruised; if (horseBreedDef.Kind == HorseKind.Pack) { herdSummary.PackAnimals++; } double num6 = ((C.HorseAge(item2) >= Horses.WorkingAge(horseBreedDef.Kind)) ? 1 : 0); if (num5 && num6 > 0.0) { herdSummary.PackCapacity += ((horseBreedDef.Kind == HorseKind.Pack) ? horseBreedDef.PackCapacity : ((double)(C.SpareRidingHorse(item2) ? 4 : 0))); } herdSummary.FeedNeed += horseBreedDef.Feed * ((C.HorseAge(item2) < 2.0) ? 0.6 : 1.0); } } if (C.PartyHasRidingPerk(p, "perk.riding.packmaster")) { herdSummary.PackCapacity *= 1.2; } if (C.PartyHasRidingPerk(p, "perk.riding.forager")) { herdSummary.FeedNeed *= 0.7; } herdSummary.Grazing = ((p.State == PartyState.InSettlement) ? 0.6 : ((list.Count == 0) ? 0.0 : list.Average((HorseState h) => Horses.Grazing(Nav.TerrainAt(p.Position).Type, Campaign.BreedOf(h))))); herdSummary.FeedFromFood = herdSummary.FeedNeed * (1.0 - herdSummary.Grazing); return herdSummary; } internal void HorseSpeedFactors(Party p, Action factor) { if (p != null && C.PartyHorses(p).Any()) { HerdSummary herdSummary = Herd(p); factor("Horses: " + herdSummary.Riders + " riding, " + herdSummary.Remounted + " remounted", herdSummary.SpeedFactor); factor("Herding " + herdSummary.Loose + " loose animals", herdSummary.HerdingFactor); } } public double HorseCargoCapacity(Party p) { if (p != null && State.Horses?.Horses != null && C.PartyHorses(p).Any()) { return Herd(p).PackCapacity; } return 0.0; } internal bool PartyMarching(Party p) { if (p != null && p.State == PartyState.Active && string.IsNullOrEmpty(p.EncounterId) && p.Order.Kind != OrderKind.None && p.Order.Kind != OrderKind.Hold && p.Order.HasPath) { return p.WaitUntilMinute <= State.Clock.Minute; } return false; } internal IEnumerable PartiesWithHorses() { IEnumerable enumerable = State.Horses?.Horses?.Values; return (from id in (from h in enumerable ?? Enumerable.Empty() where h != null && h.Place == HorsePlace.Party select h.PlaceId).Distinct().OrderBy((string id) => id, StringComparer.Ordinal) select State.Parties.Get(id) into p where p != null && p.ClanId == State.PlayerClanId && p.State != PartyState.Destroyed && p.State != PartyState.Disbanded select p).ToList(); } internal void HourlyHorses() { HorsesState horses = State.Horses; if (horses?.Horses == null || horses.Horses.Count == 0) { return; } if (horses.TravelRidingDay != State.Clock.Day) { horses.TravelRidingToday.Clear(); horses.TravelRidingDay = State.Clock.Day; } foreach (Party item in PartiesWithHorses()) { HourlyHerd(item); } } internal void HourlyHerd(Party p) { HorsesState horses = State.Horses; List list = C.PartyHorses(p).ToList(); if (list.Count == 0) { return; } bool marching = PartyMarching(p) && (p.Id != State.PlayerPartyId || State.Player.Activity == PlayerActivity.Travelling); HerdSummary herdSummary = Herd(p); HashSet working = new HashSet(); foreach (Hero item in C.PresentClanHeroes(p).Where(C.HeroRides)) { HorseState horseState = C.HeroMount(item); working.Add(horseState); if (marching) { horses.TravelRidingToday.TryGetValue(item.Id, out var value); double num = Math.Min(1.5, 40.0 - value); if (num > 0.0) { horses.TravelRidingToday[item.Id] = value + num; C.GrantSkillExperience(item, "riding", num * ((Campaign.BreedOf(horseState)?.Id == "breed.palfrey") ? 1.25 : 1.0)); } AddBond(horseState, item, 0.4); horseState.Experience += 1.0 * (C.HasHeroPerk(item, "perk.riding.trainer") ? 1.5 : 1.0); if (!C.HasHeroPerk(item, "perk.riding.endurance")) { horseState.Fatigue = Math.Min(1.0, horseState.Fatigue + Horses.FatiguePerHour(horseState.Stamina)); } } } if (marching) { foreach (HorseState item2 in (from h in list.Where(C.SpareRidingHorse) orderby C.HorseCurrentStats(h).Speed descending select h).ThenBy((HorseState h) => h.Id, StringComparer.Ordinal).Take(herdSummary.Remounted)) { working.Add(item2); item2.Fatigue = Math.Min(1.0, item2.Fatigue + Horses.FatiguePerHour(item2.Stamina) * 0.8); item2.Experience += 0.5; } } double num2 = 0.06 * (C.PartyHasRidingPerk(p, "perk.riding.groom") ? 1.3 : 1.0); foreach (HorseState item3 in list.Where((HorseState h) => !working.Contains(h) || !marching)) { if (item3.Fatigue > 0.0) { item3.Fatigue = Math.Max(0.0, item3.Fatigue - num2); } } } internal void AddBond(HorseState horse, Hero hero, double amount) { if (horse != null && hero != null && !(amount <= 0.0)) { if (horse.Bond == null) { horse.Bond = new SortedDictionary(StringComparer.Ordinal); } double num = (C.HasHeroPerk(hero, "perk.riding.horse_whisperer") ? 1.5 : 1.0) * (double)((!C.HasHeroPerk(hero, "perk.riding.born_in_the_saddle")) ? 1 : 2); horse.Bond[hero.Id] = Math.Round(Math.Min(100.0, C.HorseBond(horse, hero.Id) + amount * num), 3); } } internal void DailyHorses() { HorsesState horses = State.Horses; if (horses?.Horses == null || horses.LastDailyDay == State.Clock.Day) { return; } horses.LastDailyDay = State.Clock.Day; C.PruneHorseMarkets(); ReconcileHorseOwners(); RandomStream randomStream = State.Random.Get("horses"); foreach (Party item in PartiesWithHorses()) { FeedHerd(item); } bool flag = C.ClanHasRidingPerk("perk.riding.veterinarian"); foreach (HorseState item2 in C.ClanHorses().ToList()) { Hero hero = C.HorseRider(item2); foreach (string item3 in item2.Bond.Keys.ToList()) { if (hero != null && item3 == hero.Id && C.HeroRides(hero)) { continue; } double num = item2.Bond[item3] - 0.2; if (!(num <= 0.0)) { Hero hero2 = State.Heroes.Get(item3); if (hero2 == null || hero2.State != HeroState.Dead) { item2.Bond[item3] = Math.Round(num, 3); continue; } } item2.Bond.Remove(item3); } bool flag2 = item2.Place == HorsePlace.Stud; bool flag3 = flag2 || (item2.Place == HorsePlace.Party && C.PartyHasRidingPerk(State.Parties.Get(item2.PlaceId), "perk.riding.groom")); if (item2.Injury != HorseInjury.None) { if (item2.Injury == HorseInjury.Grave && !flag && randomStream.Chance(0.03)) { HorseDied(item2, item2.Name + " died of " + ((item2.Sex == HorseSex.Mare) ? "her" : "his") + " wounds."); continue; } int num2 = 1 + (flag ? 1 : 0) + (flag2 ? 1 : 0) + ((flag3 && randomStream.Chance(0.3)) ? 1 : 0); item2.InjuryDays = Math.Max(0, item2.InjuryDays - num2); if (item2.InjuryDays == 0) { item2.Injury = HorseInjury.None; } } if (flag2) { item2.Condition = Math.Min(1.0, item2.Condition + 0.1); item2.Fatigue = 0.0; item2.Experience += 2.0 * (C.ClanHasRidingPerk("perk.riding.trainer") ? 1.5 : 1.0); } double years = C.HorseAge(item2); if (randomStream.Chance(Horses.OldAgeDeathChance(years))) { HorseDied(item2, item2.Name + " died peacefully of old age at " + years.ToString("0", CultureInfo.InvariantCulture) + "."); } else if (item2.PregnantSinceDay >= 0 && State.Clock.Day - item2.PregnantSinceDay >= C.GestationDays()) { item2.PregnantSinceDay = -1L; item2.LastFoalDay = State.Clock.Day; Settlement settlement = State.Settlements.Get((item2.Place == HorsePlace.Stud) ? item2.PlaceId : ""); if (settlement != null) { HorseState horseState = C.Foal(item2, settlement); horses.Horses[horseState.Id] = horseState; string text = item2.Name + " foaled a " + ((horseState.Sex == HorseSex.Mare) ? "filly" : "colt") + ", " + horseState.Name + ", at " + settlement.Name + "."; State.AddLog(LogCategory.Economy, text, settlement.Id); C.Raise(CampaignEventKind.Info, text, false, settlement.Id); } else { State.AddLog(LogCategory.Economy, item2.Name + " lost her foal on the march. Mares in foal belong at a stud farm."); } item2.FoalSireTraits = new List(); } } PayStudUpkeep(); } internal void FeedHerd(Party p) { List list = C.PartyHorses(p).ToList(); if (list.Count == 0) { return; } HerdSummary herdSummary = Herd(p); double feedFromFood = herdSummary.FeedFromFood; double num = Math.Min(C.EatsCargoFood(p) ? C.FoodSupply(p) : Math.Max(0.0, p.Food), feedFromFood); if (C.EatsCargoFood(p)) { C.TakeFood(p, num); } else { p.Food = Math.Max(0.0, p.Food - num); } double num2 = ((feedFromFood <= 1E-09) ? 1.0 : (num / feedFromFood)); foreach (HorseState item in list) { double num3 = herdSummary.Grazing + (1.0 - herdSummary.Grazing) * num2; item.Condition = Math.Round(Math.Max(0.2, Math.Min(1.0, item.Condition + ((num3 >= 0.999) ? 0.05 : (-0.12 * (1.0 - num3))))), 3); } if (num2 < 0.999 && p.Id == State.PlayerPartyId) { C.Raise(CampaignEventKind.Warning, "Your horses are going hungry: the land gives them little and your food has run out.", false); } } internal void PayStudUpkeep() { foreach (StudFarmState item in State.Horses.StudFarms.ToList()) { if (item.LastUpkeepDay == State.Clock.Day) { continue; } item.LastUpkeepDay = State.Clock.Day; Settlement settlement = State.Settlements.Get(item.SettlementId); int num = C.StudHorses(item.SettlementId).Count(); long num2 = 15 + 2L * (long)num; if (-State.Transact(State.PlayerClan, -num2, LedgerAccount.Horses, "Stud farm upkeep at " + (settlement?.Name ?? item.SettlementId), allowPartial: true) >= num2) { continue; } foreach (HorseState item2 in C.StudHorses(item.SettlementId)) { item2.Condition = Math.Max(0.2, item2.Condition - 0.1); } } } internal void HorseFollows(Hero hero, Party from, Party to) { HorseState horseState = C.Horse(hero?.MountId); if (horseState != null && to != null && horseState.Place == HorsePlace.Party && (from == null || !(horseState.PlaceId != from.Id))) { horseState.PlaceId = to.Id; } } internal void ReuniteHorses(Party source, Party target) { if (source == null || target == null || source.Id == target.Id) { return; } foreach (HorseState item in C.PartyHorses(source).ToList()) { item.PlaceId = target.Id; } } internal void ReconcileHorseOwners() { foreach (Hero hero in State.Heroes) { if (!string.IsNullOrEmpty(hero.MountId)) { HorseState horseState = C.Horse(hero.MountId); if (horseState == null || horseState.Place == HorsePlace.Market || hero.ClanId != State.PlayerClanId || hero.State == HeroState.Dead) { hero.MountId = ""; } } } foreach (HorseState item in (from h in C.ClanHorses() where h.Place == HorsePlace.Party select h).ToList()) { Party party = State.Parties.Get(item.PlaceId); if (party == null || party.State == PartyState.Destroyed || party.ClanId != State.PlayerClanId) { HorseLost(item, item.Name + " was lost with " + (party?.Name ?? "its party") + "."); } } foreach (StudFarmState item2 in State.Horses.StudFarms.ToList()) { if (State.Settlements.Get(item2.SettlementId) == null) { State.Horses.StudFarms.Remove(item2); } } } internal void HorseDied(HorseState horse, string message) { RemoveHorse(horse); State.AddLog(LogCategory.Info, message); if (horse.Place != HorsePlace.Market) { C.Raise(CampaignEventKind.Info, message, false); } } internal void HorseLost(HorseState horse, string message) { RemoveHorse(horse); State.AddLog(LogCategory.Info, message); } internal void RemoveHorse(HorseState horse) { Hero hero = C.HorseRider(horse); if (hero != null) { hero.MountId = ""; } State.Horses.Horses.Remove(horse.Id); } internal void RaidStudFarm(Settlement village) { if (village == null || C.StudFarm(village.Id) == null) { return; } RandomStream rng = State.Random.Get("horses"); List list = (from _ in C.StudHorses(village.Id) where rng.Chance(0.3) select _).ToList(); foreach (HorseState item in list) { HorseLost(item, item.Name + " was driven off by raiders at " + village.Name + "."); } if (list.Count > 0) { C.Raise(CampaignEventKind.Warning, "Raiders drove off " + list.Count + " horse" + ((list.Count == 1) ? "" : "s") + " from your stud farm at " + village.Name + ".", false, village.Id); } } internal string SeizeHerd(Party source, ICollection keptRiders = null) { if (source == null) { return ""; } int num = 0; foreach (HorseState item in C.PartyHorses(source).ToList()) { Hero hero = C.HorseRider(item); if (hero == null || !(hero.PartyId == source.Id) || hero.State != HeroState.Active || (keptRiders != null && !keptRiders.Contains(hero.Id))) { HorseLost(item, item.Name + " was lost in the rout."); num++; } } if (num != 0) { return source.Name + " lost " + num + " horse" + ((num == 1) ? "" : "s") + " in the rout."; } return ""; } public MountSpec MountForBattle(Hero hero) { if (!C.HeroRides(hero)) { return C.LordMountForBattle(hero); } HorseState horseState = C.HeroMount(hero); HorseBreedDef horseBreedDef = Campaign.BreedOf(horseState); HorseStats horseStats = C.HorseCurrentStats(horseState); double num = C.HorseBond(horseState, hero.Id); double num2 = Math.Max(0, Math.Min(300, hero.Skill("riding"))); double num3 = 1.0 + num2 / 1000.0 + num / 2000.0 + (C.HasHeroPerk(hero, "perk.riding.nimble_rider") ? 0.05 : 0.0) + (C.HasHeroPerk(hero, "perk.riding.war_rider") ? 0.1 : 0.0); double num4 = 1.0 - 0.3 * Math.Max(0.0, Math.Min(1.0, horseState.Fatigue)); return new MountSpec { HorseId = horseState.Id, Name = horseState.Name, BreedId = horseBreedDef.Id, Coat = horseState.Coat, Heavy = horseBreedDef.Heavy, Speed = Math.Round(horseStats.Speed * num3 * num4, 2), Manoeuvre = Math.Round(horseStats.Manoeuvre * num3, 2), Charge = Math.Round(horseStats.Charge * (C.HasHeroPerk(hero, "perk.riding.lancer") ? 1.15 : 1.0), 2), HitPoints = Math.Round(horseStats.HitPoints * (C.HasHeroPerk(hero, "perk.riding.cavalier") ? 1.1 : 1.0), 1), Size = horseBreedDef.Size, RiderHealthBonus = (C.HasHeroPerk(hero, "perk.riding.centaur") ? 0.1 : 0.0) }; } internal void ApplyHorseBattleOutcome(Combatant c, CombatOutcome heroOutcome, CombatOutcome mountOutcome, bool heroCaptured, bool heroDied, bool won, bool simulated, RandomStream rng, List lines, Party captor = null) { MountSpec mountSpec = c?.Mount; Hero hero = State.Heroes.Get(c?.HeroId ?? ""); HorseState horseState = C.Horse(mountSpec?.HorseId); if ((horseState == null && C.LordHorsesSystem.ApplyLordHorseOutcome(c, heroOutcome, mountOutcome, heroCaptured, heroDied, simulated, captor, rng, lines)) || mountSpec == null || horseState == null || hero == null || horseState.Place == HorsePlace.Market || (!c.EverDeployed && heroOutcome != CombatOutcome.Downed)) { return; } double num = C.HorseBond(horseState, hero.Id); bool num2 = mountOutcome == CombatOutcome.Downed || (simulated && mountOutcome == CombatOutcome.Pending && rng.Chance((heroOutcome == CombatOutcome.Downed) ? 0.35 : 0.05)); if (!heroDied && !heroCaptured) { C.GrantSkillExperience(hero, "riding", (30.0 + (won ? 15.0 : 0.0)) * (double)((!C.HasHeroPerk(hero, "perk.riding.rough_rider")) ? 1 : 2)); AddBond(horseState, hero, 4.0); } horseState.Battles++; horseState.Experience += 25.0 * (C.HasHeroPerk(hero, "perk.riding.trainer") ? 1.5 : 1.0); horseState.Fatigue = Math.Min(1.0, horseState.Fatigue + 0.25); if (num2) { if (rng.Chance(Math.Max(0.15, 0.45 - num / 400.0))) { lines.Add(horseState.Name + ", " + hero.Name + "'s horse, was killed."); HorseDied(horseState, horseState.Name + " was killed in battle under " + hero.Name + "."); return; } bool flag = rng.Chance(0.4); Injure(horseState, flag ? HorseInjury.Grave : HorseInjury.Lame, flag ? rng.Range(20, 41) : rng.Range(8, 21), rng); lines.Add(horseState.Name + ", " + hero.Name + "'s horse, was " + (flag ? "gravely hurt" : "lamed") + "."); } else if (heroOutcome == CombatOutcome.Downed && rng.Chance(0.25)) { Injure(horseState, HorseInjury.Bruised, rng.Range(3, 8), rng); lines.Add(horseState.Name + " came out of the fight bruised."); } if (heroCaptured) { lines.Add(horseState.Name + " was taken with " + hero.Name + "."); HorseLost(horseState, horseState.Name + " was taken by the enemy with " + hero.Name + "."); } } internal static void Injure(HorseState horse, HorseInjury injury, int days, RandomStream rng) { if (injury <= horse.Injury) { horse.InjuryDays = Math.Max(horse.InjuryDays, days); return; } horse.Injury = injury; horse.InjuryDays = days; if (injury == HorseInjury.Grave && rng.Chance(0.25)) { switch (rng.Range(0, 3)) { case 0: horse.Speed = Math.Round(horse.Speed * 0.95, 2); break; case 1: horse.Manoeuvre = Math.Round(horse.Manoeuvre * 0.95, 2); break; default: horse.HitPoints = Math.Round(horse.HitPoints * 0.95, 1); break; } } } } internal sealed class HorseMarketsSystem { private readonly Campaign C; private NavGrid Nav => C.Nav; private CampaignState State => C.State; internal HorseMarketsSystem(Campaign host) { C = host; } public static bool IsHorseRanch(Settlement s) { if (s != null && s.Type == SettlementType.Village) { if (!(s.Product == "good.horses")) { if (string.IsNullOrEmpty(s.Product)) { return StableHash.Fnv1a64("horse-ranch:" + s.Id) % 5 == 0; } return false; } return true; } return false; } public static bool HasHorseMarket(Settlement s) { if (s != null) { if (s.Type != SettlementType.Town) { return IsHorseRanch(s); } return true; } return false; } public HorseBreedDef RanchBreed(Settlement village) { if (!IsHorseRanch(village)) { return null; } TerrainType type = Nav.TerrainAt(village.Position).Type; List list = Horses.Breeds.Where((HorseBreedDef b) => b.Kind != HorseKind.Pack && b.Cultures.Contains(village.CultureId)).ToList(); if (type == TerrainType.Desert) { list = list.Concat(Horses.Breeds.Where((HorseBreedDef b) => b.DesertGrazing > 1.5 && b.Kind != HorseKind.Pack)).Distinct().ToList(); } if (type == TerrainType.Snow) { list = list.Concat(Horses.Breeds.Where((HorseBreedDef b) => b.SnowGrazing > 1.5 && b.Kind != HorseKind.Pack)).Distinct().ToList(); } if (list.Count == 0) { list = Horses.Breeds.Where((HorseBreedDef b) => b.Id == "breed.rouncey" || b.Id == "breed.courser" || b.Id == "breed.steppe").ToList(); } list = list.OrderBy((HorseBreedDef b) => b.Id, StringComparer.Ordinal).ToList(); return list[(int)(StableHash.Fnv1a64("ranch:" + village.Id) % (ulong)list.Count)]; } internal IEnumerable BoundRanches(Settlement town) { return State.Settlements.Where((Settlement v) => IsHorseRanch(v) && v.BoundTo == town.Id); } internal static long MarketPeriod(long day) { return day / 7; } public int HorseMarketSize(Settlement s) { if (s == null) { return 0; } if (s.Type == SettlementType.Town) { int num = BoundRanches(s).Count((Settlement v) => !C.IsVillageBeingRaided(v) && (v.VillageRecovery?.Damage ?? 0) < 50); return Math.Min(9, 3 + 2 * num + ((s.Prosperity >= 3000.0) ? 1 : 0)); } if (!IsHorseRanch(s) || C.IsVillageBeingRaided(s)) { return 0; } double num2 = 1.0 - (double)Math.Max(0, Math.Min(100, s.VillageRecovery?.Damage ?? 0)) / 100.0; return (int)Math.Round(Math.Min(6.0, 2.0 + s.Prosperity / 250.0) * num2); } internal double HorseMarketMarkup(Settlement s) { return ((s.Type == SettlementType.Town) ? (1.15 - 0.05 * (double)Math.Min(3, BoundRanches(s).Count())) : 0.9) * (C.ClanHasRidingPerk("perk.riding.horse_trader") ? 0.9 : 1.0); } internal void RefreshHorseMarket(Settlement s) { HorsesState horses = State.Horses; long num = MarketPeriod(State.Clock.Day); if (horses.MarketPeriods.TryGetValue(s.Id, out var value) && value == num) { return; } foreach (string item in (from h in horses.Horses.Values where h.Place == HorsePlace.Market && h.PlaceId == s.Id select h.Id).ToList()) { horses.Horses.Remove(item); } RandomStream randomStream = new RandomStream("horses.market." + s.Id + "." + num.ToString(CultureInfo.InvariantCulture), State.Random.Seed); bool town = s.Type == SettlementType.Town; List ranchBreeds = (town ? (from b in BoundRanches(s).Select(RanchBreed) where b != null select b).ToList() : new List { RanchBreed(s) }); List weights = Horses.Breeds.Select(delegate(HorseBreedDef b) { double num5 = 0.15; if (b.Cultures.Contains(s.CultureId)) { num5 += 3.0; } num5 += (double)(ranchBreeds.Count((HorseBreedDef r) => r.Id == b.Id) * (town ? 4 : 8)); if (b.Kind == HorseKind.Pack && b.Cultures.Length == 0) { num5 = (town ? 1.2 : 0.8); } if (!town && b.Kind == HorseKind.War) { num5 *= 0.4; } return num5; }).ToList(); int num2 = HorseMarketSize(s); double num3 = Math.Max(0.0, Math.Min(1.0, s.Prosperity / 6000.0)); for (int num4 = 0; num4 < num2; num4++) { HorseBreedDef horseBreedDef = Horses.Breeds[Math.Max(0, randomStream.PickWeighted(weights))]; double ageYears = (town ? randomStream.Range(3.0, 10.0) : randomStream.Range(1.5, 8.0)); double qualityBias = (town ? (-0.01 + 0.05 * num3 * randomStream.NextDouble()) : (-0.02 + 0.06 * randomStream.NextDouble())); HorseState horseState = C.CreateHorse(horseBreedDef, randomStream, ageYears, qualityBias, (town ? "Bought at " : "Raised at ") + s.Name); horseState.Place = HorsePlace.Market; horseState.PlaceId = s.Id; horseState.StockPeriod = num; horseState.Condition = Math.Round(randomStream.Range(0.85, 1.0), 3); if (town && horseBreedDef.Kind != HorseKind.Pack) { horseState.Experience = Math.Round(randomStream.Range(0.0, 320.0), 1); } horses.Horses[horseState.Id] = horseState; } horses.MarketPeriods[s.Id] = num; State.Touch(); } public List MarketHorses(string settlementId) { Settlement s = State.Settlements.Get(settlementId ?? ""); if (!HasHorseMarket(s) || State.Horses?.Horses == null) { return new List(); } RefreshHorseMarket(s); return (from h in State.Horses.Horses.Values where h.Place == HorsePlace.Market && h.PlaceId == s.Id orderby Campaign.BreedOf(h)?.Kind select h).ThenByDescending(C.HorseValue).ThenBy((HorseState h) => h.Id, StringComparer.Ordinal).ToList(); } internal void PruneHorseMarkets() { HorsesState horses = State.Horses; long num = MarketPeriod(State.Clock.Day); foreach (KeyValuePair entry in horses.MarketPeriods.ToList()) { if (entry.Value >= num - 1 && State.Settlements.Contains(entry.Key)) { continue; } foreach (string item in (from h in horses.Horses.Values where h.Place == HorsePlace.Market && h.PlaceId == entry.Key select h.Id).ToList()) { horses.Horses.Remove(item); } horses.MarketPeriods.Remove(entry.Key); } } public string HorseMarketReason() { string text = C.DisguiseBlockReason(); if (text.Length > 0) { return text; } string text2 = C.CargoCommandReason(); if (text2.Length > 0) { return text2; } Party playerParty = State.PlayerParty; if (!string.IsNullOrEmpty(State.Player.PendingEncounterId) || !string.IsNullOrEmpty(playerParty.EncounterId) || C.MilitaryPartyReserved(playerParty.Id)) { return "Deal with the encounter first."; } Settlement settlement = C.CurrentSettlement(); if (!HasHorseMarket(settlement) || Vec2.Distance(playerParty.Position, settlement.Position) > 0.01 || !C.CanEnter(playerParty, settlement)) { return "Find a friendly town or horse ranch."; } if (settlement.Market == null) { return "This market is unavailable."; } return ""; } public long HorseBuyPrice(HorseState horse) { Settlement settlement = State.Settlements.Get(horse?.PlaceId ?? ""); if (horse != null && settlement != null) { return Math.Max(1L, (long)Math.Round((double)C.HorseValue(horse) * HorseMarketMarkup(settlement))); } return 0L; } public long HorseSalePrice(HorseState horse) { if (horse != null) { return Math.Max(1L, (long)Math.Round((double)C.HorseValue(horse) * (C.ClanHasRidingPerk("perk.riding.horse_trader") ? 0.7 : 0.55))); } return 0L; } public HorseTradeQuote QuoteHorsePurchase(string horseId) { HorseState horseState = C.Horse(horseId); HorseTradeQuote horseTradeQuote = new HorseTradeQuote { Total = HorseBuyPrice(horseState), Reason = HorseMarketReason() }; if (!horseTradeQuote.Ok) { return horseTradeQuote; } Settlement settlement = C.CurrentSettlement(); if (horseState == null || horseState.Place != HorsePlace.Market || horseState.PlaceId != settlement.Id) { horseTradeQuote.Reason = "Not for sale here."; } else if (State.PlayerClan.Gold < horseTradeQuote.Total) { horseTradeQuote.Reason = "Not enough denars."; } else if (settlement.Market.Gold > long.MaxValue - horseTradeQuote.Total) { horseTradeQuote.Reason = "The seller can't hold any more money."; } return horseTradeQuote; } public CommandResult BuyHorse(string horseId) { HorseTradeQuote horseTradeQuote = QuoteHorsePurchase(horseId); if (!horseTradeQuote.Ok) { return CommandResult.Fail(horseTradeQuote.Reason); } HorseState horseState = C.Horse(horseId); Settlement settlement = C.CurrentSettlement(); horseState.Place = HorsePlace.Party; horseState.PlaceId = State.PlayerPartyId; horseState.AcquiredDay = State.Clock.Day; settlement.Market.Gold += horseTradeQuote.Total; string text = "Bought " + horseState.Name + ", a " + C.HorseAge(horseState).ToString("0", CultureInfo.InvariantCulture) + "-year-old " + C.BreedName(horseState).ToLowerInvariant() + ", for " + horseTradeQuote.Total.ToString("N0", CultureInfo.InvariantCulture) + " denars at " + settlement.Name + "."; State.Transact(State.PlayerClan, -horseTradeQuote.Total, LedgerAccount.Horses, text); State.AddLog(LogCategory.Economy, text, settlement.Id); State.Touch(); return CommandResult.Success(text); } public HorseTradeQuote QuoteHorseSale(string horseId) { HorseState horseState = C.Horse(horseId); HorseTradeQuote horseTradeQuote = new HorseTradeQuote { Total = HorseSalePrice(horseState), Reason = HorseMarketReason() }; if (!horseTradeQuote.Ok) { return horseTradeQuote; } Settlement settlement = C.CurrentSettlement(); if (horseState == null || horseState.Place != HorsePlace.Party || horseState.PlaceId != State.PlayerPartyId) { horseTradeQuote.Reason = "You can only sell horses in your herd."; } else if (horseState.PregnantSinceDay >= 0) { horseTradeQuote.Reason = horseState.Name + " is in foal. Keep her until the foal is born."; } else if (settlement.Market.Gold < horseTradeQuote.Total) { horseTradeQuote.Reason = "The " + ((settlement.Type == SettlementType.Town) ? "horse traders" : "ranchers") + " cannot afford " + horseState.Name + "."; } else if (State.PlayerClan.Gold > long.MaxValue - horseTradeQuote.Total) { horseTradeQuote.Reason = "Your treasury's full."; } return horseTradeQuote; } public CommandResult SellHorse(string horseId) { HorseTradeQuote horseTradeQuote = QuoteHorseSale(horseId); if (!horseTradeQuote.Ok) { return CommandResult.Fail(horseTradeQuote.Reason); } HorseState horseState = C.Horse(horseId); Settlement settlement = C.CurrentSettlement(); Hero hero = C.HorseRider(horseState); if (hero != null) { hero.MountId = ""; } RefreshHorseMarket(settlement); horseState.Place = HorsePlace.Market; horseState.PlaceId = settlement.Id; horseState.StockPeriod = MarketPeriod(State.Clock.Day); horseState.Bond.Clear(); settlement.Market.Gold -= horseTradeQuote.Total; string text = "Sold " + horseState.Name + " for " + horseTradeQuote.Total.ToString("N0", CultureInfo.InvariantCulture) + " denars at " + settlement.Name + "."; State.Transact(State.PlayerClan, horseTradeQuote.Total, LedgerAccount.Horses, text); State.AddLog(LogCategory.Economy, text, settlement.Id); State.Touch(); return CommandResult.Success(text); } public StudFarmState StudFarm(string settlementId) { return State.Horses?.StudFarms?.FirstOrDefault((StudFarmState f) => f.SettlementId == settlementId); } public int StudCapacity() { return 6 + (C.ClanHasRidingPerk("perk.riding.stud_master") ? 4 : 0); } public IEnumerable StudHorses(string settlementId) { if (State.Horses?.Horses != null) { return State.Horses.Horses.Values.Where((HorseState h) => h.Place == HorsePlace.Stud && h.PlaceId == settlementId); } return Enumerable.Empty(); } internal string StudVisitReason(string settlementId) { string text = HorseMarketReason(); if (text.Length > 0) { return text; } Settlement settlement = C.CurrentSettlement(); if (settlement == null || settlement.Id != settlementId) { return "Go to the stud farm's village."; } if (StudFarm(settlementId) != null) { return ""; } return "You don't own a stud farm here."; } public string BuyStudFarmReason() { string text = HorseMarketReason(); if (text.Length > 0) { return text; } Settlement settlement = C.CurrentSettlement(); if (!IsHorseRanch(settlement)) { return "Stud farms are bought at horse-ranch villages."; } if (StudFarm(settlement.Id) != null) { return "You already own this one."; } if (State.PlayerClan.Gold < 4000) { return "A stud farm costs " + 4000L.ToString("N0", CultureInfo.InvariantCulture) + " denars."; } return ""; } public CommandResult BuyStudFarm() { string text = BuyStudFarmReason(); if (text.Length > 0) { return CommandResult.Fail(text); } Settlement settlement = C.CurrentSettlement(); State.Horses.StudFarms.Add(new StudFarmState { SettlementId = settlement.Id, PurchasePrice = 4000L, BoughtDay = State.Clock.Day, LastUpkeepDay = State.Clock.Day }); string text2 = "Bought the stud farm at " + settlement.Name + " for " + 4000L.ToString("N0", CultureInfo.InvariantCulture) + " denars."; State.Transact(State.PlayerClan, -4000L, LedgerAccount.Horses, text2); State.AddLog(LogCategory.Economy, text2, settlement.Id); State.Touch(); return CommandResult.Success(text2 + " Leave horses here to rest, train and breed."); } public string SellStudFarmReason(string settlementId) { string text = StudVisitReason(settlementId); if (text.Length > 0) { return text; } if (!StudHorses(settlementId).Any()) { return ""; } return "Take every horse out of the stud farm first."; } public CommandResult SellStudFarm(string settlementId) { string text = SellStudFarmReason(settlementId); if (text.Length > 0) { return CommandResult.Fail(text); } StudFarmState studFarmState = StudFarm(settlementId); long amount = studFarmState.PurchasePrice / 2; State.Horses.StudFarms.Remove(studFarmState); Settlement settlement = State.Settlements.Require(settlementId); string text2 = "Sold the stud farm at " + settlement.Name + " for " + amount.ToString("N0", CultureInfo.InvariantCulture) + " denars."; State.Transact(State.PlayerClan, amount, LedgerAccount.Horses, text2); State.AddLog(LogCategory.Economy, text2, settlement.Id); State.Touch(); return CommandResult.Success(text2); } public string StableAtStudReason(string horseId) { HorseState horseState = C.Horse(horseId); Settlement settlement = C.CurrentSettlement(); string text = StudVisitReason(settlement?.Id ?? ""); if (text.Length > 0) { return text; } if (horseState == null || horseState.Place != HorsePlace.Party || horseState.PlaceId != State.PlayerPartyId) { return "Pick a horse from your herd."; } if (StudHorses(settlement.Id).Count() >= StudCapacity()) { return "The stud farm is full (" + StudCapacity() + " horses)."; } return ""; } public CommandResult StableAtStud(string horseId) { string text = StableAtStudReason(horseId); if (text.Length > 0) { return CommandResult.Fail(text); } HorseState horseState = C.Horse(horseId); Settlement settlement = C.CurrentSettlement(); Hero hero = C.HorseRider(horseState); if (hero != null) { hero.MountId = ""; } horseState.Place = HorsePlace.Stud; horseState.PlaceId = settlement.Id; State.Touch(); return CommandResult.Success(horseState.Name + " was left at the stud farm."); } public string TakeFromStudReason(string horseId) { HorseState horseState = C.Horse(horseId); if (horseState == null || horseState.Place != HorsePlace.Stud) { return "Pick a horse at a stud farm."; } return StudVisitReason(horseState.PlaceId); } public CommandResult TakeFromStud(string horseId) { string text = TakeFromStudReason(horseId); if (text.Length > 0) { return CommandResult.Fail(text); } HorseState horseState = C.Horse(horseId); horseState.Place = HorsePlace.Party; horseState.PlaceId = State.PlayerPartyId; State.Touch(); return CommandResult.Success(horseState.Name + " joined your party's herd."); } public int GestationDays() { return (int)Math.Round(77.0 * (C.ClanHasRidingPerk("perk.riding.stud_master") ? 0.75 : 1.0)); } public string BreedReason(string mareId, string stallionId) { HorseState horseState = C.Horse(mareId); HorseState horseState2 = C.Horse(stallionId); if (horseState == null || horseState.Place != HorsePlace.Stud) { return "Pick a mare at your stud farm."; } string text = StudVisitReason(horseState.PlaceId); if (text.Length > 0) { return text; } if (horseState2 == null || horseState2.Place != HorsePlace.Stud || horseState2.PlaceId != horseState.PlaceId) { return "Pick a stallion at the same stud farm."; } if (horseState.Sex != HorseSex.Mare) { return horseState.Name + " is not a mare."; } if (horseState2.Sex != HorseSex.Stallion) { return horseState2.Name + " is not a stallion."; } if (horseState.PregnantSinceDay >= 0) { return horseState.Name + " is already in foal."; } double num = C.HorseAge(horseState); double num2 = C.HorseAge(horseState2); if (num < 3.0 || num > 20.0) { return horseState.Name + " must be between 3 and 20 years old to foal."; } if (num2 < 3.0 || num2 > 22.0) { return horseState2.Name + " must be between 3 and 22 years old to sire foals."; } if (horseState.LastFoalDay >= 0 && State.Clock.Day - horseState.LastFoalDay < 30) { return horseState.Name + " needs " + (30 - (State.Clock.Day - horseState.LastFoalDay)) + " more days of rest after her last foal."; } if (horseState.Injury == HorseInjury.Grave || horseState2.Injury == HorseInjury.Grave) { return "Neither can be gravely hurt."; } if (horseState.SireId == horseState2.Id || horseState2.SireId == horseState.Id || horseState.DamId == horseState2.Id || horseState2.DamId == horseState.Id || (horseState.SireId.Length > 0 && horseState.SireId == horseState2.SireId) || (horseState.DamId.Length > 0 && horseState.DamId == horseState2.DamId)) { return "Your grooms will not breed such close relatives."; } return ""; } public CommandResult BreedHorses(string mareId, string stallionId) { string text = BreedReason(mareId, stallionId); if (text.Length > 0) { return CommandResult.Fail(text); } HorseState horseState = C.Horse(mareId); HorseState horseState2 = C.Horse(stallionId); horseState.PregnantSinceDay = State.Clock.Day; horseState.FoalSireId = horseState2.Id; horseState.FoalSireName = horseState2.Name; horseState.FoalSireBreedId = horseState2.BreedId; horseState.FoalSireTraits = new List { horseState2.Speed, horseState2.Manoeuvre, horseState2.Charge, horseState2.HitPoints, horseState2.Stamina, horseState2.Temperament, horseState2.Coat }; string text2 = horseState.Name + " is in foal to " + horseState2.Name + ". The foal is due in about " + GestationDays() + " days."; State.AddLog(LogCategory.Economy, text2, horseState.PlaceId); State.Touch(); return CommandResult.Success(text2); } internal HorseState Foal(HorseState mare, Settlement stud) { RandomStream rng = State.Random.Get("horses"); List traits = mare.FoalSireTraits ?? new List(); HorseBreedDef horseBreedDef = Horses.Breed(mare.FoalSireBreedId) ?? Campaign.BreedOf(mare); double bias = (C.ClanHasRidingPerk("perk.riding.breeder") ? 0.04 : 0.0); HorseBreedDef horseBreedDef2 = Campaign.BreedOf(mare); int num = (int)Trait(6, mare.Coat); double num2 = rng.NextDouble(); return new HorseState { Id = C.NewHorseId(), Name = Horses.RandomName(rng), BreedId = horseBreedDef2.Id, CrossBreedId = ((horseBreedDef.Id != horseBreedDef2.Id) ? horseBreedDef.Id : (mare.CrossBreedId ?? "")), Sex = ((!rng.Chance(0.5)) ? HorseSex.Mare : HorseSex.Stallion), Coat = ((num2 < 0.45) ? mare.Coat : ((num2 < 0.9) ? num : horseBreedDef2.Coats[rng.Range(0, horseBreedDef2.Coats.Length)])), BornDay = State.Clock.Day, Speed = Child(mare.Speed, Trait(0, horseBreedDef.Speed), (horseBreedDef2.Speed + horseBreedDef.Speed) / 2.0), Manoeuvre = Child(mare.Manoeuvre, Trait(1, horseBreedDef.Manoeuvre), (horseBreedDef2.Manoeuvre + horseBreedDef.Manoeuvre) / 2.0), Charge = Child(mare.Charge, Trait(2, horseBreedDef.Charge), (horseBreedDef2.Charge + horseBreedDef.Charge) / 2.0), HitPoints = Math.Round(Child(mare.HitPoints, Trait(3, horseBreedDef.HitPoints), (horseBreedDef2.HitPoints + horseBreedDef.HitPoints) / 2.0), 1), Stamina = Math.Min(100.0, Child(mare.Stamina, Trait(4, horseBreedDef.Stamina), (horseBreedDef2.Stamina + horseBreedDef.Stamina) / 2.0)), Temperament = Math.Max(0, Math.Min(100, (int)Math.Round(((double)mare.Temperament + Trait(5, horseBreedDef.Temperament)) / 2.0 + Campaign.Gaussian(rng) * 8.0))), Place = HorsePlace.Stud, PlaceId = stud.Id, Condition = 1.0, AcquiredDay = State.Clock.Day, SireId = (mare.FoalSireId ?? ""), DamId = mare.Id, SireName = (mare.FoalSireName ?? ""), DamName = mare.Name, Origin = "Bred at " + stud.Name }; double Child(double dam, double sire, double breedMean) { return Math.Round(Math.Max(breedMean * 0.7, Math.Min(breedMean * 1.35, (dam + sire) / 2.0 * (1.0 + bias + 0.05 * Campaign.Gaussian(rng)))), 2); } double Trait(int i, double fallback) { if (i >= traits.Count) { return fallback; } return traits[i]; } } } internal sealed class HorsesSystem { private readonly Campaign C; private CampaignState State => C.State; internal HorsesSystem(Campaign host) { C = host; } public void EnsureHorseFields() { bool flag = false; if (State.Horses == null) { State.Horses = new HorsesState(); flag = true; } HorsesState horses = State.Horses; if (horses.Horses == null) { horses.Horses = new SortedDictionary(StringComparer.Ordinal); flag = true; } if (horses.StudFarms == null) { horses.StudFarms = new List(); flag = true; } if (horses.MarketPeriods == null) { horses.MarketPeriods = new SortedDictionary(StringComparer.Ordinal); flag = true; } if (horses.TravelRidingToday == null) { horses.TravelRidingToday = new SortedDictionary(StringComparer.Ordinal); flag = true; } foreach (HorseState value in horses.Horses.Values) { if (value != null) { if (value.Bond == null) { value.Bond = new SortedDictionary(StringComparer.Ordinal); flag = true; } if (value.FoalSireTraits == null) { value.FoalSireTraits = new List(); flag = true; } } } foreach (Hero hero in State.Heroes) { if (hero.MountId == null) { hero.MountId = ""; flag = true; } } if (!horses.RidingInitialized) { foreach (Hero hero2 in State.Heroes) { if (hero2.Skills != null && !hero2.Skills.ContainsKey("riding") && (hero2.ClanId == State.PlayerClanId || hero2.Occupation == HeroOccupation.Companion)) { hero2.Skills["riding"] = 15; } } horses.RidingInitialized = true; flag = true; } if (flag) { State.Touch(); } } public HorseState Horse(string id) { if (string.IsNullOrEmpty(id) || State.Horses?.Horses == null || !State.Horses.Horses.TryGetValue(id, out var value)) { return null; } return value; } public static HorseBreedDef BreedOf(HorseState horse) { return Horses.Breed(horse?.BreedId ?? ""); } public string BreedName(HorseState horse) { HorseBreedDef horseBreedDef = BreedOf(horse); HorseBreedDef horseBreedDef2 = Horses.Breed(horse?.CrossBreedId ?? ""); if (horseBreedDef != null) { if (horseBreedDef2 != null && !(horseBreedDef2.Id == horseBreedDef.Id)) { return horseBreedDef.Name + " × " + horseBreedDef2.Name; } return horseBreedDef.Name; } return "Unknown breed"; } public double HorseAge(HorseState horse) { return Horses.AgeYears(horse, State.Clock.Day); } public int HorseLevel(HorseState horse) { return Horses.TrainingLevel(horse?.Experience ?? 0.0); } public double HorseBond(HorseState horse, string heroId) { if (horse?.Bond == null || heroId == null || !horse.Bond.TryGetValue(heroId, out var value)) { return 0.0; } return Math.Max(0.0, Math.Min(100.0, value)); } public static double HorseQualityRatio(HorseState horse) { HorseBreedDef horseBreedDef = BreedOf(horse); if (horseBreedDef == null) { return 1.0; } return (horse.Speed / horseBreedDef.Speed + horse.Manoeuvre / horseBreedDef.Manoeuvre + horse.Charge / Math.Max(1.0, horseBreedDef.Charge) + horse.HitPoints / horseBreedDef.HitPoints + horse.Stamina / Math.Max(1.0, horseBreedDef.Stamina)) / 5.0; } public static string HorseQuality(HorseState horse) { return Horses.QualityName(HorseQualityRatio(horse)); } public HorseStats HorseCurrentStats(HorseState horse) { if (horse == null) { return new HorseStats(); } double num = Horses.AgeFactor(HorseAge(horse)); double num2 = Horses.ConditionFactor(horse.Condition, horse.Injury); double num3 = Horses.TrainingBonus(HorseLevel(horse)); return new HorseStats { Speed = horse.Speed * num * num2 * (1.0 + (num3 - 1.0) * 0.5), Manoeuvre = horse.Manoeuvre * num * num2 * num3, Charge = horse.Charge * num * num2 * num3, HitPoints = horse.HitPoints * num * num2, Stamina = horse.Stamina * num * num2 }; } public int HorseDifficulty(HorseState horse, Hero rider) { return Horses.Difficulty(BreedOf(horse), horse?.Temperament ?? 50, HorseLevel(horse), HorseBond(horse, rider?.Id), rider != null && C.HasHeroPerk(rider, "perk.riding.steady_seat")); } public Hero HorseRider(HorseState horse) { if (horse == null) { return null; } foreach (Hero hero in State.Heroes) { if (hero.MountId == horse.Id && hero.ClanId == State.PlayerClanId && hero.State != HeroState.Dead) { return hero; } } return null; } public IEnumerable PartyHorses(Party party) { if (party != null && State.Horses?.Horses != null) { return State.Horses.Horses.Values.Where((HorseState h) => h != null && h.Place == HorsePlace.Party && h.PlaceId == party.Id); } return Enumerable.Empty(); } public IEnumerable ClanHorses() { if (State.Horses?.Horses != null) { return State.Horses.Horses.Values.Where((HorseState h) => h != null && h.Place != HorsePlace.Market); } return Enumerable.Empty(); } public HorseState HeroMount(Hero hero) { HorseState horseState = Horse(hero?.MountId); if (horseState == null || horseState.Place != HorsePlace.Party || !(horseState.PlaceId == hero.PartyId)) { return null; } return horseState; } public string HorseRideReason(HorseState horse, Hero hero) { HorseBreedDef horseBreedDef = BreedOf(horse); if (horse == null || horseBreedDef == null) { return "Unknown horse."; } if (horseBreedDef.Kind == HorseKind.Pack) { return horse.Name + " is a pack animal, not a warhorse."; } double num = HorseAge(horse); if (num < Horses.WorkingAge(horseBreedDef.Kind)) { return horse.Name + " is too young to ride (" + num.ToString("0.#", CultureInfo.InvariantCulture) + " years)."; } if (!Horses.Rideable(horse.Injury)) { return horse.Name + " is " + Horses.InjuryName(horse.Injury).ToLowerInvariant() + " (" + horse.InjuryDays + " days)."; } if (hero != null && !RidingArchetype(hero)) { return hero.Name + "'s archetype cannot ride."; } int num2 = HorseDifficulty(horse, hero); if (hero != null && !C.HasHeroPerk(hero, "perk.riding.born_in_the_saddle") && hero.Skill("riding") < num2) { return hero.Name + " needs " + num2 + " Riding for " + horse.Name + " (has " + hero.Skill("riding") + ")."; } return ""; } public bool RidingArchetype(Hero hero) { UnitDef unitDef = C.UnitDef(hero?.UnitId ?? ""); if (unitDef != null && EquipmentCatalog.SupportsArchetype(unitDef)) { return Campaign.SupportsWardrobe(unitDef); } return false; } public bool HeroRides(Hero hero) { if (hero == null || hero.Dismounted || hero.ClanId != State.PlayerClanId) { return false; } HorseState horseState = HeroMount(hero); if (horseState != null) { return HorseRideReason(horseState, hero).Length == 0; } return false; } internal bool SpareRidingHorse(HorseState horse) { HorseBreedDef horseBreedDef = BreedOf(horse); if (horseBreedDef != null && horseBreedDef.Kind != HorseKind.Pack && HorseAge(horse) >= Horses.WorkingAge(horseBreedDef.Kind) && Horses.Rideable(horse.Injury)) { return !HeroRidesHorse(horse); } return false; } internal bool HeroRidesHorse(HorseState horse) { Hero hero = HorseRider(horse); if (hero != null && HeroMount(hero) == horse) { return HeroRides(hero); } return false; } public long HorseValue(HorseState horse) { HorseBreedDef horseBreedDef = BreedOf(horse); if (horseBreedDef == null) { return 0L; } double num = Math.Pow(Math.Max(0.5, HorseQualityRatio(horse)), 2.5); double num2 = HorseAge(horse); double num3 = ((num2 < 1.0) ? 0.35 : ((num2 < 2.0) ? 0.55 : ((num2 < 3.0) ? 0.8 : ((num2 <= 12.0) ? 1.0 : ((num2 <= 16.0) ? 0.75 : ((num2 <= 20.0) ? 0.5 : 0.3)))))); double num4 = 1.0 + 0.12 * (double)HorseLevel(horse); double num5 = ((horseBreedDef.Kind == HorseKind.War) ? 1.0 : (1.0 - (double)Math.Max(0, horse.Temperament - horseBreedDef.Temperament) / 200.0)); double num6 = ((horse.Sex == HorseSex.Stallion) ? 1.1 : ((horse.Sex == HorseSex.Mare) ? 1.05 : 1.0)); double num7 = ((horse.Injury == HorseInjury.None) ? 1.0 : ((horse.Injury == HorseInjury.Bruised) ? 0.9 : ((horse.Injury == HorseInjury.Lame) ? 0.6 : 0.35))); double num8 = 0.8 + 0.2 * Math.Max(0.0, Math.Min(1.0, horse.Condition)); return Math.Max(10L, (long)Math.Round((double)horseBreedDef.BasePrice * num * num3 * num4 * num5 * num6 * num7 * num8)); } internal IEnumerable PresentClanHeroes(Party party) { if (party != null) { return from id in party.Troops.Heroes select State.Heroes.Get(id) into h where h != null && h.State == HeroState.Active && h.ClanId == State.PlayerClanId && Campaign.IsPresentPartyHero(party, h) select h; } return Enumerable.Empty(); } public bool PartyHasRidingPerk(Party party, string perk) { return PresentClanHeroes(party).Any((Hero h) => C.HasHeroPerk(h, perk)); } public bool ClanHasRidingPerk(string perk) { if (!PartyHasRidingPerk(State.PlayerParty, perk)) { if (State.PlayerHero != null) { return C.HasHeroPerk(State.PlayerHero, perk); } return false; } return true; } internal string HorseHeroReason(string heroId) { string text = C.CargoCommandReason(); if (text.Length > 0) { return text; } Party playerParty = State.PlayerParty; if (!string.IsNullOrEmpty(State.Player.PendingEncounterId) || !string.IsNullOrEmpty(playerParty.EncounterId) || C.MilitaryPartyReserved(playerParty.Id)) { return "Deal with the encounter first."; } Hero hero = State.Heroes.Get(heroId ?? ""); if (hero == null || hero.ClanId != State.PlayerClanId || (hero.Id != State.PlayerHeroId && !C.IsOwnedCompanion(hero))) { return "Pick yourself or a companion."; } if (hero.State != HeroState.Active || !Campaign.IsPresentPartyHero(playerParty, hero)) { return "This hero has to be with your party."; } return ""; } public string AssignMountReason(string heroId, string horseId) { string text = HorseHeroReason(heroId); if (text.Length > 0) { return text; } Hero hero = State.Heroes.Require(heroId); HorseState horseState = Horse(horseId); if (horseState == null || horseState.Place != HorsePlace.Party || horseState.PlaceId != State.PlayerPartyId) { return "Pick a horse from your herd."; } if (hero.MountId == horseState.Id) { return hero.Name + " already rides " + horseState.Name + "."; } return HorseRideReason(horseState, hero); } public CommandResult AssignMount(string heroId, string horseId) { string text = AssignMountReason(heroId, horseId); if (text.Length > 0) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Require(heroId); HorseState horseState = Horse(horseId); Hero hero2 = HorseRider(horseState); if (hero2 != null) { hero2.MountId = ""; } hero.MountId = horseState.Id; hero.Dismounted = false; string text2 = hero.Name + " now rides " + horseState.Name + ((hero2 != null && hero2 != hero) ? (" (taken from " + hero2.Name + ")") : "") + "."; State.AddLog(LogCategory.Info, text2, hero.Id); State.Touch(); return CommandResult.Success(text2); } public string UnassignMountReason(string heroId) { string text = HorseHeroReason(heroId); if (text.Length > 0) { return text; } if (!string.IsNullOrEmpty(State.Heroes.Require(heroId).MountId)) { return ""; } return "This hero has no horse."; } public CommandResult UnassignMount(string heroId) { string text = UnassignMountReason(heroId); if (text.Length > 0) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Require(heroId); HorseState horseState = Horse(hero.MountId); hero.MountId = ""; string msg = hero.Name + " returned " + (horseState?.Name ?? "their horse") + " to the herd."; State.Touch(); return CommandResult.Success(msg); } public string SetRidingReason(string heroId, bool ride) { string text = HorseHeroReason(heroId); if (text.Length > 0) { return text; } Hero hero = State.Heroes.Require(heroId); if (string.IsNullOrEmpty(hero.MountId)) { return "Give this hero a horse first."; } if (ride == !hero.Dismounted) { if (!ride) { return hero.Name + " already goes on foot."; } return hero.Name + " already rides."; } return ""; } public CommandResult SetHeroRiding(string heroId, bool ride) { string text = SetRidingReason(heroId, ride); if (text.Length > 0) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Require(heroId); hero.Dismounted = !ride; State.Touch(); return CommandResult.Success(ride ? (hero.Name + " will ride.") : (hero.Name + " will go on foot and lead their horse.")); } internal static string CleanHorseName(string name, string fallback) { string text = new string((name ?? "").Where((char ch) => !char.IsControl(ch)).ToArray()).Trim(); if (text.Length == 0) { return fallback; } if (text.Length <= 24) { return text; } return text.Substring(0, 24).Trim(); } public string RenameHorseReason(string horseId, string name) { HorseState horseState = Horse(horseId); if (horseState == null || horseState.Place == HorsePlace.Market) { return "Choose one of your horses."; } if (CleanHorseName(name, "").Length == 0) { return "Enter a name."; } if (CleanHorseName(name, "") == horseState.Name) { return horseState.Name + " already has this name."; } return ""; } public CommandResult RenameHorse(string horseId, string name) { string text = RenameHorseReason(horseId, name); if (text.Length > 0) { return CommandResult.Fail(text); } HorseState horseState = Horse(horseId); string name2 = horseState.Name; horseState.Name = CleanHorseName(name, horseState.Name); State.Touch(); return CommandResult.Success(name2 + " is now called " + horseState.Name + "."); } public string GeldReason(string horseId) { HorseState horseState = Horse(horseId); if (horseState == null || horseState.Place == HorsePlace.Market) { return "Choose one of your horses."; } if (horseState.Sex != HorseSex.Stallion) { return "Only stallions can be gelded."; } if (horseState.Place == HorsePlace.Party && horseState.PlaceId != State.PlayerPartyId) { return "That horse is with another party."; } if (horseState.Place != HorsePlace.Stud) { return HorseHeroReason(State.PlayerHeroId); } return C.StudVisitReason(horseState.PlaceId); } public CommandResult GeldHorse(string horseId) { string text = GeldReason(horseId); if (text.Length > 0) { return CommandResult.Fail(text); } HorseState horseState = Horse(horseId); horseState.Sex = HorseSex.Gelding; horseState.Temperament = Math.Max(0, horseState.Temperament - 15); State.Touch(); return CommandResult.Success(horseState.Name + " was gelded. He is calmer now."); } internal string NewHorseId() { return "horse." + State.Horses.NextHorseNumber++.ToString(CultureInfo.InvariantCulture); } internal static double Gaussian(RandomStream rng) { double d = Math.Max(1E-12, rng.NextDouble()); double num = rng.NextDouble(); return Math.Sqrt(-2.0 * Math.Log(d)) * Math.Cos(Math.PI * 2.0 * num); } internal static double Vary(double mean, double spread, double bias, RandomStream rng) { return Math.Max(mean * 0.7, Math.Min(mean * 1.3, mean * (1.0 + bias + spread * Gaussian(rng)))); } internal HorseState CreateHorse(HorseBreedDef breed, RandomStream rng, double ageYears, double qualityBias, string origin, bool assignId = true) { double num = rng.NextDouble(); HorseState horseState = new HorseState { Id = (assignId ? NewHorseId() : ""), Name = Horses.RandomName(rng), BreedId = breed.Id, Sex = ((!(num < 0.3)) ? ((num < 0.65) ? HorseSex.Mare : HorseSex.Gelding) : HorseSex.Stallion), Coat = breed.Coats[rng.Range(0, breed.Coats.Length)], BornDay = State.Clock.Day - (long)Math.Round(ageYears * 84.0), Speed = Math.Round(Vary(breed.Speed, breed.Spread, qualityBias, rng), 2), Manoeuvre = Math.Round(Vary(breed.Manoeuvre, breed.Spread, qualityBias, rng), 2), Charge = Math.Round(Vary(breed.Charge, breed.Spread * 1.3, qualityBias, rng), 2), HitPoints = Math.Round(Vary(breed.HitPoints, breed.Spread, qualityBias, rng), 1), Stamina = Math.Round(Math.Min(100.0, Vary(breed.Stamina, breed.Spread, qualityBias, rng)), 2), Temperament = Math.Max(0, Math.Min(100, breed.Temperament + (int)Math.Round(Gaussian(rng) * 10.0))), Condition = 1.0, AcquiredDay = State.Clock.Day, Origin = (origin ?? "") }; if (horseState.Sex == HorseSex.Gelding) { horseState.Temperament = Math.Max(0, horseState.Temperament - 10); } return horseState; } } internal sealed class KeepSystem { private readonly Campaign C; private CampaignState State => C.State; internal KeepSystem(Campaign host) { C = host; } public static bool HasKeep(Settlement s) { if (s != null) { if (s.Type != SettlementType.Town) { return s.Type == SettlementType.Castle; } return true; } return false; } public string KeepFreeAccessReason(Settlement s) { if (s == null) { return ""; } if (!HasKeep(s)) { return "There is no keep here."; } Clan playerClan = State.PlayerClan; if (playerClan == null) { return ""; } if (s.OwnerClanId == playerClan.Id) { return "This is your clan's " + ((s.Type == SettlementType.Town) ? "town" : "castle") + "."; } Clan clan = State.Clans.Get(s.OwnerClanId); if (clan != null && !string.IsNullOrEmpty(playerClan.KingdomId) && clan.KingdomId == playerClan.KingdomId) { return clan.Name + " is of your realm."; } return ""; } public bool HasKeepAccess(Settlement s) { if (s == null) { return false; } if (!HasKeep(s)) { return true; } if (C.InDisguise && C.CurrentSettlement()?.Id == s.Id) { return false; } if (KeepFreeAccessReason(s).Length > 0) { return true; } if (State.Player.KeepAccessSettlementId == s.Id) { return C.CurrentSettlement()?.Id == s.Id; } return false; } public long KeepBribeCost(Settlement s) { if (s == null) { return 0L; } double num = Math.Max(0.0, s.Prosperity); return (long)(Math.Round(((s.Type == SettlementType.Town) ? (150.0 + num * 0.05) : (100.0 + num * 0.03)) / 10.0) * 10.0); } public string KeepBribeReason() { string text = C.DisguiseBlockReason(); if (text.Length > 0) { return text; } CommandResult commandResult = C.RequireFree(); if (!commandResult.Ok) { return commandResult.Message; } Settlement settlement = C.CurrentSettlement(); if (settlement == null || State.Player.Activity != PlayerActivity.InSettlement) { return "You're not in a town or castle."; } if (!HasKeep(settlement)) { return "There is no keep here."; } if (HasKeepAccess(settlement)) { return "You're already in."; } if (C.IsSettlementBesieged(settlement)) { return "The keep's shut during the siege."; } Clan clan = State.Clans.Get(settlement.OwnerClanId); if (clan != null && State.AreHostile(State.PlayerClan, clan)) { return "An enemy's guards won't take a bribe."; } long num = KeepBribeCost(settlement); if ((State.PlayerClan?.Gold ?? 0) < num) { return "You need " + num.ToString("N0") + " denars to bribe the guards."; } return ""; } public CommandResult BribeKeepGuards() { string text = KeepBribeReason(); if (text.Length > 0) { return CommandResult.Fail(text); } Settlement settlement = C.CurrentSettlement(); long num = KeepBribeCost(settlement); State.Transact(State.PlayerClan, -num, LedgerAccount.Other, "Bribed the keep guards at " + settlement.Name); State.Player.KeepAccessSettlementId = settlement.Id; State.AddLog(LogCategory.Info, "Bribed the guards of " + settlement.Name + "'s keep (" + num.ToString("N0") + " denars).", settlement.Id); State.Touch(); return CommandResult.Success("The guards take your " + num.ToString("N0") + " denars and let you into the keep."); } } internal sealed class KingdomArmyAiSystem { private readonly Campaign C; private NavGrid Nav => C.Nav; private CampaignRules Rules => C.Rules; private CampaignState State => C.State; internal KingdomArmyAiSystem(Campaign host) { C = host; } internal bool KingdomArmyAwaitingRelease(Party party) { if (party != null && C.ClanArmyContains(party.Id) && State.ClanArmy.Members.Any((ClanArmyMember member) => member.KingdomCall && member.PartyId == party.Id)) { if (C.IsKingdomArmyParty(party)) { return !C.ClanArmyPlayerAvailable(); } return true; } return false; } internal void KingdomArmyOptions(Party party, Clan clan, double strength, List<(Party party, double strength, double dist)> hostiles, List options) { Party player = State.PlayerParty; if (C.IsKingdomArmyParty(party) && player != null && State.Player.Activity != PlayerActivity.Captive) { Hero playerHero = State.PlayerHero; if (playerHero != null && playerHero.State == HeroState.Active) { C.AddFleeOrFight(party, strength, hostiles, options, canEngage: false); if (hostiles.Any(((Party party, double strength, double dist) h) => strength / Math.Max(0.01, h.strength) < Rules.FleeStrengthRatio)) { return; } List source = (from s in C.MilitaryFriendlySettlements(party) orderby Vec2.Distance(party.Position, s.Position) select s).ThenBy((Settlement s) => s.Id, StringComparer.Ordinal).ToList(); bool flag = C.IsMergedIntoArmy(party); if (C.FoodSupply(party) < C.DailyFoodNeed(party) * (flag ? 0.5 : 1.5) && clan != null && clan.Gold > 50) { Settlement market = source.FirstOrDefault((Settlement s) => C.SettlementFood(s) > 0.0 && KingdomArmyFoodBudget(clan, s) > 0); if (market != null) { options.Add(new Campaign.AiOption { Task = "Supply army party", Score = 3.0, Detail = market.Name + "; paid by " + clan.Name, Apply = delegate { KingdomArmyGoOrWait(party, market); } }); } } Hero hero = State.Heroes.Get(party.LeaderHeroId); if ((hero == null || !hero.CanFight) && !flag) { Settlement refuge = source.FirstOrDefault((Settlement s) => s.Type == SettlementType.Town || s.Type == SettlementType.Castle); options.Add(new Campaign.AiOption { Task = "Recover army captain", Score = 2.0, Detail = (refuge?.Name ?? "No friendly refuge"), Apply = delegate { KingdomArmyGoOrWait(party, refuge); } }); return; } if (player.State == PartyState.InSettlement) { Settlement place = State.Settlements.Get(player.CurrentSettlementId); bool accessible = place != null && C.CanEnter(party, place) && Nav.SameComponent(party.Position, place.Position); options.Add(new Campaign.AiOption { Task = (accessible ? ("Join army at " + place.Name) : "Wait for army"), Score = 1.0, Detail = (accessible ? "physical rendezvous" : "commander's destination is inaccessible"), Apply = delegate { KingdomArmyGoOrWait(party, accessible ? place : null); } }); return; } options.Add(new Campaign.AiOption { Task = "Follow army commander", Score = 1.0, Detail = "known position of the army commander", Apply = delegate { if (party.Order.Kind != OrderKind.Follow || party.Order.TargetId != player.Id) { C.SetMoveOrder(party, OrderKind.Follow, player.Position, player.Id, "kingdom army rendezvous"); } } }); return; } } options.Add(new Campaign.AiOption { Task = "Await army release", Score = 1.0, Detail = "army battle cleanup pending", Apply = delegate { C.ClearOrder(party); } }); } internal void KingdomArmyGoOrWait(Party party, Settlement destination) { if (destination == null) { C.ClearOrder(party); } else if (party.State == PartyState.InSettlement && party.CurrentSettlementId == destination.Id) { KingdomArmySettlementArrival(party, destination); C.ClearOrder(party); } else if (party.Order.Kind != OrderKind.GoToSettlement || party.Order.TargetId != destination.Id) { C.SetMoveOrder(party, OrderKind.GoToSettlement, destination.Position, destination.Id, "kingdom army rendezvous"); } } internal long KingdomArmyFoodBudget(Clan clan, Settlement settlement) { if (clan != null && clan.Gold > 50 && settlement?.Market != null && settlement.Market.Initialized && settlement.Market.Gold >= 0) { return Math.Min(clan.Gold - 50, long.MaxValue - settlement.Market.Gold); } return 0L; } internal void KingdomArmySettlementArrival(Party party, Settlement settlement) { if (!C.IsKingdomArmyParty(party) || C.ClanArmyPartyReserved(party.Id) || party.State != PartyState.InSettlement || party.CurrentSettlementId != settlement?.Id || Vec2.Distance(party.Position, settlement.Position) > 0.01 || !C.CanEnter(party, settlement)) { return; } Clan clan = State.Clans.Get(party.ClanId); long num = KingdomArmyFoodBudget(clan, settlement); double num2 = C.DailyFoodNeed(party) * 4.0 - party.Food; double num3 = Math.Max(1.0, C.FoodPrice(settlement)); double num4 = C.SettlementFood(settlement); if (num > 0 && Campaign.MilitaryFinite(party.Food) && party.Food >= 0.0 && num4 > 0.0 && Campaign.MilitaryFinite(num2) && num2 > 0.0 && Campaign.MilitaryFinite(num3) && num3 <= 7.922816251426434E+28) { double val = (double)(decimal.Floor((decimal)num / (decimal)num3 * 1000000m) / 1000000m); double num5 = Math.Min(num2, Math.Min(num4, val)); if (num5 > 1E-09) { decimal num6 = decimal.Ceiling((decimal)num5 * (decimal)num3); double num7 = party.Food + num5 - party.Food; double num8 = num4 - (num4 - num7); if (num6 > 0m && num6 <= (decimal)num && num7 > 0.0 && num7 <= num5 + 1E-09 && num8 > 0.0 && Math.Abs(num8 - num7) <= 1E-09) { long num9 = (long)num6; State.Transact(clan, -num9, LedgerAccount.Food, "Army supplies for " + party.Name + " at " + settlement.Name); settlement.Market.Gold += num9; party.Food += C.TakeSettlementFood(settlement, num7); State.Touch(); } } } party.WaitUntilMinute = State.Clock.Minute + 60; } } internal sealed class KingdomArmySystem { private readonly Campaign C; private bool IsBattleFrozen => C.IsBattleFrozen; private NavGrid Nav => C.Nav; private CampaignState State => C.State; internal KingdomArmySystem(Campaign host) { C = host; } internal bool KingdomArmyWar(string kingdomId) { if (!string.IsNullOrEmpty(kingdomId)) { return State.Stances.Any((StanceRecord s) => s.Stance == Stance.War && ((s.A == kingdomId && C.KnownDiplomacyFaction(s.B)) || (s.B == kingdomId && C.KnownDiplomacyFaction(s.A)))); } return false; } internal bool KingdomArmyAuthority(string kingdomId) { if (!string.IsNullOrEmpty(kingdomId) && State.PlayerClan?.KingdomId == kingdomId) { return C.CouncilMember(kingdomId, State.PlayerClanId); } return false; } internal bool KingdomArmyMemberAvailable(Party party, ClanArmyMember member) { if (member == null || !member.KingdomCall || party == null || party.Id != member.PartyId || !Campaign.ClanArmyLiveParty(party, member.OwnerClanId) || party.Kind != PartyKind.Lord || party.LeaderHeroId != member.LeaderHeroId || member.OwnerClanId == State.PlayerClanId || !KingdomArmyAuthority(member.KingdomId) || !KingdomArmyWar(member.KingdomId)) { return false; } Clan clan = State.Clans.Get(member.OwnerClanId); Hero hero = State.Heroes.Get(member.LeaderHeroId); if (clan != null && !clan.IsEliminated && !clan.IsBandit && !clan.IsPlayerClan && clan.KingdomId == member.KingdomId && hero != null && hero.State == HeroState.Active && hero.ClanId == member.OwnerClanId) { return Campaign.IsPresentPartyHero(party, hero); } return false; } public bool IsKingdomArmyParty(Party party) { ClanArmyState clanArmy = State.ClanArmy; if (party == null || clanArmy == null || !clanArmy.Active || clanArmy.OwnerClanId != State.PlayerClanId || clanArmy.LeaderPartyId != State.PlayerPartyId) { return false; } ClanArmyMember member = clanArmy.Members?.FirstOrDefault((ClanArmyMember m) => m.PartyId == party.Id && m.KingdomCall); return KingdomArmyMemberAvailable(party, member); } public int KingdomArmyGuestInfluence(Party party) { if (party != null) { return Math.Max(2, (int)Math.Ceiling((double)C.PartyCombatants(party) / 25.0)); } return 2; } public long KingdomArmyDaysServed(string partyId) { return KingdomArmyDaysRemaining(partyId); } public long KingdomArmyDaysRemaining(string partyId) { ClanArmyMember clanArmyMember = State.ClanArmy?.Members?.FirstOrDefault((ClanArmyMember m) => m.PartyId == partyId && m.KingdomCall); if (clanArmyMember != null) { return Math.Max(0L, State.Clock.Day - clanArmyMember.CalledDay); } return 0L; } internal string KingdomArmyDepartureReason(Party party, ClanArmyMember member) { if (!KingdomArmyAuthority(member.KingdomId)) { return "your kingdom command authority ended."; } if (State.Clans.Get(member.OwnerClanId)?.KingdomId != member.KingdomId) { return "its clan's allegiance changed."; } if (!KingdomArmyWar(member.KingdomId)) { return "the kingdom is at peace."; } return "its captain or warband is gone."; } public KingdomArmyCallQuote QuoteKingdomArmyCall(string partyId) { Party party = State.Parties.Get(partyId); KingdomArmyCallQuote kingdomArmyCallQuote = new KingdomArmyCallQuote { PartyId = (partyId ?? ""), OwnerClanId = (party?.ClanId ?? ""), LeaderHeroId = (party?.LeaderHeroId ?? ""), KingdomId = (State.PlayerClan?.KingdomId ?? ""), LeaderPartyId = State.PlayerPartyId, InfluenceCost = 20, DailyInfluence = KingdomArmyGuestInfluence(party), ServiceDays = 0 }; kingdomArmyCallQuote.Reason = C.CargoCommandReason(); if (!kingdomArmyCallQuote.Ok) { return kingdomArmyCallQuote; } ClanArmyState clanArmy = State.ClanArmy; Clan clan = State.Clans.Get(party?.ClanId); Hero hero = State.Heroes.Get(party?.LeaderHeroId); if (!C.ClanArmyPlayerAvailable() || !State.PlayerHero.CanFight) { kingdomArmyCallQuote.Reason = "Your commander has to be fit and free to lead."; } else if (!KingdomArmyAuthority(kingdomArmyCallQuote.KingdomId)) { kingdomArmyCallQuote.Reason = "Only sworn vassals and rulers can call kingdom warbands."; } else if (!KingdomArmyWar(kingdomArmyCallQuote.KingdomId)) { kingdomArmyCallQuote.Reason = "Kingdom warbands only come when your kingdom is at war."; } else if (clanArmy == null || clanArmy.Members == null) { kingdomArmyCallQuote.Reason = "Armies are unavailable."; } else if (!string.IsNullOrEmpty(State.Player.PendingEncounterId) || C.ClanArmyPartyReserved(State.PlayerPartyId) || C.ClanArmyBattleReserved()) { kingdomArmyCallQuote.Reason = "Wait for every army party's fighting to finish."; } else if (!clanArmy.Active && (!Campaign.MilitaryFinite(clanArmy.Cohesion) || clanArmy.Cohesion < 20.0 || clanArmy.Members.Count != 0)) { kingdomArmyCallQuote.Reason = "Get cohesion back to 20 and finish the last army's orders first."; } else if (clanArmy.Active && (clanArmy.OwnerClanId != State.PlayerClanId || clanArmy.LeaderPartyId != State.PlayerPartyId)) { kingdomArmyCallQuote.Reason = "Your commander isn't leading this army."; } else if (party == null || party.Kind != PartyKind.Lord || clan == null || clan.Id == State.PlayerClanId || clan.IsPlayerClan || clan.IsBandit || clan.IsEliminated || clan.KingdomId != kingdomArmyCallQuote.KingdomId || C.MilitaryPartyFor(party) != null) { kingdomArmyCallQuote.Reason = "Pick another clan's lord party from your kingdom."; } else if ((party.State != PartyState.Active && party.State != PartyState.InSettlement) || party.AiFrozen || hero == null || !hero.CanFight || hero.ClanId != clan.Id || !Campaign.IsPresentPartyHero(party, hero)) { kingdomArmyCallQuote.Reason = "Its captain has to be fit, free and there."; } else if (C.ClanArmyPartyReserved(party.Id)) { kingdomArmyCallQuote.Reason = "It has to finish its fight first."; } else if (C.ClanArmyContains(party.Id)) { kingdomArmyCallQuote.Reason = "This warband is already in your army."; } else if (clanArmy.Members.Count((ClanArmyMember m) => m.KingdomCall) >= 3 || clanArmy.Members.Count >= 5) { kingdomArmyCallQuote.Reason = "All three allied places are taken."; } else if (party.ActiveRaid != null || party.Order.Kind == OrderKind.Raid || party.Order.Kind == OrderKind.Besiege || State.Sieges.Any((SiegeState s) => s.BesiegerPartyId == party.Id && s.Stage != SiegeStage.Ended)) { kingdomArmyCallQuote.Reason = "It has a raid or siege to finish first."; } else if (C.ClanRelation(State.PlayerClanId, clan.Id) < 0) { kingdomArmyCallQuote.Reason = "Settle your feud with this clan first."; } else if (!Nav.IsPassable(State.PlayerParty.Position) || !Nav.IsPassable(party.Position) || !Nav.SameComponent(State.PlayerParty.Position, party.Position)) { kingdomArmyCallQuote.Reason = "It can't reach your commander."; } else if (!Campaign.MilitaryFinite(State.PlayerClan.Influence) || State.PlayerClan.Influence < 20.0) { kingdomArmyCallQuote.Reason = "Calling a warband costs " + 20 + " influence."; } else if (State.Clock.Day > 9223372036854775800L) { kingdomArmyCallQuote.Reason = "Service cannot be recorded at this date."; } return kingdomArmyCallQuote; } internal bool KingdomArmyOfferMatches(KingdomArmyCallQuote a, KingdomArmyCallQuote b) { if (a != null && b != null && a.PartyId == b.PartyId && a.OwnerClanId == b.OwnerClanId && a.LeaderHeroId == b.LeaderHeroId && a.KingdomId == b.KingdomId && a.LeaderPartyId == b.LeaderPartyId && a.InfluenceCost == b.InfluenceCost && a.DailyInfluence == b.DailyInfluence) { return a.ServiceDays == b.ServiceDays; } return false; } public CommandResult CallKingdomArmyParty(string partyId, KingdomArmyCallQuote expectedQuote = null) { KingdomArmyCallQuote kingdomArmyCallQuote = QuoteKingdomArmyCall(partyId); if (!kingdomArmyCallQuote.Ok) { return CommandResult.Fail(kingdomArmyCallQuote.Reason); } if (expectedQuote != null && !KingdomArmyOfferMatches(expectedQuote, kingdomArmyCallQuote)) { return CommandResult.Fail("The warband or terms changed. Check the call again."); } ClanArmyState clanArmy = State.ClanArmy; Party party = State.Parties.Require(partyId); State.PlayerClan.Influence -= 20.0; if (!clanArmy.Active) { clanArmy.Active = true; clanArmy.Id = State.Ids.Allocate("army"); clanArmy.OwnerClanId = State.PlayerClanId; clanArmy.LeaderPartyId = State.PlayerPartyId; clanArmy.StartedMinute = State.Clock.Minute; } clanArmy.Members.Add(new ClanArmyMember { PartyId = party.Id, KingdomCall = true, OwnerClanId = kingdomArmyCallQuote.OwnerClanId, LeaderHeroId = kingdomArmyCallQuote.LeaderHeroId, KingdomId = kingdomArmyCallQuote.KingdomId, CalledDay = State.Clock.Day, EndsDay = State.Clock.Day + 7, LastSupportDay = State.Clock.Day }); clanArmy.Members.Sort((ClanArmyMember a, ClanArmyMember b) => string.CompareOrdinal(a.PartyId, b.PartyId)); C.WakeClanArmyParty(party); string text = party.Name + " answered your call. " + 20 + " influence spent; " + KingdomArmyGuestInfluence(party) + " influence every dawn after, for as long as it serves. It's on its way to your commander."; State.AddLog(LogCategory.Politics, text, clanArmy.Id, party.Id, party.ClanId); State.Touch(); return CommandResult.Success(text); } public string KingdomArmyReleaseReason(string partyId) { string text = C.ClanArmyActionReason("", "disband"); if (text.Length > 0) { return text; } if (!State.ClanArmy.Members.Any((ClanArmyMember m) => m.PartyId == partyId && m.KingdomCall)) { return "This warband isn't answering your call."; } return ""; } internal void RemoveKingdomArmyMember(ClanArmyMember member) { C.RestoreClanArmyMember(member); State.ClanArmy.Members.Remove(member); } public CommandResult ReleaseKingdomArmyParty(string partyId) { string text = KingdomArmyReleaseReason(partyId); if (text.Length > 0) { return CommandResult.Fail(text); } ClanArmyState clanArmy = State.ClanArmy; ClanArmyMember member = clanArmy.Members.First((ClanArmyMember m) => m.PartyId == partyId && m.KingdomCall); RemoveKingdomArmyMember(member); string text2 = (State.Parties.Get(partyId)?.Name ?? "The allied warband") + " went back to its own orders. It keeps its men and goods; the influence spent is gone."; State.AddLog(LogCategory.Politics, text2, clanArmy.Id, partyId); if (clanArmy.Members.Count == 0) { C.EndClanArmy("The last supporting warband was released.", notify: false); } State.Touch(); return CommandResult.Success(text2); } public void DailyKingdomArmySupport() { ClanArmyState clanArmy = State.ClanArmy; if (clanArmy == null || !clanArmy.Active || C.ClanArmyBattleReserved() || IsBattleFrozen || !string.IsNullOrEmpty(State.Player.PendingEncounterId)) { return; } C.ReconcileClanArmy(); if (!clanArmy.Active) { return; } List list = clanArmy.Members.Where((ClanArmyMember m) => m.KingdomCall && m.LastSupportDay < State.Clock.Day).ToList(); if (list.Count == 0) { return; } int num = list.Sum((ClanArmyMember m) => KingdomArmyGuestInfluence(State.Parties.Get(m.PartyId))); if (!Campaign.MilitaryFinite(State.PlayerClan.Influence) || State.PlayerClan.Influence < (double)num) { foreach (ClanArmyMember item in clanArmy.Members.Where((ClanArmyMember m) => m.KingdomCall).ToList()) { RemoveKingdomArmyMember(item); } string text = "Your allied warbands left: the army couldn't pay " + num + " influence in daily support. Nothing was taken."; State.AddLog(LogCategory.Politics, text, clanArmy.Id); C.Raise(CampaignEventKind.Warning, text, true, clanArmy.Id); if (clanArmy.Members.Count == 0) { C.EndClanArmy("Couldn't pay for kingdom support.", notify: false); } } else { State.PlayerClan.Influence -= num; foreach (ClanArmyMember item2 in list) { item2.LastSupportDay = State.Clock.Day; } } State.Touch(); } public string RallyArmyReason() { string text = C.ClanArmyActionReason("", "disband"); if (text.Length > 0) { return text; } if (!State.PlayerHero.CanFight) { return "Let your commander recover before rallying the army."; } if (!Campaign.MilitaryFinite(State.ClanArmy.Cohesion) || State.ClanArmy.Cohesion >= 100.0) { return "The army's cohesion is already full."; } if (State.ClanArmy.LastRallyDay >= State.Clock.Day) { return "Your commander has already rallied an army today."; } if (Campaign.MilitaryFinite(State.PlayerClan.Influence) && !(State.PlayerClan.Influence < 10.0)) { return ""; } return "Rallying the army costs " + 10 + " influence."; } public CommandResult RallyArmy() { string text = RallyArmyReason(); if (text.Length > 0) { return CommandResult.Fail(text); } State.PlayerClan.Influence -= 10.0; State.ClanArmy.Cohesion = Math.Min(100.0, State.ClanArmy.Cohesion + 20.0); State.ClanArmy.LastRallyDay = State.Clock.Day; string text2 = "Your commander rallied the army for " + 10 + " influence. Cohesion is " + State.ClanArmy.Cohesion.ToString("0") + "."; State.AddLog(LogCategory.Politics, text2, State.ClanArmy.Id); State.Touch(); return CommandResult.Success(text2); } } internal sealed class KingdomsSystem { private readonly Campaign C; private CampaignState State => C.State; internal KingdomsSystem(Campaign host) { C = host; } internal string KingdomCourtReason() { string text = C.CargoCommandReason(); if (text.Length > 0) { return text; } Clan playerClan = State.PlayerClan; Hero playerHero = State.PlayerHero; Party playerParty = State.PlayerParty; if (playerClan.IsEliminated || playerClan.IsBandit) { return "Your clan can't hold court."; } if (playerHero == null || !playerHero.CanFight || playerHero.ClanId != playerClan.Id || playerClan.LeaderHeroId != playerHero.Id || playerParty.LeaderHeroId != playerHero.Id) { return "Your clan leader has to be fit and free to lead."; } if (!string.IsNullOrEmpty(State.Player.PendingEncounterId) || !string.IsNullOrEmpty(playerParty.EncounterId) || C.DiplomacyFactionReserved(State.FactionOf(playerClan))) { return "Wait for the fighting involving your warbands to finish."; } Settlement settlement = C.CurrentSettlement(); if (settlement == null || playerParty.State != PartyState.InSettlement || settlement.OwnerClanId != playerClan.Id || (settlement.Type != SettlementType.Town && settlement.Type != SettlementType.Castle) || Vec2.Distance(playerParty.Position, settlement.Position) > 0.01) { return "Hold court from a town or castle of your own."; } return ""; } public string FoundKingdomReason(string name) { string text = KingdomCourtReason(); if (text.Length > 0) { return text; } ClanServiceState clanService = State.ClanService; if (clanService == null || !clanService.Initialized || clanService.Kind != ClanServiceKind.Independent || !string.IsNullOrEmpty(clanService.KingdomId) || !string.IsNullOrEmpty(State.PlayerClan.KingdomId)) { return "You have to be independent to found a kingdom."; } if (State.Diplomacy == null || !State.Diplomacy.Initialized || State.Diplomacy.Truces == null) { return "Diplomacy is unavailable."; } string trimmed = (name ?? "").Trim(); if (trimmed.Length < 3 || trimmed.Length > 40 || trimmed.Any((char ch) => char.IsControl(ch) || ch == '<' || ch == '>')) { return "Pick a name 3 to 40 characters long, plain text only."; } if (State.Kingdoms.Any((Kingdom k) => !k.IsEliminated && string.Equals(k.Name?.Trim(), trimmed, StringComparison.OrdinalIgnoreCase))) { return "A kingdom already goes by that name."; } if (double.IsNaN(State.PlayerClan.Renown) || double.IsInfinity(State.PlayerClan.Renown) || State.PlayerClan.Renown < 200.0) { return "Earn " + 200 + " renown before founding a kingdom."; } if (State.PlayerClan.Gold < 1000) { return "Founding a kingdom costs " + 1000L + " denars."; } foreach (StanceRecord item in State.Stances.Where((StanceRecord s) => s.A == State.PlayerClanId || s.B == State.PlayerClanId)) { if (C.DiplomacyFactionReserved((item.A == State.PlayerClanId) ? item.B : item.A)) { return "Wait for the other side's fights to finish."; } } foreach (DiplomaticTruce item2 in State.Diplomacy.Truces.Where((DiplomaticTruce t) => t.A == State.PlayerClanId || t.B == State.PlayerClanId)) { if (C.DiplomacyFactionReserved((item2.A == State.PlayerClanId) ? item2.B : item2.A)) { return "Wait for the other side's fights to finish."; } } return ""; } public CommandResult FoundKingdom(string name) { string text = FoundKingdomReason(name); if (text.Length > 0) { return CommandResult.Fail(text); } Clan playerClan = State.PlayerClan; string id; do { id = State.Ids.Allocate("kingdom"); } while (State.Kingdoms.Contains(id) || State.Clans.Contains(id)); Kingdom kingdom = new Kingdom { Id = id, Name = name.Trim(), CultureId = playerClan.CultureId, RulerClanId = playerClan.Id, Color = playerClan.Color, Symbol = playerClan.Symbol }; State.Transact(playerClan, -1000L, LedgerAccount.Other, "Founded kingdom: " + kingdom.Name); State.Kingdoms.Add(kingdom); C.MigrateIndependentDiplomacy(playerClan.Id, kingdom.Id); playerClan.KingdomId = kingdom.Id; ClanServiceState clanService = State.ClanService; clanService.Kind = ClanServiceKind.Ruler; clanService.KingdomId = kingdom.Id; clanService.StartedDay = State.Clock.Day; clanService.EndsDay = -1L; clanService.LastPaidDay = State.Clock.Day; clanService.LastPayment = 0L; State.AddLog(LogCategory.Politics, playerClan.Name + " founded " + kingdom.Name + ". Its wars and truces carry on.", kingdom.Id, playerClan.Id); C.OnDiplomacyChanged(); C.TrainDiplomacy(100.0); State.Touch(); return CommandResult.Success(kingdom.Name + " founded. You rule it; your wars and truces carry on."); } public string SecedeKingdomReason() { string text = KingdomCourtReason(); if (text.Length > 0) { return text; } ClanServiceState clanService = State.ClanService; if (clanService == null || !clanService.Initialized || clanService.Kind != ClanServiceKind.Vassal || string.IsNullOrEmpty(clanService.KingdomId) || State.PlayerClan.KingdomId != clanService.KingdomId) { return "Only a landed vassal can break away and keep its fiefs."; } Clan clan = C.ServiceRuler(clanService.KingdomId); if (clan == null || clan.Id == State.PlayerClanId) { return "There's no ruler to break away from."; } if (C.DiplomacyFactionReserved(clanService.KingdomId) || C.DiplomacyFactionReserved(State.PlayerClanId)) { return "Wait for the fighting involving your warbands to finish."; } return ""; } public CommandResult SecedeKingdom() { string text = SecedeKingdomReason(); if (text.Length > 0) { return CommandResult.Fail(text); } string kingdomId = State.ClanService.KingdomId; C.BecomeIndependent(); State.SetStance(State.PlayerClanId, kingdomId, Stance.War); State.AddLog(LogCategory.Politics, State.PlayerClan.Name + " seceded from " + State.Kingdoms.Require(kingdomId).Name + ", kept its fiefs and went to war with its old kingdom. Its influence there is gone.", State.PlayerClanId, kingdomId); C.OnDiplomacyChanged(); State.Touch(); return CommandResult.Success("Independent. You keep your fiefs, and your old kingdom is at war with you."); } } internal sealed class LegendsSystem { private readonly Campaign C; private NavGrid Nav => C.Nav; private CampaignState State => C.State; internal LegendsSystem(Campaign host) { C = host; } internal static SiteKind LegendSiteKind(string place) { string text = place.ToLowerInvariant(); if (text.Contains("tower")) { return SiteKind.Tower; } if (text.Contains("cave") || text.Contains("hollow")) { return SiteKind.Cave; } if (text.Contains("barrow") || text.Contains("crypt")) { return SiteKind.Barrow; } if (text.Contains("camp") || text.Contains("field") || text.Contains("valley") || text.Contains("lodge") || text.Contains("hut")) { return SiteKind.Camp; } if (text.Contains("stones") || text.Contains("shrine") || text.Contains("temple") || text.Contains("grove") || text.Contains("dojo") || text.Contains("pavilion")) { return SiteKind.Shrine; } return SiteKind.Ruins; } public void EnsureLegendFields() { if (State.Legends == null) { State.Legends = new LegendsState(); } if (State.Legends.Joined == null) { State.Legends.Joined = new SortedSet(StringComparer.Ordinal); } if (State.Quests == null || !State.Quests.Started) { return; } bool flag = false; foreach (DiscoverySite item in State.Quests.Sites.Where((DiscoverySite x) => x != null && x.Stock == null)) { item.Stock = new SortedDictionary(StringComparer.Ordinal); flag = true; } foreach (DiscoverySite item2 in State.Quests.Sites.Where((DiscoverySite x) => x != null && x.LegendPlace == null)) { item2.LegendPlace = ""; flag = true; } if (!State.Legends.SitesPlaced) { State.Legends.SitesPlaced = true; PlaceLegendSites(); flag = true; } if (flag) { State.Touch(); } } internal void PlaceLegendSites() { if (Nav == null) { return; } List sites = State.Quests.Sites; List list = State.Settlements.Where((Settlement s) => s.Type != SettlementType.Hideout).OrderBy((Settlement s) => s.Id, StringComparer.Ordinal).ToList(); if (list.Count == 0) { return; } RandomStream randomStream = new RandomStream("legends.place", State.Random.Seed); int num = 0; foreach (string place in Legends.Places) { LegendDef def = Legends.All.First((LegendDef l) => l.Route == LegendRoute.Site && l.Place == place); List list2 = list.Where((Settlement s) => def.Culture.Length > 0 && s.CultureId == def.Culture).ToList(); if (list2.Count == 0) { list2 = list; } Vec2? spot = null; for (int tries = 0; tries < 400; tries++) { if (spot.HasValue) { break; } Settlement settlement = list2[randomStream.Range(0, list2.Count)]; double num2 = randomStream.NextDouble() * Math.PI * 2.0; double num3 = 5.0 + randomStream.NextDouble() * 12.0; Vec2 p = new Vec2(settlement.Position.X + Math.Cos(num2) * num3, settlement.Position.Y + Math.Sin(num2) * num3); if (!(p.X < 1.0) && !(p.Y < 1.0) && !(p.X > Nav.WorldWidth - 1.0) && !(p.Y > Nav.WorldHeight - 1.0) && Nav.IsPassable(p) && Nav.SameComponent(p, settlement.Position) && !State.Settlements.Any((Settlement s) => Vec2.Distance(s.Position, p) < 3.5) && !sites.Any((DiscoverySite s) => Vec2.Distance(s.Position, p) < (double)((tries < 250) ? 6 : 3))) { spot = p; } } if (!spot.HasValue) { continue; } Settlement settlement2 = list.OrderBy((Settlement s) => Vec2.Distance(s.Position, spot.Value)).ThenBy((Settlement s) => s.Id, StringComparer.Ordinal).First(); DiscoverySite discoverySite = new DiscoverySite(); int num4 = ++num; discoverySite.Id = "site.legend." + num4.ToString(CultureInfo.InvariantCulture); discoverySite.Kind = LegendSiteKind(place); discoverySite.Name = Campaign.Cap(place); discoverySite.Position = spot.Value; discoverySite.RegionSettlementId = settlement2.Id; discoverySite.LegendPlace = place; DiscoverySite discoverySite2 = discoverySite; foreach (LegendDef item in from l in LegendsAt(place) where !l.Unique select l) { discoverySite2.Stock[item.Unit] = 2 + randomStream.Range(0, 2); } if (discoverySite2.Stock.Count > 0) { discoverySite2.NextStockDay = State.Clock.Day + 14; } sites.Add(discoverySite2); } } internal static IEnumerable LegendsAt(string place) { return Legends.All.Where((LegendDef l) => l.Route == LegendRoute.Site && l.Place == place); } internal void DailyLegendSites() { if (State.Quests?.Sites == null) { return; } foreach (DiscoverySite item in State.Quests.Sites.Where((DiscoverySite x) => x != null && !string.IsNullOrEmpty(x.LegendPlace) && x.Stock != null && x.Stock.Count > 0 && x.NextStockDay >= 0)) { if (State.Clock.Day < item.NextStockDay) { continue; } RandomStream randomStream = new RandomStream("legends.stock|" + item.Id + "|" + State.Clock.Day.ToString(CultureInfo.InvariantCulture), State.Random.Seed); foreach (string item2 in item.Stock.Keys.ToList()) { item.Stock[item2] = Math.Min(3, item.Stock[item2] + 1 + randomStream.Range(0, 2)); } item.NextStockDay = State.Clock.Day + 14; State.Touch(); } } internal StoryPrompt LegendSitePrompt(DiscoverySite s) { List list = LegendsAt(s.LegendPlace).ToList(); if (list.Count == 0) { return null; } string text = ((!(C.SiteHere()?.Id == s.Id)) ? ("Travel to " + s.Name + " first.") : C.QuestActionReason()); StoryPrompt storyPrompt = new StoryPrompt { Kind = "site", SubjectId = s.Id, Title = s.Name, SpeakerRole = Campaign.SiteKindName(s.Kind) }; storyPrompt.Lines.Add(list[0].Story); Clan playerClan = State.PlayerClan; int num = Campaign.ClanTier(playerClan); if (list.Count == 1 && list[0].Unique) { LegendDef legendDef = list[0]; UnitDef unitDef = C.UnitDef(legendDef.Unit); if (unitDef == null) { return null; } if (State.Legends.Joined.Contains(legendDef.Unit)) { storyPrompt.Lines.Add("The place is quiet now: " + unitDef.Name + " travels with you."); storyPrompt.Options.Add(new StoryOption { Id = "leave", Text = "Move on." }); return storyPrompt; } long num2 = unitDef.RecruitCost; string reason = ((text.Length > 0) ? text : ((num < legendDef.MinClanTier) ? (unitDef.Name + " will not follow a clan below tier " + legendDef.MinClanTier + " (yours is " + num + ").") : ((playerClan.Gold < num2) ? ("You need " + num2.ToString("N0") + " denars.") : ""))); storyPrompt.Options.Add(new StoryOption { Id = "join", Text = "Ask " + unitDef.Name + " to join you. (" + num2.ToString("N0") + " denars)", Reason = reason, Hint = "A legend: once a campaign. Wage " + unitDef.DailyWage.ToString("0.#", CultureInfo.InvariantCulture) + " a day." }); storyPrompt.Options.Add(new StoryOption { Id = "leave", Text = "Leave them be." }); return storyPrompt; } storyPrompt.Lines.Add((s.Stock.Values.Sum() == 0) ? ("Nobody here is looking for work just now; come back after day " + (s.NextStockDay + 1) + ".") : "Some of them would follow you, for a price. More come every two weeks."); Party playerParty = State.PlayerParty; int num3 = ((playerParty != null) ? (C.PartySizeLimit(playerParty) - playerParty.Troops.TotalTroops - playerParty.Troops.Heroes.Count) : 0); foreach (LegendDef item in list.Where((LegendDef x) => !x.Unique)) { UnitDef unitDef2 = C.UnitDef(item.Unit); if (unitDef2 != null) { int value; int num4 = (s.Stock.TryGetValue(item.Unit, out value) ? value : 0); string reason2 = ((text.Length > 0) ? text : ((num4 <= 0) ? ("None left until day " + (s.NextStockDay + 1) + ".") : ((num3 <= 0) ? "Your party is full." : ((playerClan.Gold < unitDef2.RecruitCost) ? ("You need " + unitDef2.RecruitCost.ToString("N0") + " denars.") : "")))); storyPrompt.Options.Add(new StoryOption { Id = "hire:" + item.Unit, Text = "Hire a " + unitDef2.Name + ". (" + unitDef2.RecruitCost.ToString("N0") + " denars · " + num4 + " here)", Reason = reason2, Hint = "Tier " + unitDef2.Tier + " " + unitDef2.Role.ToString().ToLowerInvariant() + ", wage " + unitDef2.DailyWage.ToString("0.#", CultureInfo.InvariantCulture) + " a day." }); } } storyPrompt.Options.Add(new StoryOption { Id = "leave", Text = "Move on." }); return storyPrompt; } internal CommandResult ChooseLegendSite(DiscoverySite s, StoryPrompt prompt, string option) { StoryOption storyOption = prompt.Options.FirstOrDefault((StoryOption x) => x.Id == option); if (storyOption == null) { return CommandResult.Fail("That choice is not open."); } if (!storyOption.Enabled) { return CommandResult.Fail(storyOption.Reason); } if (option == "leave") { return CommandResult.Success(); } Party playerParty = State.PlayerParty; string id = ((option == "join") ? LegendsAt(s.LegendPlace).First().Unit : (option.StartsWith("hire:", StringComparison.Ordinal) ? option.Substring(5) : "")); UnitDef unitDef = C.UnitDef(id); if (unitDef == null) { return CommandResult.Fail("Nobody here by that name."); } State.Transact(State.PlayerClan, -unitDef.RecruitCost, LedgerAccount.Recruitment, ((option == "join") ? "Won over " : "Hired ") + unitDef.Name + " at " + s.Name); playerParty.Troops.Add(unitDef.Id, 1); string text; if (option == "join") { State.Legends.Joined.Add(unitDef.Id); State.PlayerClan.Renown += 5.0; text = unitDef.Name + " joins your party."; } else { s.Stock[unitDef.Id] = Math.Max(0, (s.Stock.TryGetValue(unitDef.Id, out var value) ? value : 0) - 1); text = "A " + unitDef.Name + " joins your party."; } if (!s.Explored) { s.Explored = true; s.ExploredMinute = State.Clock.Minute; } s.Outcome = text; State.AddLog(LogCategory.Recruitment, s.Name + ": " + text, s.RegionSettlementId); State.Touch(); return CommandResult.Success(text); } public string LegendSiteSummary(string siteId) { DiscoverySite s = C.Site(siteId); if (s == null || string.IsNullOrEmpty(s.LegendPlace)) { return ""; } List list = LegendsAt(s.LegendPlace).ToList(); if (list.Count == 1 && list[0].Unique) { UnitDef unitDef = C.UnitDef(list[0].Unit); if (unitDef != null) { if (!State.Legends.Joined.Contains(unitDef.Id)) { return unitDef.Name + " lives here (clan tier " + list[0].MinClanTier + ", " + unitDef.RecruitCost.ToString("N0") + " denars)."; } return unitDef.Name + " travels with you."; } return ""; } int value; return "For hire: " + string.Join(", ", list.Select((LegendDef l) => (C.UnitDef(l.Unit)?.Name ?? l.Unit) + " ×" + (s.Stock.TryGetValue(l.Unit, out value) ? value : 0))) + " · restocks day " + (s.NextStockDay + 1) + "."; } internal static IEnumerable LegendQuestTemplates() { return Legends.All.Where((LegendDef l) => l.Route == LegendRoute.Quest).Select((Func)((LegendDef l) => new Campaign.LegendQuest(l))); } } internal sealed class LordHorsesSystem { private readonly Campaign C; private CampaignState State => C.State; private SortedDictionary Store { get { if (State.Horses == null) { return null; } if (State.Horses.LordHorses == null) { State.Horses.LordHorses = new SortedDictionary(StringComparer.Ordinal); } if (State.Horses.LordRemountDay == null) { State.Horses.LordRemountDay = new SortedDictionary(StringComparer.Ordinal); } return State.Horses.LordHorses; } } internal LordHorsesSystem(Campaign host) { C = host; } public bool KeepsLordHorse(Hero h) { if (h == null || h.Occupation != HeroOccupation.Lord || h.State == HeroState.Dead || !C.IsGrown(h)) { return false; } Clan clan = State.Clans.Get(h.ClanId); if (clan != null && !clan.IsBandit && !clan.IsEliminated && clan.Id != State.PlayerClanId) { return C.RidingArchetype(h); } return false; } public HorseState LordHorse(Hero h) { if (h == null || Store == null || !Store.TryGetValue(h.Id, out var value)) { return null; } return value; } internal HorseBreedDef LordBreed(Hero h, RandomStream rng) { Clan clan = State.Clans.Get(h.ClanId); string culture = clan?.CultureId ?? h.CultureId; bool num = clan?.LeaderHeroId == h.Id; List list = Horses.Breeds.Where((HorseBreedDef b) => b.Kind != HorseKind.Pack && b.Cultures.Contains(culture)).ToList(); if (list.Count == 0) { list = Horses.Breeds.Where((HorseBreedDef b) => b.Kind != HorseKind.Pack && b.Cultures.Contains(h.CultureId)).ToList(); } if (list.Count == 0) { list = Horses.Breeds.Where((HorseBreedDef b) => b.Kind == HorseKind.Riding).ToList(); } List list2 = list.Where((HorseBreedDef b) => b.Kind == HorseKind.War).ToList(); if (num && list2.Count > 0) { list = list2; } list = list.OrderBy((HorseBreedDef b) => b.Id, StringComparer.Ordinal).ToList(); if (list.Count != 0) { return list[rng.Range(0, list.Count)]; } return null; } internal HorseState NewLordHorse(Hero h) { RandomStream randomStream = new RandomStream("lordhorse|" + h.Id + "|" + State.Clock.Day, State.Random.Seed); HorseBreedDef horseBreedDef = LordBreed(h, randomStream); if (horseBreedDef == null) { return null; } Clan clan = State.Clans.Get(h.ClanId); double qualityBias = ((clan?.LeaderHeroId == h.Id) ? 0.06 : 0.02) + Math.Min(0.04, (double)(clan?.Gold ?? 0) / 500000.0); HorseState horseState = C.CreateHorse(horseBreedDef, randomStream, 5 + randomStream.Range(0, 6), qualityBias, "Bred for " + h.Name, assignId: false); horseState.Id = "lordhorse." + h.Id + "." + State.Clock.Day; horseState.Place = HorsePlace.Party; horseState.PlaceId = ""; horseState.Experience = 40 + randomStream.Range(0, 120); horseState.Bond = new SortedDictionary(StringComparer.Ordinal) { { h.Id, Math.Round(20.0 + (double)randomStream.Range(0, 40) * 1.0, 3) } }; return horseState; } public void EnsureLordHorses() { SortedDictionary store = Store; if (store == null) { return; } bool flag = false; foreach (Hero item in State.Heroes.Where(KeepsLordHorse).ToList()) { if (!store.ContainsKey(item.Id) && !State.Horses.LordRemountDay.ContainsKey(item.Id)) { HorseState horseState = NewLordHorse(item); if (horseState != null) { store[item.Id] = horseState; flag = true; } } } if (flag) { State.Touch(); } } internal void LoseLordHorse(Hero h, int remountDays) { if (h != null && Store != null && Store.Remove(h.Id) && KeepsLordHorse(h)) { State.Horses.LordRemountDay[h.Id] = State.Clock.Day + remountDays; } } public void DailyLordHorses() { SortedDictionary store = Store; if (store == null || State.Horses.LordHorsesDay >= State.Clock.Day) { return; } State.Horses.LordHorsesDay = State.Clock.Day; RandomStream randomStream = State.Random.Get("lordhorses"); foreach (string item in store.Keys.ToList()) { Hero hero = State.Heroes.Get(item); HorseState horseState = store[item]; if (!KeepsLordHorse(hero)) { store.Remove(item); State.Horses.LordRemountDay.Remove(item); continue; } horseState.Fatigue = 0.0; horseState.Condition = 1.0; if (horseState.Injury != HorseInjury.None) { if (horseState.Injury == HorseInjury.Grave && randomStream.Chance(0.03)) { LoseLordHorse(hero, 14); State.AddLog(LogCategory.Politics, horseState.Name + ", " + hero.Name + "'s horse, died of its wounds.", hero.Id); continue; } horseState.InjuryDays = Math.Max(0, horseState.InjuryDays - 1); if (horseState.InjuryDays == 0) { horseState.Injury = HorseInjury.None; } } if (C.HorseAge(horseState) >= 18.0) { store.Remove(item); State.Horses.LordRemountDay[item] = State.Clock.Day; } } foreach (string item2 in State.Horses.LordRemountDay.Keys.ToList()) { Hero hero2 = State.Heroes.Get(item2); if (!KeepsLordHorse(hero2)) { State.Horses.LordRemountDay.Remove(item2); } else { if (State.Horses.LordRemountDay[item2] > State.Clock.Day) { continue; } HorseState horseState2 = NewLordHorse(hero2); if (horseState2 != null) { Clan clan = State.Clans.Get(hero2.ClanId); long num = C.HorseValue(horseState2); if (clan == null || clan.Gold < num * 3) { State.Horses.LordRemountDay[item2] = State.Clock.Day + 14; continue; } State.Transact(clan, -num, LedgerAccount.Horses, "A new horse for " + hero2.Name); horseState2.Origin = "Bought for " + hero2.Name; store[item2] = horseState2; State.Horses.LordRemountDay.Remove(item2); } } } EnsureLordHorses(); State.Touch(); } public MountSpec LordMountForBattle(Hero hero) { if (!KeepsLordHorse(hero) || hero.Dismounted) { return null; } HorseState horseState = LordHorse(hero); HorseBreedDef horseBreedDef = Campaign.BreedOf(horseState); if (horseState == null || horseBreedDef == null || !Horses.Rideable(horseState.Injury) || C.HorseAge(horseState) < Horses.WorkingAge(horseBreedDef.Kind)) { return null; } HorseStats horseStats = C.HorseCurrentStats(horseState); double num = Math.Max(0, Math.Min(300, hero.Skill("riding"))); double num2 = 1.0 + num / 1000.0 + C.HorseBond(horseState, hero.Id) / 2000.0; return new MountSpec { HorseId = horseState.Id, Name = horseState.Name, BreedId = horseBreedDef.Id, Coat = horseState.Coat, Heavy = horseBreedDef.Heavy, Speed = Math.Round(horseStats.Speed * num2, 2), Manoeuvre = Math.Round(horseStats.Manoeuvre * num2, 2), Charge = Math.Round(horseStats.Charge, 2), HitPoints = Math.Round(horseStats.HitPoints, 1), Size = horseBreedDef.Size }; } internal bool ApplyLordHorseOutcome(Combatant c, CombatOutcome heroOutcome, CombatOutcome mountOutcome, bool heroCaptured, bool heroDied, bool simulated, Party captor, RandomStream rng, List lines) { Hero hero = State.Heroes.Get(c?.HeroId ?? ""); HorseState horseState = LordHorse(hero); if (c?.Mount == null || horseState == null || horseState.Id != c.Mount.HorseId) { return false; } if (!c.EverDeployed && heroOutcome != CombatOutcome.Downed) { return true; } horseState.Battles++; horseState.Experience += 25.0; if (mountOutcome == CombatOutcome.Downed || (simulated && mountOutcome == CombatOutcome.Pending && rng.Chance((heroOutcome == CombatOutcome.Downed) ? 0.35 : 0.05))) { if (rng.Chance(0.35)) { lines.Add(horseState.Name + ", " + hero.Name + "'s horse, was killed."); LoseLordHorse(hero, 14); return true; } bool flag = rng.Chance(0.4); HorseLifeSystem.Injure(horseState, flag ? HorseInjury.Grave : HorseInjury.Lame, flag ? rng.Range(20, 41) : rng.Range(8, 21), rng); lines.Add(horseState.Name + ", " + hero.Name + "'s horse, was " + (flag ? "gravely hurt" : "lamed") + "."); } if (heroDied) { LoseLordHorse(hero, 14); return true; } if (heroCaptured) { if (captor != null && captor.Id == State.PlayerPartyId && State.Horses?.Horses != null) { Store.Remove(hero.Id); if (KeepsLordHorse(hero)) { State.Horses.LordRemountDay[hero.Id] = State.Clock.Day + 14; } horseState.Id = C.NewHorseId(); horseState.Place = HorsePlace.Party; horseState.PlaceId = State.PlayerPartyId; horseState.Bond = new SortedDictionary(StringComparer.Ordinal); horseState.Origin = "Taken from " + hero.Name; horseState.AcquiredDay = State.Clock.Day; horseState.Fatigue = Math.Min(1.0, horseState.Fatigue); State.Horses.Horses[horseState.Id] = horseState; lines.Add("You took " + horseState.Name + ", " + hero.Name + "'s " + C.BreedName(horseState).ToLowerInvariant() + ", into your herd."); State.AddLog(LogCategory.Battle, "You took " + horseState.Name + ", " + hero.Name + "'s horse.", hero.Id); } else { lines.Add(horseState.Name + " was taken with " + hero.Name + "."); LoseLordHorse(hero, 14); } } return true; } internal void BringLordHorseIntoClan(Hero h) { if (h == null || Store == null || !Store.TryGetValue(h.Id, out var value)) { return; } Store.Remove(h.Id); State.Horses.LordRemountDay.Remove(h.Id); if (State.Horses.Horses != null && State.PlayerParty != null) { value.Id = C.NewHorseId(); value.Place = HorsePlace.Party; value.PlaceId = State.PlayerPartyId; value.AcquiredDay = State.Clock.Day; State.Horses.Horses[value.Id] = value; if (string.IsNullOrEmpty(h.MountId)) { h.MountId = value.Id; } State.AddLog(LogCategory.Info, h.Name + " brought " + value.Name + " into your herd.", h.Id); } } internal void ForgetLordHorse(Hero h) { if (h != null && Store != null) { Store.Remove(h.Id); State.Horses.LordRemountDay.Remove(h.Id); } } } internal sealed class MerchantCaravansSystem { private readonly Campaign C; private ContentDatabase Content => C.Content; private CampaignState State => C.State; internal MerchantCaravansSystem(Campaign host) { C = host; } public bool IsMerchantCaravan(Party p) { if (p != null && p.Kind == PartyKind.Caravan) { return !string.IsNullOrEmpty(p.MerchantTownId); } return false; } public CaravanState MerchantCaravanOf(string townId) { return State.Caravans.FirstOrDefault((CaravanState c) => c.Merchant && c.IsActive && c.HomeSettlementId == townId); } public void EnsureMerchantCaravans() { if (State.MerchantCaravanDue == null) { State.MerchantCaravanDue = new SortedDictionary(StringComparer.Ordinal); State.Touch(); } if (!State.MerchantCaravansStarted) { StartMerchantCaravans(); } } public void StartMerchantCaravans() { if (State.MerchantCaravanDue == null) { State.MerchantCaravanDue = new SortedDictionary(StringComparer.Ordinal); } foreach (Settlement item in Towns()) { if (MerchantCaravanOf(item.Id) == null && MerchantCaravanReason(item).Length == 0) { FormMerchantCaravan(item, replacement: false); } } State.MerchantCaravansStarted = true; State.Touch(); } internal IEnumerable Towns() { return State.Settlements.Where((Settlement s) => s.Type == SettlementType.Town).OrderBy((Settlement s) => s.Id, StringComparer.Ordinal).ToList(); } public string MerchantCaravanReason(Settlement town) { if (town == null || town.Type != SettlementType.Town) { return "Only towns send out merchant caravans."; } Clan clan = State.Clans.Get(town.OwnerClanId); if (clan == null || clan.IsBandit || clan.IsEliminated) { return "The town has no rightful holder."; } if (C.IsSettlementBesieged(town)) { return "The town is under siege."; } if (town.Market?.Stock == null || !town.Market.Initialized) { return "The market here is closed."; } if (MerchantCaravanEscort(town.CultureId, 30).Count == 0) { return "Nobody here to guard a caravan."; } return ""; } internal Party FormMerchantCaravan(Settlement town, bool replacement) { RandomStream randomStream = State.Random.Get("world"); long minute = State.Clock.Minute; Party party = new Party { Id = State.Ids.Allocate("party"), Name = "Caravan of " + town.Name, Kind = PartyKind.Caravan, ClanId = town.OwnerClanId, HomeSettlementId = town.Id, MerchantTownId = town.Id, State = PartyState.InSettlement, CurrentSettlementId = town.Id, Position = town.Position, Gold = 2000L, Morale = 50.0, CreatedAtMinute = minute, NextThinkMinute = minute, WaitUntilMinute = minute + 60 * randomStream.Range(1, 25) }; foreach (var (unitId, healthy) in MerchantCaravanEscort(town.CultureId, MerchantCaravanSizeFor(town) + randomStream.Range(-2, 3))) { party.Troops.Add(unitId, healthy); } CaravanState item = new CaravanState { Id = State.Ids.Allocate("caravan"), PartyId = party.Id, OwnerClanId = party.ClanId, HomeSettlementId = town.Id, StartedMinute = minute, Merchant = true }; State.Parties.Add(party); State.Caravans.Add(item); State.MerchantCaravanDue.Remove(town.Id); C.ResupplyCaravan(party, town); if (replacement) { State.AddLog(LogCategory.Economy, "The merchants of " + town.Name + " sent out a new caravan.", party.Id, town.Id); } State.Touch(); return party; } public int MerchantCaravanSizeFor(Settlement town) { if (town == null) { return 30; } double num = 0.65 + 0.7 * (double)(StableHash.Fnv1a64("caravan-size|" + town.Id) % 1000) / 1000.0; double num2 = Math.Max(0.85, Math.Min(1.2, 0.7 + town.Prosperity / 1500.0)); return Math.Max(12, (int)Math.Round(30.0 * num * num2)); } public List<(string unit, int count)> MerchantCaravanEscort(string cultureId, int size) { List<(string, int)> list = new List<(string, int)>(); if (size <= 0) { return list; } List units = Content.Units.Where((UnitDef u) => u.Culture == cultureId && u.Slots == 1 && u.Workload <= 3.0 && u.Role != TroopRole.Monster && u.Role != TroopRole.Siege).ToList(); UnitDef foot = Nearest((UnitDef u) => u.Role == TroopRole.Infantry && !u.Mounted, 2) ?? C.UnitDef(Content.Cultures.Get(cultureId)?.BasicTroop ?? ""); if (foot == null) { return list; } UnitDef unitDef = Nearest((UnitDef u) => u.Role == TroopRole.Infantry && !u.Mounted && u.Id != foot.Id && u.Tier > foot.Tier && u.Tier <= 4, 3); UnitDef unitDef2 = Nearest((UnitDef u) => u.Role == TroopRole.Ranged && !u.Mounted && u.Tier <= 4, 2); UnitDef unitDef3 = Nearest((UnitDef u) => (u.Role == TroopRole.Cavalry || u.Mounted) && u.Tier <= 5, 3); int num = ((unitDef3 != null) ? Math.Max(1, size / 10) : 0); int num2 = ((unitDef2 != null) ? (size * 3 / 10) : 0); int num3 = size - num - num2; int num4 = ((unitDef != null) ? (num3 * 2 / 5) : 0); if (num3 - num4 > 0) { list.Add((foot.Id, num3 - num4)); } if (num4 > 0) { list.Add((unitDef.Id, num4)); } if (num2 > 0) { list.Add((unitDef2.Id, num2)); } if (num > 0) { list.Add((unitDef3.Id, num)); } return list; UnitDef Nearest(Func fits, int tier) { return (from u in units.Where(fits) orderby Math.Abs(u.Tier - tier), u.Tier select u).ThenBy((UnitDef u) => u.Id, StringComparer.Ordinal).FirstOrDefault(); } } internal void DailyMerchantCaravans() { if (State.MerchantCaravanDue == null) { State.MerchantCaravanDue = new SortedDictionary(StringComparer.Ordinal); } foreach (CaravanState item in State.Caravans.Where((CaravanState x) => x.Merchant && x.IsActive).ToList()) { Party party = State.Parties.Get(item.PartyId); Settlement settlement = State.Settlements.Get(item.HomeSettlementId); if (party == null || settlement == null || party.ClanId == settlement.OwnerClanId || party.State == PartyState.Engaged || !string.IsNullOrEmpty(party.EncounterId)) { continue; } Clan clan = State.Clans.Get(settlement.OwnerClanId); if (clan != null && !clan.IsBandit) { party.ClanId = clan.Id; item.OwnerClanId = clan.Id; Settlement settlement2 = ((party.State == PartyState.InSettlement) ? State.Settlements.Get(party.CurrentSettlementId) : null); if (settlement2 != null && !C.CanEnter(party, settlement2)) { C.LeaveSettlementInternal(party); } party.NextThinkMinute = State.Clock.Minute; State.Touch(); } } if (!State.MerchantCaravansStarted) { return; } foreach (Settlement item2 in Towns()) { long value; if (MerchantCaravanOf(item2.Id) != null) { if (State.MerchantCaravanDue.Remove(item2.Id)) { State.Touch(); } } else if (!State.MerchantCaravanDue.TryGetValue(item2.Id, out value)) { State.MerchantCaravanDue[item2.Id] = State.Clock.Minute + 20160; State.Touch(); } else if (State.Clock.Minute >= value && MerchantCaravanReason(item2).Length == 0) { FormMerchantCaravan(item2, replacement: true); } } } internal bool MerchantCaravanShouldGoHome(Party p) { if (p.Troops.TotalHealthy >= MerchantCaravanSizeFor(State.Settlements.Get(p.MerchantTownId ?? "") ?? State.Settlements.Get(p.HomeSettlementId ?? "")) / 2) { return p.Gold > 6000; } return true; } internal void SettleMerchantAccounts(Party p, Settlement home) { MarketState market = home.Market; if (market == null || !market.Initialized) { return; } int num = MerchantCaravanSizeFor(home) - p.Troops.TotalTroops; if (num > 0) { int num2 = 0; foreach (var item3 in MerchantCaravanEscort(home.CultureId, num)) { string item = item3.unit; int item2 = item3.count; long num3 = Math.Max(0, C.UnitDef(item)?.RecruitCost ?? 0); int num4 = (int)((num3 == 0L) ? item2 : Math.Min(item2, p.Gold / num3)); if (num4 > 0) { p.Troops.Add(item, num4); p.Gold -= num4 * num3; PayMarket(p, market, num4 * num3); num2 += num4; } } if (num2 > 0) { State.AddLog(LogCategory.Economy, p.Name + " hired " + num2 + " new guards at " + home.Name + ".", p.Id, home.Id); State.Touch(); } } if (p.Gold < 2000) { long num5 = Math.Min(2000 - p.Gold, Math.Max(0L, market.Gold - 500)); if (num5 > 0) { market.Gold -= num5; p.Gold += num5; State.Touch(); } } else if (p.Gold > 4000) { long num6 = p.Gold - 2000; p.Gold -= num6; PayMarket(p, market, num6); State.Touch(); } } internal void PayMarket(Party p, MarketState market, long amount) { if (amount > 0 && market != null) { if (!IsMerchantCaravan(p)) { market.Gold = ((market.Gold > long.MaxValue - amount) ? long.MaxValue : (market.Gold + amount)); } else if (market.Gold < 5000) { market.Gold += Math.Min(amount, 5000 - market.Gold); } } } internal Settlement MerchantSourceTown(Party p, Settlement current, List markets) { List list = markets.Concat(new Settlement[1] { current }).ToList(); int count = TradeGoods.All.Count; long[,] array = new long[list.Count, count]; long[,] array2 = new long[list.Count, count]; int[,] array3 = new int[list.Count, count]; for (int i = 0; i < list.Count; i++) { for (int j = 0; j < count; j++) { Settlement settlement = list[i]; string id = TradeGoods.All[j].Id; int num = (array3[i, j] = C.MarketStock(settlement, id)); array[i, j] = ((num >= 5) ? C.CommodityPrice(settlement, id, buying: true, num) : long.MaxValue); long num2 = ((num + 1 <= 500) ? C.CommodityPrice(settlement, id, buying: false, num + 1) : 0); array2[i, j] = ((num2 <= settlement.Market.Gold) ? num2 : 0); } } Settlement settlement2 = null; double num3 = 0.0; for (int k = 0; k < markets.Count; k++) { double num4 = Vec2.Distance(current.Position, list[k].Position); for (int l = 0; l < count; l++) { long num5 = array[k, l]; if (num5 == long.MaxValue) { continue; } for (int m = 0; m < list.Count; m++) { if (m == k) { continue; } long num6 = array2[m, l] - num5; if (num6 > 0) { double num7 = (double)(num6 * Math.Min(20, array3[k, l])) / (10.0 + num4 + Vec2.Distance(list[k].Position, list[m].Position)); if (num7 > num3) { num3 = num7; settlement2 = list[k]; } } } } } if (settlement2 != null) { return settlement2; } if (current.Id == p.MerchantTownId) { return null; } return markets.FirstOrDefault((Settlement s) => s.Id == p.MerchantTownId); } internal bool ReconcileMerchantCaravan(CaravanState c) { Party party = State.Parties.Get(c.PartyId); if (party != null && party.Kind == PartyKind.Caravan && party.ClanId == c.OwnerClanId && party.MerchantTownId == c.HomeSettlementId && party.State != PartyState.Destroyed && party.State != PartyState.Disbanded && party.Troops.TotalTroops > 0) { return false; } if (party != null && party.State != PartyState.Destroyed && party.State != PartyState.Disbanded) { party.Troops.Stacks.Clear(); OutcomeCommitter.DestroyParty(C, party, "no guards left"); } c.Status = "Lost"; c.CargoCosts.Clear(); State.MerchantCaravanDue[c.HomeSettlementId] = State.Clock.Minute + 20160; Settlement settlement = State.Settlements.Get(c.HomeSettlementId); State.AddLog(LogCategory.Economy, (party?.Name ?? "A merchant caravan") + " was lost; the merchants of " + (settlement?.Name ?? "its town") + " will send out another in " + 14 + " days.", c.PartyId, c.HomeSettlementId); return true; } } internal sealed class MilitaryAiSystem { private readonly Campaign C; private NavGrid Nav => C.Nav; private CampaignRules Rules => C.Rules; private CampaignState State => C.State; internal MilitaryAiSystem(Campaign host) { C = host; } internal IEnumerable MilitaryFriendlySettlements(Party party) { return State.Settlements.Where(delegate(Settlement s) { if (s.Type != SettlementType.Hideout) { Clan clan = State.Clans.Get(s.OwnerClanId); if (clan != null && !clan.IsEliminated && C.CanEnter(party, s) && Nav.IsPassable(s.Position)) { return Nav.SameComponent(party.Position, s.Position); } } return false; }); } public Settlement MilitaryRecallSettlement(Party party, MilitaryPartyState record) { if (party == null || record == null) { return null; } List source = (from s in MilitaryFriendlySettlements(party) where s.Type == SettlementType.Town || s.Type == SettlementType.Castle select s).ToList(); return source.FirstOrDefault((Settlement s) => s.Id == record.HomeSettlementId) ?? source.OrderBy((Settlement s) => Vec2.Distance(party.Position, s.Position)).ThenBy((Settlement s) => s.Id, StringComparer.Ordinal).FirstOrDefault(); } internal void MilitaryOptions(Party party, Clan clan, double strength, List<(Party party, double strength, double dist)> hostiles, List options) { MilitaryPartyState record = C.MilitaryPartyFor(party); if (record == null || clan == null) { return; } Hero hero = State.Heroes.Get(record.LeaderHeroId); if (hero == null || hero.State != HeroState.Active || !Campaign.IsPresentPartyHero(party, hero)) { return; } Party player = State.PlayerParty; int num; if (player != null && player.State != PartyState.Destroyed && player.State != PartyState.Disbanded && State.Player.Activity != PlayerActivity.Captive) { Hero playerHero = State.PlayerHero; num = ((playerHero != null && playerHero.State == HeroState.Active) ? 1 : 0); } else { num = 0; } bool flag = (byte)num != 0; if (record.Directive == MilitaryPartyDirective.Follow && !flag) { if (C.ClanArmyContains(party.Id)) { options.Add(new Campaign.AiOption { Task = "Await commander", Score = 1.0, Detail = "army battle cleanup pending", Apply = delegate { C.ClearOrder(party); } }); return; } record.Directive = MilitaryPartyDirective.Recall; C.ClearOrder(party); State.AddLog(LogCategory.Travel, party.Name + " is returning to a friendly holding because your warband is unavailable.", party.Id); State.Touch(); } bool flag2 = hostiles.Any(((Party party, double strength, double dist) h) => strength / Math.Max(0.01, h.strength) < Rules.FleeStrengthRatio); C.AddFleeOrFight(party, strength, hostiles, options, !flag2 && record.Directive == MilitaryPartyDirective.Patrol && hero.CanFight && C.PartyCombatants(party) >= 2); if (flag2) { return; } double num2 = C.DailyFoodNeed(party); if (C.FoodSupply(party) < num2 * (C.IsMergedIntoArmy(party) ? 0.5 : 1.5) && C.MilitaryAvailableTreasury(record, clan) > 0 && C.MilitaryFoodBudgetRemaining(record) > 0) { Settlement market = (from s in MilitaryFriendlySettlements(party) where C.SettlementFood(s) > 0.0 && C.MilitaryFoodPurchaseBudget(record, clan, s) > 0 orderby Vec2.Distance(party.Position, s.Position) select s).ThenBy((Settlement s) => s.Id, StringComparer.Ordinal).FirstOrDefault(); if (market != null) { options.Add(new Campaign.AiOption { Task = "Supply at " + market.Name, Score = 3.0, Detail = "buy existing food from clan funds", Apply = delegate { MilitaryGoOrWait(party, market, "military supply"); } }); } } if (!hero.CanFight) { Settlement refuge = MilitaryRecallSettlement(party, record); options.Add(new Campaign.AiOption { Task = "Recover captain", Score = 2.0, Detail = (refuge?.Name ?? "No friendly refuge"), Apply = delegate { MilitaryGoOrWait(party, refuge, "captain recovery"); } }); return; } Settlement settlement = ((record.Directive == MilitaryPartyDirective.Recall) ? MilitaryRecallSettlement(party, record) : null); object obj; if (record.Directive == MilitaryPartyDirective.Follow) { Party party2 = player; if (party2 != null && party2.State == PartyState.InSettlement) { obj = State.Settlements.Get(player.CurrentSettlementId); goto IL_048a; } } obj = null; goto IL_048a; IL_048a: Settlement settlement2 = (Settlement)obj; Settlement waitingAt = settlement ?? settlement2; if (waitingAt != null && party.State == PartyState.InSettlement && party.CurrentSettlementId == waitingAt.Id && C.CanEnter(party, waitingAt)) { options.Add(new Campaign.AiOption { Task = ((record.Directive == MilitaryPartyDirective.Recall) ? "Await reunion" : "Wait with your warband"), Score = 1.0, Detail = waitingAt.Name, Apply = delegate { MilitaryGoOrWait(party, waitingAt, "await reunion"); } }); return; } if (record.Directive == MilitaryPartyDirective.Recall) { Settlement home = settlement; options.Add(new Campaign.AiOption { Task = "Return military party", Score = 1.0, Detail = (home?.Name ?? "No friendly holding"), Apply = delegate { MilitaryGoOrWait(party, home, "military recall"); } }); return; } if (record.Directive == MilitaryPartyDirective.Follow) { if (player.State == PartyState.InSettlement) { Settlement location = State.Settlements.Get(player.CurrentSettlementId); if (location != null && C.CanEnter(party, location) && Nav.SameComponent(party.Position, location.Position)) { options.Add(new Campaign.AiOption { Task = "Join your warband", Score = 1.0, Detail = location.Name, Apply = delegate { MilitaryGoOrWait(party, location, "follow warband"); } }); } else { options.Add(new Campaign.AiOption { Task = "Wait for your warband", Score = 1.0, Detail = "the destination is inaccessible", Apply = delegate { C.ClearOrder(party); } }); } return; } options.Add(new Campaign.AiOption { Task = "Follow your warband", Score = 1.0, Detail = "known position of your own party", Apply = delegate { if (party.Order.Kind != OrderKind.Follow || party.Order.TargetId != player.Id) { C.SetMoveOrder(party, OrderKind.Follow, player.Position, player.Id, "military follow"); } } }); return; } if (C.MilitaryRecruitmentBaseReason(record, party).Length == 0) { Settlement market2 = (from s in MilitaryFriendlySettlements(party) where C.MilitaryRecruitCandidate(record, party, s) >= 0 orderby Vec2.Distance(party.Position, s.Position) select s).ThenBy((Settlement s) => s.Id, StringComparer.Ordinal).FirstOrDefault(); if (market2 != null) { options.Add(new Campaign.AiOption { Task = "Recruit at " + market2.Name, Score = 1.1, Detail = "replenish from available recruits within clan budgets", Apply = delegate { MilitaryGoOrWait(party, market2, "military recruitment"); } }); } } Settlement anchor = MilitaryRecallSettlement(party, record); options.Add(new Campaign.AiOption { Task = "Patrol holding", Score = 0.7, Detail = (anchor?.Name ?? "No friendly holding"), Apply = delegate { if (anchor == null) { C.ClearOrder(party); } else if (party.Order.Kind != OrderKind.Patrol || !party.Order.HasPath || Vec2.Distance(party.Order.PathGoal, anchor.Position) > Rules.PatrolRadius * 1.5) { C.PatrolNear(party, anchor.Position); } } }); } internal void MilitaryGoOrWait(Party party, Settlement destination, string reason) { if (destination == null) { C.ClearOrder(party); } else if (party.State == PartyState.InSettlement && party.CurrentSettlementId == destination.Id) { MilitarySettlementArrival(party, destination); C.ClearOrder(party); } else if (party.Order.Kind != OrderKind.GoToSettlement || party.Order.TargetId != destination.Id) { C.SetMoveOrder(party, OrderKind.GoToSettlement, destination.Position, destination.Id, reason); } } internal void MilitarySettlementArrival(Party party, Settlement settlement) { if (C.MilitaryPartyFor(party) != null && party.State == PartyState.InSettlement && !(party.CurrentSettlementId != settlement?.Id) && !(Vec2.Distance(party.Position, settlement.Position) > 0.01) && C.CanEnter(party, settlement)) { ResupplyMilitaryParty(party, settlement); C.RecruitMilitaryParty(party, settlement); party.WaitUntilMinute = State.Clock.Minute + 60; } } internal void ResupplyMilitaryParty(Party party, Settlement settlement) { Clan clan = State.Clans.Get(party.ClanId); MilitaryPartyState militaryPartyState = C.MilitaryPartyFor(party); if (C.MilitaryBudgetPartyReason(militaryPartyState, party).Length > 0 || clan == null || clan.Gold <= 0 || settlement?.Market == null || !settlement.Market.Initialized || !C.CanEnter(party, settlement) || C.SettlementFood(settlement) <= 0.0 || settlement.Market.Gold < 0 || !Campaign.MilitaryFinite(party.Food) || party.Food < 0.0 || party.State != PartyState.InSettlement || party.CurrentSettlementId != settlement.Id || Vec2.Distance(party.Position, settlement.Position) > 0.01) { return; } double num = Math.Max(0.0, C.DailyFoodNeed(party) * 4.0 - party.Food); double num2 = Math.Max(1.0, C.FoodPrice(settlement)); long num3 = C.MilitaryFoodPurchaseBudget(militaryPartyState, clan, settlement); if (num3 <= 0 || !Campaign.MilitaryFinite(num2) || !Campaign.MilitaryFinite(num) || num2 > 7.922816251426434E+28) { return; } double val = (double)(decimal.Floor((decimal)num3 / (decimal)num2 * 1000000m) / 1000000m); double num4 = Math.Min(num, Math.Min(C.SettlementFood(settlement), val)); if (num4 <= 1E-09 || double.IsInfinity(num4) || double.IsNaN(num4)) { return; } decimal num5 = decimal.Ceiling((decimal)num4 * (decimal)num2); if (!(num5 <= 0m) && !(num5 > (decimal)num3)) { long num6 = (long)num5; double num7 = party.Food + num4 - party.Food; if (!(num7 <= 0.0) && !(num7 > num4 + 1E-09)) { State.Transact(clan, -num6, LedgerAccount.Food, "Supplies for " + party.Name + " at " + settlement.Name); C.BeginMilitarySpending(militaryPartyState); militaryPartyState.FoodSpentToday += num6; settlement.Market.Gold += num6; party.Food += C.TakeSettlementFood(settlement, num7); State.Touch(); } } } public void DailyMilitaryParties() { C.ReconcileMilitaryParties(); foreach (MilitaryPartyState item in State.MilitaryParties.Where((MilitaryPartyState x) => x.IsActive).OrderBy((MilitaryPartyState x) => x.Id, StringComparer.Ordinal)) { Party party = State.Parties.Get(item.PartyId); if (party != null && party.State == PartyState.InSettlement && !C.MilitaryPartyReserved(item.PartyId) && string.IsNullOrEmpty(party.EncounterId)) { Settlement settlement = State.Settlements.Get(party.CurrentSettlementId); if (settlement != null && C.CanEnter(party, settlement)) { ResupplyMilitaryParty(party, settlement); C.RecruitMilitaryParty(party, settlement); } else { party.WaitUntilMinute = 0L; party.NextThinkMinute = 0L; } } } } } internal sealed class MilitaryBudgetsSystem { private readonly Campaign C; private CampaignRules Rules => C.Rules; private CampaignState State => C.State; internal MilitaryBudgetsSystem(Campaign host) { C = host; } internal static string MilitaryBudgetValuesReason(int target, long recruitBudget, long foodBudget, long wageLimit, long reserve) { if (target < 0 || target > 1000) { return "Choose a troop target from 0 to 1000."; } if (recruitBudget < 0 || foodBudget < -1 || wageLimit < -1 || reserve < 0) { return "Warband budgets cannot be negative; -1 means unlimited food or wages."; } return ""; } internal string MilitaryBudgetPartyReason(MilitaryPartyState record, Party party) { if (record != null && record.IsActive && !(record.OwnerClanId != State.PlayerClanId) && party != null && !(party.ClanId != record.OwnerClanId) && party.Kind == PartyKind.Lord && (party.State == PartyState.Active || party.State == PartyState.InSettlement || party.State == PartyState.Engaged)) { Clan clan = State.Clans.Get(record.OwnerClanId); if (clan != null && !clan.IsEliminated) { if (C.MilitaryPartyReserved(party.Id) || !string.IsNullOrEmpty(party.EncounterId)) { return "Battle in progress."; } Hero hero = State.Heroes.Get(record.LeaderHeroId); if (!C.IsOwnedCompanion(hero) || hero.State != HeroState.Active || party.LeaderHeroId != hero.Id || !Campaign.IsPresentPartyHero(party, hero)) { return "Captain unavailable."; } return ""; } } return "Warband unavailable."; } public string MilitaryPartyBudgetReason(string id, bool autoRecruit, int target, long recruitBudget, long foodBudget, long wageLimit, long reserve) { string text = C.CargoCommandReason(); if (text.Length > 0) { return text; } if (C.MilitaryPartyReserved(State.PlayerPartyId) || !string.IsNullOrEmpty(State.PlayerParty.EncounterId)) { return "Resolve your encounter first."; } MilitaryPartyState militaryPartyState = State.MilitaryParties?.FirstOrDefault((MilitaryPartyState r) => r.Id == id); text = MilitaryBudgetPartyReason(militaryPartyState, State.Parties.Get(militaryPartyState?.PartyId ?? "")); if (text.Length > 0) { return text; } text = MilitaryBudgetValuesReason(target, recruitBudget, foodBudget, wageLimit, reserve); if (text.Length > 0) { return text; } if (militaryPartyState.AutoRecruit != autoRecruit || militaryPartyState.RecruitmentTarget != target || militaryPartyState.DailyRecruitBudget != recruitBudget || militaryPartyState.DailyFoodBudget != foodBudget || militaryPartyState.RecruitmentWageLimit != wageLimit || militaryPartyState.TreasuryReserve != reserve) { return ""; } return "Budgets are unchanged."; } public CommandResult SetMilitaryPartyBudget(string id, bool autoRecruit, int target, long recruitBudget, long foodBudget, long wageLimit, long reserve) { string text = MilitaryPartyBudgetReason(id, autoRecruit, target, recruitBudget, foodBudget, wageLimit, reserve); if (text.Length > 0) { return CommandResult.Fail(text); } MilitaryPartyState militaryPartyState = State.MilitaryParties.First((MilitaryPartyState r) => r.Id == id); militaryPartyState.AutoRecruit = autoRecruit; militaryPartyState.RecruitmentTarget = target; militaryPartyState.DailyRecruitBudget = recruitBudget; militaryPartyState.DailyFoodBudget = foodBudget; militaryPartyState.RecruitmentWageLimit = wageLimit; militaryPartyState.TreasuryReserve = reserve; State.Touch(); return CommandResult.Success("Warband budgets updated."); } public long MilitaryRecruitBudgetRemaining(MilitaryPartyState record) { if (record != null && record.DailyRecruitBudget >= 0) { return Math.Max(0L, record.DailyRecruitBudget - ((record.SpendingDay == State.Clock.Day) ? Math.Max(0L, record.RecruitmentSpentToday) : 0)); } return 0L; } public long MilitaryFoodBudgetRemaining(MilitaryPartyState record) { if (record != null && record.DailyFoodBudget >= -1) { if (record.DailyFoodBudget != -1) { return Math.Max(0L, record.DailyFoodBudget - ((record.SpendingDay == State.Clock.Day) ? Math.Max(0L, record.FoodSpentToday) : 0)); } return long.MaxValue; } return 0L; } internal bool MilitarySpendingValid(MilitaryPartyState record) { if (record != null && MilitaryBudgetValuesReason(record.RecruitmentTarget, record.DailyRecruitBudget, record.DailyFoodBudget, record.RecruitmentWageLimit, record.TreasuryReserve).Length == 0 && record.SpendingDay >= -1 && record.SpendingDay <= State.Clock.Day && record.RecruitmentSpentToday >= 0 && record.FoodSpentToday >= 0 && record.RecruitsToday >= 0 && record.RecruitsToday <= 3 && (record.SpendingDay < 0 || record.SpendingDay >= record.StartedMinute / 1440) && (record.RecruitmentSpentToday == 0L || record.RecruitsToday > 0)) { if (record.SpendingDay == -1) { if (record.RecruitmentSpentToday == 0L && record.FoodSpentToday == 0L) { return record.RecruitsToday == 0; } return false; } return true; } return false; } internal long MilitaryAvailableTreasury(MilitaryPartyState record, Clan clan) { if (clan != null && MilitarySpendingValid(record) && clan.Gold > record.TreasuryReserve) { return clan.Gold - record.TreasuryReserve; } return 0L; } internal long MilitaryFoodPurchaseBudget(MilitaryPartyState record, Clan clan, Settlement settlement) { if (settlement?.Market == null || !settlement.Market.Initialized || settlement.Market.Gold < 0 || !MilitarySpendingValid(record)) { return 0L; } long num = ((record.SpendingDay == State.Clock.Day) ? record.FoodSpentToday : 0); return Math.Min(Math.Min(MilitaryAvailableTreasury(record, clan), MilitaryFoodBudgetRemaining(record)), Math.Min(long.MaxValue - settlement.Market.Gold, long.MaxValue - num)); } internal void BeginMilitarySpending(MilitaryPartyState record) { if (record.SpendingDay != State.Clock.Day) { record.SpendingDay = State.Clock.Day; record.RecruitmentSpentToday = 0L; record.FoodSpentToday = 0L; record.RecruitsToday = 0; } } internal string MilitaryRecruitmentBaseReason(MilitaryPartyState record, Party party) { string text = MilitaryBudgetPartyReason(record, party); if (text.Length > 0) { return text; } if (!MilitarySpendingValid(record)) { return "Invalid spending record."; } if (!record.AutoRecruit) { return "Recruitment off."; } if (C.ClanArmyContains(party.Id)) { return "Army duty."; } if (record.Directive != MilitaryPartyDirective.Patrol) { return record.Directive.ToString() + " order."; } if (!State.Heroes.Require(record.LeaderHeroId).CanFight) { return "Captain recovering."; } if (record.SpendingDay == State.Clock.Day && record.RecruitsToday >= 3) { return "Daily recruit limit."; } if (party.Troops == null || party.Troops.Stacks == null || party.Troops.Stacks.Any((TroopStack s) => s == null) || C.MilitaryRosterMergeReason(party.Troops, new TroopRoster(), prisoners: false).Length > 0) { return "Invalid troop roster."; } if (Campaign.MilitaryTroopCount(party.Troops) >= Math.Min(record.RecruitmentTarget, C.PartySizeLimit(party))) { return "Troop target reached."; } if (party.UnpaidDays > 0) { return "Unpaid wages."; } if (party.StarvingDays > 0 || !Campaign.MilitaryFinite(party.Food) || party.Food < C.DailyFoodNeed(party)) { return "Need supplies."; } return ""; } internal string MilitaryRecruitSlotReason(MilitaryPartyState record, Party party, Settlement settlement, int index) { string text = MilitaryRecruitmentBaseReason(record, party); if (text.Length > 0) { return text; } Clan clan = State.Clans.Get(settlement?.OwnerClanId ?? ""); if (settlement == null || settlement.Type == SettlementType.Hideout || clan == null || clan.IsBandit || clan.IsEliminated || !C.CanEnter(party, settlement)) { return "No friendly recruitment market."; } if (settlement.Recruits != null && index >= 0 && index < settlement.Recruits.Count) { RecruitSlot recruitSlot = settlement.Recruits[index]; if (recruitSlot != null && recruitSlot.Available) { RecruitSlot recruitSlot2 = settlement.Recruits[index]; text = C.RecruitSlotRelationReason(settlement, recruitSlot2, party.ClanId); if (text.Length > 0) { return text; } UnitDef unitDef = C.UnitDef(recruitSlot2.UnitId); if (unitDef == null || unitDef.RecruitCost < 0 || !Campaign.MilitaryFinite(unitDef.DailyWage) || unitDef.DailyWage < 0.0 || !Campaign.MilitaryFinite(unitDef.FoodUse) || unitDef.FoodUse < 0.0 || unitDef.Rarity == UnitRarity.Unique || unitDef.Access == null || !unitDef.Access.Any((AccessKind a) => a == AccessKind.VillageRecruit || a == AccessKind.TownRecruit || a == AccessKind.Upgrade || a == AccessKind.Mercenary || a == AccessKind.Bandit)) { return "Recruit unavailable."; } Clan clan2 = State.Clans.Get(party.ClanId); long num = C.RecruitPrice(party, unitDef); if (num > MilitaryRecruitBudgetRemaining(record)) { return "Recruitment budget reached."; } if (num > MilitaryAvailableTreasury(record, clan2)) { return "Treasury reserve protected."; } double num2 = unitDef.DailyWage * (C.HasRolePerk(party, PartyRole.Quartermaster, "perk.quartermaster.paymaster") ? 0.9 : 1.0) * C.PerkReduction(party, PerkEffect.Wages); double num3 = Math.Ceiling(C.DailyWages(party) + num2); if (!Campaign.MilitaryFinite(num3) || (record.RecruitmentWageLimit >= 0 && num3 > (double)record.RecruitmentWageLimit)) { return "Recruitment wage limit."; } double num4 = unitDef.FoodUse * Rules.FoodPerTroopPerDay * (1.0 - Math.Min(0.25, (double)C.RoleSkill(party, PartyRole.Quartermaster) / 1000.0)) * (C.HasRolePerk(party, PartyRole.Quartermaster, "perk.quartermaster.frugal") ? 0.9 : 1.0) * C.PerkReduction(party, PerkEffect.FoodUse); if (!Campaign.MilitaryFinite(num4) || party.Food + 1E-09 < C.DailyFoodNeed(party) + num4) { return "Need supplies."; } Clan clan3 = new Clan { Id = clan2.Id, Gold = clan2.Gold - num }; if (!C.ClanCanAffordUpkeep(clan3, num3 - Math.Ceiling(C.DailyWages(party)) + num4 * Rules.FoodPrice)) { return "Cannot sustain new upkeep."; } return ""; } } return "No available recruits."; } internal int MilitaryRecruitCandidate(MilitaryPartyState record, Party party, Settlement settlement) { if (settlement?.Recruits != null) { return (from i in Enumerable.Range(0, settlement.Recruits.Count) where MilitaryRecruitSlotReason(record, party, settlement, i).Length == 0 orderby C.UnitDef(settlement.Recruits[i].UnitId).RecruitCost, i select i).DefaultIfEmpty(-1).First(); } return -1; } public string MilitaryRecruitmentStatus(string id) { MilitaryPartyState militaryPartyState = State.MilitaryParties?.FirstOrDefault((MilitaryPartyState r) => r.Id == id); Party party = State.Parties.Get(militaryPartyState?.PartyId ?? ""); string text = MilitaryRecruitmentBaseReason(militaryPartyState, party); if (text.Length > 0) { return text; } Settlement settlement = State.Settlements.Get(party.CurrentSettlementId); if (party.State != PartyState.InSettlement || settlement == null || Vec2.Distance(party.Position, settlement.Position) > 0.01) { return "Seeking recruits."; } if (MilitaryRecruitCandidate(militaryPartyState, party, settlement) >= 0) { return "Ready to recruit."; } int index = settlement.Recruits?.FindIndex((RecruitSlot r) => r?.Available ?? false) ?? (-1); return MilitaryRecruitSlotReason(militaryPartyState, party, settlement, index); } internal void RecruitMilitaryParty(Party party, Settlement settlement) { MilitaryPartyState militaryPartyState = C.MilitaryPartyFor(party); if (party == null || party.State != PartyState.InSettlement || settlement == null || party.CurrentSettlementId != settlement.Id || Vec2.Distance(party.Position, settlement.Position) > 0.01) { return; } for (int i = 0; i < 3; i++) { int num = MilitaryRecruitCandidate(militaryPartyState, party, settlement); if (num < 0) { break; } RecruitSlot recruitSlot = settlement.Recruits[num]; UnitDef unitDef = C.UnitDef(recruitSlot.UnitId); Clan clan = State.Clans.Require(party.ClanId); long num2 = C.RecruitPrice(party, unitDef); State.Transact(clan, -num2, LedgerAccount.Recruitment, party.Name + " recruits " + unitDef.Name + " at " + settlement.Name); BeginMilitarySpending(militaryPartyState); militaryPartyState.RecruitmentSpentToday += num2; militaryPartyState.RecruitsToday++; party.Troops.Add(unitDef.Id, 1); recruitSlot.Available = false; State.Touch(); } } } internal sealed class MilitaryPartiesSystem { private readonly Campaign C; private CampaignState State => C.State; internal MilitaryPartiesSystem(Campaign host) { C = host; } public void EnsureMilitaryPartyFields() { if (State.MilitaryParties == null) { State.MilitaryParties = new List(); State.Touch(); } } public MilitaryPartyState MilitaryPartyFor(Party party) { if (party != null) { return State.MilitaryParties?.FirstOrDefault((MilitaryPartyState record) => record.IsActive && record.PartyId == party.Id); } return null; } public bool IsPlayerMilitaryParty(Party party) { MilitaryPartyState militaryPartyState = MilitaryPartyFor(party); if (militaryPartyState != null && militaryPartyState.OwnerClanId == State.PlayerClanId && party.ClanId == militaryPartyState.OwnerClanId && party.Kind == PartyKind.Lord && party.State != PartyState.Destroyed) { return party.State != PartyState.Disbanded; } return false; } internal Settlement MilitaryMeetingPlace() { Settlement settlement = C.CurrentSettlement(); if (settlement == null || (settlement.Type != SettlementType.Town && settlement.Type != SettlementType.Castle) || !C.CanEnter(State.PlayerParty, settlement) || !(Vec2.Distance(State.PlayerParty.Position, settlement.Position) <= 0.01)) { return null; } return settlement; } internal static bool MilitaryFinite(double value) { if (!double.IsNaN(value)) { return !double.IsInfinity(value); } return false; } internal static long MilitaryTroopCount(TroopRoster roster) { return roster.Stacks.Sum((TroopStack stack) => (long)stack.Healthy + (long)stack.Wounded); } public string LaunchMilitaryPartyReason(string heroId, string unitId) { string text = C.CargoCommandReason(); if (text.Length > 0) { return text; } if (MilitaryMeetingPlace() == null) { return "Warbands are formed in friendly towns or castles."; } if (State.MilitaryParties == null) { return "Clan warbands are unavailable."; } if (State.MilitaryParties.Count((MilitaryPartyState record) => record.IsActive && record.OwnerClanId == State.PlayerClanId) >= 2) { return "Two companion warbands is the limit."; } Hero hero = State.Heroes.Get(heroId); Party playerParty = State.PlayerParty; if (!C.IsOwnedCompanion(hero) || !hero.CanFight || !Campaign.IsPresentPartyHero(playerParty, hero)) { return "Pick a healthy companion who's with you."; } if (C.GovernorAssignedSettlement(hero.Id) != null) { return "Recall this governor first."; } if (State.Parties.Any((Party party) => party.LeaderHeroId == hero.Id && party.State != PartyState.Destroyed && party.State != PartyState.Disbanded)) { return "This companion already commands a party."; } if (C.UnitDef(unitId) == null || playerParty.Troops.Healthy(unitId) < 10) { return "Pick ten healthy soldiers of one type."; } long num = MilitaryTroopCount(playerParty.Troops); if (num - 10 > C.PartySizeLimit(playerParty)) { return "You'd still be over your troop limit."; } long num2 = C.PrisonerLimit(playerParty) + (num - 10) / 4 - num / 4; if (MilitaryTroopCount(playerParty.Prisoners) > num2) { return "Keep enough men back to guard your prisoners."; } Party p = new Party { ClanId = State.PlayerClanId, LeaderHeroId = hero.Id }; if (10 > C.PartySizeLimit(p)) { return "This companion can't command ten men yet."; } double num3 = C.FoodSupply(playerParty); if (!MilitaryFinite(playerParty.Food) || num3 < 2.0 || Math.Abs(num3 - (num3 - 2.0) - 2.0) > 1E-06) { return "You need at least two food to send with them."; } if (!string.IsNullOrEmpty(playerParty.EncounterId) || C.MilitaryPartyReserved(playerParty.Id)) { return "Deal with the encounter first."; } return ""; } public CommandResult LaunchMilitaryParty(string heroId, string unitId) { string text = LaunchMilitaryPartyReason(heroId, unitId); if (text.Length > 0) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Require(heroId); Party playerParty = State.PlayerParty; Settlement settlement = MilitaryMeetingPlace(); int xp = playerParty.Troops.Find(unitId).Xp; playerParty.Troops.RemoveHealthy(unitId, 10); int xp2 = xp - (playerParty.Troops.Find(unitId)?.Xp ?? 0); Party party = new Party { Id = State.Ids.Allocate("party"), Name = hero.Name + "'s Warband", Kind = PartyKind.Lord, ClanId = State.PlayerClanId, LeaderHeroId = hero.Id, HomeSettlementId = settlement.Id, Position = settlement.Position, State = PartyState.InSettlement, CurrentSettlementId = settlement.Id, Food = 2.0, Gold = 0L, CreatedAtMinute = State.Clock.Minute, NextThinkMinute = State.Clock.Minute }; party.Troops.Add(unitId, 10, 0, xp2); party.Troops.Heroes.Add(hero.Id); C.TakeFood(playerParty, 2.0); C.ClearHeroRoleAssignments(hero.Id); playerParty.Troops.Heroes.Remove(hero.Id); hero.PartyId = party.Id; hero.SettlementId = ""; C.HorseFollows(hero, playerParty, party); MilitaryPartyState item = new MilitaryPartyState { Id = State.Ids.Allocate("military"), PartyId = party.Id, OwnerClanId = State.PlayerClanId, LeaderHeroId = hero.Id, HomeSettlementId = settlement.Id, StartedMinute = State.Clock.Minute }; State.Parties.Add(party); State.MilitaryParties.Add(item); State.AddLog(LogCategory.Recruitment, party.Name + " formed at " + settlement.Name + " with ten soldiers and two food. You pay the wages.", party.Id, hero.Id, settlement.Id); State.Touch(); return CommandResult.Success(party.Name + " is ready to patrol."); } internal string MilitaryRosterMergeReason(TroopRoster source, TroopRoster destination, bool prisoners) { if (source.Stacks.Select((TroopStack stack) => stack.UnitId).Distinct().Count() != source.Stacks.Count || destination.Stacks.Select((TroopStack stack) => stack.UnitId).Distinct().Count() != destination.Stacks.Count) { return "The roster contains duplicate troop stacks."; } foreach (TroopStack item in source.Stacks.Concat(destination.Stacks)) { if (C.UnitDef(item.UnitId) == null || item.Healthy < 0 || item.Wounded < 0 || item.Xp < 0 || (long)item.Healthy + (long)item.Wounded > int.MaxValue || !MilitaryFinite(item.PrisonerRecruitment) || item.PrisonerRecruitment < 0.0 || item.PrisonerRecruitment > (double)((long)item.Healthy + (long)item.Wounded) + 1E-07) { return "The roster contains invalid troop accounting."; } } foreach (TroopStack stack in source.Stacks) { TroopStack troopStack = destination.Find(stack.UnitId); if ((long)stack.Healthy + (long)(troopStack?.Healthy ?? 0) + stack.Wounded + (troopStack?.Wounded ?? 0) > int.MaxValue || (long)stack.Xp + (long)(troopStack?.Xp ?? 0) > int.MaxValue) { return prisoners ? "Your prisoner roster cannot hold more troops or training experience." : "Your roster cannot hold more troops or training experience."; } if (!MilitaryFinite(stack.PrisonerRecruitment + (troopStack?.PrisonerRecruitment ?? 0.0))) { return "Your prisoner roster cannot hold more recruitment progress."; } } return ""; } public string MilitaryPartyActionReason(string id, string action) { string text = C.CargoCommandReason(); if (text.Length > 0) { return text; } if (C.MilitaryPartyReserved(State.PlayerPartyId) || !string.IsNullOrEmpty(State.PlayerParty.EncounterId)) { return "Deal with the encounter first."; } if (action != "patrol" && action != "follow" && action != "recall" && action != "disband" && action != "transfer") { return "Unknown warband action."; } MilitaryPartyState militaryPartyState = State.MilitaryParties?.FirstOrDefault((MilitaryPartyState candidate) => candidate.Id == id); Party party = State.Parties.Get(militaryPartyState?.PartyId ?? ""); if (militaryPartyState == null || !militaryPartyState.IsActive || militaryPartyState.OwnerClanId != State.PlayerClanId || party == null || party.Kind != PartyKind.Lord || party.ClanId != militaryPartyState.OwnerClanId || party.State == PartyState.Destroyed || party.State == PartyState.Disbanded) { return "That warband's gone."; } if (C.MilitaryPartyReserved(party.Id) || !string.IsNullOrEmpty(party.EncounterId)) { return "Wait until it's finished its battle."; } if (action != "transfer" && C.ClanArmyContains(party.Id)) { return "Release it from your army before giving it its own orders."; } Hero hero = State.Heroes.Get(militaryPartyState.LeaderHeroId); if (!C.IsOwnedCompanion(hero) || hero.State != HeroState.Active || party.LeaderHeroId != hero.Id || !Campaign.IsPresentPartyHero(party, hero)) { return "This warband has lost its commander."; } if (action != "disband" && action != "transfer") { MilitaryPartyDirective militaryPartyDirective = ((action == "follow") ? MilitaryPartyDirective.Follow : ((action == "recall") ? MilitaryPartyDirective.Recall : MilitaryPartyDirective.Patrol)); if (militaryPartyState.Directive != militaryPartyDirective) { return ""; } return "It's already doing that."; } Settlement settlement = MilitaryMeetingPlace(); if (settlement == null || party.State != PartyState.InSettlement || party.CurrentSettlementId != settlement.Id || Vec2.Distance(party.Position, settlement.Position) > 0.01 || !C.CanEnter(party, settlement)) { return "Meet it in the same friendly town or castle to regroup."; } if (action == "transfer") { return ""; } Party playerParty = State.PlayerParty; text = MilitaryRosterMergeReason(party.Troops, playerParty.Troops, prisoners: false); if (text.Length > 0) { return text; } text = MilitaryRosterMergeReason(party.Prisoners, playerParty.Prisoners, prisoners: true); if (text.Length > 0) { return text; } long num = MilitaryTroopCount(playerParty.Troops) + MilitaryTroopCount(party.Troops); if (num > C.PartySizeLimit(playerParty)) { return "No room for the survivors."; } long num2 = C.PrisonerLimit(playerParty) + num / 4 - MilitaryTroopCount(playerParty.Troops) / 4; if (MilitaryTroopCount(playerParty.Prisoners) + MilitaryTroopCount(party.Prisoners) > num2) { return "No room for its prisoners."; } if (party.Troops.Heroes.Distinct().Count() != party.Troops.Heroes.Count || party.Prisoners.Heroes.Distinct().Count() != party.Prisoners.Heroes.Count) { return "The warband has duplicate hero records."; } foreach (string hero4 in party.Troops.Heroes) { Hero hero2 = State.Heroes.Get(hero4); if (!C.IsOwnedCompanion(hero2) || hero2.State != HeroState.Active || !Campaign.IsPresentPartyHero(party, hero2) || playerParty.Troops.Heroes.Contains(hero4) || playerParty.Prisoners.Heroes.Contains(hero4) || party.Prisoners.Heroes.Contains(hero4) || C.GovernorAssignedSettlement(hero4) != null) { return "A travelling companion has an incompatible location."; } } foreach (string hero5 in party.Prisoners.Heroes) { Hero hero3 = State.Heroes.Get(hero5); if (hero3 == null || hero3.State != HeroState.Captive || hero3.CaptorPartyId != party.Id || !string.IsNullOrEmpty(hero3.CaptorSettlementId) || !string.IsNullOrEmpty(hero3.PartyId) || playerParty.Prisoners.Heroes.Contains(hero5) || playerParty.Troops.Heroes.Contains(hero5)) { return "A named prisoner's custody must be resolved first."; } } foreach (KeyValuePair cargo in party.Cargo) { if (!TradeGoods.All.Any((TradeGoodDef good) => good.Id == cargo.Key) || cargo.Value < 0 || (long)cargo.Value + (long)C.CargoCount(playerParty, cargo.Key) > int.MaxValue) { return "You can't carry that much."; } } string text2 = C.EquipmentReunionReason(party, playerParty); if (text2.Length > 0) { return text2; } double num3 = C.CargoCapacity(playerParty) + (double)(MilitaryTroopCount(party.Troops) * 2) + (double)(party.Troops.Heroes.Count * 10); if (C.CargoWeight(playerParty) + C.CargoWeight(party) > num3 + 1E-09) { return "No room for its cargo."; } if (party.Gold < 0 || State.PlayerClan.Gold > long.MaxValue - party.Gold) { return "Your treasury can't take that much."; } double num4 = playerParty.Food + party.Food; if (!MilitaryFinite(playerParty.Food) || !MilitaryFinite(party.Food) || party.Food < 0.0 || !MilitaryFinite(num4) || Math.Abs(num4 - playerParty.Food - party.Food) > 1E-06) { return "You can't carry that much food."; } return ""; } public CommandResult SetMilitaryPartyDirective(string id, MilitaryPartyDirective directive) { if (!Enum.IsDefined(typeof(MilitaryPartyDirective), directive)) { return CommandResult.Fail("Unknown warband directive."); } string text = MilitaryPartyActionReason(id, directive switch { MilitaryPartyDirective.Recall => "recall", MilitaryPartyDirective.Follow => "follow", _ => "patrol", }); if (text.Length > 0) { return CommandResult.Fail(text); } MilitaryPartyState militaryPartyState = State.MilitaryParties.First((MilitaryPartyState candidate) => candidate.Id == id); Party party = State.Parties.Require(militaryPartyState.PartyId); militaryPartyState.Directive = directive; C.ClearOrder(party); party.NextThinkMinute = State.Clock.Minute; party.WaitUntilMinute = State.Clock.Minute; string text2 = party.Name + directive switch { MilitaryPartyDirective.Recall => " is heading to a friendly town or castle. Meet it there.", MilitaryPartyDirective.Follow => " will follow your warband.", _ => " will patrol near its home.", }; State.AddLog(LogCategory.Info, text2, party.Id, militaryPartyState.HomeSettlementId); State.Touch(); return CommandResult.Success(text2); } public CommandResult DisbandMilitaryParty(string id) { string text = MilitaryPartyActionReason(id, "disband"); if (text.Length > 0) { return CommandResult.Fail(text); } MilitaryPartyState militaryPartyState = State.MilitaryParties.First((MilitaryPartyState candidate) => candidate.Id == id); Party party = State.Parties.Require(militaryPartyState.PartyId); Party playerParty = State.PlayerParty; foreach (TroopStack stack in party.Troops.Stacks) { playerParty.Troops.Add(stack.UnitId, stack.Healthy, stack.Wounded, stack.Xp); } party.Troops.Stacks.Clear(); foreach (string item in party.Troops.Heroes.ToList()) { C.JoinCompanionToPlayerParty(State.Heroes.Require(item)); } party.Troops.Heroes.Clear(); foreach (TroopStack stack2 in party.Prisoners.Stacks) { playerParty.Prisoners.Add(stack2.UnitId, stack2.Healthy, stack2.Wounded, stack2.Xp); playerParty.Prisoners.Find(stack2.UnitId).PrisonerRecruitment += stack2.PrisonerRecruitment; } party.Prisoners.Stacks.Clear(); foreach (string hero in party.Prisoners.Heroes) { playerParty.Prisoners.Heroes.Add(hero); State.Heroes.Require(hero).CaptorPartyId = playerParty.Id; } party.Prisoners.Heroes.Clear(); foreach (KeyValuePair item2 in party.Cargo) { if (item2.Value > 0) { playerParty.Cargo[item2.Key] = C.CargoCount(playerParty, item2.Key) + item2.Value; } } party.Cargo.Clear(); C.ReuniteEquipment(party, playerParty); C.ReuniteHorses(party, playerParty); playerParty.Food += party.Food; party.Food = 0.0; State.Transact(State.PlayerClan, party.Gold, LedgerAccount.Other, "Reunited " + party.Name); party.Gold = 0L; party.State = PartyState.Disbanded; party.LeaderHeroId = ""; party.CurrentSettlementId = ""; party.RoleAssignments.Clear(); C.ClearOrder(party); militaryPartyState.Status = "Disbanded"; State.PlayerSightings.Remove(party.Id); State.AddLog(LogCategory.Recruitment, party.Name + " rejoined you with its survivors, prisoners and supplies.", party.Id, militaryPartyState.LeaderHeroId); C.TrimMilitaryPartyHistory(); State.Touch(); return CommandResult.Success("Warbands reunited."); } } internal sealed class MilitaryRecoverySystem { private readonly Campaign C; private CampaignState State => C.State; internal MilitaryRecoverySystem(Campaign host) { C = host; } internal bool MilitaryPartyReserved(string partyId) { Party party = State.Parties.Get(partyId); if (party == null || party.State != PartyState.Engaged) { return State.Encounters.Any((Encounter e) => e.Phase != EncounterPhase.Committed && e.Phase != EncounterPhase.Cancelled && (e.InitiatorPartyId == partyId || e.AllParties.Contains(partyId))); } return true; } public void ReconcileMilitaryParties() { bool flag = false; foreach (MilitaryPartyState item in State.MilitaryParties.Where((MilitaryPartyState x) => x.IsActive).ToList()) { if (MilitaryPartyReserved(item.PartyId)) { continue; } Party party = State.Parties.Get(item.PartyId); Hero hero = State.Heroes.Get(item.LeaderHeroId); if (party != null && party.Kind == PartyKind.Lord && party.ClanId == item.OwnerClanId && party.LeaderHeroId == item.LeaderHeroId && party.State != PartyState.Destroyed && party.State != PartyState.Disbanded && hero != null && hero.State == HeroState.Active && hero.ClanId == item.OwnerClanId && Campaign.IsPresentPartyHero(party, hero)) { continue; } if (party != null) { if (party.State != PartyState.Destroyed && party.State != PartyState.Disbanded) { RecoverLeaderlessMilitaryParty(party, item); } else { party.Troops.Stacks.Clear(); foreach (string item2 in party.Troops.Heroes.ToList()) { Hero hero2 = State.Heroes.Get(item2); if (hero2 != null && hero2.State == HeroState.Active && hero2.PartyId == party.Id && hero2.Occupation == HeroOccupation.Companion) { C.ShelterCompanion(hero2, party.Position, "their military party was lost"); } } party.Troops.Heroes.Clear(); foreach (string item3 in party.Prisoners.Heroes.ToList()) { OutcomeCommitter.ReleaseHero(C, State.Heroes.Get(item3), "their military captors were lost"); } party.Prisoners.Heroes.Clear(); party.Prisoners.Stacks.Clear(); party.Cargo?.Clear(); party.Equipment?.Clear(); party.Food = 0.0; party.RoleAssignments?.Clear(); C.ClearOrder(party); } party.Gold = 0L; if (hero != null && hero.PartyId == party.Id) { if (hero.State == HeroState.Active && hero.Occupation == HeroOccupation.Companion) { C.ShelterCompanion(hero, party.Position, "their military party lost its captain"); } else { hero.PartyId = ""; } } } else if (hero != null && hero.State == HeroState.Active && hero.PartyId == item.PartyId) { C.ShelterCompanion(hero, State.Settlements.Get(item.HomeSettlementId)?.Position ?? State.PlayerParty?.Position ?? Vec2.Zero, "their military party was lost"); } item.Status = "Lost"; string text = (party?.Name ?? "Military party") + " was lost." + ((hero != null && hero.State == HeroState.Captive) ? (" " + hero.Name + " remains captive.") : ""); State.AddLog(LogCategory.Battle, text, item.PartyId, item.LeaderHeroId); if (item.OwnerClanId == State.PlayerClanId) { C.Raise(CampaignEventKind.Warning, text, false, item.PartyId, item.LeaderHeroId); } flag = true; } if (TrimMilitaryPartyHistory()) { flag = true; } if (flag) { State.Touch(); } C.ReconcileClanArmy(); } internal void RecoverLeaderlessMilitaryParty(Party party, MilitaryPartyState record) { Settlement settlement = State.Settlements.Get(record.HomeSettlementId); bool num = settlement != null && settlement.OwnerClanId == record.OwnerClanId && party.ClanId == record.OwnerClanId; long num2 = 0L; if (num) { foreach (TroopStack stack in party.Troops.Stacks) { if (MilitaryRosterCanReceive(settlement.Garrison, stack)) { settlement.Garrison.Add(stack.UnitId, stack.Healthy, stack.Wounded, stack.Xp); num2 += (long)stack.Healthy + (long)stack.Wounded; } } foreach (TroopStack stack2 in party.Prisoners.Stacks) { if (MilitaryRosterCanReceive(settlement.Prisoners, stack2)) { settlement.Prisoners.Add(stack2.UnitId, stack2.Healthy, stack2.Wounded, stack2.Xp); settlement.Prisoners.Find(stack2.UnitId).PrisonerRecruitment += stack2.PrisonerRecruitment; } } foreach (string item in party.Prisoners.Heroes.ToList()) { Hero hero = State.Heroes.Get(item); if (hero != null && hero.State == HeroState.Captive && !(hero.CaptorPartyId != party.Id)) { if (!settlement.Prisoners.Heroes.Contains(item)) { settlement.Prisoners.Heroes.Add(item); } hero.CaptorPartyId = ""; hero.CaptorSettlementId = settlement.Id; party.Prisoners.Heroes.Remove(item); } } } long num3 = party.Troops.Stacks.Sum((TroopStack s) => (long)s.Healthy + (long)s.Wounded) - num2; party.Troops.Stacks.Clear(); party.Prisoners.Stacks.Clear(); OutcomeCommitter.DestroyParty(C, party, (num2 > 0) ? ("captain lost; " + num2 + " troops returned to " + settlement.Name) : "military captain lost"); party.Gold = 0L; if (num3 > 0) { State.AddLog(LogCategory.Battle, num3 + " troops of " + party.Name + " scattered after losing their captain.", party.Id); } } internal static bool MilitaryRosterCanReceive(TroopRoster roster, TroopStack stack) { TroopStack troopStack = roster.Find(stack.UnitId); long num = (long)(troopStack?.Healthy ?? 0) + (long)(troopStack?.Wounded ?? 0) + stack.Healthy + stack.Wounded; double num2 = (troopStack?.PrisonerRecruitment ?? 0.0) + stack.PrisonerRecruitment; if (num <= int.MaxValue && (long)(troopStack?.Xp ?? 0) + (long)stack.Xp <= int.MaxValue && !double.IsNaN(num2) && !double.IsInfinity(num2) && num2 >= 0.0) { return num2 <= (double)num; } return false; } public bool TrimMilitaryPartyHistory() { bool result = false; foreach (MilitaryPartyState record in (from x in State.MilitaryParties where !x.IsActive orderby x.StartedMinute descending select x).ThenByDescending((MilitaryPartyState x) => x.Id, StringComparer.Ordinal).Skip(30).ToList()) { if (C.ClanArmyContains(record.PartyId) || MilitaryPartyReserved(record.PartyId) || State.Encounters.Any((Encounter e) => e.InitiatorPartyId == record.PartyId || e.AllParties.Contains(record.PartyId)) || State.Heroes.Any((Hero h) => h.PartyId == record.PartyId || h.CaptorPartyId == record.PartyId)) { continue; } Party party = State.Parties.Get(record.PartyId); if (party != null) { if (party.Kind != PartyKind.Lord || (party.State != PartyState.Destroyed && party.State != PartyState.Disbanded) || !party.Troops.IsEmpty || !party.Prisoners.IsEmpty || party.Gold != 0L || party.Food != 0.0) { continue; } SortedDictionary cargo = party.Cargo; if (cargo != null && cargo.Count > 0) { continue; } SortedDictionary equipment = party.Equipment; if (equipment != null && equipment.Count > 0) { continue; } State.Parties.Remove(party.Id); } State.PlayerSightings.Remove(record.PartyId); State.MilitaryParties.Remove(record); result = true; } return result; } } internal sealed class MilitaryTransfersSystem { private readonly Campaign C; private CampaignState State => C.State; internal MilitaryTransfersSystem(Campaign host) { C = host; } public string MilitaryTroopTransferReason(string id, string unitId, int count, bool toMilitary) { string text = C.MilitaryPartyActionReason(id, "transfer"); if (text.Length > 0) { return text; } if (count <= 0) { return "Pick at least one soldier."; } if (C.UnitDef(unitId) == null) { return "Unknown troop type."; } MilitaryPartyState militaryPartyState = State.MilitaryParties.First((MilitaryPartyState candidate) => candidate.Id == id); Party party = State.Parties.Require(militaryPartyState.PartyId); Party party2 = (toMilitary ? State.PlayerParty : party); Party party3 = (toMilitary ? party : State.PlayerParty); TroopStack troopStack = party2.Troops.Find(unitId); if (troopStack == null || troopStack.Healthy < count) { return "It hasn't got that many healthy soldiers."; } TroopStack troopStack2 = party3.Troops.Find(unitId); if (troopStack.Healthy < 0 || troopStack.Wounded < 0 || troopStack.Xp < 0 || (long)troopStack.Healthy + (long)troopStack.Wounded > int.MaxValue || (troopStack2 != null && (troopStack2.Healthy < 0 || troopStack2.Wounded < 0 || troopStack2.Xp < 0))) { return "The troop accounting is invalid."; } if (Campaign.MilitaryTroopCount(party3.Troops) + count > C.PartySizeLimit(party3)) { return "No room there for them."; } if ((long)(troopStack2?.Healthy ?? 0) + (long)(troopStack2?.Wounded ?? 0) + count > int.MaxValue) { return "The receiving roster cannot hold that many soldiers."; } long num = (long)troopStack.Healthy + (long)troopStack.Wounded; int num2 = (int)Math.Round((double)troopStack.Xp * (double)(num - count) / (double)num); int num3 = troopStack.Xp - num2; if ((long)(troopStack2?.Xp ?? 0) + (long)num3 > int.MaxValue) { return "The receiving soldiers cannot hold more training experience."; } long num4 = Campaign.MilitaryTroopCount(party2.Troops); long num5 = C.PrisonerLimit(party2) + (num4 - count) / 4 - num4 / 4; if (Campaign.MilitaryTroopCount(party2.Prisoners) > num5) { return "Leave enough to guard its prisoners."; } return ""; } public CommandResult TransferMilitaryTroops(string id, string unitId, int count, bool toMilitary) { string text = MilitaryTroopTransferReason(id, unitId, count, toMilitary); if (text.Length > 0) { return CommandResult.Fail(text); } MilitaryPartyState militaryPartyState = State.MilitaryParties.First((MilitaryPartyState candidate) => candidate.Id == id); Party party = State.Parties.Require(militaryPartyState.PartyId); Party party2 = (toMilitary ? State.PlayerParty : party); Party party3 = (toMilitary ? party : State.PlayerParty); int xp = party2.Troops.Find(unitId).Xp; party2.Troops.RemoveHealthy(unitId, count); int xp2 = xp - (party2.Troops.Find(unitId)?.Xp ?? 0); party3.Troops.Add(unitId, count, 0, xp2); party.NextThinkMinute = State.Clock.Minute; string text2 = "Transferred " + count + " " + C.UnitDef(unitId).Name + " from " + party2.Name + " to " + party3.Name + "."; State.AddLog(LogCategory.Recruitment, text2, party2.Id, party3.Id); State.Touch(); return CommandResult.Success(text2); } public string MilitaryFoodTransferReason(string id, double amount, bool toMilitary) { string text = C.MilitaryPartyActionReason(id, "transfer"); if (text.Length > 0) { return text; } if (!Campaign.MilitaryFinite(amount) || amount <= 0.0) { return "Choose a positive, finite food amount."; } MilitaryPartyState militaryPartyState = State.MilitaryParties.First((MilitaryPartyState candidate) => candidate.Id == id); Party party = State.Parties.Require(militaryPartyState.PartyId); Party party2 = (toMilitary ? State.PlayerParty : party); Party party3 = (toMilitary ? party : State.PlayerParty); if (!Campaign.MilitaryFinite(party2.Food) || !Campaign.MilitaryFinite(party3.Food) || party2.Food < 0.0 || party3.Food < 0.0) { return "The food accounting is invalid."; } double num = (C.EatsCargoFood(party2) ? C.FoodSupply(party2) : party2.Food); if (num < amount) { return "It isn't carrying that much food."; } double num2 = num - amount; double num3 = party3.Food + amount; double num4 = num - num2; double num5 = num3 - party3.Food; if (!Campaign.MilitaryFinite(num3) || num4 <= 0.0 || num5 <= 0.0 || Math.Abs(num4 - amount) > 1E-07 || Math.Abs(num5 - amount) > 1E-07 || Math.Abs(num4 - num5) > 1E-07) { return "That food quantity cannot be transferred accurately."; } return ""; } public CommandResult TransferMilitaryFood(string id, double amount, bool toMilitary) { string text = MilitaryFoodTransferReason(id, amount, toMilitary); if (text.Length > 0) { return CommandResult.Fail(text); } MilitaryPartyState militaryPartyState = State.MilitaryParties.First((MilitaryPartyState candidate) => candidate.Id == id); Party party = State.Parties.Require(militaryPartyState.PartyId); Party party2 = (toMilitary ? State.PlayerParty : party); Party party3 = (toMilitary ? party : State.PlayerParty); C.TakeFood(party2, amount); party3.Food += amount; party.NextThinkMinute = State.Clock.Minute; string text2 = "Transferred " + amount.ToString("0.##") + " food from " + party2.Name + " to " + party3.Name + "."; State.AddLog(LogCategory.Economy, text2, party2.Id, party3.Id); State.Touch(); return CommandResult.Success(text2); } } internal sealed class MovementSystem { private readonly Campaign C; private NavGrid Nav => C.Nav; private CampaignRules Rules => C.Rules; private CampaignState State => C.State; internal MovementSystem(Campaign host) { C = host; } public SpeedBreakdown ComputeSpeed(Party p) { SpeedBreakdown speedBreakdown = ComputeUnaccompaniedSpeed(p); ClanArmyState clanArmy = State.ClanArmy; if (clanArmy == null || !clanArmy.Active || State.ClanArmy.LeaderPartyId != p.Id) { List list = C.MergedMembers(p).ToList(); if (list.Count == 0) { return speedBreakdown; } double num = list.Min((Party m) => ComputeUnaccompaniedSpeed(m).Speed); if (num < speedBreakdown.Speed) { speedBreakdown.Factors.Add(new SpeedFactor { Label = "Army marching pace", Multiplier = num / speedBreakdown.Speed }); speedBreakdown.Speed = num; } return speedBreakdown; } double num2 = speedBreakdown.Speed; foreach (Party item in from member in C.AssembledArmyParties() where member.Id != p.Id select member) { Hero hero = State.Heroes.Get(item.LeaderHeroId); if (hero != null && hero.CanFight && item.Order.Kind != OrderKind.Flee && (item.State != PartyState.Active || item.Order.Kind == OrderKind.None || (item.Order.Kind == OrderKind.Follow && !(item.Order.TargetId != p.Id)))) { num2 = Math.Min(num2, ComputeUnaccompaniedSpeed(item).Speed); } } if (num2 < speedBreakdown.Speed) { speedBreakdown.Factors.Add(new SpeedFactor { Label = "Army marching pace", Multiplier = num2 / speedBreakdown.Speed }); speedBreakdown.Speed = num2; } return speedBreakdown; } internal SpeedBreakdown ComputeUnaccompaniedSpeed(Party p) { SpeedBreakdown b = new SpeedBreakdown(); double speed = Rules.BaseSpeed; TerrainDef terrainDef = Nav.TerrainAt(p.Position); F("Terrain: " + terrainDef.Type, terrainDef.Speed); int num = p.Troops.TotalTroops + p.Troops.Heroes.Count; F("Party size", 1.0 + Rules.SmallPartyBonus - Rules.SizePenaltyMax * (double)num / ((double)num + Rules.SizePenaltyHalfSize)); if (num > 0) { double num2 = (double)p.Troops.TotalWounded / (double)num; F("Wounded troops", 1.0 - num2 * Rules.WoundedPenaltyMax); double num3 = Math.Min(1.0, (double)p.Prisoners.TotalTroops / (double)num); F("Prisoners", 1.0 - num3 * Rules.PrisonerPenaltyMax); double num4 = 0.0; int num5 = 0; foreach (TroopStack stack in p.Troops.Stacks) { UnitDef unitDef = C.UnitDef(stack.UnitId); num4 += (double)stack.Total * (unitDef?.MapSpeed ?? 1.0); num5 += stack.Total; } if (num5 > 0) { double num6 = 1.0 + (num4 / (double)num5 - 1.0) * Rules.TroopPaceSpread; F((num6 >= 1.0) ? "Mounted troops" : "Slow troops", Math.Max(1.0 - Rules.MountedBonusMax, Math.Min(1.0 + Rules.MountedBonusMax, num6))); } } C.HorseSpeedFactors(p, F); if (p.StarvingDays > 0) { F("Starving", 1.0 - Rules.StarvingPenalty); } if (p.Morale < 25.0) { F("Low morale", 1.0 - Rules.LowMoralePenalty); } int num7 = C.RoleSkill(p, PartyRole.Scout); if (num7 > 0) { F("Scout: " + C.RoleHolder(p, PartyRole.Scout).Name, 1.0 + (double)num7 / 1000.0); } if (C.HasRolePerk(p, PartyRole.Scout, "perk.scout.pathfinder")) { F("Pathfinder", 1.05); } if (p.ClanId == State.PlayerClanId) { F("Perks", 1.0 + C.PartyPerk(p, PerkEffect.PartySpeed)); double num8 = C.PartyPerk(p, PerkEffect.FootSpeed); if (num8 > 0.0 && num > 0) { int num9 = p.Troops.Heroes.Count; foreach (TroopStack stack2 in p.Troops.Stacks) { UnitDef unitDef2 = C.UnitDef(stack2.UnitId); if (unitDef2 == null || !unitDef2.Mounted) { num9 += stack2.Total; } } F("Perks: on foot", 1.0 + num8 * (double)num9 / (double)num); } if (terrainDef.Speed < 1.0) { F("Perks: rough ground", 1.0 + C.PartyPerk(p, PerkEffect.TerrainSpeed)); } } double num10 = C.CargoWeight(p); double num11 = C.CargoCapacity(p); if (num10 > num11) { F("Cargo overload", Math.Max(0.6, num11 / num10)); } if (p.Id == State.PlayerPartyId && C.EscortingWagons()) { F("Escorting wagons", 0.85); } if (p.Id == State.PlayerPartyId) { F("Difficulty", 1.0 + C.Settings.PlayerMapSpeedBonus); } b.Speed = Math.Max(Rules.MinSpeed, Math.Min(Rules.MaxSpeed, speed)); return b; void F(string label, double m) { if (!(Math.Abs(m - 1.0) < 1E-06)) { b.Factors.Add(new SpeedFactor { Label = label, Multiplier = m }); speed *= m; } } } public double SightRange(Party p) { int num = C.RoleSkill(p, PartyRole.Scout); return Rules.BaseSightRange * Nav.TerrainAt(p.Position).Sight * (1.0 + (double)num / 100.0) * (C.HasRolePerk(p, PartyRole.Scout, "perk.scout.keen_eye") ? 1.2 : 1.0) * (1.0 + C.PartyPerk(p, PerkEffect.Sight)) * NightSight(p, num); } public double NightSight(Party p, int scouting) { if (p == null || p.State == PartyState.InSettlement) { return 1.0; } return DayNight.SightFactor(State.Clock.Minute, scouting); } public double PlayerNightSight() { if (State.PlayerParty != null) { return NightSight(State.PlayerParty, C.RoleSkill(State.PlayerParty, PartyRole.Scout)); } return 1.0; } public bool SetMoveOrder(Party p, OrderKind kind, Vec2 point, string targetId = "", string reason = "") { if (p.Id == State.PlayerPartyId && p.State == PartyState.InSettlement && C.BesiegedAgainst(p, State.Settlements.Get(p.CurrentSettlementId))) { C.Raise(CampaignEventKind.Warning, "The besiegers have " + State.Settlements.Get(p.CurrentSettlementId).Name + " surrounded. Break out through their lines first.", false); return false; } PathResult pathResult = Nav.FindPath(p.Position, point); MovementOrder movementOrder = new MovementOrder { Kind = kind, Point = (pathResult.Success ? pathResult.Goal : point), TargetId = (targetId ?? ""), IssuedAtMinute = State.Clock.Minute, Reason = (reason ?? ""), LastKnownTargetPosition = point }; if (!pathResult.Success) { if (p.Id == State.PlayerPartyId) { C.Raise(CampaignEventKind.Unreachable, pathResult.Message, false); } return false; } C.CancelRaid(p, "new orders", notify: false); C.EndPartySiege(p, "New orders lifted the siege."); if (p.State == PartyState.InSettlement) { LeaveSettlementInternal(p); } movementOrder.Path = pathResult.Points; movementOrder.PathGoal = pathResult.Goal; p.Order = movementOrder; if (pathResult.GoalAdjusted && p.Id == State.PlayerPartyId) { C.Raise(CampaignEventKind.PathAdjusted, pathResult.Message, false); } return true; } public void ClearOrder(Party p) { C.CancelRaid(p, "orders cancelled", notify: false); C.EndPartySiege(p, "Orders cancelled; siege lifted."); p.Order = new MovementOrder(); } internal void Repath(Party p, Vec2 goal) { PathResult pathResult = Nav.FindPath(p.Position, goal); if (!pathResult.Success) { p.Order.Path.Clear(); p.Order.PathIndex = 0; } else { p.Order.Path = pathResult.Points; p.Order.PathIndex = 0; p.Order.PathGoal = pathResult.Goal; } } internal bool CanMove(Party p) { if (p.State == PartyState.Active) { return !string.IsNullOrEmpty(p.Id); } return false; } internal List MoveParties(double hours) { List list = new List(); ClanArmyState clanArmy = State.ClanArmy; double? num = ((clanArmy != null && clanArmy.Active) ? new double?(ComputeSpeed(State.PlayerParty).Speed) : ((double?)null)); foreach (Party item in State.Parties.OrderBy((Party party2) => (party2.Order.Kind == OrderKind.Engage) ? 1 : 0).ToList()) { if (!CanMove(item) || (C.ClanArmyContains(item.Id) && C.ClanArmyPartyReserved(item.Id)) || C.KingdomArmyAwaitingRelease(item) || (item.Id == State.PlayerPartyId && State.Player.Activity == PlayerActivity.Captive)) { continue; } Vec2 position = item.Position; UpdateDynamicTarget(item); Hero worker = C.RoleHolder(item, PartyRole.Scout); double num2 = 0.0; if (item.Order.Kind != OrderKind.None && item.Order.Kind != OrderKind.Hold && item.Order.HasPath) { if (!Nav.LineWalkable(item.Position, item.Order.Path[item.Order.PathIndex])) { Repath(item, item.Order.PathGoal); } double num3 = ((item.Id == State.PlayerPartyId && num.HasValue) ? num.Value : ComputeSpeed(item).Speed) * hours; for (int num4 = 0; num4 < 2; num4++) { while (num3 > 1E-09 && item.Order.HasPath) { Vec2 vec = item.Order.Path[item.Order.PathIndex]; double num5 = Vec2.Distance(item.Position, vec); if (num5 <= num3) { item.Position = vec; num3 -= num5; num2 += num5; item.Order.PathIndex++; } else { item.Position = Vec2.MoveTowards(item.Position, vec, num3); num2 += num3; num3 = 0.0; } } Party party = ChasedTarget(item); if (num3 <= 1E-09 || party == null) { break; } double num6 = Vec2.Distance(item.Position, party.Position); if (num6 < 1E-06) { break; } if (Nav.LineWalkable(item.Position, party.Position)) { double num7 = Math.Min(num3, num6); item.Position = Vec2.MoveTowards(item.Position, party.Position, num7); num2 += num7; item.Order.LastKnownTargetPosition = party.Position; break; } Repath(item, party.Position); } } C.ApplyRoleTraining(item, PartyRole.Scout, worker, num2); C.TrainAthleticsOnTheMarch(item, num2); list.Add(new MoveSegment { PartyId = item.Id, From = position, To = item.Position }); } foreach (Party item2 in State.Parties.ToList()) { if (CanMove(item2) && item2.Order.Kind != OrderKind.None && !item2.Order.HasPath && (!C.ClanArmyContains(item2.Id) || !C.ClanArmyPartyReserved(item2.Id)) && !C.KingdomArmyAwaitingRelease(item2)) { OnPathCompleted(item2); } } return list; } internal void UpdateDynamicTarget(Party p) { MovementOrder order = p.Order; if (order.Kind == OrderKind.Engage || order.Kind == OrderKind.Follow) { Party party = State.Parties.Get(order.TargetId); if (party == null || party.State == PartyState.Destroyed || party.State == PartyState.Disbanded) { if (p.Id == State.PlayerPartyId) { C.Raise(CampaignEventKind.TargetLost, "The party you were following is gone.", true); } ClearOrder(p); return; } bool flag = (order.Kind == OrderKind.Follow && (C.MilitaryPartyFor(p) != null || C.IsKingdomArmyParty(p)) && party.Id == State.PlayerPartyId && State.Player.Activity != PlayerActivity.Captive) || (order.Kind == OrderKind.Follow && C.MarchesWithAiArmy(p, party)) || CanSee(p, party); if (party.State == PartyState.InSettlement) { flag = false; order.LastKnownTargetPosition = party.Position; } if (flag) { order.TargetLost = false; order.LastKnownTargetPosition = party.Position; if (!order.HasPath || Vec2.Distance(order.PathGoal, party.Position) > Rules.RepathDistance) { Repath(p, party.Position); } } else if (!order.TargetLost) { order.TargetLost = true; Repath(p, order.LastKnownTargetPosition); if (p.Id == State.PlayerPartyId) { C.Raise(CampaignEventKind.TargetLost, "Lost sight of " + party.Name + "; heading to its last known position.", false, party.Id); } } } else { if (order.Kind != OrderKind.Flee) { return; } Party party2 = State.Parties.Get(order.ThreatId); if (party2 == null || party2.State != PartyState.Active || !CanSee(p, party2)) { if (!order.HasPath) { ClearOrder(p); } } else if (!order.HasPath || State.Clock.Minute - order.IssuedAtMinute >= 60) { Vec2 vec = (p.Position - party2.Position).Normalized; if (vec.LengthSquared < 1E-09) { vec = new Vec2(1.0, 0.0); } Vec2 target = p.Position + vec * 6.0; if (Nav.TryNearestReachable(p.Position, target, out var result)) { Repath(p, result); } order.IssuedAtMinute = State.Clock.Minute; } } } private Party ChasedTarget(Party p) { MovementOrder order = p.Order; if (order.Kind != OrderKind.Engage || order.TargetLost) { return null; } Party party = State.Parties.Get(order.TargetId); if (party == null || party.State != PartyState.Active || !(party.Id != p.Id)) { return null; } return party; } internal void OnPathCompleted(Party p) { MovementOrder order = p.Order; switch (order.Kind) { case OrderKind.GoToSettlement: { Settlement settlement = State.Settlements.Get(order.TargetId); if (settlement != null && Vec2.Distance(p.Position, settlement.Position) <= Rules.SettlementEnterRadius + 0.01) { ClearOrder(p); TryEnterSettlement(p, settlement); } else { ClearOrder(p); } break; } case OrderKind.Engage: case OrderKind.Follow: { Party party = State.Parties.Get(order.TargetId); if (order.TargetLost) { if (p.Id == State.PlayerPartyId) { C.Raise(CampaignEventKind.TargetLost, "No trace of " + (party?.Name ?? "the target") + " at its last known position.", true, order.TargetId); } ClearOrder(p); } else if (party != null && party.State == PartyState.InSettlement) { if (p.Id == State.PlayerPartyId) { C.Raise(CampaignEventKind.TargetLost, (order.Kind == OrderKind.Follow) ? (party.Name + " went into " + State.Settlements.Get(party.CurrentSettlementId)?.Name + ".") : (party.Name + " has taken refuge in " + State.Settlements.Get(party.CurrentSettlementId)?.Name + "."), true, party.Id); } ClearOrder(p); } break; } case OrderKind.MoveToPoint: ClearOrder(p); if (p.Id == State.PlayerPartyId) { C.Raise(CampaignEventKind.ArrivedAtDestination, "Arrived at destination.", false); } break; default: ClearOrder(p); break; case OrderKind.Raid: case OrderKind.Besiege: break; } if (p.Id == State.PlayerPartyId) { C.UpdatePlayerTimeStates(); } } public bool CanEnter(Party p, Settlement s) { if (s.Type == SettlementType.Hideout) { if (!string.IsNullOrEmpty(p.HideoutGuardOf)) { return p.HideoutGuardOf == s.Id; } return false; } Clan b = State.Clans.Get(s.OwnerClanId); Clan clan = State.Clans.Get(p.ClanId); if (clan == null || clan.IsBandit) { return false; } if (C.IsSettlementBesieged(s) && (p.Kind == PartyKind.Villager || p.Kind == PartyKind.Caravan)) { return false; } SiegeState siegeState = C.SiegeForSettlement(s.Id); if (siegeState != null && siegeState.Stage == SiegeStage.Assault) { return false; } if (p.Id == State.PlayerPartyId && C.BesiegedAgainst(p, s)) { return false; } return !State.AreHostile(clan, b); } internal void TryEnterSettlement(Party p, Settlement s) { if (C.StopAtGate(p, s)) { C.StopPlayerAtGate(p, s); return; } if (!CanEnter(p, s)) { if (p.Id == State.PlayerPartyId) { C.Raise(CampaignEventKind.Warning, (C.BesiegedAgainst(p, s) && !State.AreHostile(State.Clans.Get(p.ClanId), State.Clans.Get(s.OwnerClanId))) ? (s.Name + " is under siege. Break in through the besiegers' lines, or keep your distance.") : (s.Name + " won't open its gates to you."), true, s.Id); } return; } p.State = PartyState.InSettlement; p.CurrentSettlementId = s.Id; p.Position = s.Position; if (p.Id == State.PlayerPartyId) { State.Player.MenuSettlementId = s.Id; State.Player.KeepAccessSettlementId = ""; State.Player.Activity = PlayerActivity.InSettlement; C.RefreshContractOffers(); C.Raise(CampaignEventKind.ArrivedAtSettlement, "Arrived at " + s.Name + ".", true, s.Id); } else { C.OnAiEnteredSettlement(p, s); } } internal void LeaveSettlementInternal(Party p) { if (p.State != PartyState.InSettlement) { return; } p.State = PartyState.Active; p.CurrentSettlementId = ""; if (p.Id == State.PlayerPartyId) { State.Player.MenuSettlementId = ""; State.Player.KeepAccessSettlementId = ""; if (State.Crime != null) { State.Crime.DisguisedSettlementId = ""; } if (State.Player.Activity == PlayerActivity.InSettlement || State.Player.Activity == PlayerActivity.Waiting) { State.Player.Activity = PlayerActivity.Idle; } } } public bool CanSee(Party observer, Party target) { if (target.State == PartyState.InSettlement) { return false; } return Vec2.Distance(observer.Position, target.Position) <= SightRange(observer); } internal void UpdateVisibility() { Party player = State.PlayerParty; if (player == null) { return; } bool fullInformation = State.Settings.FullInformation; List list = State.ActiveParties.Where((Party x) => x.Id == player.Id).ToList(); List list2 = list.Select((Party o) => SightRange(o)).ToList(); foreach (Party party2 in State.Parties) { if (party2.Id == player.Id) { continue; } bool flag = party2.State == PartyState.Active || party2.State == PartyState.Engaged; bool flag2 = false; for (int num = 0; num < list.Count; num++) { if (flag2) { break; } Party party = list[num]; flag2 = party.State != PartyState.Destroyed && party2.State != PartyState.InSettlement && Vec2.Distance(party.Position, party2.Position) <= list2[num]; } bool num2 = flag && (IsPlayerCaravan(party2) || C.IsPlayerMilitaryParty(party2) || C.IsKingdomArmyParty(party2) || fullInformation || flag2 || IsNearOwnedSettlement(party2)); State.PlayerSightings.TryGetValue(party2.Id, out var value); if (num2) { if (value == null) { value = new Sighting { PartyId = party2.Id }; State.PlayerSightings[party2.Id] = value; } value.Position = party2.Position; value.SeenAtMinute = State.Clock.Minute; value.CurrentlyVisible = true; value.EstimatedStrength = EstimateCount(C.PartyCombatants(party2)); } else if (value != null) { value.CurrentlyVisible = false; } } C.NoteHeroesMet(); } internal bool IsNearOwnedSettlement(Party p) { foreach (Settlement settlement in State.Settlements) { if (settlement.OwnerClanId == State.PlayerClanId && Vec2.Distance(settlement.Position, p.Position) <= Rules.BaseSightRange * 0.75) { return true; } } return false; } public static int EstimateCount(int n) { if (n <= 5) { return n; } if (n <= 20) { return (int)Math.Round((double)n / 5.0) * 5; } return (int)Math.Round((double)n / 10.0) * 10; } internal void ExpireSightings() { long cutoff = State.Clock.Minute - (long)(Rules.SightingExpiryHours * 60.0); foreach (string item in (from s in State.PlayerSightings.Values where !s.CurrentlyVisible && s.SeenAtMinute < cutoff select s.PartyId).ToList()) { State.PlayerSightings.Remove(item); } foreach (string item2 in State.PlayerSightings.Keys.ToList()) { Party party = State.Parties.Get(item2); if (party == null || party.State == PartyState.Destroyed || party.State == PartyState.Disbanded) { State.PlayerSightings.Remove(item2); } } } public bool IsKnownToPlayer(Party p) { if (!(p.Id == State.PlayerPartyId) && !IsPlayerCaravan(p) && !C.IsPlayerMilitaryParty(p) && !C.IsPlayerGarrisonParty(p) && !C.IsKingdomArmyParty(p)) { if (State.PlayerSightings.TryGetValue(p.Id, out var value)) { if (!value.CurrentlyVisible) { return IsQuestQuarry(p.Id); } return true; } return false; } return true; } internal bool IsQuestQuarry(string partyId) { if (State.Quests?.Quests?.Any((QuestState q) => q != null && q.Status == QuestStatus.Active && q.TargetPartyId == partyId) != true) { return State.Contracts?.Any((ContractState c) => c.Status == ContractStatus.Active && c.Progress == 0 && c.TargetPartyId == partyId) ?? false; } return true; } public bool IsPlayerCaravan(Party p) { if (p != null && p.Kind == PartyKind.Caravan && p.ClanId == State.PlayerClanId && string.IsNullOrEmpty(p.MerchantTownId) && p.State != PartyState.Destroyed) { return p.State != PartyState.Disbanded; } return false; } } internal sealed class NamedCustodySystem { private readonly Campaign C; private CampaignState State => C.State; internal NamedCustodySystem(Campaign host) { C = host; } public string NamedCustodyIntegrityReason(string heroId) { Hero hero = State.Heroes.Get(heroId); if (hero == null || hero.State != HeroState.Captive) { return "That hero isn't a prisoner."; } if (hero.CaptiveSinceMinute < 0 || hero.CaptiveSinceMinute > State.Clock.Minute) { return "The prisoner's capture time is invalid."; } if (!string.IsNullOrEmpty(hero.PartyId) || !string.IsNullOrEmpty(hero.SettlementId)) { return "The prisoner's location conflicts with their custody record."; } bool flag = !string.IsNullOrEmpty(hero.CaptorPartyId); bool flag2 = !string.IsNullOrEmpty(hero.CaptorSettlementId); if (flag == flag2) { return "The prisoner must have exactly one custodian."; } TroopRoster prisoners; if (flag) { Party party = State.Parties.Get(hero.CaptorPartyId); if (party == null || !State.Clans.Contains(party.ClanId) || (party.State != PartyState.Active && party.State != PartyState.InSettlement && party.State != PartyState.Engaged)) { return "The prisoner's captor party is no longer available."; } prisoners = party.Prisoners; } else { Settlement settlement = State.Settlements.Get(hero.CaptorSettlementId); if (settlement == null || settlement.Type == SettlementType.Hideout || !State.Clans.Contains(settlement.OwnerClanId)) { return "The prisoner's holding settlement is not available."; } prisoners = settlement.Prisoners; } if (prisoners?.Heroes == null || prisoners.Heroes.Count((string id) => id == hero.Id) != 1) { return "The prisoner is missing from their custodian's roster or recorded more than once."; } if (State.Parties.Sum((Party p) => (p.Prisoners?.Heroes?.Count((string id) => id == hero.Id)).GetValueOrDefault()) + State.Settlements.Sum((Settlement s) => (s.Prisoners?.Heroes?.Count((string id) => id == hero.Id)).GetValueOrDefault()) != 1 || State.Parties.Any(delegate(Party p) { TroopRoster troops = p.Troops; return troops != null && troops.Heroes?.Contains(hero.Id) == true; }) || State.Settlements.Any(delegate(Settlement s) { TroopRoster garrison = s.Garrison; return garrison != null && garrison.Heroes?.Contains(hero.Id) == true; })) { return "The prisoner has conflicting roster records."; } return ""; } public Clan HeroCaptorClan(Hero hero) { if (hero == null || NamedCustodyIntegrityReason(hero.Id).Length > 0) { return null; } hero = State.Heroes.Get(hero.Id); return State.Clans.Get(string.IsNullOrEmpty(hero.CaptorPartyId) ? State.Settlements.Get(hero.CaptorSettlementId)?.OwnerClanId : State.Parties.Get(hero.CaptorPartyId)?.ClanId); } internal bool NamedCustodyPartyReserved(string partyId) { Party party = State.Parties.Get(partyId); if (party != null) { if (party.State != PartyState.Engaged && string.IsNullOrEmpty(party.EncounterId)) { return State.Encounters.Any((Encounter e) => e.Phase != EncounterPhase.Committed && e.Phase != EncounterPhase.Cancelled && (e.InitiatorPartyId == partyId || e.AllParties.Contains(partyId))); } return true; } return false; } public bool NamedCustodyReserved(Hero hero) { hero = ((hero == null) ? null : State.Heroes.Get(hero.Id)); if (hero != null && !string.IsNullOrEmpty(hero.CaptorPartyId)) { return NamedCustodyPartyReserved(hero.CaptorPartyId); } return false; } internal Settlement NamedPrisonerDungeon() { Settlement settlement = C.CurrentSettlement(); if (settlement == null || !(settlement.OwnerClanId == State.PlayerClanId) || (settlement.Type != SettlementType.Town && settlement.Type != SettlementType.Castle) || !C.CanEnter(State.PlayerParty, settlement) || !(Vec2.Distance(State.PlayerParty.Position, settlement.Position) <= 0.01)) { return null; } return settlement; } public string NamedPrisonerActionReason(string heroId, bool inDungeon) { string text = C.PrisonerCommandReason(); if (text.Length > 0) { return text; } if (NamedCustodyPartyReserved(State.PlayerPartyId)) { return "Deal with the encounter first."; } text = NamedCustodyIntegrityReason(heroId); if (text.Length > 0) { return text; } Hero hero = State.Heroes.Get(heroId); if (hero.IsPlayer || hero.Id == State.PlayerHeroId) { return "You cannot manage your own captivity here."; } if (NamedCustodyReserved(hero)) { return "Wait for the captor's fight to finish."; } if (!inDungeon) { if (!(hero.CaptorPartyId == State.PlayerPartyId)) { return "You're not holding that hero."; } return ""; } Settlement settlement = NamedPrisonerDungeon(); if (settlement == null || !(hero.CaptorSettlementId == settlement.Id)) { return "Go to the dungeon where they're held, in a town or castle of yours."; } return ""; } public string PrisonerHeroTransferReason(string heroId, bool toDungeon) { string text = NamedPrisonerActionReason(heroId, !toDungeon); if (text.Length > 0) { return text; } Settlement settlement = NamedPrisonerDungeon(); if (settlement == null) { return "Go to a town or castle of yours to move named prisoners."; } if (!(toDungeon ? settlement.Prisoners : State.PlayerParty.Prisoners).Heroes.Contains(heroId)) { return ""; } return "The receiving roster already records this prisoner."; } public CommandResult TransferPrisonerHero(string heroId, bool toDungeon) { string text = PrisonerHeroTransferReason(heroId, toDungeon); if (text.Length > 0) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Get(heroId); Settlement settlement = NamedPrisonerDungeon(); TroopRoster troopRoster = (toDungeon ? State.PlayerParty.Prisoners : settlement.Prisoners); TroopRoster obj = (toDungeon ? settlement.Prisoners : State.PlayerParty.Prisoners); troopRoster.Heroes.Remove(hero.Id); obj.Heroes.Add(hero.Id); hero.CaptorPartyId = (toDungeon ? "" : State.PlayerPartyId); hero.CaptorSettlementId = (toDungeon ? settlement.Id : ""); string text2 = hero.Name + " transferred to " + (toDungeon ? (settlement.Name + "'s dungeon") : "your party") + "."; State.AddLog(LogCategory.Captivity, text2, hero.Id, settlement.Id); State.Touch(); return CommandResult.Success(text2); } public CommandResult ReleasePrisonerHero(string heroId, bool inDungeon) { string text = NamedPrisonerActionReason(heroId, inDungeon); if (text.Length > 0) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Get(heroId); OutcomeCommitter.ReleaseHero(C, hero, inDungeon ? "released from your dungeon" : "released by your warband"); string text2 = ""; if (!string.IsNullOrEmpty(hero.ClanId) && hero.ClanId != State.PlayerClanId) { Clan clan = State.Clans.Get(hero.ClanId); if (clan != null && !clan.IsBandit) { Campaign.Personality personality = Campaign.PersonalityOf(hero); int num = 4 + ((personality.Honor > 0) ? 2 : 0) + ((personality.Mercy > 0) ? 2 : 0); C.AdjustClanRelation(State.PlayerClanId, hero.ClanId, num); C.RememberHero(hero, "released"); text2 = $" Relation with {State.Clans.Get(hero.ClanId).Name} +{num}."; C.CompanionsReactToRelease(hero); } } State.Touch(); return CommandResult.Success("Released " + hero.Name + "." + text2); } } internal sealed class NotablesSystem { private readonly Campaign C; private CampaignState State => C.State; internal NotablesSystem(Campaign host) { C = host; } public void EnsureNotableFields() { bool flag = false; if (State.Notables == null) { State.Notables = new List(); flag = true; } foreach (Settlement settlement in State.Settlements.Where((Settlement x) => x.Type != SettlementType.Hideout)) { NotableState notableState = (from x in State.Notables where x.SettlementId == settlement.Id orderby x.Generation descending select x).ThenBy((NotableState x) => x.Id, StringComparer.Ordinal).FirstOrDefault(); if (notableState == null) { notableState = CreateNotable(settlement, null); State.Notables.Add(notableState); flag = true; } if (settlement.Recruits == null) { settlement.Recruits = new List(); flag = true; } for (int num = 0; num < settlement.Recruits.Count; num++) { RecruitSlot recruitSlot = settlement.Recruits[num]; if (recruitSlot == null) { recruitSlot = new RecruitSlot(); settlement.Recruits[num] = recruitSlot; flag = true; } if (string.IsNullOrEmpty(recruitSlot.ProviderId)) { recruitSlot.ProviderId = notableState.Id; recruitSlot.RequiredRelation = ((num >= 2) ? ((num < 4) ? 10 : 20) : 0); flag = true; } } } if (flag) { State.Touch(); } } internal NotableState CreateNotable(Settlement settlement, NotableState predecessor) { int generation = ((predecessor != null) ? (predecessor.Generation + 1) : 0); NotableDef notableDef = Notables.Get(settlement.Id); return new NotableState { Id = "notable." + settlement.Id + "." + generation.ToString(CultureInfo.InvariantCulture), SettlementId = settlement.Id, Name = Notables.NameFor(settlement.Id, settlement.Name, generation), Occupation = (notableDef?.Occupation ?? ((settlement.Type == SettlementType.Castle) ? "Castellan" : ((settlement.Type == SettlementType.Town) ? "Guild steward" : "Village elder"))), CultureId = (predecessor?.CultureId ?? settlement.CultureId), OwnerClanId = settlement.OwnerClanId, Generation = generation, PredecessorId = (predecessor?.Id ?? ""), LastRecruitRefillDay = (predecessor?.LastRecruitRefillDay ?? State.Clock.Day) }; } public NotableState SettlementNotable(string settlementId) { return (from x in State.Notables?.Where((NotableState x) => x.IsAlive && x.SettlementId == settlementId) orderby x.Generation descending select x).ThenBy((NotableState x) => x.Id, StringComparer.Ordinal).FirstOrDefault(); } public int NotableRelationFor(string clanId, NotableState notable) { if (notable == null || !(clanId == State.PlayerClanId)) { return 0; } return notable.PlayerRelation; } public void AdjustNotableRelation(string notableId, int delta, string reason) { NotableState notableState = State.Notables?.FirstOrDefault((NotableState x) => x.Id == notableId && x.IsAlive); if (notableState == null || delta == 0) { return; } if (delta > 0) { delta += C.RelationPerkBonus(); } int num = (int)Math.Max(-100L, Math.Min(100L, (long)notableState.PlayerRelation + (long)delta)); int num2 = num - notableState.PlayerRelation; if (num2 != 0) { notableState.PlayerRelation = num; if (num2 > 0) { C.TrainCharm(num2); } State.AddLog(LogCategory.Info, notableState.Name + ": relation " + ((num2 > 0) ? "+" : "") + num2 + " (" + reason + ").", notableState.SettlementId); State.Touch(); } } public void ReplaceUnavailableNotables() { bool flag = false; foreach (Settlement settlement in State.Settlements.Where((Settlement x) => x.Type != SettlementType.Hideout)) { NotableState notableState = SettlementNotable(settlement.Id); if (notableState == null) { NotableState predecessor = (from x in State.Notables where x.SettlementId == settlement.Id orderby x.Generation descending select x).ThenBy((NotableState x) => x.Id, StringComparer.Ordinal).FirstOrDefault(); notableState = CreateNotable(settlement, predecessor); State.Notables.Add(notableState); foreach (RecruitSlot recruit in settlement.Recruits) { recruit.ProviderId = notableState.Id; } State.AddLog(LogCategory.Info, notableState.Name + " now handles recruitment at " + settlement.Name + ".", settlement.Id); flag = true; } if (notableState.OwnerClanId != settlement.OwnerClanId) { notableState.OwnerClanId = settlement.OwnerClanId; flag = true; } } HashSet referenced = new HashSet(from x in State.Contracts ?? new List() where x.Status == ContractStatus.Active || x.Status == ContractStatus.Offered select x.IssuerNotableId, StringComparer.Ordinal); if (State.Notables.RemoveAll((NotableState x) => !x.IsAlive && !referenced.Contains(x.Id)) > 0) { flag = true; } if (flag) { State.Touch(); } } public bool TryBeginRecruitPoolRecovery(Settlement settlement) { if (settlement == null || settlement.Type == SettlementType.Hideout) { return false; } NotableState notableState = SettlementNotable(settlement.Id); if (notableState == null || notableState.LastRecruitRefillDay >= State.Clock.Day) { return false; } notableState.LastRecruitRefillDay = State.Clock.Day; State.Touch(); return C.VillageRecruitmentReason(settlement).Length == 0; } public string RecruitSlotRelationReason(Settlement settlement, RecruitSlot slot, string clanId) { if (settlement == null || slot == null) { return "No recruitment provider is available."; } string text = C.VillageRecruitmentReason(settlement); if (text.Length > 0) { return text; } NotableState notableState = State.Notables?.FirstOrDefault((NotableState x) => x.Id == slot.ProviderId && x.SettlementId == settlement.Id && x.IsAlive); if (notableState == null) { return "The local recruitment provider is unavailable."; } if (settlement.OwnerClanId == clanId) { return ""; } if (NotableRelationFor(clanId, notableState) >= slot.RequiredRelation) { return ""; } return notableState.Name + " requires " + slot.RequiredRelation + " relation (" + NotableRelationFor(clanId, notableState) + " now)."; } public string RecruitmentReason(int slotIndex) { string text = C.DisguiseBlockReason(); if (text.Length > 0) { return text; } CommandResult commandResult = C.RequireFree(); if (!commandResult.Ok) { return commandResult.Message; } Party playerParty = State.PlayerParty; Hero playerHero = State.PlayerHero; if (playerParty.ClanId != State.PlayerClanId || !string.IsNullOrEmpty(playerParty.EncounterId)) { return "Can't recruit right now."; } if (playerHero == null || playerHero.State != HeroState.Active || !Campaign.IsPresentPartyHero(playerParty, playerHero)) { return "You have to be with the party to recruit."; } Settlement settlement = C.CurrentSettlement(); if (settlement == null || playerParty.State != PartyState.InSettlement || Vec2.Distance(playerParty.Position, settlement.Position) > 0.01) { return "Recruits are found in settlements."; } Clan clan = State.Clans.Get(settlement.OwnerClanId); if (settlement.Type == SettlementType.Hideout || clan == null || clan.IsBandit || clan.IsEliminated || !C.CanEnter(playerParty, settlement)) { return "You cannot recruit in a hostile settlement."; } if (slotIndex < 0 || slotIndex >= settlement.Recruits.Count || settlement.Recruits[slotIndex] == null || !settlement.Recruits[slotIndex].Available) { return "Nobody in that slot."; } RecruitSlot recruitSlot = settlement.Recruits[slotIndex]; string text2 = RecruitSlotRelationReason(settlement, recruitSlot, playerParty.ClanId); if (text2.Length > 0) { return text2; } UnitDef unitDef = C.UnitDef(recruitSlot.UnitId); if (unitDef == null || unitDef.RecruitCost < 0) { return "This recruit has invalid content."; } if (playerParty.Troops.TotalTroops >= C.PartySizeLimit(playerParty)) { return "Your party is full (" + C.PartySizeLimit(playerParty) + ")."; } long num = C.RecruitPrice(playerParty, unitDef); if (State.PlayerClan == null || State.PlayerClan.Gold < num) { return "You need " + num + " denars to recruit a " + unitDef.Name + "."; } return ""; } } internal sealed class PactsSystem { private readonly Campaign C; private CampaignState State => C.State; internal IEnumerable LiveAgreements => State.Diplomacy?.Agreements?.Where((DiplomaticAgreement a) => a != null && a.EndsDay > State.Clock.Day) ?? Enumerable.Empty(); internal PactsSystem(Campaign host) { C = host; } internal void EnsurePactFields(ref bool changed) { DiplomacyState diplomacy = State.Diplomacy; if (diplomacy.Agreements == null) { diplomacy.Agreements = new List(); changed = true; } if (diplomacy.Calls == null) { diplomacy.Calls = new List(); changed = true; } if (diplomacy.Captures == null) { diplomacy.Captures = new List(); changed = true; } if (diplomacy.PendingElections == null) { diplomacy.PendingElections = new List(); changed = true; } if (diplomacy.LastPactAiDay < 0) { diplomacy.LastPactAiDay = State.Clock.Day; changed = true; } } internal static bool Pair(DiplomaticAgreement x, string a, string b) { if (!(x.A == a) || !(x.B == b)) { if (x.A == b) { return x.B == a; } return false; } return true; } public bool Allied(string a, string b) { if (a != b) { return LiveAgreements.Any((DiplomaticAgreement x) => x.Kind == AgreementKind.Alliance && Pair(x, a, b)); } return false; } public bool HasTradeAgreement(string a, string b) { if (a != b) { return LiveAgreements.Any((DiplomaticAgreement x) => x.Kind == AgreementKind.TradeAgreement && Pair(x, a, b)); } return false; } public DiplomaticAgreement TributeBetween(string a, string b) { return LiveAgreements.FirstOrDefault((DiplomaticAgreement x) => x.Kind == AgreementKind.Tribute && Pair(x, a, b)); } public List AgreementsOf(string faction) { return (from x in LiveAgreements where x.A == faction || x.B == faction orderby x.Kind select x).ThenBy((DiplomaticAgreement x) => x.Id, StringComparer.Ordinal).ToList(); } public List AlliesOf(string faction) { return (from x in LiveAgreements where x.Kind == AgreementKind.Alliance && (x.A == faction || x.B == faction) select (!(x.A == faction)) ? x.A : x.B).Distinct().OrderBy((string x) => x, StringComparer.Ordinal).ToList(); } public List PendingCallsTo(string faction) { return (from c in State.Diplomacy?.Calls?.Where((CallToWarRequest c) => c.AllyFactionId == faction && c.Status == CallToWarStatus.Pending) orderby c.CreatedDay select c).ToList() ?? new List(); } internal Clan FactionPurse(string faction) { if (State.Kingdoms.Get(faction) != null) { return C.LivingDiplomacyRuler(faction); } Clan clan = State.Clans.Get(faction); if (clan == null || clan.IsEliminated || clan.IsBandit || !string.IsNullOrEmpty(clan.KingdomId)) { return null; } return clan; } public double FactionStrength(string faction) { if (State.Kingdoms.Get(faction) != null) { return C.KingdomMilitaryStrength(faction); } double num = State.ActiveParties.Where((Party p) => (p.Kind == PartyKind.Lord || p.Kind == PartyKind.Player) && p.ClanId == faction).Sum((Func)C.PartyStrength); foreach (Settlement item in State.Settlements.Where((Settlement s) => (s.Type == SettlementType.Town || s.Type == SettlementType.Castle) && s.OwnerClanId == faction)) { num += item.Garrison.Stacks.Sum((TroopStack x) => (double)x.Healthy * C.UnitPower(x.UnitId)); } return num; } internal int OtherWars(string faction, string except) { return State.Stances.Count((StanceRecord s) => s.Stance == Stance.War && ((s.A == faction && s.B != except && C.KnownDiplomacyFaction(s.B)) || (s.B == faction && s.A != except && C.KnownDiplomacyFaction(s.A)))); } public double WarAdvantage(string a, string b) { double num = FactionStrength(a); double num2 = FactionStrength(b); double num3 = ((num + num2 <= 0.0) ? 0.0 : ((num - num2) / (num + num2))); long since = (State.FindStance(a, b)?.SinceMinute ?? 0) / 1440; int valueOrDefault = (State.Diplomacy?.Captures?.Count((WarCapture c) => c.CaptorFactionId == a && c.LoserFactionId == b && c.Day >= since)).GetValueOrDefault(); int valueOrDefault2 = (State.Diplomacy?.Captures?.Count((WarCapture c) => c.CaptorFactionId == b && c.LoserFactionId == a && c.Day >= since)).GetValueOrDefault(); return Math.Max(-1.0, Math.Min(1.0, num3 * 0.7 + (double)(valueOrDefault - valueOrDefault2) * 0.15)); } internal void RecordWarCapture(string captorFaction, string loserFaction, string settlementId) { if (State.Diplomacy?.Captures != null && !string.IsNullOrEmpty(captorFaction) && !string.IsNullOrEmpty(loserFaction) && !(captorFaction == loserFaction)) { State.Diplomacy.Captures.Add(new WarCapture { CaptorFactionId = captorFaction, LoserFactionId = loserFaction, SettlementId = (settlementId ?? ""), Day = State.Clock.Day }); State.Touch(); } } internal void ClearWarCaptures(string a, string b) { State.Diplomacy?.Captures?.RemoveAll((WarCapture c) => (c.CaptorFactionId == a && c.LoserFactionId == b) || (c.CaptorFactionId == b && c.LoserFactionId == a)); } internal long TributeFor(double advantage) { return Math.Max(10L, Math.Min(100L, (long)Math.Round(Math.Abs(advantage) * 100.0 / 5.0) * 5)); } internal double PeaceWillingness(string faction, string other) { StanceRecord stanceRecord = State.FindStance(faction, other); double num = ((stanceRecord == null) ? 0.0 : Math.Max(0.0, (double)(State.Clock.Minute - stanceRecord.SinceMinute) / 1440.0)); return 0.0 - WarAdvantage(faction, other) + Math.Min(0.4, num / 150.0) + 0.15 * (double)OtherWars(faction, other); } public List PeaceOffers(string targetKingdomId) { string text = C.PlayerDiplomacyReason(targetKingdomId); string text2 = State.FactionOf(State.PlayerClan); if (text.Length == 0 && !State.AtWar(text2, targetKingdomId)) { text = "You are already at peace with this kingdom."; } double advantage = ((text.Length == 0) ? WarAdvantage(text2, targetKingdomId) : 0.0); long num = TributeFor(advantage); double num2 = ((text.Length == 0) ? PeaceWillingness(targetKingdomId, text2) : 0.0); List list = new List { new PeaceOffer { Kind = PeaceTermKind.WhitePeace, Days = 0, Reason = text, Accepted = (num2 >= 0.1), Why = ((num2 >= 0.1) ? "They are ready to end the war as it stands." : "They think the war still favours them.") }, new PeaceOffer { Kind = PeaceTermKind.PayTribute, DailyTribute = num, Days = 28, Reason = text, Accepted = (num2 >= -0.25), Why = ((num2 >= -0.25) ? "Your tribute would buy their peace." : "They expect to win more than your tribute.") }, new PeaceOffer { Kind = PeaceTermKind.DemandTribute, DailyTribute = num, Days = 28, Reason = text, Accepted = (num2 >= 0.35), Why = ((num2 >= 0.35) ? "They are losing badly enough to pay." : "They are not losing badly enough to pay you.") } }; if (text.Length == 0) { if (State.PlayerClan.Gold < num * 3) { list[1].Reason = "Your treasury cannot keep up a tribute of " + num + " a day."; } if (State.Clock.Day > long.MaxValue - Math.Max(28, 7)) { foreach (PeaceOffer item in list) { item.Reason = "Terms cannot be recorded at this date."; } } } return list; } public CommandResult NegotiatePeace(string targetKingdomId, PeaceTermKind kind) { PeaceOffer peaceOffer = PeaceOffers(targetKingdomId).FirstOrDefault((PeaceOffer o) => o.Kind == kind); if (peaceOffer == null) { return CommandResult.Fail("Unknown terms."); } if (!peaceOffer.Ok) { return CommandResult.Fail(peaceOffer.Reason); } if (!peaceOffer.Accepted) { return CommandResult.Fail(C.DiplomacyFactionName(targetKingdomId) + " refuses: " + peaceOffer.Why); } string text = State.FactionOf(State.PlayerClan); string msg = MakeNegotiatedPeace(text, targetKingdomId, (kind == PeaceTermKind.PayTribute) ? text : ((kind == PeaceTermKind.DemandTribute) ? targetKingdomId : ""), peaceOffer.DailyTribute); C.TrainDiplomacy(80.0); return CommandResult.Success(msg); } internal string MakeNegotiatedPeace(string a, string b, string payer, long dailyTribute) { State.SetStance(a, b, Stance.Peace); C.AddDiplomacyTruce(a, b, "", "", 0L); ClearWarCaptures(a, b); State.Diplomacy.Agreements.RemoveAll((DiplomaticAgreement x) => x.Kind == AgreementKind.Tribute && Pair(x, a, b)); string text = C.DiplomacyFactionName(a) + " and " + C.DiplomacyFactionName(b) + " made peace"; if (!string.IsNullOrEmpty(payer) && dailyTribute > 0) { string text2 = ((payer == a) ? b : a); AddAgreement(AgreementKind.Tribute, a, b, 28, payer, text2, dailyTribute); text = text + "; " + C.DiplomacyFactionName(payer) + " pays " + C.DiplomacyFactionName(text2) + " " + dailyTribute + " denars a day for " + 28 + " days"; } text = text + ". A " + 7 + "-day truce was signed."; C.FinishDiplomacyChange(a, b, text); return text; } internal DiplomaticAgreement AddAgreement(AgreementKind kind, string a, string b, int days, string payer = "", string recipient = "", long daily = 0L) { string id; do { id = State.Ids.Allocate("pact"); } while (State.Diplomacy.Agreements.Any((DiplomaticAgreement x) => x.Id == id)); DiplomaticAgreement diplomaticAgreement = new DiplomaticAgreement { Id = id, Kind = kind, A = ((string.CompareOrdinal(a, b) < 0) ? a : b), B = ((string.CompareOrdinal(a, b) < 0) ? b : a), SignedDay = State.Clock.Day, EndsDay = State.Clock.Day + days, PayerFactionId = (payer ?? ""), RecipientFactionId = (recipient ?? ""), DailyAmount = daily }; State.Diplomacy.Agreements.Add(diplomaticAgreement); State.Diplomacy.Agreements.Sort((DiplomaticAgreement x, DiplomaticAgreement y) => string.CompareOrdinal(x.Id, y.Id)); State.Touch(); return diplomaticAgreement; } internal string PlayerSovereignReason(string targetKingdomId) { string text = C.PlayerDiplomacyReason(targetKingdomId); if (text.Length > 0) { return text; } if (State.Kingdoms.Get(State.FactionOf(State.PlayerClan)) != null) { return ""; } return "Only a kingdom can sign this: found or rule one first."; } internal double AllianceInterest(string faction, string other, out string why) { why = ""; if (Allied(faction, other)) { why = "They are already allies."; return -9.0; } if (State.AtWar(faction, other)) { why = "You are at war."; return -9.0; } if (AlliesOf(faction).Count >= 2) { why = "They already have " + 2 + " allies."; return -9.0; } if (AlliesOf(faction).Any((string ally) => State.AtWar(ally, other))) { why = "They are allied to your enemy."; return -9.0; } List list = (from s in State.Stances where s.Stance == Stance.War && (s.A == faction || s.B == faction) select (!(s.A == faction)) ? s.A : s.B).Where(C.KnownDiplomacyFaction).ToList(); int num = list.Count((string e) => State.AtWar(other, e)); Clan clan = FactionPurse(faction); Clan clan2 = FactionPurse(other); double num2 = ((clan == null || clan2 == null) ? 0.0 : ((double)C.ClanRelation(clan.Id, clan2.Id) / 100.0)); double num3 = ((FactionStrength(other) >= FactionStrength(faction) * 0.8) ? 0.2 : 0.0); double num4 = (double)num * 0.6 + num2 + num3 - ((list.Count == 0) ? 0.3 : 0.0); why = ((num > 0) ? ("You share " + num + ((num == 1) ? " enemy." : " enemies.")) : ((num2 < 0.0) ? "Its ruler dislikes yours." : ((list.Count == 0) ? "They have no war that an ally would help with." : "You share no enemy."))); if (num4 >= 0.5 && num > 0) { why = "You share " + num + ((num == 1) ? " enemy" : " enemies") + " and they welcome a strong friend."; } return num4; } internal double TradeInterest(string faction, string other, out string why) { why = ""; if (State.AtWar(faction, other)) { why = "You are at war."; return -9.0; } if (HasTradeAgreement(faction, other)) { why = "They already trade freely with you."; return -9.0; } if (!towns(faction) || !towns(other)) { why = "Both realms need towns to trade."; return -9.0; } Clan clan = FactionPurse(faction); Clan clan2 = FactionPurse(other); double num = ((clan == null || clan2 == null) ? 0.0 : ((double)C.ClanRelation(clan.Id, clan2.Id) / 100.0)); double num2 = 0.4 + num - (AlliesOf(faction).Any((string ally) => State.AtWar(ally, other)) ? 0.5 : 0.0); why = ((num2 >= 0.2) ? "Their merchants would welcome it." : "Relations are too poor for open trade."); return num2; bool towns(string f) { return State.Settlements.Any((Settlement s) => s.Type == SettlementType.Town && State.FactionOf(State.Clans.Get(s.OwnerClanId)) == f); } } public PactQuote QuoteAlliance(string targetKingdomId) { PactQuote pactQuote = new PactQuote { Reason = PlayerSovereignReason(targetKingdomId) }; if (!pactQuote.Ok) { return pactQuote; } string text = State.FactionOf(State.PlayerClan); if (Allied(text, targetKingdomId)) { pactQuote.Reason = "You are already allies."; return pactQuote; } if (State.AtWar(text, targetKingdomId)) { pactQuote.Reason = "Make peace first."; return pactQuote; } if (AlliesOf(text).Count >= 2) { pactQuote.Reason = "Your realm already has " + 2 + " allies."; return pactQuote; } if (AlliesOf(text).Any((string ally) => State.AtWar(ally, targetKingdomId))) { pactQuote.Reason = "One of your allies is at war with them."; return pactQuote; } pactQuote.Accepted = AllianceInterest(targetKingdomId, text, out pactQuote.Why) >= 0.5; return pactQuote; } public CommandResult ProposeAlliance(string targetKingdomId) { PactQuote pactQuote = QuoteAlliance(targetKingdomId); if (!pactQuote.Ok) { return CommandResult.Fail(pactQuote.Reason); } if (!pactQuote.Accepted) { return CommandResult.Fail(C.DiplomacyFactionName(targetKingdomId) + " declines: " + pactQuote.Why); } string text = State.FactionOf(State.PlayerClan); AddAgreement(AgreementKind.Alliance, text, targetKingdomId, 84, "", "", 0L); string text2 = C.DiplomacyFactionName(text) + " and " + C.DiplomacyFactionName(targetKingdomId) + " swore an alliance for " + 84 + " days."; C.FinishDiplomacyChange(text, targetKingdomId, text2); C.TrainDiplomacy(80.0); return CommandResult.Success(text2); } public PactQuote QuoteTradeAgreement(string targetKingdomId) { PactQuote pactQuote = new PactQuote { Reason = PlayerSovereignReason(targetKingdomId) }; if (!pactQuote.Ok) { return pactQuote; } string text = State.FactionOf(State.PlayerClan); if (HasTradeAgreement(text, targetKingdomId)) { pactQuote.Reason = "You already have a trade agreement."; return pactQuote; } if (State.AtWar(text, targetKingdomId)) { pactQuote.Reason = "Make peace first."; return pactQuote; } pactQuote.Accepted = TradeInterest(targetKingdomId, text, out pactQuote.Why) >= 0.2; return pactQuote; } public CommandResult ProposeTradeAgreement(string targetKingdomId) { PactQuote pactQuote = QuoteTradeAgreement(targetKingdomId); if (!pactQuote.Ok) { return CommandResult.Fail(pactQuote.Reason); } if (!pactQuote.Accepted) { return CommandResult.Fail(C.DiplomacyFactionName(targetKingdomId) + " declines: " + pactQuote.Why); } string text = State.FactionOf(State.PlayerClan); AddAgreement(AgreementKind.TradeAgreement, text, targetKingdomId, 84, "", "", 0L); string text2 = C.DiplomacyFactionName(text) + " and " + C.DiplomacyFactionName(targetKingdomId) + " signed a trade agreement for " + 84 + " days."; C.FinishDiplomacyChange(text, targetKingdomId, text2); C.TrainDiplomacy(80.0); return CommandResult.Success(text2); } internal void AddPactProsperity(StatForecast f, Settlement s) { if (s == null || s.Type != SettlementType.Town) { return; } string faction = State.FactionOf(State.Clans.Get(s.OwnerClanId)); if (string.IsNullOrEmpty(faction)) { return; } foreach (DiplomaticAgreement item in LiveAgreements.Where((DiplomaticAgreement x) => x.Kind == AgreementKind.TradeAgreement && (x.A == faction || x.B == faction))) { f.Add("Trade agreement with " + C.DiplomacyFactionName((item.A == faction) ? item.B : item.A), 0.2); } } internal double CallToWarInterest(string ally, string caller, string enemy, long payment, out string why) { Clan clan = FactionPurse(ally); Clan clan2 = FactionPurse(enemy); double num = ((clan == null || clan2 == null) ? 0.0 : ((double)(-C.ClanRelation(clan.Id, clan2.Id)) / 100.0)); double num2 = FactionStrength(ally) + FactionStrength(caller); double num3 = Math.Max(1.0, FactionStrength(enemy)); double num4 = Math.Max(-0.5, Math.Min(0.5, (num2 / num3 - 1.2) * 0.4)); double num5 = num + num4 + (double)payment / 2000.0 - (double)OtherWars(ally, enemy) * 0.3; why = ((!(num5 >= 0.2)) ? ((num4 < 0.0) ? "They fear the enemy is too strong." : ((OtherWars(ally, enemy) > 0) ? "They have wars enough of their own." : "It is not worth it to them.")) : ((payment > 0) ? "The gold and the odds persuade them." : "They like the odds.")); return num5; } internal string CallToWarReason(string caller, string ally, string enemy) { if (!Allied(caller, ally)) { return C.DiplomacyFactionName(ally) + " is not your ally."; } if (!State.AtWar(caller, enemy)) { return "You are not at war with " + C.DiplomacyFactionName(enemy) + "."; } if (State.AtWar(ally, enemy)) { return C.DiplomacyFactionName(ally) + " is already at war with them."; } if (Allied(ally, enemy)) { return C.DiplomacyFactionName(ally) + " is allied with them."; } long num = C.TruceDaysRemaining(ally, enemy); if (num > 0) { return C.DiplomacyFactionName(ally) + " has a truce with them for " + num + " more days."; } if (State.Diplomacy.Calls.Any((CallToWarRequest c) => c.CallerFactionId == caller && c.AllyFactionId == ally && c.EnemyFactionId == enemy && (c.Status == CallToWarStatus.Pending || State.Clock.Day - c.CreatedDay < 14))) { return "You asked them recently."; } if (C.DiplomacyFactionReserved(ally) || C.DiplomacyFactionReserved(enemy)) { return "Wait for their battles to finish."; } return ""; } public PactQuote QuoteCallToWar(string allyId, string enemyId, long payment) { string caller = State.FactionOf(State.PlayerClan); PactQuote pactQuote = new PactQuote { Payment = payment, Reason = PlayerSovereignReason(allyId) }; if (pactQuote.Ok) { pactQuote.Reason = CallToWarReason(caller, allyId, enemyId); } if (pactQuote.Ok && (payment < 0 || State.PlayerClan.Gold < payment)) { pactQuote.Reason = "Your clan cannot pay " + payment + " denars."; } if (pactQuote.Ok && FactionPurse(allyId) == null) { pactQuote.Reason = "They have no ruler to receive it."; } if (pactQuote.Ok) { pactQuote.Accepted = CallToWarInterest(allyId, caller, enemyId, payment, out pactQuote.Why) >= 0.2; } return pactQuote; } public CommandResult CallAllyToWar(string allyId, string enemyId, long payment) { PactQuote pactQuote = QuoteCallToWar(allyId, enemyId, payment); if (!pactQuote.Ok) { return CommandResult.Fail(pactQuote.Reason); } string caller = State.FactionOf(State.PlayerClan); CallToWarRequest call = NewCall(caller, allyId, enemyId, payment); AnswerCall(call, pactQuote.Accepted, pactQuote.Why); if (!pactQuote.Accepted) { return CommandResult.Fail(C.DiplomacyFactionName(allyId) + " declines: " + pactQuote.Why); } return CommandResult.Success(C.DiplomacyFactionName(allyId) + " joins the war against " + C.DiplomacyFactionName(enemyId) + "."); } internal CallToWarRequest NewCall(string caller, string ally, string enemy, long payment) { string id; do { id = State.Ids.Allocate("call"); } while (State.Diplomacy.Calls.Any((CallToWarRequest c) => c.Id == id)); CallToWarRequest callToWarRequest = new CallToWarRequest { Id = id, CallerFactionId = caller, AllyFactionId = ally, EnemyFactionId = enemy, Payment = payment, CreatedDay = State.Clock.Day, ExpiresDay = State.Clock.Day + 5, Status = CallToWarStatus.Pending }; State.Diplomacy.Calls.Add(callToWarRequest); State.Touch(); return callToWarRequest; } internal void AnswerCall(CallToWarRequest call, bool accept, string why) { if (call.Status != CallToWarStatus.Pending) { return; } call.Status = (accept ? CallToWarStatus.Accepted : CallToWarStatus.Declined); call.AnsweredDay = State.Clock.Day; Clan clan = FactionPurse(call.CallerFactionId); Clan clan2 = FactionPurse(call.AllyFactionId); if (accept) { long num = 0L; if (clan != null && clan2 != null && call.Payment > 0) { num = -State.Transact(clan, -call.Payment, LedgerAccount.Other, "Payment to " + clan2.Name + " for joining the war", allowPartial: true); if (num > 0) { State.Transact(clan2, num, LedgerAccount.Other, "Payment from " + clan.Name + " for joining the war"); } } C.RemoveExpiredPairTruces(call.AllyFactionId, call.EnemyFactionId); State.SetStance(call.AllyFactionId, call.EnemyFactionId, Stance.War); if (clan != null && clan2 != null) { C.AdjustClanRelation(clan.Id, clan2.Id, 10); } C.FinishDiplomacyChange(call.AllyFactionId, call.EnemyFactionId, C.DiplomacyFactionName(call.AllyFactionId) + " answered " + C.DiplomacyFactionName(call.CallerFactionId) + "'s call and declared war on " + C.DiplomacyFactionName(call.EnemyFactionId) + ((num > 0) ? (" (" + num + " denars paid).") : ".")); } else { if (clan != null && clan2 != null) { C.AdjustClanRelation(clan.Id, clan2.Id, -5); } State.AddLog(LogCategory.Politics, C.DiplomacyFactionName(call.AllyFactionId) + " declined " + C.DiplomacyFactionName(call.CallerFactionId) + "'s call to war against " + C.DiplomacyFactionName(call.EnemyFactionId) + (string.IsNullOrEmpty(why) ? "." : (": " + why)), call.CallerFactionId, call.AllyFactionId); } State.Touch(); } public string AnswerCallToWarReason(string callId, bool accept) { CallToWarRequest callToWarRequest = State.Diplomacy?.Calls?.FirstOrDefault((CallToWarRequest c) => c.Id == callId); if (callToWarRequest == null || callToWarRequest.Status != CallToWarStatus.Pending) { return "That call has already been answered."; } string text = State.FactionOf(State.PlayerClan); if (callToWarRequest.AllyFactionId != text) { return "That call was not made to your realm."; } string text2 = PlayerSovereignReason(callToWarRequest.CallerFactionId); if (text2.Length > 0) { return text2; } if (accept) { if (State.AtWar(text, callToWarRequest.EnemyFactionId)) { return "You are already at war with them."; } long num = C.TruceDaysRemaining(text, callToWarRequest.EnemyFactionId); if (num > 0) { return "Your truce with them lasts " + num + " more days."; } } return ""; } public CommandResult AnswerCallToWar(string callId, bool accept) { string text = AnswerCallToWarReason(callId, accept); if (text.Length > 0) { return CommandResult.Fail(text); } CallToWarRequest callToWarRequest = State.Diplomacy.Calls.First((CallToWarRequest c) => c.Id == callId); AnswerCall(callToWarRequest, accept, accept ? "" : "you refused."); return CommandResult.Success(accept ? ("You join " + C.DiplomacyFactionName(callToWarRequest.CallerFactionId) + "'s war against " + C.DiplomacyFactionName(callToWarRequest.EnemyFactionId) + ".") : ("You decline. " + C.DiplomacyFactionName(callToWarRequest.CallerFactionId) + " will remember it.")); } internal void DailyPacts() { DiplomacyState diplomacy = State.Diplomacy; if (diplomacy?.Agreements == null || diplomacy.Calls == null) { return; } long today = State.Clock.Day; foreach (DiplomaticAgreement item in diplomacy.Agreements.ToList()) { bool flag = !C.KnownDiplomacyFaction(item.A) || !C.KnownDiplomacyFaction(item.B); bool flag2 = item.Kind != AgreementKind.Tribute && State.AtWar(item.A, item.B); if (item.EndsDay <= today || flag || flag2) { diplomacy.Agreements.Remove(item); if (item.Kind != AgreementKind.Tribute || flag || flag2) { State.AddLog(LogCategory.Politics, AgreementName(item.Kind) + " between " + C.DiplomacyFactionName(item.A) + " and " + C.DiplomacyFactionName(item.B) + ((item.EndsDay <= today) ? " came to its end." : (flag ? " ended: a party to it is no more." : " ended with war between them.")), item.A, item.B); } else { State.AddLog(LogCategory.Politics, C.DiplomacyFactionName(item.PayerFactionId) + " paid the last of its tribute to " + C.DiplomacyFactionName(item.RecipientFactionId) + ".", item.A, item.B); } State.Touch(); } else { if (item.Kind != AgreementKind.Tribute || item.DailyAmount <= 0) { continue; } Clan clan = FactionPurse(item.PayerFactionId); Clan clan2 = FactionPurse(item.RecipientFactionId); if (clan == null || clan2 == null) { continue; } long num = -State.Transact(clan, -item.DailyAmount, LedgerAccount.Other, "Tribute to " + C.DiplomacyFactionName(item.RecipientFactionId), allowPartial: true); if (num > 0) { State.Transact(clan2, num, LedgerAccount.Other, "Tribute from " + C.DiplomacyFactionName(item.PayerFactionId)); } item.PaidTotal += num; item.MissedDays = ((num < item.DailyAmount) ? (item.MissedDays + 1) : 0); if (item.MissedDays >= 3) { diplomacy.Agreements.Remove(item); C.AdjustClanRelation(clan.Id, clan2.Id, -20); string text = C.DiplomacyFactionName(item.PayerFactionId) + " failed to pay its tribute to " + C.DiplomacyFactionName(item.RecipientFactionId) + " for " + 3 + " days; the tribute is void and " + clan2.Name + " is aggrieved."; State.AddLog(LogCategory.Politics, text, item.A, item.B); if (item.PayerFactionId == State.FactionOf(State.PlayerClan) || item.RecipientFactionId == State.FactionOf(State.PlayerClan)) { C.Raise(CampaignEventKind.Warning, text, false, item.A, item.B); } } State.Touch(); } } foreach (CallToWarRequest item2 in diplomacy.Calls.Where((CallToWarRequest c) => c.Status == CallToWarStatus.Pending && c.ExpiresDay <= today).ToList()) { item2.Status = CallToWarStatus.Expired; item2.AnsweredDay = today; Clan clan3 = FactionPurse(item2.CallerFactionId); Clan clan4 = FactionPurse(item2.AllyFactionId); if (clan3 != null && clan4 != null) { C.AdjustClanRelation(clan3.Id, clan4.Id, -5); } State.Touch(); } diplomacy.Calls.RemoveAll((CallToWarRequest c) => c.Status != CallToWarStatus.Pending && today - c.AnsweredDay > 60); if (today - diplomacy.LastPactAiDay >= 7) { diplomacy.LastPactAiDay = today; State.Touch(); AiPacts(); } } public static string AgreementName(AgreementKind kind) { return kind switch { AgreementKind.TradeAgreement => "The trade agreement", AgreementKind.Alliance => "The alliance", _ => "The tribute", }; } internal void AiPacts() { string text = State.FactionOf(State.PlayerClan); List source = State.Kingdoms.Where((Kingdom kingdom) => C.LivingDiplomacyRuler(kingdom.Id) != null).OrderBy((Kingdom kingdom) => kingdom.Id, StringComparer.Ordinal).ToList(); foreach (Kingdom k in source.Where((Kingdom kingdom) => kingdom.RulerClanId != State.PlayerClanId)) { foreach (string item in (from s in State.Stances where s.Stance == Stance.War && (s.A == k.Id || s.B == k.Id) select (!(s.A == k.Id)) ? s.A : s.B).Where(C.KnownDiplomacyFaction).OrderBy((string x) => x, StringComparer.Ordinal).ToList()) { if (WarAdvantage(k.Id, item) > 0.1) { continue; } foreach (string item2 in AlliesOf(k.Id)) { if (CallToWarReason(k.Id, item2, item).Length <= 0) { long num = Math.Max(0L, Math.Min(1000L, (FactionPurse(k.Id)?.Gold ?? 0) / 4)) / 100 * 100; CallToWarRequest call = NewCall(k.Id, item2, item, num); if (item2 == text && State.Kingdoms.Get(text)?.RulerClanId == State.PlayerClanId) { C.Raise(CampaignEventKind.Warning, k.Name + " calls on you, its ally, to join its war against " + C.DiplomacyFactionName(item) + ((num > 0) ? (" and offers " + num + " denars") : "") + ". Answer in Realm → Diplomacy within " + 5 + " days.", true, k.Id, item); } else { AnswerCall(call, CallToWarInterest(item2, k.Id, item, num, out var why) >= 0.2, why); } } } } } List list = source.Where((Kingdom kingdom) => kingdom.RulerClanId != State.PlayerClanId).ToList(); bool flag = false; bool flag2 = false; for (int num2 = 0; num2 < list.Count; num2++) { if (flag && flag2) { break; } for (int num3 = num2 + 1; num3 < list.Count; num3++) { if (flag && flag2) { break; } string id = list[num2].Id; string id2 = list[num3].Id; if (!C.DiplomacyFactionReserved(id) && !C.DiplomacyFactionReserved(id2)) { if (!flag && AllianceInterest(id, id2, out var why2) >= 0.6 && AllianceInterest(id2, id, out why2) >= 0.6) { AddAgreement(AgreementKind.Alliance, id, id2, 84, "", "", 0L); C.FinishDiplomacyChange(id, id2, list[num2].Name + " and " + list[num3].Name + " swore an alliance for " + 84 + " days against their common enemies."); flag = true; } else if (!flag2 && C.DiplomacyFrontier(id, id2) && TradeInterest(id, id2, out why2) >= 0.35 && TradeInterest(id2, id, out why2) >= 0.35) { AddAgreement(AgreementKind.TradeAgreement, id, id2, 84, "", "", 0L); State.AddLog(LogCategory.Politics, list[num2].Name + " and " + list[num3].Name + " signed a trade agreement for " + 84 + " days.", id, id2); flag2 = true; } } } } } } internal sealed class PartyFoodSystem { private readonly Campaign C; private CampaignState State => C.State; internal PartyFoodSystem(Campaign host) { C = host; } public bool EatsCargoFood(Party p) { if (p != null) { return p.Id == State.PlayerPartyId; } return false; } public int CargoHeldForContracts(string goodId) { if (State.Contracts != null) { return State.Contracts.Where((ContractState c) => c.Status == ContractStatus.Active && Campaign.IsCargoContract(c) && c.GoodId == goodId).Sum((ContractState c) => Math.Max(0, c.Quantity)); } return 0; } public int EdibleCargoCount(Party p, string goodId) { if (!EatsCargoFood(p)) { return 0; } TradeGoodDef tradeGoodDef = TradeGoods.Get(goodId ?? ""); if (tradeGoodDef == null || tradeGoodDef.Category != GoodCategory.Food) { return 0; } return Math.Max(0, C.CargoCount(p, goodId) - CargoHeldForContracts(goodId)); } public List> EdibleCargo(Party p) { List> list = new List>(); if (!EatsCargoFood(p)) { return list; } foreach (TradeGoodDef item in (from g in TradeGoods.All where g.Category == GoodCategory.Food orderby g.BasePrice select g).ThenBy((TradeGoodDef g) => g.Id, StringComparer.Ordinal)) { int num = EdibleCargoCount(p, item.Id); if (num > 0) { list.Add(new KeyValuePair(item, num)); } } return list; } public int EdibleCargoTotal(Party p) { return EdibleCargo(p).Sum((KeyValuePair pair) => pair.Value); } public static double Provisions(Party p) { if (p != null && !double.IsNaN(p.Food) && !double.IsInfinity(p.Food)) { return Math.Max(0.0, p.Food); } return 0.0; } public double FoodSupply(Party p) { return Provisions(p) + (double)EdibleCargoTotal(p); } internal double TakeFood(Party p, double amount) { if (p == null || !(amount > 0.0)) { return 0.0; } if (!EatsCargoFood(p)) { p.Food -= amount; return amount; } double num = Provisions(p); if (num + 1E-09 >= amount) { p.Food = Math.Max(0.0, num - amount); return amount; } double num2 = num; double num3 = amount - num; p.Food = 0.0; foreach (KeyValuePair item in EdibleCargo(p)) { int num4 = Math.Min(item.Value, (int)Math.Ceiling(num3 - 1E-09)); if (num4 <= 0) { break; } int num5 = C.CargoCount(p, item.Key.Id) - num4; if (num5 <= 0) { p.Cargo.Remove(item.Key.Id); } else { p.Cargo[item.Key.Id] = num5; } double num6 = Math.Min(num3, num4); num2 += num6; num3 -= num6; p.Food += (double)num4 - num6; if (num3 <= 1E-09) { break; } } State.Touch(); return num2; } public string FoodSupplyBreakdown(Party p) { if (p == null) { return ""; } double num = Provisions(p); if (!EatsCargoFood(p)) { return num.ToString("0.#") + " provisions."; } List> list = EdibleCargo(p); string text = ((list.Count == 0) ? "no food goods in cargo" : (list.Sum((KeyValuePair pair) => pair.Value) + " food goods in cargo (" + string.Join(", ", list.Select((KeyValuePair pair) => pair.Value + " " + pair.Key.Name)) + ")")); List list2 = (from g in TradeGoods.All where g.Category == GoodCategory.Food && C.CargoCount(p, g.Id) > 0 && CargoHeldForContracts(g.Id) > 0 select Math.Min(C.CargoCount(p, g.Id), CargoHeldForContracts(g.Id)) + " " + g.Name).ToList(); return num.ToString("0.#") + " provisions (food carried apart from goods: what you set out with or took in raids) + " + text + ". Provisions are eaten first, then the cheapest food goods" + ((list2.Count > 0) ? ("; " + string.Join(", ", list2) + " kept for your delivery contracts.") : "."); } } internal sealed class PartySizesSystem { private readonly Campaign C; private static int[] ClanTierRenown => Campaign.ClanTierRenown; private CampaignRules Rules => C.Rules; private CampaignState State => C.State; internal PartySizesSystem(Campaign host) { C = host; } public static int ClanTier(Clan clan) { if (clan == null) { return 0; } int result = 0; for (int i = 0; i < ClanTierRenown.Length; i++) { if (clan.Renown >= (double)ClanTierRenown[i]) { result = i; } } return result; } public bool IsAiLordParty(Party p) { if (p == null || p.Kind != PartyKind.Lord) { return false; } Clan clan = State.Clans.Get(p.ClanId); if (clan != null && !clan.IsBandit && clan.Id != State.PlayerClanId) { return C.MilitaryPartyFor(p) == null; } return false; } internal int AiLordPartySizeLimit(Party p) { Clan clan = State.Clans.Get(p.ClanId); Hero hero = State.Heroes.Get(p.LeaderHeroId); int num = 20 + ClanTier(clan) * 15; if (hero != null) { num += hero.Skill("leadership") / 4; if (clan.LeaderHeroId == hero.Id) { num += 10; Kingdom kingdom = State.Kingdoms.Get(clan.KingdomId ?? ""); if (kingdom != null && !kingdom.IsEliminated && kingdom.RulerClanId == clan.Id) { num += 25; } } } int val = State.Settlements.Count((Settlement s) => s.OwnerClanId == clan.Id && (s.Type == SettlementType.Town || s.Type == SettlementType.Castle)); num += 5 * Math.Min(4, val); return (int)Math.Round((double)num * C.Settings.AiLordStrength); } public static double LordTemperament(string heroId) { return 0.8 + 0.35 * (double)(StableHash.Fnv1a64("temperament|" + heroId) % 10000) / 10000.0; } public static double LordMuster(string heroId) { double num = (double)(StableHash.Fnv1a64("muster|" + heroId) % 10000) / 10000.0; if (num < 0.22) { return Math.Round(0.45 + 0.3 * num / 0.22, 3); } if (num < 0.86) { return Math.Round(0.8 + 0.35 * (num - 0.22) / 0.64, 3); } return Math.Round(1.3 + 0.3 * (num - 0.86) / 0.14, 3); } public static string LordMusterName(double muster) { if (!(muster < 0.78)) { if (!(muster < 1.25)) { return "warlord"; } return "steady"; } return "modest"; } internal double LordBudgetWeight(Party p) { Clan clan = State.Clans.Get(p?.ClanId ?? ""); double num = LordMuster(p?.LeaderHeroId); if (clan != null && clan.LeaderHeroId == p.LeaderHeroId) { num *= 1.4; Kingdom kingdom = State.Kingdoms.Get(clan.KingdomId ?? ""); if (kingdom != null && !kingdom.IsEliminated && kingdom.RulerClanId == clan.Id) { num *= 1.3; } } return num; } internal double PartyUpkeep(Party p) { return Math.Ceiling(C.DailyWages(p)) + C.DailyFoodNeed(p) * Rules.FoodPrice; } internal double LordUpkeepShare(Party p) { Clan clan = State.Clans.Get(p?.ClanId ?? ""); if (clan == null) { return 0.0; } double num = Math.Max(C.DailyIncome(clan.Id) * 0.95, (double)clan.Gold / 60.0); double num2 = 0.0; double num3 = 0.0; foreach (Settlement settlement in State.Settlements) { if (settlement.OwnerClanId == clan.Id) { num2 += C.GarrisonDailyWages(settlement) + C.GovernorDailyWages(settlement); } } foreach (Party party in State.Parties) { if (!(party.ClanId != clan.Id) && party.Kind == PartyKind.Lord && !(party.Id == State.PlayerPartyId) && (party.State == PartyState.Active || party.State == PartyState.InSettlement || party.State == PartyState.Engaged)) { num3 += LordBudgetWeight(party); } } if (num3 <= 0.0) { return 0.0; } return Math.Max(0.0, num - num2) * LordBudgetWeight(p) / num3 * 1.15; } public bool LordCanGrowParty(Party p, double extraDaily) { Clan clan = State.Clans.Get(p?.ClanId ?? ""); if (!ClanCanGrowParty(clan, extraDaily)) { return false; } if (!IsAiLordParty(p)) { return true; } return PartyUpkeep(p) + extraDaily <= LordUpkeepShare(p); } public bool ClanAtWar(Clan clan) { if (clan == null) { return false; } string faction = State.FactionOf(clan); return State.Stances.Any((StanceRecord s) => s.Stance == Stance.War && (s.A == faction || s.B == faction)); } public bool ClanCanGrowParty(Clan clan, double extraDaily) { if (clan == null) { return false; } double num = C.DailyIncome(clan.Id); double num2 = C.DailyExpenses(clan.Id) + extraDaily; if (!(num2 <= num * 0.95)) { return (double)clan.Gold > num2 * 60.0; } return true; } public int AiLordRecruitTarget(Party p) { int num = C.PartySizeLimit(p); if (!IsAiLordParty(p)) { return num; } Clan clan = State.Clans.Get(p.ClanId); double num2 = (ClanAtWar(clan) ? 1.0 : 0.6); double num3 = ((!ClanCanGrowParty(clan, 0.0)) ? 0.5 : ((clan.Gold < 1500) ? 0.75 : 1.0)); int val = (int)Math.Round((double)num * Math.Min(1.0, num2 * LordMuster(p.LeaderHeroId) * num3)); return Math.Max(Math.Min(Rules.LordRecruitThreshold, num), Math.Min(num, val)); } } internal sealed class PerksSystem { private readonly Campaign C; private static readonly PartyRole[] Roles = (PartyRole[])Enum.GetValues(typeof(PartyRole)); private CampaignState State => C.State; internal PerksSystem(Campaign host) { C = host; } internal static bool IsActive(Hero hero, HeroPerkDef perk) { if (hero?.Perks == null || perk == null || !hero.Perks.Contains(perk.Id) || hero.Skill(perk.Skill) < perk.RequiredSkill) { return false; } int num = 0; foreach (string perk2 in hero.Perks) { HeroPerkDef heroPerkDef = HeroPerks.Get(perk2); if (heroPerkDef != null && heroPerkDef.Group == perk.Group) { num++; } } return num == 1; } internal static double HeroValue(Hero hero, PerkEffect effect, PerkScope scope, string target = null) { if (hero?.Perks == null || hero.Perks.Count == 0 || hero.State == HeroState.Dead) { return 0.0; } double num = 0.0; foreach (string perk in hero.Perks) { HeroPerkDef heroPerkDef = HeroPerks.Get(perk); if (heroPerkDef == null || heroPerkDef.Mods.Count == 0) { continue; } bool flag = false; bool flag2 = false; foreach (PerkMod mod in heroPerkDef.Mods) { if (mod.Effect == effect && mod.Scope == scope && (mod.Target.Length <= 0 || target == null || !(mod.Target != target)) && (mod.Target.Length <= 0 || target != null)) { if (!flag2) { flag = IsActive(hero, heroPerkDef); flag2 = true; } if (flag) { num += mod.Value; } } } } return num; } public double PersonalPerk(Hero hero, PerkEffect effect, string target = null) { return HeroValue(hero, effect, PerkScope.Personal, target); } public static PerkScope RoleScope(PartyRole role) { return role switch { PartyRole.Scout => PerkScope.Scout, PartyRole.Surgeon => PerkScope.Surgeon, PartyRole.Engineer => PerkScope.Engineer, _ => PerkScope.Quartermaster, }; } public double PartyPerk(Party party, PerkEffect effect, string target = null) { if (party == null || string.IsNullOrEmpty(party.ClanId) || party.ClanId != State.PlayerClanId || party.State == PartyState.Destroyed || party.State == PartyState.Disbanded) { return 0.0; } double num = 0.0; Hero hero = State.Heroes.Get(party.LeaderHeroId ?? ""); if (hero != null && hero.CanFight && Campaign.IsPresentPartyHero(party, hero)) { num += HeroValue(hero, effect, PerkScope.Leader, target); } PartyRole[] roles = Roles; foreach (PartyRole role in roles) { Hero hero2 = C.RoleHolder(party, role); if (hero2 != null) { num += HeroValue(hero2, effect, RoleScope(role), target); } } return num; } public double ClanPerk(Clan clan, PerkEffect effect) { if (clan == null || clan.Id != State.PlayerClanId) { return 0.0; } Hero hero = State.Heroes.Get(clan.LeaderHeroId ?? ""); if (hero != null && hero.State != HeroState.Dead) { return HeroValue(hero, effect, PerkScope.ClanLeader); } return 0.0; } public double SettlementPerk(Settlement settlement, PerkEffect effect) { if (settlement == null || string.IsNullOrEmpty(settlement.OwnerClanId) || settlement.OwnerClanId != State.PlayerClanId) { return 0.0; } double num = ClanPerk(State.Clans.Get(settlement.OwnerClanId), effect); Hero hero = C.SettlementGovernor(settlement); if (hero != null && C.IsStationedGovernor(settlement, hero)) { num += HeroValue(hero, effect, PerkScope.Governor); } return num; } public string CombatantWeaponSkill(Combatant c) { if (c == null || !c.IsHero) { return ""; } Hero hero = State.Heroes.Get(c.HeroId); if (hero != null) { return C.MainWeaponSkill(hero); } return ""; } public double TroopHealthMultiplier(Combatant c) { if (c == null || c.IsHero || c.Id < 0) { return 1.0; } Party party = State.Parties.Get(c.PartyId ?? ""); return 1.0 + Math.Max(0.0, PartyPerk(party, PerkEffect.TroopHealth, c.Role.ToString())); } public double DamageMultiplier(Combatant c) { if (c == null) { return 1.0; } if (!c.IsHero) { Party party = State.Parties.Get(c.PartyId ?? ""); return 1.0 + Math.Max(0.0, PartyPerk(party, PerkEffect.TroopDamage, c.Role.ToString())); } Hero hero = State.Heroes.Get(c.HeroId); if (hero == null) { return 1.0; } string text = C.MainWeaponSkill(hero); double num = Math.Max(0, Math.Min(300, hero.Skill(text))); return 1.0 + num / 300.0 * 0.15 + Math.Max(0.0, PersonalPerk(hero, PerkEffect.HeroDamage, text)); } public double DamageTakenMultiplier(Combatant c) { if (c == null || !c.IsHero) { return 1.0; } Hero hero = State.Heroes.Get(c.HeroId); return Math.Max(0.4, 1.0 - Math.Max(0.0, PersonalPerk(hero, PerkEffect.HeroDamageTaken))); } } internal sealed class PlayerSystem { private readonly Campaign C; internal const double UntilStoppedHours = 201600.0; private ContentDatabase Content => C.Content; private CampaignRules Rules => C.Rules; private CampaignState State => C.State; public bool IsIronman => C.Settings.Ironman; internal PlayerSystem(Campaign host) { C = host; } public void UpdatePlayerTimeStates() { PlayerState player = State.Player; if (player.Activity == PlayerActivity.Captive || player.Activity == PlayerActivity.InEncounter || player.Activity == PlayerActivity.InBattle) { return; } Party playerParty = State.PlayerParty; if (playerParty != null) { if (playerParty.State == PartyState.InSettlement) { player.Activity = ((player.WaitUntilMinute > State.Clock.Minute) ? PlayerActivity.Waiting : PlayerActivity.InSettlement); } else if (C.PlayerSiege != null && (C.PlayerSiege.Stage == SiegeStage.Preparing || C.PlayerSiege.Stage == SiegeStage.Ready)) { player.Activity = PlayerActivity.Besieging; } else if (playerParty.ActiveRaid != null && playerParty.Order.Kind == OrderKind.Raid) { player.Activity = PlayerActivity.Raiding; } else if (playerParty.Order.Kind != OrderKind.None) { player.Activity = PlayerActivity.Travelling; } else if (player.WaitUntilMinute > State.Clock.Minute) { player.Activity = PlayerActivity.Waiting; } else { player.Activity = PlayerActivity.Idle; } } } internal CommandResult RequireFree() { if (C.AwaitingHeir) { return CommandResult.Fail("Choose your heir first."); } if (C.LineEnded) { return CommandResult.Fail("Your line has ended."); } switch (State.Player.Activity) { case PlayerActivity.Captive: return CommandResult.Fail("You are a prisoner."); case PlayerActivity.InEncounter: return CommandResult.Fail("Deal with the encounter first."); case PlayerActivity.InBattle: return CommandResult.Fail("A battle is in progress."); default: if (State.PlayerParty == null || State.PlayerParty.State == PartyState.Destroyed) { return CommandResult.Fail("You have no party."); } return CommandResult.Success(); } } public CommandResult MoveTo(Vec2 point) { CommandResult commandResult = RequireFree(); if (!commandResult.Ok) { return commandResult; } if (C.MarchingWithArmyReason().Length > 0) { return CommandResult.Fail(C.MarchingWithArmyReason()); } if (C.TournamentBusyReason().Length > 0) { return CommandResult.Fail(C.TournamentBusyReason()); } Party playerParty = State.PlayerParty; State.Player.WaitUntilMinute = 0L; if (!C.SetMoveOrder(playerParty, OrderKind.MoveToPoint, point, "", "player")) { return CommandResult.Fail("You can't get there."); } UpdatePlayerTimeStates(); C.ResumeIfPaused(); State.Touch(); return CommandResult.Success(playerParty.Order.Point.Equals(point) ? "" : "Heading as close as you can get."); } public CommandResult GoToSettlement(string settlementId) { CommandResult commandResult = RequireFree(); if (!commandResult.Ok) { return commandResult; } if (C.MarchingWithArmyReason().Length > 0) { return CommandResult.Fail(C.MarchingWithArmyReason()); } if (C.TournamentBusyReason().Length > 0) { return CommandResult.Fail(C.TournamentBusyReason()); } Settlement settlement = State.Settlements.Get(settlementId); if (settlement == null) { return CommandResult.Fail("Unknown settlement."); } Party playerParty = State.PlayerParty; if (playerParty.State == PartyState.InSettlement && playerParty.CurrentSettlementId == settlement.Id) { return CommandResult.Fail("You are already there."); } State.Player.WaitUntilMinute = 0L; if (!C.SetMoveOrder(playerParty, OrderKind.GoToSettlement, settlement.Position, settlement.Id, "player")) { return CommandResult.Fail(settlement.Name + " cannot be reached."); } UpdatePlayerTimeStates(); C.ResumeIfPaused(); State.Touch(); return CommandResult.Success(C.CanEnter(playerParty, settlement) ? "" : (settlement.Name + " is hostile and won't let you in.")); } public CommandResult EngageParty(string partyId) { CommandResult commandResult = RequireFree(); if (!commandResult.Ok) { return commandResult; } if (C.MarchingWithArmyReason().Length > 0) { return CommandResult.Fail(C.MarchingWithArmyReason()); } if (C.TournamentBusyReason().Length > 0) { return CommandResult.Fail(C.TournamentBusyReason()); } Party playerParty = State.PlayerParty; Party party = State.Parties.Get(partyId); if (party == null || !C.IsKnownToPlayer(party)) { return CommandResult.Fail("You don't know where that party is."); } if (!State.AreHostile(playerParty, party)) { return CommandResult.Fail("You are not at war with " + party.Name + "."); } if (party.State == PartyState.InSettlement) { return CommandResult.Fail(party.Name + " is inside a settlement."); } Sighting value; Vec2 point = (State.PlayerSightings.TryGetValue(party.Id, out value) ? value.Position : party.Position); State.Player.WaitUntilMinute = 0L; if (!C.SetMoveOrder(playerParty, OrderKind.Engage, point, party.Id, "player")) { return CommandResult.Fail("Cannot reach that party."); } playerParty.Order.TargetLost = !(value?.CurrentlyVisible ?? false); UpdatePlayerTimeStates(); C.ResumeIfPaused(); State.Touch(); return CommandResult.Success(); } public CommandResult FollowParty(string partyId) { CommandResult commandResult = RequireFree(); if (!commandResult.Ok) { return commandResult; } if (C.MarchingWithArmyReason().Length > 0) { return CommandResult.Fail(C.MarchingWithArmyReason()); } if (C.TournamentBusyReason().Length > 0) { return CommandResult.Fail(C.TournamentBusyReason()); } Party playerParty = State.PlayerParty; Party party = State.Parties.Get(partyId); if (party == null || party.State == PartyState.Destroyed || party.State == PartyState.Disbanded) { return CommandResult.Fail("That party is gone."); } if (State.AreHostile(playerParty, party)) { return CommandResult.Fail(party.Name + " is hostile."); } State.Player.WaitUntilMinute = 0L; if (!C.SetMoveOrder(playerParty, OrderKind.Follow, party.Position, party.Id, "player")) { return CommandResult.Fail("Cannot reach that party."); } UpdatePlayerTimeStates(); C.ResumeIfPaused(); State.Touch(); return CommandResult.Success("Following " + party.Name + "."); } public string MeetPartyReason(string partyId) { Party playerParty = State.PlayerParty; Party party = State.Parties.Get(partyId); if (playerParty == null || party == null || party.Id == playerParty.Id || party.State != PartyState.Active) { return "That party isn't out on the road."; } if (playerParty.State != PartyState.Active || State.Player.Activity == PlayerActivity.Captive) { return "You're not free to meet anyone."; } if (State.AreHostile(playerParty, party)) { return party.Name + " is hostile."; } if (!C.IsKnownToPlayer(party) || C.HiddenOnMap(party)) { return "You can't see " + party.Name + "."; } if (Vec2.Distance(playerParty.Position, party.Position) > 1.0) { return "Get closer to " + party.Name + "."; } return ""; } public Party PartyOfHero(string heroId) { if (!string.IsNullOrEmpty(heroId)) { return State.Parties.FirstOrDefault((Party p) => p.State != PartyState.Destroyed && p.State != PartyState.Disbanded && p.Troops.Heroes.Contains(heroId)); } return null; } public CommandResult Stop() { Party playerParty = State.PlayerParty; if (playerParty == null) { return CommandResult.Fail("You have no party."); } C.ClearOrder(playerParty); State.Player.WaitUntilMinute = 0L; UpdatePlayerTimeStates(); State.Touch(); return CommandResult.Success(); } public CommandResult Wait(double hours) { CommandResult commandResult = RequireFree(); if (!commandResult.Ok) { return commandResult; } if (C.TournamentBusyReason().Length > 0) { return CommandResult.Fail(C.TournamentBusyReason()); } if (hours <= 0.0) { return CommandResult.Fail("Choose a positive duration."); } C.ClearOrder(State.PlayerParty); State.Player.WaitUntilMinute = State.Clock.Minute + (long)Math.Round(hours * 60.0); UpdatePlayerTimeStates(); C.ResumeIfPaused(); State.Touch(); return CommandResult.Success(); } public CommandResult WaitHere() { if (State.Player.Activity != PlayerActivity.Idle) { return CommandResult.Success(); } return Wait(201600.0); } public CommandResult WaitInSettlement() { if (CurrentSettlement() == null) { return CommandResult.Fail("You're not in a settlement."); } return Wait(201600.0); } public CommandResult LeaveSettlement() { Party party = C.ArmyHead(State.PlayerParty); if (party != null && party.Id != State.PlayerPartyId && party.State == PartyState.InSettlement) { return CommandResult.Fail("Your army is staying here: " + C.MarchingWithArmyReason()); } Party playerParty = State.PlayerParty; if (playerParty == null || playerParty.State != PartyState.InSettlement) { return CommandResult.Fail("You're not in a settlement."); } if (C.TournamentBusyReason().Length > 0) { return CommandResult.Fail(C.TournamentBusyReason()); } Settlement settlement = State.Settlements.Get(playerParty.CurrentSettlementId); if (C.BesiegedAgainst(playerParty, settlement)) { return CommandResult.Fail("The besiegers have " + settlement.Name + " surrounded. Break out through their lines, or stay and defend it."); } State.Player.WaitUntilMinute = 0L; C.LeaveSettlementInternal(playerParty); UpdatePlayerTimeStates(); State.Touch(); return CommandResult.Success(); } internal Settlement CurrentSettlement() { Party playerParty = State.PlayerParty; if (playerParty == null || playerParty.State != PartyState.InSettlement) { return null; } return State.Settlements.Get(playerParty.CurrentSettlementId); } public CommandResult Recruit(int slotIndex) { string text = C.RecruitmentReason(slotIndex); if (text.Length > 0) { return CommandResult.Fail(text); } Settlement settlement = CurrentSettlement(); Party playerParty = State.PlayerParty; UnitDef unitDef = C.UnitDef(settlement.Recruits[slotIndex].UnitId); Clan playerClan = State.PlayerClan; State.Transact(playerClan, -C.RecruitPrice(playerParty, unitDef), LedgerAccount.Recruitment, "Recruited " + unitDef.Name + " at " + settlement.Name); playerParty.Troops.Add(unitDef.Id, 1); settlement.Recruits[slotIndex].Available = false; State.AddLog(LogCategory.Recruitment, "Recruited a " + unitDef.Name + " at " + settlement.Name + ".", settlement.Id); State.Touch(); return CommandResult.Success("A " + unitDef.Name + " joins your party."); } public CommandResult SellPrisoners() { return C.RansomAllOrdinaryPrisoners(); } public CommandResult UpgradeTroops(string fromUnit, string toUnit, int count) { CommandResult commandResult = RequireFree(); if (!commandResult.Ok) { return commandResult; } Party playerParty = State.PlayerParty; UnitDef unitDef = C.UnitDef(fromUnit); UpgradeDef upgradeDef = unitDef?.Upgrades.FirstOrDefault((UpgradeDef u) => u.To == toUnit); if (upgradeDef == null) { return CommandResult.Fail("That upgrade path does not exist."); } TroopStack troopStack = playerParty.Troops.Find(fromUnit); if (troopStack == null || troopStack.Healthy < count || count <= 0) { return CommandResult.Fail("Not enough healthy troops."); } if (!string.IsNullOrEmpty(upgradeDef.RequiresSettlement)) { Settlement settlement = CurrentSettlement(); if (settlement == null || settlement.Type.ToString() != upgradeDef.RequiresSettlement) { return CommandResult.Fail("This upgrade requires a " + upgradeDef.RequiresSettlement + "."); } } long num = (long)upgradeDef.Xp * (long)count; if (troopStack.Xp < num) { return CommandResult.Fail($"Needs {num} XP; the stack has {troopStack.Xp}."); } long num2 = C.UpgradePrice(playerParty, upgradeDef.Gold) * count; if (State.PlayerClan.Gold < num2) { return CommandResult.Fail($"Needs {num2} denars."); } State.Transact(State.PlayerClan, -num2, LedgerAccount.Upgrade, $"Upgraded {count} {unitDef.Name} to {C.UnitDef(toUnit).Name}"); troopStack.Xp -= (int)num; playerParty.Troops.RemoveHealthy(fromUnit, count); playerParty.Troops.Add(toUnit, count); State.Touch(); return CommandResult.Success($"{count} {unitDef.Name} became {C.UnitDef(toUnit).Name}."); } public CommandResult TransferToGarrison(string unitId, int count) { Settlement settlement = CurrentSettlement(); if (settlement == null || settlement.OwnerClanId != State.PlayerClanId) { return CommandResult.Fail("You can only garrison your own settlements."); } int num = State.PlayerParty.Troops.RemoveHealthy(unitId, count); if (num == 0) { return CommandResult.Fail("No healthy troops of that type."); } settlement.Garrison.Add(unitId, num); State.Touch(); return CommandResult.Success($"{num} moved to the garrison of {settlement.Name}."); } public string TroopReleaseReason(string unitId, int count) { CommandResult commandResult = RequireFree(); if (!commandResult.Ok) { return commandResult.Message; } TroopStack troopStack = State.PlayerParty.Troops.Find(unitId ?? ""); if (troopStack == null || troopStack.Total == 0) { return "You have none of those."; } if (count <= 0) { return "Choose how many to release."; } if (count > troopStack.Total) { return "You only have " + troopStack.Total + "."; } return ""; } public CommandResult ReleaseTroops(string unitId, int count) { string text = TroopReleaseReason(unitId, count); if (text.Length > 0) { return CommandResult.Fail(text); } Party playerParty = State.PlayerParty; int num = playerParty.Troops.Remove(unitId, count, woundedFirst: true); string arg = C.UnitDef(unitId)?.Name ?? unitId; string text2 = $"Released {num} {arg}. They head home."; State.AddLog(LogCategory.Recruitment, text2, playerParty.Id); State.Touch(); return CommandResult.Success(text2); } public CommandResult TakeFromGarrison(string unitId, int count) { Settlement settlement = CurrentSettlement(); if (settlement == null || settlement.OwnerClanId != State.PlayerClanId) { return CommandResult.Fail("You can only draw troops from your own settlements."); } Party playerParty = State.PlayerParty; int num = C.PartySizeLimit(playerParty) - playerParty.Troops.TotalTroops; if (num <= 0) { return CommandResult.Fail("Your party is full."); } int num2 = settlement.Garrison.RemoveHealthy(unitId, Math.Min(num, count)); if (num2 == 0) { return CommandResult.Fail("No healthy troops of that type in the garrison."); } playerParty.Troops.Add(unitId, num2); State.Touch(); return CommandResult.Success($"{num2} joined your party from {settlement.Name}."); } public void AcknowledgeReport() { if (State.Player.LastReportSeen) { return; } BattleReport lastReport = State.Player.LastReport; if (lastReport != null) { int num = lastReport.RescuedTroops?.TotalTroops ?? 0; lastReport.RescuedReleased += num; lastReport.RescuedTroops?.Stacks.Clear(); if (lastReport.RescuedRecruited + lastReport.RescuedReleased > 0) { State.AddLog(LogCategory.Recruitment, $"Rescued troops: {lastReport.RescuedRecruited} joined your warband; {lastReport.RescuedReleased} were released.", lastReport.EncounterId); } } State.Player.LastReportSeen = true; State.Touch(); } public EncounterOptions GetEncounterOptions() { Encounter enc = C.PendingPlayerEncounter; EncounterOptions encounterOptions = new EncounterOptions(); if (enc == null || enc.Phase != EncounterPhase.AwaitingDecision) { return encounterOptions; } string text = C.SiegeBattleValidation(enc); if (text.Length > 0) { encounterOptions.FightReason = text; encounterOptions.CanLeave = enc.InitiatorPartyId == State.PlayerPartyId && !enc.MustFight; return encounterOptions; } Party playerParty = State.PlayerParty; BattleSide playerSide = enc.PlayerSide; BattleSide side = ((playerSide == BattleSide.Attacker) ? BattleSide.Defender : BattleSide.Attacker); encounterOptions.FriendlyTroops = enc.PartiesOn(playerSide).Sum((string id) => C.PartyCombatants(State.Parties.Get(id))); encounterOptions.EnemyEstimate = Campaign.EstimateCount(enc.PartiesOn(side).Sum((string id) => C.PartyCombatants(State.Parties.Get(id)))); encounterOptions.WinEstimate = AutoResolver.EstimateWinChance(C, enc, playerSide); encounterOptions.FightReason = ((encounterOptions.CanFight = C.PartyCombatants(playerParty) > 0) ? "" : "Nobody in your party is fit to fight."); encounterOptions.CanSimulate = encounterOptions.FriendlyTroops > 0; bool flag = (encounterOptions.CanLeave = enc.InitiatorPartyId == playerParty.Id); encounterOptions.LeaveReason = (flag ? "" : "The enemy caught you; you cannot simply ride away."); int totalHealthy = playerParty.Troops.TotalHealthy; encounterOptions.SacrificeCount = Math.Max(1, (int)Math.Ceiling((double)totalHealthy * 0.15)); encounterOptions.CanSacrifice = !flag && enc.Kind != EncounterKind.Siege && totalHealthy > encounterOptions.SacrificeCount; encounterOptions.CanSurrender = !flag; if (encounterOptions.CanSurrender && enc.Kind == EncounterKind.Siege) { SiegeState siegeState = State.Sieges?.FirstOrDefault((SiegeState s) => s.Id == enc.SiegeId); encounterOptions.CanSurrender = siegeState != null && State.Settlements.Get(siegeState.SettlementId)?.OwnerClanId == State.PlayerClanId; } if (enc.MustFight) { encounterOptions.CanLeave = false; encounterOptions.LeaveReason = "Ironman: you've started this battle, so it has to be settled — fight, auto-resolve or surrender."; encounterOptions.CanSacrifice = false; } return encounterOptions; } public CommandResult ChooseLeave() { Encounter pendingPlayerEncounter = C.PendingPlayerEncounter; if (pendingPlayerEncounter == null || pendingPlayerEncounter.Phase != EncounterPhase.AwaitingDecision) { return CommandResult.Fail("No encounter."); } if (!GetEncounterOptions().CanLeave) { return CommandResult.Fail("There's no leaving this one."); } C.CancelEncounter(pendingPlayerEncounter, "The player withdrew before battle."); foreach (string item in pendingPlayerEncounter.PartiesOn((pendingPlayerEncounter.PlayerSide == BattleSide.Attacker) ? BattleSide.Defender : BattleSide.Attacker)) { Party party = State.Parties.Get(item); if (party != null) { party.DisengagedUntilMinute = State.Clock.Minute + 60; } } return CommandResult.Success(); } public CommandResult ChooseSacrifice() { Encounter pendingPlayerEncounter = C.PendingPlayerEncounter; EncounterOptions encounterOptions = GetEncounterOptions(); if (pendingPlayerEncounter == null || !encounterOptions.CanSacrifice) { return CommandResult.Fail("You cannot escape that way."); } Party playerParty = State.PlayerParty; Party party = (from id in pendingPlayerEncounter.PartiesOn((pendingPlayerEncounter.PlayerSide == BattleSide.Attacker) ? BattleSide.Defender : BattleSide.Attacker) select State.Parties.Get(id) into p orderby p.Troops.TotalTroops descending select p).First(); int num = 0; foreach (TroopStack item in playerParty.Troops.Stacks.OrderBy((TroopStack s) => C.UnitDef(s.UnitId)?.Tier ?? 1).ThenBy((TroopStack s) => s.UnitId, StringComparer.Ordinal).ToList()) { if (num >= encounterOptions.SacrificeCount) { break; } int num2 = playerParty.Troops.RemoveHealthy(item.UnitId, encounterOptions.SacrificeCount - num); party.Prisoners.Add(item.UnitId, num2); num += num2; } State.AddLog(LogCategory.Battle, $"You escaped {party.Name} by leaving {num} troops behind.", party.Id); C.CancelEncounter(pendingPlayerEncounter, "The player escaped by sacrificing troops.", playerParty.Id); return CommandResult.Success($"{num} troops stayed behind so the rest could escape."); } public CommandResult ChooseSurrender() { Encounter pendingPlayerEncounter = C.PendingPlayerEncounter; if (pendingPlayerEncounter == null || pendingPlayerEncounter.Phase != EncounterPhase.AwaitingDecision) { return CommandResult.Fail("You cannot surrender here."); } string text = C.SiegeBattleValidation(pendingPlayerEncounter); if (text.Length > 0) { return CommandResult.Fail(text); } if (!GetEncounterOptions().CanSurrender) { return CommandResult.Fail("You cannot surrender here."); } BattleManifest battleManifest = BeginAttempt(pendingPlayerEncounter, 0); BattleResult battleResult = new BattleResult { CampaignId = State.CampaignId, EncounterId = pendingPlayerEncounter.Id, AttemptId = pendingPlayerEncounter.CurrentAttemptId, ExpectedRevision = pendingPlayerEncounter.ExpectedRevision, EndKind = BattleEndKind.Surrender, LosingSide = pendingPlayerEncounter.PlayerSide, Winner = ((pendingPlayerEncounter.PlayerSide != BattleSide.Attacker) ? WinnerSide.Attacker : WinnerSide.Defender) }; foreach (Combatant combatant in battleManifest.Combatants) { battleResult.Outcomes.Add(new CombatantResult { Id = combatant.Id, Outcome = CombatOutcome.Unhurt }); } CommitResult commitResult = OutcomeCommitter.Commit(C, battleResult); if (!commitResult.Success) { return CommandResult.Fail(commitResult.Error); } return CommandResult.Success(pendingPlayerEncounter.ResultSummary); } public CommitResult ChooseAutoResolve() { Encounter pendingPlayerEncounter = C.PendingPlayerEncounter; if (pendingPlayerEncounter == null || pendingPlayerEncounter.Phase != EncounterPhase.AwaitingDecision) { return new CommitResult { Error = "Nothing waiting on a decision." }; } string text = C.SiegeBattleValidation(pendingPlayerEncounter); if (text.Length > 0) { return new CommitResult { Error = text }; } BattleManifest manifest = BeginAttempt(pendingPlayerEncounter, 0); BattleResult result = AutoResolver.Resolve(C, pendingPlayerEncounter, manifest); return OutcomeCommitter.Commit(C, result); } internal BattleManifest BeginAttempt(Encounter enc, int budget) { enc.AttemptCounter++; enc.CurrentAttemptId = enc.Id + "#" + enc.AttemptCounter; BattleManifest battleManifest = ManifestBuilder.Build(C, enc, budget); battleManifest.AttemptId = enc.CurrentAttemptId; enc.Manifest = battleManifest; enc.ExpectedRevision = State.Revision; enc.Phase = EncounterPhase.InBattle; return battleManifest; } public BattlePlan PrepareBattle(int? budgetOverride = null) { Encounter pendingPlayerEncounter = C.PendingPlayerEncounter; if (pendingPlayerEncounter == null || pendingPlayerEncounter.Phase != EncounterPhase.AwaitingDecision) { throw new InvalidOperationException("Nothing waiting on a decision."); } string text = C.SiegeBattleValidation(pendingPlayerEncounter); if (text.Length > 0) { throw new InvalidOperationException(text); } (BattleMapDef map, bool standIn) tuple = SelectBattleMap(pendingPlayerEncounter); BattleMapDef item = tuple.map; bool item2 = tuple.standIn; int num = budgetOverride ?? State.Settings.ActiveUnitBudget; if (pendingPlayerEncounter.IsKeepBattle) { num = Math.Min(num, 60); } pendingPlayerEncounter.AttemptCounter++; pendingPlayerEncounter.CurrentAttemptId = pendingPlayerEncounter.Id + "#" + pendingPlayerEncounter.AttemptCounter; BattleManifest battleManifest = ManifestBuilder.Build(C, pendingPlayerEncounter, num); battleManifest.AttemptId = pendingPlayerEncounter.CurrentAttemptId; pendingPlayerEncounter.Manifest = battleManifest; pendingPlayerEncounter.Phase = EncounterPhase.Preparing; pendingPlayerEncounter.BattleMapId = item?.Id ?? ""; BattleSide playerSide = pendingPlayerEncounter.PlayerSide; BattleSide side = ((playerSide == BattleSide.Attacker) ? BattleSide.Defender : BattleSide.Attacker); int num2 = ((playerSide == BattleSide.Attacker) ? battleManifest.AttackerAllowance : battleManifest.DefenderAllowance); int num3 = ((playerSide == BattleSide.Attacker) ? battleManifest.DefenderAllowance : battleManifest.AttackerAllowance); BattlePlan battlePlan = new BattlePlan { Encounter = pendingPlayerEncounter, Manifest = battleManifest, Budget = num, PlayerSide = playerSide, PlayerSideAllowance = num2, EnemySideAllowance = num3, Map = item, MapIsStandIn = item2, Config = ReinforcementConfig.FromRules(Rules, Math.Min(num, item?.MaxActiveUnits ?? num)) }; battlePlan.PlayerSideShares = SlotAllocator.SplitAmongParties(battleManifest, playerSide, num2, State.PlayerPartyId); battlePlan.EnemySideShares = SlotAllocator.SplitAmongParties(battleManifest, side, num3, null); battlePlan.SuggestedInitial = SlotAllocator.AutoSelectInitial(battleManifest, playerSide, num2, battlePlan.PlayerSideShares); battlePlan.EnemyInitial = SlotAllocator.AutoSelectInitial(battleManifest, side, num3, battlePlan.EnemySideShares); State.Touch(); return battlePlan; } public string ValidateInitialSelection(BattlePlan plan, IList playerChoice) { int num = 0; HashSet hashSet = new HashSet(); foreach (int item in playerChoice) { Combatant combatant = plan.Manifest.Get(item); if (combatant == null || combatant.Side != plan.PlayerSide) { return $"Combatant {item} is not on your side."; } if (!hashSet.Add(item)) { return $"Combatant {item} chosen twice."; } num += combatant.Slots; } if (num > plan.PlayerSideAllowance) { return $"Your side may deploy {plan.PlayerSideAllowance} slots initially; {num} selected."; } return ""; } public CommandResult CancelPreparation() { Encounter pendingPlayerEncounter = C.PendingPlayerEncounter; if (pendingPlayerEncounter == null || pendingPlayerEncounter.Phase != EncounterPhase.Preparing) { return CommandResult.Fail("No battle being set up."); } pendingPlayerEncounter.Phase = EncounterPhase.AwaitingDecision; pendingPlayerEncounter.Manifest = null; State.Touch(); return CommandResult.Success(); } public string BeginBattle() { Encounter pendingPlayerEncounter = C.PendingPlayerEncounter; if (pendingPlayerEncounter == null || pendingPlayerEncounter.Phase != EncounterPhase.Preparing) { throw new InvalidOperationException("Prepare the battle first."); } pendingPlayerEncounter.Phase = EncounterPhase.InBattle; pendingPlayerEncounter.ExpectedRevision = State.Revision; State.Player.Activity = PlayerActivity.InBattle; return pendingPlayerEncounter.CurrentAttemptId; } public CommitResult SubmitBattleResult(BattleResult result) { return OutcomeCommitter.Commit(C, result); } public void AbortBattle(string reason) { Encounter pendingPlayerEncounter = C.PendingPlayerEncounter; if (pendingPlayerEncounter != null && (pendingPlayerEncounter.Phase == EncounterPhase.InBattle || pendingPlayerEncounter.Phase == EncounterPhase.Preparing)) { if (C.Settings.Ironman && pendingPlayerEncounter.Phase == EncounterPhase.InBattle) { pendingPlayerEncounter.MustFight = true; } pendingPlayerEncounter.Phase = EncounterPhase.AwaitingDecision; pendingPlayerEncounter.Manifest = null; pendingPlayerEncounter.CurrentAttemptId = pendingPlayerEncounter.Id + "#retired" + pendingPlayerEncounter.AttemptCounter; State.Player.Activity = PlayerActivity.InEncounter; State.AddLog(LogCategory.Battle, "Battle interrupted: " + reason + ". Back to the encounter.", pendingPlayerEncounter.Id); State.Touch(); } } public bool RecoverPlayerEncounter(string reason) { Encounter pendingPlayerEncounter = C.PendingPlayerEncounter; if (pendingPlayerEncounter != null && pendingPlayerEncounter.Phase == EncounterPhase.Preparing && State.Player.Activity != PlayerActivity.InBattle) { CancelPreparation(); return true; } if (pendingPlayerEncounter != null && (pendingPlayerEncounter.Phase == EncounterPhase.InBattle || pendingPlayerEncounter.Phase == EncounterPhase.Preparing)) { AbortBattle(reason); return true; } if (State.Player.Activity == PlayerActivity.InBattle && C.PlayerTournament != null && C.PlayerTournament.Run.AttemptId.Length > 0) { C.AbortTournamentMatch(reason); return true; } if (State.Player.Activity == PlayerActivity.InBattle) { State.Player.Activity = PlayerActivity.Idle; State.Player.PendingEncounterId = ""; State.AddLog(LogCategory.Battle, "Battle interrupted: " + reason + "."); UpdatePlayerTimeStates(); State.Touch(); return true; } return false; } public (BattleMapDef map, bool standIn) SelectBattleMap(Encounter enc) { if (enc.Kind == EncounterKind.Siege) { BattleMapDef battleMapDef = Content.BattleMaps.Get("map.bannerlord_siege_v1"); if (battleMapDef == null || battleMapDef.ContentVersion != 2 || battleMapDef.GenericStandIn || !battleMapDef.EncounterKinds.Contains(EncounterKind.Siege) || !battleMapDef.TabsMapMatch.Contains("00_simulation_day")) { throw new InvalidOperationException("The siege fortress map is unavailable or unsupported. Restore the mod's battle-map content before assaulting."); } return (map: battleMapDef, standIn: false); } if (C.FieldSiteOverride != null && FieldBattlefield.Supports(enc.Kind)) { BattleMapDef battleMapDef2 = Content.BattleMaps.Get("map.bannerlord_field_v1"); if (battleMapDef2 == null || battleMapDef2.ContentVersion != 1) { throw new InvalidOperationException("The open-field battlefield is unavailable or unsupported. Restore the mod's battle-map content."); } return (map: battleMapDef2, standIn: false); } List source = Content.BattleMaps.Where((BattleMapDef m) => (m.Id != "map.bannerlord_field_v1" || m.ContentVersion == 1) && (string.IsNullOrEmpty(m.Prefab) || Campaign.BattleSceneAvailable == null || Campaign.BattleSceneAvailable(m.Prefab))).ToList(); List list = source.Where((BattleMapDef m) => !m.GenericStandIn).ToList(); if (list.Any((BattleMapDef m) => m.EncounterKinds.Contains(enc.Kind) || m.EncounterKinds.Contains(EncounterKind.FieldBattle))) { source = list; } List list2 = source.Where((BattleMapDef m) => m.EncounterKinds.Contains(enc.Kind)).ToList(); if (list2.Count == 0) { list2 = source.Where((BattleMapDef m) => m.EncounterKinds.Contains(EncounterKind.FieldBattle)).ToList(); } List list3 = list2.Where((BattleMapDef m) => m.Biomes.Contains(enc.Biome)).ToList(); List list4 = ((list3.Count > 0) ? list3 : list2); if (list4.Count == 0) { return (map: null, standIn: true); } BattleMapDef field = list4.FirstOrDefault((BattleMapDef m) => m.Id == "map.bannerlord_field_v1"); if (field != null && list4.Count > 1) { list4 = ((StableHash.Fnv1a64("field-pick|" + enc.Id) % 2 != 0L) ? list4.Where((BattleMapDef m) => m != field).ToList() : new List { field }); } int index = (int)(StableHash.Fnv1a64(enc.Id) % (ulong)list4.Count); BattleMapDef battleMapDef3 = list4[index]; return (map: battleMapDef3, standIn: list3.Count == 0 || battleMapDef3.GenericStandIn); } } internal sealed class PoliciesSystem { private readonly Campaign C; private CampaignState State => C.State; internal PoliciesSystem(Campaign host) { C = host; } public bool LawInForce(string kingdomId, KingdomLaw law) { if (!string.IsNullOrEmpty(kingdomId) && law != KingdomLaw.None && State.Politics?.Laws != null && State.Politics.Laws.Any((KingdomLawState l) => l != null && l.KingdomId == kingdomId && l.Law == law)) { Kingdom kingdom = State.Kingdoms.Get(kingdomId); if (kingdom == null) { return false; } return !kingdom.IsEliminated; } return false; } public List LawsInForce(string kingdomId) { if (State.Politics?.Laws != null) { return (from l in (from l in State.Politics.Laws where l != null && l.KingdomId == kingdomId && l.Law != KingdomLaw.None select l.Law).Distinct() orderby (int)l select l).ToList(); } return new List(); } internal string LawKingdomAt(Settlement s) { Clan clan = State.Clans.Get(s?.OwnerClanId ?? ""); if (clan == null || clan.IsEliminated || string.IsNullOrEmpty(clan.KingdomId)) { return ""; } Kingdom kingdom = State.Kingdoms.Get(clan.KingdomId); if (kingdom == null || kingdom.IsEliminated) { return ""; } return clan.KingdomId; } internal bool LawAt(Settlement s, KingdomLaw law) { return LawInForce(LawKingdomAt(s), law); } internal string LawKingdomOf(Clan clan) { if (clan != null && !clan.IsEliminated && !string.IsNullOrEmpty(clan.KingdomId)) { Kingdom kingdom = State.Kingdoms.Get(clan.KingdomId); if (kingdom != null && !kingdom.IsEliminated) { return clan.KingdomId; } } return ""; } internal bool IsRulingClan(Clan clan, string kingdomId) { if (clan != null && !string.IsNullOrEmpty(kingdomId)) { return C.ServiceRuler(kingdomId)?.Id == clan.Id; } return false; } public double LawTaxFactor(Settlement s) { string text = LawKingdomAt(s); if (text.Length == 0 || s == null) { return 1.0; } double num = 1.0; bool num2 = s.Type == SettlementType.Town; bool flag = s.Type == SettlementType.Castle; if (num2 && LawInForce(text, KingdomLaw.RoadTolls)) { num *= 1.1; } if (s.Type == SettlementType.Village && LawInForce(text, KingdomLaw.Serfdom)) { num *= 1.25; } if (flag && LawInForce(text, KingdomLaw.GrazingRights)) { num *= 0.9; } if ((num2 || flag) && LawInForce(text, KingdomLaw.Magistrates)) { num *= 0.95; } if (num2 && LawInForce(text, KingdomLaw.Cantons)) { num *= 0.95; } if ((num2 || flag) && LawInForce(text, KingdomLaw.NobleRetinues)) { num *= 0.95; } if ((num2 || flag) && LawInForce(text, KingdomLaw.MilitaryCoronae)) { num *= 0.95; } if (flag && LawInForce(text, KingdomLaw.Marches)) { num *= 0.9; } if ((num2 || flag) && LawInForce(text, KingdomLaw.LandGrantsForVeterans)) { num *= 0.95; } return num; } internal void AddLawLoyalty(StatForecast f, Settlement s) { if (s == null || s.Type == SettlementType.Hideout) { return; } bool flag = s.Type == SettlementType.Town; bool flag2 = s.Type == SettlementType.Castle; string text = LawKingdomAt(s); Clan clan = State.Clans.Get(s.OwnerClanId); if ((flag || flag2) && clan != null && !clan.IsBandit && !string.IsNullOrEmpty(clan.CultureId) && !string.IsNullOrEmpty(s.CultureId) && clan.CultureId != s.CultureId) { f.Add("Ruled by a lord of another culture" + (LawInForce(text, KingdomLaw.Cantons) ? " (Cantons: halved)" : ""), -0.75 * (LawInForce(text, KingdomLaw.Cantons) ? 0.5 : 1.0)); } if (text.Length != 0) { if (LawInForce(text, KingdomLaw.DebasementOfTheCurrency)) { f.Add("Debasement of the Currency", -0.5); } if (LawInForce(text, KingdomLaw.Citizenship) && s.CultureId == State.Kingdoms.Get(text)?.CultureId) { f.Add("Citizenship", 0.75); } if (flag && LawInForce(text, KingdomLaw.CouncilOfTheCommons)) { f.Add("Council of the Commons", 0.5); } if (flag && LawInForce(text, KingdomLaw.TribunesOfThePeople)) { f.Add("Tribunes of the People", 0.5); } if (flag2 && LawInForce(text, KingdomLaw.CastleCharters)) { f.Add("Castle Charters", 1.0); } if (LawInForce(text, KingdomLaw.SacredMajesty)) { f.Add("Sacred Majesty", 0.25); } } } public double LawSecurity(Settlement s) { string text = LawKingdomAt(s); if (text.Length == 0) { return 0.0; } bool num = s.Type == SettlementType.Town; bool flag = s.Type == SettlementType.Castle; double num2 = 0.0; if ((num || flag) && LawInForce(text, KingdomLaw.Magistrates)) { num2 += 1.0; } if ((num || flag) && LawInForce(text, KingdomLaw.Bailiffs)) { num2 += 0.5; } if (num && LawInForce(text, KingdomLaw.TrialByJury)) { num2 += 0.5; } if (flag && LawInForce(text, KingdomLaw.Marches)) { num2 += 1.0; } return num2; } internal void AddLawProsperity(StatForecast f, Settlement s) { string text = LawKingdomAt(s); if (text.Length == 0) { return; } if (s.Type == SettlementType.Town && LawInForce(text, KingdomLaw.RoadTolls)) { f.Add("Road Tolls", -0.5); } if (s.Type == SettlementType.Castle && LawInForce(text, KingdomLaw.CastleCharters)) { f.Add("Castle Charters", 0.5); } if (s.Type == SettlementType.Village) { if (LawInForce(text, KingdomLaw.Serfdom)) { f.Add("Serfdom", -0.25); } if (LawInForce(text, KingdomLaw.GrazingRights)) { f.Add("Grazing Rights", 0.25); } if (LawInForce(text, KingdomLaw.HuntingRights)) { f.Add("Hunting Rights", -0.1); } } } public double LawMilitiaFactor(Settlement s) { if (!LawAt(s, KingdomLaw.LandGrantsForVeterans)) { return 1.0; } return 1.25; } public double LawGarrisonWageFactor(Settlement s) { string text = LawKingdomAt(s); if (text.Length == 0) { return 1.0; } double num = 1.0; if ((s.Type == SettlementType.Town || s.Type == SettlementType.Castle) && LawInForce(text, KingdomLaw.Bailiffs)) { num *= 1.1; } if (s.Type == SettlementType.Castle && LawInForce(text, KingdomLaw.Marches)) { num *= 0.75; } return num; } public double LawPartySizeFactor(Party p) { if (p == null || (p.Kind != PartyKind.Lord && p.Kind != PartyKind.Player)) { return 1.0; } Clan clan = State.Clans.Get(p.ClanId); string text = LawKingdomOf(clan); if (text.Length == 0) { return 1.0; } double num = 1.0; if (LawInForce(text, KingdomLaw.NobleRetinues)) { num *= 1.15; } if (LawInForce(text, KingdomLaw.TribunesOfThePeople)) { num *= 0.9; } if (LawInForce(text, KingdomLaw.RoyalGuard) && IsRulingClan(clan, text)) { num *= 1.25; } return num; } public double LawFoodFactor(Party p) { if (p == null || (p.Kind != PartyKind.Lord && p.Kind != PartyKind.Player)) { return 1.0; } if (!LawInForce(LawKingdomOf(State.Clans.Get(p.ClanId)), KingdomLaw.HuntingRights)) { return 1.0; } return 0.9; } public double LawInfluence(Clan clan, string kingdomId) { if (clan == null || string.IsNullOrEmpty(kingdomId)) { return 0.0; } bool flag = IsRulingClan(clan, kingdomId); double num = 0.0; if (LawInForce(kingdomId, KingdomLaw.Citizenship)) { num -= 0.25; } if (flag && LawInForce(kingdomId, KingdomLaw.CouncilOfTheCommons)) { num -= 0.5; } if (!flag && LawInForce(kingdomId, KingdomLaw.RoyalGuard)) { num -= 0.25; } if (flag && LawInForce(kingdomId, KingdomLaw.CastleCharters)) { num -= 0.25; } if (flag && LawInForce(kingdomId, KingdomLaw.RoyalPrivilege)) { num += 0.5; } if (flag && LawInForce(kingdomId, KingdomLaw.SacredMajesty)) { num += 1.0; } if (LawInForce(kingdomId, KingdomLaw.Senate)) { num += (flag ? (-1.0) : 0.5); } return num; } public double LawBattleInfluenceFactor(Clan clan) { if (!LawInForce(LawKingdomOf(clan), KingdomLaw.MilitaryCoronae)) { return 1.0; } return 1.5; } internal int LawBallotMultiplier(KingdomDecision decision, string clanId) { if (decision == null || !(clanId == decision.RulerClanId) || !LawInForce(decision.KingdomId, KingdomLaw.RoyalPrivilege)) { return 1; } return 2; } public int CouncilProposalCostFor(Clan clan) { string text = LawKingdomOf(clan); return 10 + ((text.Length > 0 && LawInForce(text, KingdomLaw.SacredMajesty) && !IsRulingClan(clan, text)) ? 5 : 0); } public int PlayerProposalCost() { return CouncilProposalCostFor(State.PlayerClan); } public int ExecutionInfluenceCost(Clan clan) { if (!LawInForce(LawKingdomOf(clan), KingdomLaw.TrialByJury)) { return 0; } return 30; } internal void DailyLawIncome() { foreach (Kingdom kingdom in State.Kingdoms.Where((Kingdom k) => !k.IsEliminated && LawInForce(k.Id, KingdomLaw.DebasementOfTheCurrency))) { Clan clan = C.ServiceRuler(kingdom.Id); if (clan != null) { long num = (long)Math.Round((double)State.Settlements.Count((Settlement s) => (s.Type == SettlementType.Town || s.Type == SettlementType.Castle) && LawKingdomAt(s) == kingdom.Id) * 20.0); if (num > 0) { State.Transact(clan, num, LedgerAccount.Taxes, "Debasement of the Currency in " + kingdom.Name); } } } } public string ProposeLawReason(KingdomLaw law, bool repeal) { string text = C.NewCouncilProposalReason(); if (text.Length > 0) { return text; } return LawChangeReason(State.PlayerClan.KingdomId, law, repeal); } internal string LawChangeReason(string kingdomId, KingdomLaw law, bool repeal) { KingdomLawDef kingdomLawDef = KingdomLaws.Get(law); if (kingdomLawDef == null || law == KingdomLaw.None) { return "Unknown policy."; } bool flag = LawInForce(kingdomId, law); if (repeal) { if (!flag) { return kingdomLawDef.Name + " is not in force."; } return ""; } if (flag) { return kingdomLawDef.Name + " is already in force."; } if (kingdomLawDef.Excludes != KingdomLaw.None && LawInForce(kingdomId, kingdomLawDef.Excludes)) { return kingdomLawDef.Name + " cannot stand beside " + KingdomLaws.Name(kingdomLawDef.Excludes) + ". Repeal it first."; } return ""; } public CommandResult ProposeLaw(KingdomLaw law, bool repeal) { string text = ProposeLawReason(law, repeal); if (text.Length > 0) { return CommandResult.Fail(text); } int num = PlayerProposalCost(); KingdomDecision kingdomDecision = C.NewCouncilDecision(State.PlayerClan.KingdomId, State.PlayerClanId, KingdomDecisionKind.Law); kingdomDecision.Law = law; kingdomDecision.Repeal = repeal; State.PlayerClan.Influence -= num; State.Politics.Decisions.Add(kingdomDecision); C.OpenCouncilDecision(kingdomDecision); C.TrainDiplomacy(50.0); State.Touch(); return CommandResult.Success((repeal ? "Repeal of " : "") + KingdomLaws.Name(law) + " proposed. The council votes for two days; " + num + " influence is spent."); } internal string LawDecisionStaleReason(KingdomDecision decision) { return LawChangeReason(decision.KingdomId, decision.Law, decision.Repeal); } internal void ApplyLawDecision(KingdomDecision decision, out string effect) { List laws = State.Politics.Laws; string text = KingdomLaws.Name(decision.Law); if (decision.Repeal) { laws.RemoveAll((KingdomLawState l) => l != null && l.KingdomId == decision.KingdomId && l.Law == decision.Law); effect = text + " is repealed."; return; } laws.Add(new KingdomLawState { KingdomId = decision.KingdomId, Law = decision.Law, EnactedMinute = State.Clock.Minute }); laws.Sort(delegate(KingdomLawState a, KingdomLawState b) { if (!(a.KingdomId == b.KingdomId)) { return string.CompareOrdinal(a.KingdomId, b.KingdomId); } int law = (int)a.Law; return law.CompareTo((int)b.Law); }); effect = text + " is now in force."; } public double LawInterest(Clan clan, string kingdomId, KingdomLaw law, out string why) { why = ""; if (clan == null) { return 0.0; } bool flag = IsRulingClan(clan, kingdomId); Kingdom kingdom = State.Kingdoms.Get(kingdomId); List list = State.Settlements.Where((Settlement s) => s.OwnerClanId == clan.Id && (s.Type == SettlementType.Town || s.Type == SettlementType.Castle)).ToList(); int num = list.Count((Settlement s) => s.Type == SettlementType.Town); int num2 = list.Count - num; int num3 = State.Settlements.Count((Settlement s) => s.OwnerClanId == clan.Id && s.Type == SettlementType.Village); int num4 = list.Count((Settlement s) => s.Loyalty < 40.0); int num5 = list.Count((Settlement s) => s.Security < 40.0); int num6 = list.Count((Settlement s) => !string.IsNullOrEmpty(s.CultureId) && s.CultureId != clan.CultureId); int num7 = list.Count((Settlement s) => kingdom != null && s.CultureId == kingdom.CultureId); bool flag2 = C.ClanAtWar(clan); bool flag3 = clan.Gold < 2000; double result; switch (law) { case KingdomLaw.RoadTolls: result = (double)num * 1.5 + (double)(flag3 ? 1 : 0) - 1.5 - (double)num4 * 0.5; why = ((num > 0) ? "its towns' takings" : "dearer roads"); break; case KingdomLaw.Serfdom: result = (double)num3 * 0.4 - 1.0 - (double)num4 * 0.25; why = ((num3 > 0) ? "its villages' dues" : "the villagers' lot"); break; case KingdomLaw.DebasementOfTheCurrency: result = (flag ? 3.0 : (-1.0 - (double)list.Count * 0.5)); why = (flag ? "the crown's coin" : "fiefs losing loyalty to fill the crown's purse"); break; case KingdomLaw.GrazingRights: result = (double)num3 * 0.4 - (double)num2 - 0.5; why = ((num3 > num2) ? "its villages' herds" : "its castles' taxes"); break; case KingdomLaw.HuntingRights: result = 1.0 - (double)num3 * 0.3; why = ((num3 > 3) ? "its villages' forests" : "feeding its men"); break; case KingdomLaw.Magistrates: result = (double)(num5 * 2) - (double)list.Count * 0.5 - 0.5; why = ((num5 > 0) ? "lawless fiefs" : "the cost to its taxes"); break; case KingdomLaw.Bailiffs: result = (double)num4 * 2.5 - (double)list.Count * 0.3 - 0.5; why = ((num4 > 0) ? "restless fiefs" : "dearer garrisons"); break; case KingdomLaw.TrialByJury: result = (double)num * 0.5 - (flag ? 1.5 : 0.25); why = (flag ? "the crown's justice" : "safer streets"); break; case KingdomLaw.Citizenship: result = (double)num7 * 0.75 - 1.0; why = ((num7 > 0) ? "its fiefs of the realm's own people" : "the influence it costs"); break; case KingdomLaw.Cantons: result = (double)(num6 * 2) - (double)num * 0.5 - 0.5; why = ((num6 > 0) ? "its fiefs of another culture" : "the cost to its towns' taxes"); break; case KingdomLaw.CouncilOfTheCommons: result = (flag ? (-2.5) : ((double)num * 0.75 + (double)num4 - 0.5)); why = (flag ? "a check on the crown" : "its towns' loyalty"); break; case KingdomLaw.TribunesOfThePeople: result = (double)num * 0.75 + (double)num4 - (flag2 ? 2.0 : 0.5); why = (flag2 ? "smaller armies in wartime" : "its towns' loyalty"); break; case KingdomLaw.NobleRetinues: result = (flag2 ? 2.0 : 0.5) - (double)list.Count * 0.25; why = (flag2 ? "larger retinues for the war" : "the cost to its fiefs"); break; case KingdomLaw.RoyalGuard: result = (flag ? 3.0 : (-1.5)); why = (flag ? "the crown's guard" : "the crown's growing strength"); break; case KingdomLaw.MilitaryCoronae: result = (flag2 ? 2.0 : (-0.5)) - (double)list.Count * 0.25; why = (flag2 ? "honours for the war" : "the cost in peacetime"); break; case KingdomLaw.Marches: result = (double)num2 * 1.5 - 1.0 + (double)(flag2 ? 1 : 0); why = ((num2 > 0) ? "its castles on the border" : "lower castle taxes"); break; case KingdomLaw.CastleCharters: result = (double)num2 * 1.5 - 1.0 - (flag ? 0.5 : 0.0); why = ((num2 > 0) ? "its castles' loyalty" : "nothing for it"); break; case KingdomLaw.LandGrantsForVeterans: result = (double)((flag2 ? 1 : 0) + num5) - (double)list.Count * 0.25; why = (flag2 ? "militia for the war" : "the cost to its taxes"); break; case KingdomLaw.RoyalPrivilege: result = (flag ? 4 : (-2)); why = (flag ? "the crown's voice" : "the council's freedom"); break; case KingdomLaw.SacredMajesty: result = (flag ? 4.0 : (-2.0 + (double)num4 * 0.5)); why = (flag ? "the crown's majesty" : "the council's freedom"); break; case KingdomLaw.Senate: result = (flag ? (-4) : 2); why = (flag ? "the crown's authority" : "a voice for the great clans"); break; default: result = 0.0; break; } return result; } internal bool CouncilLawPreference(KingdomDecision decision, Clan clan, out string reason) { string why; double num = LawInterest(clan, decision.KingdomId, decision.Law, out why); if (decision.Repeal) { num = 0.0 - num; } double num2 = num + (double)C.ClanRelation(clan.Id, decision.ProposerClanId) / 20.0; if (clan.Id == decision.ProposerClanId) { num2 = Math.Max(num2, 1.0); } bool flag = num2 > 0.0; string text = (flag ? "Supports" : "Opposes"); reason = ((clan.Id == decision.ProposerClanId) ? "Supports its own proposal." : ((Math.Abs(C.ClanRelation(clan.Id, decision.ProposerClanId)) >= 40 && Math.Abs(num) < 2.0) ? (flag ? "A friend of the proposer, and that settles it." : "At feud with the proposer, and that settles it.") : (text + " it, thinking of " + why + "."))); return flag; } internal void DailyLawProposals() { PoliticsState politics = State.Politics; if (politics == null || !politics.Initialized || politics.Laws == null || politics.Decisions == null) { return; } if (politics.NextLawProposalDay == null) { politics.NextLawProposalDay = new SortedDictionary(StringComparer.Ordinal); } long day = State.Clock.Day; foreach (Kingdom kingdom in State.Kingdoms.Where((Kingdom k) => !k.IsEliminated).OrderBy((Kingdom k) => k.Id, StringComparer.Ordinal).ToList()) { if (!politics.NextLawProposalDay.TryGetValue(kingdom.Id, out var value)) { politics.NextLawProposalDay[kingdom.Id] = day + 10 + (long)(StableHash.Fnv1a64("laws|" + kingdom.Id) % 7); State.Touch(); } else { if (day < value) { continue; } politics.NextLawProposalDay[kingdom.Id] = day + 7 + (long)(StableHash.Fnv1a64("laws|" + kingdom.Id + "|" + day) % 5); State.Touch(); Clan clan = C.ServiceRuler(kingdom.Id); if (clan == null || !C.CouncilMember(kingdom.Id, clan.Id) || C.DiplomacyFactionReserved(kingdom.Id) || politics.Decisions.Any((KingdomDecision d) => Campaign.CouncilIsLive(d) && d.KingdomId == kingdom.Id) || State.Clock.Minute > 9223372036854772927L) { continue; } List source = C.CouncilMembers(kingdom.Id).ToList(); (Clan, KingdomLaw, bool, double) tuple = (null, KingdomLaw.None, false, 0.0); foreach (Clan item in source.Where((Clan c) => c.Id != State.PlayerClanId && c.Influence >= (double)CouncilProposalCostFor(c))) { KingdomLawDef[] all = KingdomLaws.All; foreach (KingdomLawDef kingdomLawDef in all) { bool num2 = LawInForce(kingdom.Id, kingdomLawDef.Law); string why; double num3 = LawInterest(item, kingdom.Id, kingdomLawDef.Law, out why); bool flag = num2; double num4 = (flag ? (0.0 - num3) : num3); if (!(num4 < 1.5) && LawChangeReason(kingdom.Id, kingdomLawDef.Law, flag).Length <= 0) { KingdomDecision probe = new KingdomDecision { KingdomId = kingdom.Id, ProposerClanId = item.Id, RulerClanId = clan.Id, Kind = KingdomDecisionKind.Law, Law = kingdomLawDef.Law, Repeal = flag }; string reason; int num5 = source.Sum((Clan c) => CouncilLawPreference(probe, c, out reason) ? LawBallotMultiplier(probe, c.Id) : 0); int num6 = source.Sum((Clan c) => LawBallotMultiplier(probe, c.Id)); if (num5 * 2 > num6 && (num4 > tuple.Item4 || (num4 == tuple.Item4 && tuple.Item1 != null && string.CompareOrdinal(item.Id, tuple.Item1.Id) < 0))) { tuple = (item, kingdomLawDef.Law, flag, num4); } } } } if (tuple.Item1 != null) { KingdomDecision kingdomDecision = C.NewCouncilDecision(kingdom.Id, tuple.Item1.Id, KingdomDecisionKind.Law); kingdomDecision.Law = tuple.Item2; kingdomDecision.Repeal = tuple.Item3; tuple.Item1.Influence -= CouncilProposalCostFor(tuple.Item1); politics.Decisions.Add(kingdomDecision); C.OpenCouncilDecision(kingdomDecision); } } } } } internal sealed class PoliticsSystem { private readonly Campaign C; private CampaignState State => C.State; internal PoliticsSystem(Campaign host) { C = host; } public void EnsurePoliticsFields() { bool flag = false; if (State.Politics == null) { State.Politics = new PoliticsState(); flag = true; } PoliticsState politics = State.Politics; if (politics.Decisions == null) { politics.Decisions = new List(); flag = true; } if (politics.KingdomPolicies == null) { politics.KingdomPolicies = new List(); flag = true; } if (politics.Relations == null) { politics.Relations = new List(); flag = true; } if (politics.Laws == null) { politics.Laws = new List(); flag = true; } if (politics.NextLawProposalDay == null) { politics.NextLawProposalDay = new SortedDictionary(StringComparer.Ordinal); flag = true; } if (!politics.Initialized) { politics.Initialized = true; politics.LastInfluenceDay = State.Clock.Day; flag = true; } if (flag) { State.Touch(); } } internal bool LivingPoliticalClan(Clan clan) { if (clan == null || clan.IsBandit || clan.IsEliminated) { return false; } Hero hero = State.Heroes.Get(clan.LeaderHeroId); if (hero != null && hero.ClanId == clan.Id && hero.State != HeroState.Dead) { return hero.State != HeroState.Inactive; } return false; } public IEnumerable CouncilMembers(string kingdomId) { Kingdom kingdom = State.Kingdoms.Get(kingdomId); if (kingdom == null || kingdom.IsEliminated || C.ServiceRuler(kingdomId) == null) { return Enumerable.Empty(); } return State.Clans.Where((Clan c) => c.KingdomId == kingdomId && LivingPoliticalClan(c) && (c.Id != State.PlayerClanId || (State.ClanService != null && State.ClanService.Initialized && State.ClanService.KingdomId == kingdomId && (State.ClanService.Kind == ClanServiceKind.Vassal || State.ClanService.Kind == ClanServiceKind.Ruler)))).OrderBy((Clan c) => c.Id, StringComparer.Ordinal); } public string PlayerCouncilReason() { string text = PlayerPoliticalActorReason(); if (text.Length > 0) { return text; } if (State.Politics == null || !State.Politics.Initialized) { return "The council can't sit right now."; } if (!CouncilMembers(State.PlayerClan.KingdomId).Any((Clan c) => c.Id == State.PlayerClanId)) { return "Only sworn vassals and rulers sit on the council."; } if (string.IsNullOrEmpty(State.Player.PendingEncounterId) && !C.DiplomacyFactionReserved(State.PlayerClan.KingdomId)) { return ""; } return "Wait for your kingdom's fighting to finish."; } internal string PlayerPoliticalActorReason() { string text = C.CargoCommandReason(); if (text.Length > 0) { return text; } Clan playerClan = State.PlayerClan; Hero playerHero = State.PlayerHero; if (!LivingPoliticalClan(playerClan) || playerHero == null || !playerHero.CanFight || playerHero.Id != playerClan.LeaderHeroId || State.PlayerParty.LeaderHeroId != playerHero.Id) { return "Your clan leader has to be fit and free to lead."; } return ""; } public void AddPoliticalInfluence(Clan clan, double amount) { if (clan != null && !double.IsNaN(amount) && !double.IsInfinity(amount) && !(amount <= 0.0) && !double.IsNaN(clan.Influence) && !double.IsInfinity(clan.Influence) && !(clan.Influence < 0.0) && !(clan.Influence >= 1000.0)) { amount *= 1.0 + Math.Max(0.0, C.ClanPerk(clan, PerkEffect.Influence)); clan.Influence = Math.Min(1000.0, clan.Influence + amount); State.Touch(); } } public void DailyPoliticalInfluence() { if (State.Politics == null || !State.Politics.Initialized || State.Politics.LastInfluenceDay >= State.Clock.Day) { return; } State.Politics.LastInfluenceDay = State.Clock.Day; foreach (Kingdom kingdom in State.Kingdoms) { foreach (Clan item in CouncilMembers(kingdom.Id)) { AddPoliticalInfluence(item, 1.0 + C.LawInfluence(item, kingdom.Id)); } } C.DailyLawIncome(); C.DailyLawProposals(); State.Touch(); } public void RecordPoliticalBattleInfluence(Encounter encounter, BattleResult result, BattleReport report) { if (encounter == null || result == null || report == null || State.Encounters.Get(encounter.Id) != encounter || encounter.Phase != EncounterPhase.Committed || !State.CommittedEncounters.Contains(encounter.Id) || result.EncounterId != encounter.Id || report.EncounterId != encounter.Id || result.EndKind != BattleEndKind.Victory || result.Winner == WinnerSide.None || report.Winner != result.Winner || report.EndKind != result.EndKind || encounter.Manifest == null || result.Outcomes == null) { return; } BattleSide side = ((result.Winner != WinnerSide.Attacker) ? BattleSide.Defender : BattleSide.Attacker); double num = result.Outcomes.Count((CombatantResult o) => o.Outcome == CombatOutcome.Downed && encounter.Manifest.Get(o.Id) != null && encounter.Manifest.Get(o.Id).Side != side); var list = (from p in report.Parties where p.Side == side && p.Fought > 0 select new { Report = p, Party = State.Parties.Get(p.PartyId) } into p where p.Party != null && (p.Party.Kind == PartyKind.Player || p.Party.Kind == PartyKind.Lord || p.Party.Kind == PartyKind.SiegeDefender) group p by p.Party.ClanId into g select new { Clan = State.Clans.Get(g.Key), Fought = g.Sum(p => (double)p.Report.Fought) } into g where g.Clan != null && CouncilMembers(g.Clan.KingdomId).Any((Clan c) => c.Id == g.Clan.Id) select g).ToList(); if (num <= 0.0 || list.Count == 0 || !State.AppliedEventIds.Add("politics.battle:" + encounter.Id)) { return; } double num2 = Math.Min(5.0, num / 5.0); double num3 = list.Sum(g => g.Fought); foreach (var item in list) { double influence = item.Clan.Influence; AddPoliticalInfluence(item.Clan, num2 * item.Fought / num3 * C.LawBattleInfluenceFactor(item.Clan)); if (item.Clan.Id == State.PlayerClanId && item.Clan.Influence > influence) { report.Lines.Add("Council influence +" + (item.Clan.Influence - influence).ToString("0.##") + "."); } } } internal ClanRelationState ClanRelationRecord(string a, string b) { return State.Politics?.Relations?.FirstOrDefault((ClanRelationState r) => r != null && ((r.A == a && r.B == b) || (r.A == b && r.B == a))); } public int ClanRelation(string a, string b) { if (!string.IsNullOrEmpty(a) && !string.IsNullOrEmpty(b) && !(a == b)) { return ClanRelationRecord(a, b)?.Value ?? 0; } return 0; } public void AdjustClanRelation(string a, string b, int delta) { if (a == b || delta == 0 || !State.Clans.Contains(a) || !State.Clans.Contains(b) || State.Clans.Get(a).IsBandit || State.Clans.Get(b).IsBandit || State.Politics?.Relations == null) { return; } if (delta > 0 && (a == State.PlayerClanId || b == State.PlayerClanId)) { delta += C.RelationPerkBonus(); } ClanRelationState clanRelationState = ClanRelationRecord(a, b); int num = clanRelationState?.Value ?? 0; int num2 = (int)Math.Max(-100L, Math.Min(100L, (long)num + (long)delta)); if (num != num2) { if (clanRelationState == null) { clanRelationState = new ClanRelationState { A = ((string.CompareOrdinal(a, b) < 0) ? a : b), B = ((string.CompareOrdinal(a, b) < 0) ? b : a) }; State.Politics.Relations.Add(clanRelationState); } clanRelationState.Value = num2; if (num2 > num && (a == State.PlayerClanId || b == State.PlayerClanId)) { C.TrainCharm(num2 - num); } State.Touch(); } } public string ClanGiftReason(string targetClanId, long amount) { string text = PlayerPoliticalActorReason(); if (text.Length > 0) { return text; } if (State.Politics == null || !State.Politics.Initialized) { return "Clan relations are unavailable."; } Clan clan = State.Clans.Get(targetClanId); if (!LivingPoliticalClan(clan) || clan.Id == State.PlayerClanId) { return "Pick another noble clan."; } if (amount != 100 && amount != 500) { return "Offer 100 or 500 denars."; } if (State.PlayerClan.Gold < amount) { return "You can't afford the gift."; } if (clan.Gold < 0 || clan.Gold > long.MaxValue - amount) { return "This clan can't take the gift."; } if (ClanRelation(State.PlayerClanId, clan.Id) >= 100) { return "They couldn't think better of you if they tried."; } if ((ClanRelationRecord(State.PlayerClanId, clan.Id)?.LastGiftDay ?? (-1)) >= State.Clock.Day) { return "You've already sent them a gift today."; } if (C.DiplomacyFactionReserved(State.FactionOf(State.PlayerClan)) || C.DiplomacyFactionReserved(State.FactionOf(clan))) { return "Wait for the fighting involving these factions to finish."; } return ""; } public CommandResult GiveClanGift(string targetClanId, long amount) { string text = ClanGiftReason(targetClanId, amount); if (text.Length > 0) { return CommandResult.Fail(text); } Clan clan = State.Clans.Require(targetClanId); State.Transact(State.PlayerClan, -amount, LedgerAccount.Other, "Gift to " + clan.Name); State.Transact(clan, amount, LedgerAccount.Other, "Gift from " + State.PlayerClan.Name); AdjustClanRelation(State.PlayerClanId, clan.Id, (amount == 100) ? 2 : 10); ClanRelationRecord(State.PlayerClanId, clan.Id).LastGiftDay = State.Clock.Day; string text2 = "Sent " + amount + " denars to " + clan.Name + ". Clan relation is now " + ClanRelation(State.PlayerClanId, clan.Id) + "."; State.AddLog(LogCategory.Politics, text2, State.PlayerClanId, clan.Id); State.Touch(); return CommandResult.Success(text2); } public RealmPolicy RealmPolicyFor(string kingdomId) { Kingdom kingdom = State.Kingdoms.Get(kingdomId); if (kingdom == null || kingdom.IsEliminated) { return RealmPolicy.Balanced; } return (State.Politics?.KingdomPolicies?.FirstOrDefault((KingdomPolicyState p) => p.KingdomId == kingdomId)?.Policy).GetValueOrDefault(); } internal RealmPolicy RealmPolicyAt(Settlement settlement) { return RealmPolicyFor(State.Clans.Get(settlement?.OwnerClanId)?.KingdomId); } public double RealmPolicyTaxFactor(Settlement settlement) { if (RealmPolicyAt(settlement) != RealmPolicy.LocalCharters) { if (RealmPolicyAt(settlement) != RealmPolicy.WarLevy) { return 1.0; } return 1.15; } return 0.9; } public double RealmPolicyLoyaltyChange(Settlement settlement) { if (RealmPolicyAt(settlement) != RealmPolicy.LocalCharters) { if (RealmPolicyAt(settlement) != RealmPolicy.WarLevy) { return 0.0; } return -0.5; } return 0.5; } } internal sealed class PrisonerRansomsSystem { private readonly Campaign C; private CampaignRules Rules => C.Rules; private CampaignState State => C.State; internal PrisonerRansomsSystem(Campaign host) { C = host; } internal string RansomTownReason() { string text = C.PrisonerCommandReason(); if (text.Length > 0) { return text; } if (C.NamedCustodyPartyReserved(State.PlayerPartyId)) { return "Deal with the encounter first."; } Settlement settlement = C.CurrentSettlement(); if (settlement == null || settlement.Type != SettlementType.Town || !C.CanEnter(State.PlayerParty, settlement) || !(Vec2.Distance(State.PlayerParty.Position, settlement.Position) <= 0.01)) { return "Ransoms are arranged in friendly towns."; } return ""; } internal string OrdinaryRansomRosterReason() { List stacks = State.PlayerParty.Prisoners.Stacks; if (stacks.Any((TroopStack s) => s == null || C.UnitDef(s.UnitId) == null || s.Healthy < 0 || s.Wounded < 0 || (long)s.Healthy + (long)s.Wounded > int.MaxValue) || (from s in stacks group s by s.UnitId).Any((IGrouping g) => g.Count() > 1)) { return "Your prisoners' troop records must be valid before ransom."; } if (State.PlayerParty.Prisoners.Heroes.Any((string id) => C.NamedCustodyIntegrityReason(id).Length > 0 || State.Heroes.Get(id)?.CaptorPartyId != State.PlayerPartyId)) { return "Your prisoners' custody records must be valid before ransom."; } return ""; } internal TradeQuote OrdinaryRansomPrice(string unitId, int count) { TradeQuote tradeQuote = new TradeQuote(); UnitDef unitDef = C.UnitDef(unitId); double ransomPerTier = Rules.RansomPerTier; if (unitDef == null || unitDef.Tier < 0 || double.IsNaN(ransomPerTier) || double.IsInfinity(ransomPerTier) || ransomPerTier < 0.0) { tradeQuote.Reason = "The ransom price is unavailable."; return tradeQuote; } double num = Math.Round((double)count * (double)unitDef.Tier * ransomPerTier * (1.0 + Math.Max(0.0, C.PartyPerk(State.PlayerParty, PerkEffect.Ransom)))); if (double.IsNaN(num) || double.IsInfinity(num) || num < 0.0 || num >= 9.223372036854776E+18) { tradeQuote.Reason = "That ransom amount is too large."; return tradeQuote; } tradeQuote.Total = (long)num; return tradeQuote; } internal TradeQuote FundOrdinaryRansom(TradeQuote quote) { if (!quote.Ok) { return quote; } MarketState market = C.CurrentSettlement().Market; if (market == null || !market.Initialized || market.Stock == null || market.Gold < 0) { quote.Reason = "There's no ransom broker here."; } else if (market.Gold < quote.Total) { quote.Reason = "The town can't afford that. Offer fewer."; } else if (State.PlayerClan.Gold < 0 || State.PlayerClan.Gold > long.MaxValue - quote.Total) { quote.Reason = "Your treasury can't take that much."; } return quote; } public TradeQuote QuotePrisonerRansom(string unitId, int count) { TradeQuote tradeQuote = new TradeQuote { Reason = RansomTownReason() }; if (!tradeQuote.Ok) { return tradeQuote; } tradeQuote.Reason = OrdinaryRansomRosterReason(); if (!tradeQuote.Ok) { return tradeQuote; } tradeQuote.Reason = C.PrisonerStackReason(State.PlayerParty.Prisoners, unitId, count); if (!tradeQuote.Ok) { return tradeQuote; } return FundOrdinaryRansom(OrdinaryRansomPrice(unitId, count)); } public TradeQuote QuoteAllPrisonerRansom() { TradeQuote tradeQuote = new TradeQuote { Reason = RansomTownReason() }; if (!tradeQuote.Ok) { return tradeQuote; } tradeQuote.Reason = OrdinaryRansomRosterReason(); if (!tradeQuote.Ok) { return tradeQuote; } if (!State.PlayerParty.Prisoners.Stacks.Any((TroopStack s) => s.Total > 0)) { tradeQuote.Reason = "You're not holding any ordinary prisoners."; return tradeQuote; } foreach (TroopStack stack in State.PlayerParty.Prisoners.Stacks) { TradeQuote tradeQuote2 = OrdinaryRansomPrice(stack.UnitId, stack.Total); if (!tradeQuote2.Ok) { tradeQuote.Reason = tradeQuote2.Reason; return tradeQuote; } if (tradeQuote.Total > long.MaxValue - tradeQuote2.Total) { tradeQuote.Reason = "That ransom amount is too large."; return tradeQuote; } tradeQuote.Total += tradeQuote2.Total; } return FundOrdinaryRansom(tradeQuote); } public CommandResult RansomPrisoners(string unitId, int count) { TradeQuote tradeQuote = QuotePrisonerRansom(unitId, count); if (!tradeQuote.Ok) { return CommandResult.Fail(tradeQuote.Reason); } State.PlayerParty.Prisoners.Remove(unitId, count); return CommitOrdinaryRansom(tradeQuote.Total, count); } public CommandResult RansomAllOrdinaryPrisoners() { TradeQuote tradeQuote = QuoteAllPrisonerRansom(); if (!tradeQuote.Ok) { return CommandResult.Fail(tradeQuote.Reason); } long num = 0L; foreach (TroopStack item in State.PlayerParty.Prisoners.Stacks.ToList()) { num += item.Total; State.PlayerParty.Prisoners.Remove(item.UnitId, item.Total); } return CommitOrdinaryRansom(tradeQuote.Total, num); } internal CommandResult CommitOrdinaryRansom(long total, long count) { Settlement settlement = C.CurrentSettlement(); settlement.Market.Gold -= total; string text = $"Ransomed {count} prisoners for {total} denars at {settlement.Name}."; State.Transact(State.PlayerClan, total, LedgerAccount.Ransom, text); State.AddLog(LogCategory.Captivity, text, State.PlayerPartyId, settlement.Id); C.TrainDiplomacyForRansom(count); C.TrainRoguery(Math.Min(60.0, (double)count * 2.0)); State.Touch(); return CommandResult.Success(text); } public TradeQuote HeroRansomQuote(string heroId, bool buyback, bool inDungeon = false) { TradeQuote tradeQuote = new TradeQuote { Total = 300L, Reason = RansomTownReason() }; if (!tradeQuote.Ok) { return tradeQuote; } Hero hero = State.Heroes.Get(heroId); tradeQuote.Reason = (buyback ? C.NamedCustodyIntegrityReason(heroId) : C.NamedPrisonerActionReason(heroId, inDungeon)); if (!tradeQuote.Ok) { return tradeQuote; } if (hero.IsPlayer) { tradeQuote.Reason = "Your own captivity uses the release and escape controls."; return tradeQuote; } if (C.NamedCustodyReserved(hero)) { tradeQuote.Reason = "Wait for the captor's fight to finish."; return tradeQuote; } Clan clan = C.HeroCaptorClan(hero); Clan clan2 = State.Clans.Get(hero.ClanId); if (buyback && hero.ClanId != State.PlayerClanId) { tradeQuote.Reason = "You can only arrange the return of your own clan's people."; return tradeQuote; } if (clan == null || (buyback && clan.Id == State.PlayerClanId)) { tradeQuote.Reason = "Your clan doesn't ransom from itself. Just release them."; return tradeQuote; } if (!buyback && (clan.Id != State.PlayerClanId || clan2 == null || clan2.Id == State.PlayerClanId)) { tradeQuote.Reason = "A ransom needs another clan to pay."; return tradeQuote; } Clan clan3 = (buyback ? State.PlayerClan : clan2); Clan clan4 = (buyback ? clan : State.PlayerClan); if (clan3 == null || clan3.IsEliminated || clan4 == null || clan4.IsEliminated || clan3.Gold < 0 || clan4.Gold < 0) { tradeQuote.Reason = "Both clans must have an available treasury."; } else if (clan3.Gold < tradeQuote.Total) { tradeQuote.Reason = (buyback ? "You can't afford it." : "Their clan can't afford it."); } else if (clan4.Gold > long.MaxValue - tradeQuote.Total) { tradeQuote.Reason = "They can't take that much."; } return tradeQuote; } public CommandResult RansomPrisonerHero(string heroId, bool inDungeon = false) { return CommitHeroRansom(heroId, buyback: false, inDungeon); } public CommandResult RansomClanHero(string heroId) { return CommitHeroRansom(heroId, buyback: true, inDungeon: false); } internal CommandResult CommitHeroRansom(string heroId, bool buyback, bool inDungeon) { TradeQuote tradeQuote = HeroRansomQuote(heroId, buyback, inDungeon); if (!tradeQuote.Ok) { return CommandResult.Fail(tradeQuote.Reason); } Hero hero = State.Heroes.Get(heroId); Clan clan = C.HeroCaptorClan(hero); Clan clan2 = (buyback ? State.PlayerClan : State.Clans.Get(hero.ClanId)); Clan clan3 = (buyback ? clan : State.PlayerClan); string text = $"{clan2.Name} paid {tradeQuote.Total} denars to {clan3.Name} for {hero.Name}'s release."; State.Transact(clan2, -tradeQuote.Total, LedgerAccount.Ransom, text); State.Transact(clan3, tradeQuote.Total, LedgerAccount.Ransom, text); OutcomeCommitter.ReleaseHero(C, hero, "ransomed by " + clan2.Name); if (!buyback) { C.RememberHero(hero, "ransomed"); } State.AddLog(LogCategory.Captivity, text, hero.Id, clan2.Id, clan3.Id); C.TrainDiplomacy(40.0); State.Touch(); return CommandResult.Success(text); } } internal sealed class PrisonersSystem { private readonly Campaign C; private CampaignRules Rules => C.Rules; private CampaignState State => C.State; internal PrisonersSystem(Campaign host) { C = host; } public double PrisonerRecruitmentDays(string unitId) { return Math.Max(1.0, Rules.PrisonerRecruitmentBaseDays + (double)(C.UnitDef(unitId)?.Tier ?? 1)); } public int PrisonerReadyCount(TroopStack stack) { if (stack != null) { return Math.Min(stack.Healthy, (int)Math.Floor(PrisonerProgress(stack) + 1E-09)); } return 0; } internal static double PrisonerProgress(TroopStack stack) { if (stack == null || double.IsNaN(stack.PrisonerRecruitment) || double.IsInfinity(stack.PrisonerRecruitment)) { return 0.0; } return Math.Max(0.0, Math.Min(stack.Total, stack.PrisonerRecruitment)); } internal string PrisonerCommandReason() { CommandResult commandResult = C.RequireFree(); if (!commandResult.Ok) { return commandResult.Message; } Party playerParty = State.PlayerParty; Hero playerHero = State.PlayerHero; if (State.PlayerClan == null || playerParty.ClanId != State.PlayerClanId) { return "Your party has no valid clan."; } if (playerParty.State != PartyState.Active && playerParty.State != PartyState.InSettlement) { return "Can't manage prisoners right now."; } if (C.MilitaryPartyReserved(playerParty.Id) || !string.IsNullOrEmpty(playerParty.EncounterId)) { return "Deal with the encounter first."; } if (playerHero == null || playerHero.State != HeroState.Active || !Campaign.IsPresentPartyHero(playerParty, playerHero)) { return "You have to be with the party to manage prisoners."; } return ""; } internal string PrisonerStackReason(TroopRoster roster, string unitId, int count) { if (count <= 0) { return "Pick at least one."; } if (string.IsNullOrEmpty(unitId) || C.UnitDef(unitId) == null) { return "Unknown prisoner troop type."; } TroopStack troopStack = roster.Find(unitId); if (troopStack != null && troopStack.Total >= count) { return ""; } return "Not enough prisoners of that type."; } public string PrisonerRecruitmentReason(string unitId, int count) { string text = PrisonerCommandReason(); if (text.Length > 0) { return text; } Party playerParty = State.PlayerParty; text = PrisonerStackReason(playerParty.Prisoners, unitId, count); if (text.Length > 0) { return text; } TroopStack troopStack = playerParty.Prisoners.Find(unitId); if (troopStack.Healthy < count) { return "The wounded have to heal before they'll join."; } if (PrisonerReadyCount(troopStack) < count) { return "They're not ready to join you yet."; } if (count > C.PartySizeLimit(playerParty) - playerParty.Troops.TotalTroops) { return "Not enough room in your party."; } double num = Math.Max(0.0, Rules.PrisonerRecruitmentMoraleCost) * (double)count; if (playerParty.Morale - num < Rules.PrisonerRecruitmentMinMorale) { return $"You can't drop below {Rules.PrisonerRecruitmentMinMorale:0} morale."; } return ""; } public CommandResult RecruitPrisoners(string unitId, int count) { string text = PrisonerRecruitmentReason(unitId, count); if (text.Length > 0) { return CommandResult.Fail(text); } Party playerParty = State.PlayerParty; double val = Math.Max(0.0, PrisonerProgress(playerParty.Prisoners.Find(unitId)) - (double)count); playerParty.Prisoners.RemoveHealthy(unitId, count); TroopStack troopStack = playerParty.Prisoners.Find(unitId); if (troopStack != null) { troopStack.PrisonerRecruitment = Math.Min(troopStack.Total, val); } playerParty.Troops.Add(unitId, count); playerParty.Morale -= Math.Max(0.0, Rules.PrisonerRecruitmentMoraleCost) * (double)count; string text2 = $"{count} {C.UnitDef(unitId).Name} joined your warband from captivity."; State.AddLog(LogCategory.Recruitment, text2, playerParty.Id); State.Touch(); return CommandResult.Success(text2); } public string PrisonerReleaseReason(string unitId, int count) { string text = PrisonerCommandReason(); if (text.Length <= 0) { return PrisonerStackReason(State.PlayerParty.Prisoners, unitId, count); } return text; } public CommandResult ReleasePrisoners(string unitId, int count) { string text = PrisonerReleaseReason(unitId, count); if (text.Length > 0) { return CommandResult.Fail(text); } State.PlayerParty.Prisoners.Remove(unitId, count); string text2 = $"Released {count} {C.UnitDef(unitId).Name}."; State.AddLog(LogCategory.Captivity, text2, State.PlayerPartyId); State.Touch(); return CommandResult.Success(text2); } public string PrisonerHeroReleaseReason(string heroId) { return C.NamedPrisonerActionReason(heroId, inDungeon: false); } public CommandResult ReleasePrisonerHero(string heroId) { return C.ReleasePrisonerHero(heroId, inDungeon: false); } public Settlement PrisonerDungeon() { if (PrisonerCommandReason().Length > 0) { return null; } Settlement settlement = C.CurrentSettlement(); if (settlement == null || settlement.OwnerClanId != State.PlayerClanId || (settlement.Type != SettlementType.Town && settlement.Type != SettlementType.Castle)) { return null; } if (!(Vec2.Distance(State.PlayerParty.Position, settlement.Position) <= Rules.SettlementEnterRadius + 0.01)) { return null; } return settlement; } public string PrisonerTransferReason(string unitId, int count, bool toDungeon) { string text = PrisonerCommandReason(); if (text.Length > 0) { return text; } Settlement settlement = PrisonerDungeon(); if (settlement == null) { return "Prisoners are moved in your own towns or castles."; } Party playerParty = State.PlayerParty; TroopRoster roster = (toDungeon ? playerParty.Prisoners : settlement.Prisoners); TroopRoster troopRoster = (toDungeon ? settlement.Prisoners : playerParty.Prisoners); text = PrisonerStackReason(roster, unitId, count); if (text.Length > 0) { return text; } int num = (toDungeon ? Math.Max(0, Rules.DungeonPrisonerLimit) : C.PrisonerLimit(playerParty)); if (count > num - troopRoster.TotalTroops) { if (!toDungeon) { return "No room for more prisoners."; } return "No room in this dungeon."; } return ""; } public CommandResult TransferPrisoners(string unitId, int count, bool toDungeon) { string text = PrisonerTransferReason(unitId, count, toDungeon); if (text.Length > 0) { return CommandResult.Fail(text); } Settlement settlement = PrisonerDungeon(); Party playerParty = State.PlayerParty; TroopRoster troopRoster = (toDungeon ? playerParty.Prisoners : settlement.Prisoners); TroopRoster troopRoster2 = (toDungeon ? settlement.Prisoners : playerParty.Prisoners); TroopStack troopStack = troopRoster.Find(unitId); int num = Math.Min(count, troopStack.Healthy); int wounded = count - num; int xp = troopStack.Xp; double num2 = PrisonerProgress(troopStack); troopRoster.Remove(unitId, count); TroopStack troopStack2 = troopRoster.Find(unitId); int xp2 = xp - (troopStack2?.Xp ?? 0); double val = num2 - PrisonerProgress(troopStack2); troopRoster2.Add(unitId, num, wounded, xp2); TroopStack troopStack3 = troopRoster2.Find(unitId); troopStack3.PrisonerRecruitment = Math.Min(troopStack3.Total, PrisonerProgress(troopStack3) + Math.Max(0.0, val)); string text2 = string.Format("{0} {1} transferred to {2}.", count, C.UnitDef(unitId).Name, toDungeon ? (settlement.Name + "'s dungeon") : "your party"); State.AddLog(LogCategory.Captivity, text2, playerParty.Id, settlement.Id); State.Touch(); return CommandResult.Success(text2); } public string PrisonerRansomReason() { string text = C.DisguiseBlockReason(); if (text.Length > 0) { return text; } return C.QuoteAllPrisonerRansom().Reason; } public void DailyPrisonerCare() { foreach (Party party in State.Parties) { if (party.State != PartyState.Active && party.State != PartyState.InSettlement) { continue; } int num; if (party.Id == State.PlayerPartyId && party.StarvingDays == 0 && State.Player.Activity != PlayerActivity.Captive) { Hero playerHero = State.PlayerHero; if (playerHero != null && playerHero.State == HeroState.Active) { num = (Campaign.IsPresentPartyHero(party, State.PlayerHero) ? 1 : 0); goto IL_0091; } } num = 0; goto IL_0091; IL_0091: bool gainWillingness = (byte)num != 0; CareForPrisoners(party.Prisoners, gainWillingness); } foreach (Settlement settlement in State.Settlements) { CareForPrisoners(settlement.Prisoners, gainWillingness: false); } } internal void CareForPrisoners(TroopRoster roster, bool gainWillingness) { foreach (TroopStack stack in roster.Stacks) { int healthy = stack.Healthy; if (stack.Wounded > 0) { roster.Heal(stack.UnitId, Math.Max(1, (int)Math.Round((double)stack.Wounded * 0.25))); } double num = ((gainWillingness && C.UnitDef(stack.UnitId) != null) ? ((double)healthy / PrisonerRecruitmentDays(stack.UnitId)) : 0.0); stack.PrisonerRecruitment = Math.Min(stack.Total, PrisonerProgress(stack) + num); } } } internal sealed class ProgressionSystem { private readonly Campaign C; private CampaignState State => C.State; internal ProgressionSystem(Campaign host) { C = host; } public void EnsureHeroProgressionFields() { bool flag = false; foreach (Hero hero in State.Heroes) { if (hero.Perks == null) { hero.Perks = new List(); flag = true; } if (hero.SkillFocus == null) { hero.SkillFocus = new SortedDictionary(StringComparer.Ordinal); flag = true; } if (hero.SkillXpRemainders == null) { hero.SkillXpRemainders = new SortedDictionary(StringComparer.Ordinal); flag = true; } if (hero.RoleTrainingEarned == null) { hero.RoleTrainingEarned = new SortedDictionary(StringComparer.Ordinal); flag = true; } } if (flag) { State.Touch(); } } public static long HeroXpForLevel(int level) { int num = Math.Max(1, Math.Min(50, level)); return 125L * (long)num * (num - 1); } public static int HeroLevelForXp(long xp) { int i; for (i = 1; i < 50 && xp >= HeroXpForLevel(i + 1); i++) { } return i; } public double HeroBattleHealthBonus(string heroId) { Hero hero = (string.IsNullOrEmpty(heroId) ? null : State.Heroes.Get(heroId)); if (hero != null) { return (double)(HeroLevel(hero) - 1) * 0.02 + Math.Max(0.0, C.PersonalPerk(hero, PerkEffect.HeroHealth)); } return 0.0; } public int HeroLevel(Hero hero) { if (hero != null) { return Math.Max(HeroLevelForXp(hero.Xp), Math.Max(1, Math.Min(50, hero.Level))); } return 1; } public void GrantHeroExperience(Hero hero, int xp) { if (CanEarnExperience(hero) && xp > 0) { long num = Math.Max(0L, hero.Xp); hero.Xp = ((num > long.MaxValue - xp) ? long.MaxValue : (num + xp)); hero.Level = HeroLevel(hero); } } public void GrantSkillExperience(Hero hero, string skill, double xp, bool grantHeroXp = true) { if (!CanEarnExperience(hero) || !SkillIds.All.Contains(skill) || !PositiveFinite(xp)) { return; } if (hero.SkillXpRemainders == null) { hero.SkillXpRemainders = new SortedDictionary(StringComparer.Ordinal); } hero.Skills.TryGetValue(skill, out var value); if (value >= 300) { hero.Skills[skill] = 300; hero.SkillXp[skill] = 0; hero.SkillXpRemainders.Remove(skill); return; } hero.SkillXpRemainders.TryGetValue(skill, out var value2); if (double.IsNaN(value2) || double.IsInfinity(value2) || value2 < 0.0 || value2 >= 1.0) { value2 = 0.0; } double num = Math.Min(2147483647.0, Math.Min(2147483647.0, xp) * C.HeroLearningRate(hero, skill) * (1.0 + Math.Max(0.0, C.PersonalPerk(hero, PerkEffect.Learning, skill)))) + value2; double num2 = Math.Round(num); if (Math.Abs(num - num2) < 1E-09) { num = num2; } int num3 = (int)Math.Min(2147483647.0, Math.Floor(num)); hero.SkillXpRemainders[skill] = Math.Max(0.0, Math.Min(0.999999999999, num - (double)num3)); if (num3 <= 0) { return; } hero.SkillXp.TryGetValue(skill, out var value3); long num4 = (long)Math.Max(0, value3) + (long)num3; for (value = Math.Max(0, value); value < 300; value++) { int num5 = 50 + value * 10; if (num4 < num5) { break; } num4 -= num5; } hero.Skills[skill] = value; hero.SkillXp[skill] = (int)((value != 300) ? num4 : 0); if (value == 300) { hero.SkillXpRemainders.Remove(skill); } int xp2 = (int)((value == 300) ? Math.Max(0L, num3 - num4) : num3); if (grantHeroXp) { GrantHeroExperience(hero, xp2); } } public void ApplyRoleTraining(Party party, PartyRole role, Hero worker, double work) { if (PositiveFinite(work) && worker != null && C.RoleHolder(party, role) == worker && (role != PartyRole.Quartermaster || party.Troops.TotalTroops > 0)) { string text; double num; double num2; switch (role) { default: return; case PartyRole.Scout: text = "scouting"; num = 5.0; num2 = 100.0; break; case PartyRole.Surgeon: text = "medicine"; num = 1.0; num2 = 60.0; break; case PartyRole.Quartermaster: text = "stewardship"; num = 2.0; num2 = 60.0; break; case PartyRole.Engineer: text = "engineering"; num = 1.0; num2 = 60.0; break; } if (worker.RoleTrainingEarned == null) { worker.RoleTrainingEarned = new SortedDictionary(StringComparer.Ordinal); } long day = State.Clock.Day; if (worker.RoleTrainingDay != day) { worker.RoleTrainingEarned.Clear(); worker.RoleTrainingDay = day; } worker.RoleTrainingEarned.TryGetValue(text, out var value); if (double.IsNaN(value) || double.IsInfinity(value)) { value = num2; } value = Math.Max(0.0, Math.Min(num2, value)); double num3 = Math.Min(num2 - value, work * num); if (!(num3 <= 0.0)) { worker.RoleTrainingEarned[text] = value + num3; GrantSkillExperience(worker, text, num3); } } } public void GrantDailySkillExperience(Hero hero, string skill, double xp, double limit) { if (CanEarnExperience(hero) && PositiveFinite(xp) && PositiveFinite(limit)) { if (hero.RoleTrainingEarned == null) { hero.RoleTrainingEarned = new SortedDictionary(StringComparer.Ordinal); } long day = State.Clock.Day; if (hero.RoleTrainingDay != day) { hero.RoleTrainingEarned.Clear(); hero.RoleTrainingDay = day; } hero.RoleTrainingEarned.TryGetValue(skill, out var value); if (double.IsNaN(value) || double.IsInfinity(value)) { value = limit; } value = Math.Max(0.0, Math.Min(limit, value)); double num = Math.Min(limit - value, xp); if (!(num <= 0.0)) { hero.RoleTrainingEarned[skill] = value + num; GrantSkillExperience(hero, skill, num); } } } public string HeroPerkChoiceReason(string heroId, string perkId) { string text = C.CompanionCommandReason(); if (!string.IsNullOrEmpty(text)) { return text; } Party playerParty = State.PlayerParty; if (playerParty.State != PartyState.Active && playerParty.State != PartyState.InSettlement) { return "Can't choose perks right now."; } Hero hero = State.Heroes.Get(heroId ?? ""); if (hero == null || hero.ClanId != State.PlayerClanId || (hero.Id != State.PlayerHeroId && !C.IsOwnedCompanion(hero))) { return "Pick yourself or a companion."; } if (hero.State != HeroState.Active || !Campaign.IsPresentPartyHero(playerParty, hero)) { return "They have to be in your party to choose a perk."; } HeroPerkDef perk = HeroPerks.All.FirstOrDefault((HeroPerkDef p) => p.Id == perkId); if (perk == null) { return "Unknown perk."; } if (hero.Perks != null && hero.Perks.Contains(perkId)) { return "Already chosen."; } if (hero.Perks != null && HeroPerks.All.Any((HeroPerkDef p) => p.Group == perk.Group && hero.Perks.Contains(p.Id))) { return "The other perk of this pair is already chosen."; } if (hero.Skill(perk.Skill) < perk.RequiredSkill) { return $"Requires {perk.RequiredSkill} {Skills.Name(perk.Skill)}."; } return ""; } public bool HasPerkToChoose(string heroId) { return HeroPerks.All.Any((HeroPerkDef perk) => HeroPerkChoiceReason(heroId, perk.Id).Length == 0); } public CommandResult ChooseHeroPerk(string heroId, string perkId) { string text = HeroPerkChoiceReason(heroId, perkId); if (!string.IsNullOrEmpty(text)) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Get(heroId); HeroPerkDef heroPerkDef = HeroPerks.All.First((HeroPerkDef p) => p.Id == perkId); if (hero.Perks == null) { hero.Perks = new List(); } hero.Perks.Add(heroPerkDef.Id); string text2 = hero.Name + " chose " + heroPerkDef.Name + "."; State.AddLog(LogCategory.Info, text2, hero.Id, heroPerkDef.Id); State.Touch(); return CommandResult.Success(text2); } public bool HasRolePerk(Party party, PartyRole role, string perkId) { Hero hero = C.RoleHolder(party, role); if (hero?.Perks == null || !hero.Perks.Contains(perkId)) { return false; } string group = role switch { PartyRole.Quartermaster => "quartermaster", PartyRole.Surgeon => "surgeon", PartyRole.Scout => "scout", _ => "", }; if (group.Length == 0) { return false; } HeroPerkDef heroPerkDef = HeroPerks.All.FirstOrDefault((HeroPerkDef p) => p.Id == perkId && p.Group == group); if (heroPerkDef != null && hero.Skill(heroPerkDef.Skill) >= heroPerkDef.RequiredSkill) { return HeroPerks.All.Count((HeroPerkDef p) => p.Group == group && hero.Perks.Contains(p.Id)) == 1; } return false; } internal static bool CanEarnExperience(Hero hero) { if (hero != null && hero.State != HeroState.Dead) { return hero.State != HeroState.Inactive; } return false; } internal static bool PositiveFinite(double value) { if (value > 0.0 && !double.IsInfinity(value)) { return !double.IsNaN(value); } return false; } } internal sealed class QuestChainsSystem { private readonly Campaign C; private ContentDatabase Content => C.Content; private CampaignState State => C.State; internal QuestChainsSystem(Campaign host) { C = host; } internal DiscoverySite NewQuestSite(QuestState q, SiteKind kind, string name, Vec2 near, double min, double max, RandomStream rng) { Vec2 spot = C.QuestSpotNear(near, min, max, rng); Settlement settlement = (from s in State.Settlements where s.Type != SettlementType.Hideout orderby Vec2.Distance(s.Position, spot) select s).ThenBy((Settlement s) => s.Id, StringComparer.Ordinal).FirstOrDefault(); DiscoverySite discoverySite = new DiscoverySite { Id = "site." + q.Id + "." + (State.Quests.Sites.Count((DiscoverySite x) => x.QuestId == q.Id) + 1).ToString(CultureInfo.InvariantCulture), Kind = kind, Name = name, Position = spot, RegionSettlementId = (settlement?.Id ?? ""), QuestId = q.Id, Found = true, FoundMinute = State.Clock.Minute }; State.Quests.Sites.Add(discoverySite); return discoverySite; } internal string GiveRelicWeapon(string name, RandomStream rng) { C.EnsureSmithingFields(); CraftedWeaponState weapon = C.WeaponPrize(rng).Weapon; if (!string.IsNullOrEmpty(name)) { weapon.Name = name; } weapon.Id = "crafted." + State.Smithing.NextWeaponNumber++.ToString(CultureInfo.InvariantCulture); State.Smithing.Weapons[weapon.Id] = weapon; SortedDictionary equipment = State.PlayerParty.Equipment; equipment[weapon.Id] = (equipment.TryGetValue(weapon.Id, out var value) ? value : 0) + 1; return OwnedItems.CraftedName(weapon); } internal UnitDef CultureSoldier(string cultureId, int maxTier, bool rare) { return (from u in Content.Units where u.Culture == cultureId && u.Tier <= maxTier && !u.Mounted && u.Slots <= 1 && (!rare || u.Rarity == UnitRarity.Rare || u.Rarity == UnitRarity.Elite) orderby u.Tier descending select u).ThenBy((UnitDef u) => u.Id, StringComparer.Ordinal).FirstOrDefault(); } } internal sealed class QuestDelegationSystem { private readonly Campaign C; public const string Option = "delegate"; public const string Stage = "delegated"; private CampaignState State => C.State; internal QuestDelegationSystem(Campaign host) { C = host; } internal static bool IsDelegated(QuestState q) { if (q != null && q.Approach == "delegate") { return !string.IsNullOrEmpty(q.DelegateHeroId); } return false; } public QuestState DelegatedQuestOf(string heroId) { if (!string.IsNullOrEmpty(heroId)) { return State.Quests?.Quests?.FirstOrDefault((QuestState q) => q != null && q.Status == QuestStatus.Active && q.DelegateHeroId == heroId); } return null; } internal Hero BestDelegate(Campaign.QuestTemplate t) { Party party = State.PlayerParty; if (party == null || string.IsNullOrEmpty(t?.DelegateSkill)) { return null; } return (from id in party.Troops.Heroes select State.Heroes.Get(id) into h where h != null && C.IsOwnedCompanion(h) && h.CanFight && Campaign.IsPresentPartyHero(party, h) && C.GovernorAssignedSettlement(h.Id) == null && DelegatedQuestOf(h.Id) == null orderby h.Skill(t.DelegateSkill) descending, h.Health descending select h).ThenBy((Hero h) => h.Id, StringComparer.Ordinal).FirstOrDefault(); } public static double Chance(Campaign.QuestTemplate t, Hero h) { if (h != null) { return Math.Max(0.15, Math.Min(0.95, 0.5 + ((double)h.Skill(t.DelegateSkill) - t.DelegateDifficulty) / 150.0 + (double)(h.Level - 5) * 0.005)); } return 0.0; } internal static string SkillName(string id) { if (!string.IsNullOrEmpty(id)) { return char.ToUpperInvariant(id[0]) + id.Substring(1); } return ""; } internal StoryOption OfferOption(Campaign.QuestTemplate t, QuestState q) { if (string.IsNullOrEmpty(t?.DelegateSkill)) { return null; } Hero hero = BestDelegate(t); string text = ((t.DelegateTroops > 0) ? (" and " + t.DelegateTroops + " soldiers") : ""); if (hero == null) { return new StoryOption { Id = "delegate", Text = "Send one of my companions" + text + ".", Reason = "Bring a healthy companion who can be spared.", Hint = "A companion with " + SkillName(t.DelegateSkill) + " can see to it while you do other things." }; } double num = Chance(t, hero); string text2 = ((C.HandableTroops(1) < t.DelegateTroops) ? ("You need " + t.DelegateTroops + " healthy soldiers to send with them.") : t.DelegateEscrowReason(C, q)); StoryOption storyOption = new StoryOption(); storyOption.Id = "delegate"; storyOption.Text = "Send " + hero.Name + text + ". (" + (int)Math.Round(num * 100.0) + "% chance)"; storyOption.Reason = text2 ?? ""; storyOption.Hint = hero.Name + " (" + SkillName(t.DelegateSkill) + " " + hero.Skill(t.DelegateSkill) + ") is away about " + t.DelegateDays + " days. Success pays the reward; failure costs some of the soldiers and the giver's regard."; return storyOption; } internal Settlement WaitingPlace(QuestState q) { string[] array = new string[3] { q.TargetSettlementId, q.GiverSettlementId, State.PlayerParty?.CurrentSettlementId }; foreach (string text in array) { Settlement settlement = State.Settlements.Get(text ?? ""); if (settlement != null && settlement.Type != SettlementType.Hideout) { return settlement; } } Vec2 at = State.PlayerParty?.Position ?? Vec2.Zero; return (from s in State.Settlements where s.Type == SettlementType.Town orderby Vec2.Distance(at, s.Position) select s).ThenBy((Settlement s) => s.Id, StringComparer.Ordinal).FirstOrDefault(); } internal CommandResult Accept(Campaign.QuestTemplate t, QuestState q) { Hero hero = BestDelegate(t); if (hero == null) { return CommandResult.Fail("Bring a healthy companion who can be spared."); } if (C.HandableTroops(1) < t.DelegateTroops) { return CommandResult.Fail("You need " + t.DelegateTroops + " healthy soldiers to send with them."); } Settlement settlement = WaitingPlace(q); if (settlement == null) { return CommandResult.Fail("There is nowhere for them to set out from."); } if (!t.DelegateEscrow(C, q)) { string text = t.DelegateEscrowReason(C, q); return CommandResult.Fail((text != null && text.Length > 0) ? text : "The reward can't be raised just now."); } q.DelegateChance = Chance(t, hero); q.DelegateUnits = new SortedDictionary(StringComparer.Ordinal); foreach (string item in C.TakeTroops(t.DelegateTroops, 1, null)) { q.DelegateUnits[item] = (q.DelegateUnits.TryGetValue(item, out var value) ? value : 0) + 1; } C.ClearHeroRoleAssignments(hero.Id); State.PlayerParty.Troops.Heroes.Remove(hero.Id); hero.PartyId = ""; hero.SettlementId = settlement.Id; q.DelegateHeroId = hero.Id; q.Stage = "delegated"; q.DelegateDueMinute = State.Clock.Minute + (long)t.DelegateDays * 1440L; q.DeadlineMinute = Math.Max(q.DeadlineMinute, q.DelegateDueMinute + 2880); C.QuestLog(q, hero.Name + " set out to see to it" + ((t.DelegateTroops > 0) ? (" with " + t.DelegateTroops + " of your soldiers") : "") + "."); return CommandResult.Success(hero.Name + " sets out. Expect word in about " + t.DelegateDays + " days."); } internal void Daily(QuestState q, Campaign.QuestTemplate t) { if (!IsDelegated(q) || q.Stage != "delegated" || State.Clock.Minute < q.DelegateDueMinute) { return; } Hero hero = State.Heroes.Get(q.DelegateHeroId); RandomStream randomStream = State.Random.Get("quests"); if (hero == null || hero.State != HeroState.Active || hero.ClanId != State.PlayerClanId) { C.EndQuest(q, QuestStatus.Failed, "Nobody came back to finish the task.", 3); return; } bool flag = randomStream.Chance(q.DelegateChance); int num = q.DelegateUnits.Values.Sum(); int num2 = ((num != 0) ? ((int)Math.Round((double)(num * (flag ? randomStream.Range(0, 21) : randomStream.Range(30, 61))) / 100.0)) : 0); foreach (string item in q.DelegateUnits.Keys.OrderBy((string k) => k, StringComparer.Ordinal).ToList()) { if (num2 <= 0) { break; } int num3 = Math.Min(num2, q.DelegateUnits[item]); q.DelegateUnits[item] -= num3; num2 -= num3; if (q.DelegateUnits[item] <= 0) { q.DelegateUnits.Remove(item); } } int num4 = q.DelegateUnits.Values.Sum(); C.GrantSkillExperience(hero, t.DelegateSkill, flag ? 80 : 30); if (flag) { t.DelegatedSuccess(C, q, hero); C.EndQuest(q, QuestStatus.Succeeded, hero.Name + " saw to it" + ((num > num4) ? (", losing " + (num - num4) + " of the soldiers") : "") + "."); } else { hero.Health = Math.Min(hero.Health, 0.6); C.EndQuest(q, QuestStatus.Failed, hero.Name + " could not see it through and came back hurt" + ((num > num4) ? (", with " + (num - num4) + " fewer soldiers") : "") + ".", 3); } } internal void Return(QuestState q) { if (q == null || string.IsNullOrEmpty(q.DelegateHeroId)) { return; } Hero hero = State.Heroes.Get(q.DelegateHeroId); SortedDictionary obj = q.DelegateUnits ?? new SortedDictionary(StringComparer.Ordinal); q.DelegateHeroId = ""; q.DelegateUnits = new SortedDictionary(StringComparer.Ordinal); Party playerParty = State.PlayerParty; int num; if (playerParty != null && State.Player.Activity != PlayerActivity.Captive && string.IsNullOrEmpty(playerParty.EncounterId) && playerParty.State != PartyState.Engaged) { Hero playerHero = State.PlayerHero; num = ((playerHero != null && playerHero.State == HeroState.Active) ? 1 : 0); } else { num = 0; } bool flag = (byte)num != 0; bool flag2 = false; if (flag && hero != null && hero.State == HeroState.Active && hero.ClanId == State.PlayerClanId && string.IsNullOrEmpty(hero.PartyId) && C.GovernorAssignedSettlement(hero.Id) == null) { C.JoinCompanionToPlayerParty(hero); flag2 = true; } int num2 = 0; int num3 = 0; foreach (KeyValuePair item in obj) { int num4 = (flag ? C.JoinPlayer(item.Key, item.Value) : 0); num2 += num4; num3 += item.Value - num4; } string text = ((hero != null && !flag2 && hero.State == HeroState.Active) ? (" " + hero.Name + " waits at " + (State.Settlements.Get(hero.SettlementId)?.Name ?? "a town") + ".") : ""); if (hero != null || num2 + num3 > 0) { State.AddLog(LogCategory.Info, (flag2 ? (hero.Name + " is back with your party") : "Your people are back") + ((num2 > 0) ? (" with " + num2 + " soldiers") : "") + ((num3 > 0) ? ("; " + num3 + " who had no room went home") : "") + "." + text, hero?.Id ?? ""); } } } internal sealed class QuestsLordSystem { private readonly Campaign C; private CampaignState State => C.State; internal QuestsLordSystem(Campaign host) { C = host; } internal void AddQuestTalkOptions(Conversation c, Hero h) { if (State.Quests == null || !State.Quests.Started || h == null) { return; } QuestState questState = C.OpenQuestFrom(h.Id); if (questState == null || questState.Status == QuestStatus.Offered) { string reason = C.QuestWorkReason(h.Id); c.Options.Add(new ConversationOption { Id = "quest:ask", Text = ((questState != null) ? "About that task you mentioned..." : "Have you any work for me?"), Reason = reason }); } foreach (QuestState item in C.ActiveQuests.OrderBy((QuestState x) => x.Id, StringComparer.Ordinal)) { if (C.QuestPrompt(item.Id, h.Id) != null && (!(item.GiverHeroId != h.Id) || !(item.TargetHeroId != h.Id))) { c.Options.Add(new ConversationOption { Id = "quest:talk:" + item.Id, Text = ((item.GiverHeroId == h.Id) ? ("About " + LowerFirst(item.Title) + "...") : ("I come on behalf of " + item.GiverName + ".")) }); } } } internal static string LowerFirst(string s) { if (!string.IsNullOrEmpty(s)) { return char.ToLowerInvariant(s[0]) + s.Substring(1); } return s; } internal void BuildQuestTalkOptions(Conversation c, string questId) { StoryPrompt storyPrompt = C.QuestPrompt(questId, c.HeroId); if (storyPrompt == null) { c.Topic = "root"; return; } foreach (StoryOption option in storyPrompt.Options) { c.Options.Add(new ConversationOption { Id = "quest:do:" + questId + ":" + option.Id, Text = option.Text + ((option.Hint.Length > 0 && option.Enabled) ? "" : ""), Reason = option.Reason }); } } internal bool AnswerQuestTalk(Conversation c, Hero h, string id) { if (!id.StartsWith("quest:", StringComparison.Ordinal)) { return false; } if (id == "quest:ask") { string questId; CommandResult commandResult = C.AskForWork(h.Id, out questId); if (!commandResult.Ok) { c.Lines.Add(Campaign.Pick(C.TalkRandom(c, id), "No, nothing for now.", "Not at present. Ask me another time.", "I have nothing that needs doing, thank you.")); c.Note = commandResult.Message; return true; } StoryPrompt storyPrompt = C.QuestPrompt(questId, h.Id); c.Lines.AddRange(storyPrompt?.Lines ?? new List()); if (storyPrompt != null && storyPrompt.Note.Length > 0) { c.Note = storyPrompt.Note; } c.Topic = "quest:" + questId; return true; } if (id.StartsWith("quest:talk:", StringComparison.Ordinal)) { string text = id.Substring(11); StoryPrompt storyPrompt2 = C.QuestPrompt(text, h.Id); if (storyPrompt2 == null) { c.Lines.Add("Hm? What about it?"); return true; } c.Lines.AddRange(storyPrompt2.Lines); c.Topic = "quest:" + text; return true; } if (id.StartsWith("quest:do:", StringComparison.Ordinal)) { string text2 = id.Substring(9); int num = text2.LastIndexOf(':'); if (num <= 0) { return true; } string text3 = text2.Substring(0, num); string text4 = text2.Substring(num + 1); QuestState questState = C.Quest(text3); CommandResult commandResult2 = C.ChooseQuestOption(text3, text4, h.Id); c.Note = commandResult2.Message; if (!commandResult2.Ok) { c.Lines.Add("Hm. Not like that."); c.Topic = "root"; return true; } StoryPrompt storyPrompt3 = C.QuestPrompt(text3, h.Id); if (questState != null && questState.Status == QuestStatus.Active && storyPrompt3 != null && text4 != "close") { c.Lines.AddRange(storyPrompt3.Lines); c.Topic = "quest:" + text3; return true; } Random r = C.TalkRandom(c, id); c.Lines.Add((text4 == "decline") ? Campaign.Pick(r, "As you wish.", "Another time, then.") : ((questState != null && questState.Status == QuestStatus.Succeeded) ? Campaign.Pick(r, new string[2] { "Well done. You have my thanks.", "I will remember this, " + Campaign.First(State.PlayerHero) + "." }) : ((questState != null && questState.Status == QuestStatus.Active) ? Campaign.Pick(r, "Good. I will be waiting.", "Then go, and good luck.") : Campaign.Pick(r, "So be it.", "Very well.")))); c.Topic = "root"; return true; } return true; } } internal static class QuestsNotableSystem { internal static long Round10(double v) { return (long)Math.Round(v / 10.0) * 10; } internal static void QuestLog(Campaign c, QuestState q, string text) { c.QuestLog(q, text); } } internal sealed class QuestsSystem { private readonly Campaign C; private static Campaign.QuestTemplate[] AllQuestTemplates => Campaign.AllQuestTemplates; private NavGrid Nav => C.Nav; private CampaignState State => C.State; public IEnumerable ActiveQuests => State.Quests?.Quests?.Where((QuestState x) => x != null && x.Status == QuestStatus.Active) ?? Enumerable.Empty(); public static IEnumerable QuestTemplateIds => AllQuestTemplates.Select((Campaign.QuestTemplate t) => t.Id); public QuestState TrackedQuest { get { QuestState questState = Quest(State.Quests?.TrackedQuestId ?? ""); if (questState == null || questState.Status != QuestStatus.Active) { return null; } return questState; } } internal string PlayerFirstName => State.PlayerHero?.Name?.Split(new char[1] { ' ' }).FirstOrDefault() ?? "friend"; internal QuestsSystem(Campaign host) { C = host; } public void EnsureQuestFields() { bool flag = false; if (State.Quests == null) { State.Quests = new QuestsState(); flag = true; } QuestsState quests = State.Quests; if (quests.Quests == null) { quests.Quests = new List(); flag = true; } if (quests.GiverNextDay == null) { quests.GiverNextDay = new SortedDictionary(StringComparer.Ordinal); flag = true; } if (quests.StoriesTold == null) { quests.StoriesTold = new SortedDictionary(StringComparer.Ordinal); flag = true; } if (quests.Sites == null) { quests.Sites = new List(); flag = true; } if (quests.TrackedQuestId == null) { quests.TrackedQuestId = ""; flag = true; } if (quests.NextQuestNumber < 1) { quests.NextQuestNumber = 1; flag = true; } foreach (QuestState item in quests.Quests.Where((QuestState x) => x != null && x.Log == null)) { item.Log = new List(); flag = true; } if (!quests.Started) { quests.Started = true; quests.LastDay = State.Clock.Day; C.PlaceDiscoverySites(); flag = true; } if (flag) { State.Touch(); } } public QuestState Quest(string id) { return State.Quests?.Quests?.FirstOrDefault((QuestState x) => x != null && x.Id == id); } internal Campaign.QuestTemplate TemplateOf(QuestState q) { if (q != null) { return QuestTemplateFor(q.TemplateId); } return null; } internal static Campaign.QuestTemplate QuestTemplateFor(string id) { Campaign.QuestTemplate[] allQuestTemplates = AllQuestTemplates; foreach (Campaign.QuestTemplate questTemplate in allQuestTemplates) { if (questTemplate.Id == id) { return questTemplate; } } return null; } internal Campaign.QuestGiver ResolveGiver(string giverId) { if (string.IsNullOrEmpty(giverId)) { return null; } if (giverId.StartsWith("tavern:", StringComparison.Ordinal)) { Settlement settlement = State.Settlements.Get(giverId.Substring(7)); if (settlement != null && settlement.Type == SettlementType.Town) { return new Campaign.QuestGiver { Id = giverId, Kind = "tavern", Settlement = settlement, Name = TavernStrangerName(settlement) }; } return null; } NotableState notableState = State.Notables?.FirstOrDefault((NotableState n) => n.Id == giverId); if (notableState != null) { Settlement settlement2 = State.Settlements.Get(notableState.SettlementId); if (settlement2 == null || !notableState.IsAlive) { return null; } return new Campaign.QuestGiver { Id = giverId, Notable = notableState, Settlement = settlement2, Name = notableState.Name, Kind = ((settlement2.Type == SettlementType.Village) ? "village" : ((settlement2.Type == SettlementType.Castle) ? "castle" : "town")) }; } Hero hero = State.Heroes.Get(giverId); if (hero == null || hero.State != HeroState.Active || hero.Occupation != HeroOccupation.Lord || hero.ClanId == State.PlayerClanId) { return null; } Clan clan = State.Clans.Get(hero.ClanId); if (clan == null || clan.IsEliminated || clan.IsBandit) { return null; } return new Campaign.QuestGiver { Id = giverId, Kind = "lord", Hero = hero, Name = hero.Name, Settlement = C.MeetingPlace() }; } internal string TavernStrangerName(Settlement town) { string[] array = new string[8] { "Old Bertram", "Grizzled Hilde", "One-Eyed Rolf", "Mother Agathe", "Toothless Wim", "Sir Dunmore (retired)", "Crooked Annik", "Long Tobias" }; return array[(uint)(StableHash.Fnv1a64("stranger|" + town.Id) % (ulong)array.Length)]; } internal RandomStream QuestWeekRandom(string giverId, long week) { return new RandomStream("quests|" + giverId + "|" + week.ToString(CultureInfo.InvariantCulture), State.Random.Seed); } internal QuestState OpenQuestFrom(string giverId) { return State.Quests.Quests.FirstOrDefault((QuestState q) => q != null && (q.Status == QuestStatus.Offered || q.Status == QuestStatus.Active) && (q.GiverNotableId == giverId || q.GiverHeroId == giverId || (q.GiverName.Length > 0 && "tavern:" + q.GiverSettlementId == giverId && q.Source == QuestSource.Chain && string.IsNullOrEmpty(q.GiverNotableId)))); } public string QuestWorkReason(string giverId) { if (State.Quests == null || !State.Quests.Started) { return "Nobody has work for you yet."; } Campaign.QuestGiver questGiver = ResolveGiver(giverId); if (questGiver == null) { return "They have no work for you."; } if (OpenQuestFrom(giverId) != null) { return ""; } if (State.Quests.GiverNextDay.TryGetValue(giverId, out var value) && value > State.Clock.Day) { return questGiver.Name + " has nothing more for you for now (until day " + (value + 1) + ")."; } if (questGiver.Kind == "lord" && C.HeroIsEnemy(questGiver.Hero)) { return questGiver.Name + " will not give work to an enemy."; } if (questGiver.Kind != "lord" && questGiver.Kind != "tavern" && !C.ContractFriendlySettlement(questGiver.Settlement)) { return "Nobody here will deal with you."; } if (BuildQuestOffer(questGiver, out var why) != null) { return ""; } return why; } internal QuestState BuildQuestOffer(Campaign.QuestGiver giver, out string why) { why = giver.Name + " has no work for you this week."; long week = State.Clock.Day / 7; RandomStream randomStream = QuestWeekRandom(giver.Id, week); int num = ((giver.Kind == "lord") ? 50 : ((giver.Kind == "tavern") ? 25 : 65)); if (randomStream.Range(0, 100) >= num) { return null; } List list = AllQuestTemplates.Where((Campaign.QuestTemplate t) => t.GiverKinds.Contains(giver.Kind) && (t.Source != QuestSource.Chain || (!State.Quests.StoriesTold.ContainsKey(t.Id) && !State.Quests.Quests.Any((QuestState q) => q.TemplateId == t.Id && (q.Status == QuestStatus.Active || q.Status == QuestStatus.Offered))))).ToList(); for (int num2 = list.Count - 1; num2 > 0; num2--) { int index = randomStream.Range(0, num2 + 1); Campaign.QuestTemplate value = list[num2]; list[num2] = list[index]; list[index] = value; } foreach (Campaign.QuestTemplate item in list) { QuestState questState = item.TryOffer(C, giver, randomStream); if (questState != null) { return FillOffer(questState, item, giver); } } return null; } internal QuestState FillOffer(QuestState q, Campaign.QuestTemplate t, Campaign.QuestGiver giver) { q.TemplateId = t.Id; q.Source = t.Source; q.Status = QuestStatus.Offered; q.OfferedMinute = State.Clock.Minute; q.DeadlineMinute = (State.Clock.Day / 7 + 1) * 7 * 1440; q.GiverName = giver.Name; q.GiverSettlementId = giver.Settlement?.Id ?? q.GiverSettlementId; if (giver.Notable != null) { q.GiverNotableId = giver.Notable.Id; q.GiverClanId = giver.Settlement?.OwnerClanId ?? ""; } if (giver.Hero != null) { q.GiverHeroId = giver.Hero.Id; q.GiverClanId = giver.Hero.ClanId; } return q; } public CommandResult DeveloperOfferQuest(string templateId, string giverId, out string questId) { questId = ""; if (!State.DeveloperTools) { return CommandResult.Fail("Developer tools were not enabled when this campaign was created."); } if (State.Quests == null || !State.Quests.Started) { EnsureQuestFields(); } Campaign.QuestTemplate questTemplate = QuestTemplateFor(templateId); Campaign.QuestGiver questGiver = ResolveGiver(giverId); if (questTemplate == null) { return CommandResult.Fail("Unknown kind of quest."); } if (questGiver == null) { return CommandResult.Fail("Nobody to give it."); } if (!questTemplate.GiverKinds.Contains(questGiver.Kind)) { return CommandResult.Fail(questGiver.Name + " does not give that kind of task."); } if (OpenQuestFrom(giverId) != null) { return CommandResult.Fail(questGiver.Name + " already has a task for you."); } QuestState questState = questTemplate.TryOffer(C, questGiver, QuestWeekRandom(giverId + "|developer|" + templateId, State.Clock.Day)); if (questState == null) { return CommandResult.Fail("That task does not fit " + questGiver.Name + " or the world just now."); } FillOffer(questState, questTemplate, questGiver); questState.Id = "quest." + State.Quests.NextQuestNumber++.ToString(CultureInfo.InvariantCulture); State.Quests.Quests.Add(questState); questId = questState.Id; State.Touch(); return CommandResult.Success("Developer: " + questGiver.Name + " offers \"" + questState.Title + "\"."); } public CommandResult DeveloperRevealSites() { if (!State.DeveloperTools) { return CommandResult.Fail("Developer tools were not enabled when this campaign was created."); } if (State.Quests == null || !State.Quests.Started) { EnsureQuestFields(); } int num = 0; foreach (DiscoverySite item in State.Quests.Sites.Where((DiscoverySite x) => !x.Found && string.IsNullOrEmpty(x.QuestId))) { item.Found = true; item.FoundMinute = State.Clock.Minute; num++; } State.Touch(); return CommandResult.Success("Developer: " + num + " hidden places revealed."); } public CommandResult AskForWork(string giverId, out string questId) { questId = ""; string why = QuestWorkReason(giverId); if (why.Length > 0) { return CommandResult.Fail(why); } QuestState questState = OpenQuestFrom(giverId); if (questState != null) { questId = questState.Id; return CommandResult.Success(); } Campaign.QuestGiver giver = ResolveGiver(giverId); QuestState questState2 = BuildQuestOffer(giver, out why); if (questState2 == null) { return CommandResult.Fail(why); } questState2.Id = "quest." + State.Quests.NextQuestNumber++.ToString(CultureInfo.InvariantCulture); State.Quests.Quests.Add(questState2); questId = questState2.Id; State.Touch(); return CommandResult.Success(); } internal Campaign.QuestContext PlayerQuestContext(Hero talkingTo = null) { Party playerParty = State.PlayerParty; Settlement here = ((playerParty != null && playerParty.State == PartyState.InSettlement) ? State.Settlements.Get(playerParty.CurrentSettlementId) : null); return new Campaign.QuestContext { TalkingTo = talkingTo, Here = here, Site = C.SiteHere() }; } internal string QuestActionReason() { if (C.AwaitingHeir || C.LineEnded) { return "Choose your heir first."; } Party playerParty = State.PlayerParty; Hero playerHero = State.PlayerHero; if (playerParty == null || playerHero == null || playerHero.State != HeroState.Active) { return "Your character is not free."; } switch (State.Player.Activity) { case PlayerActivity.Captive: return "You are a prisoner."; case PlayerActivity.InEncounter: case PlayerActivity.InBattle: return "Finish the encounter first."; default: if (!State.Player.LastReportSeen && State.Player.LastReport != null) { return "Read the battle report first."; } if (C.DisguiseBlockReason().Length > 0) { return C.DisguiseBlockReason(); } if (C.TournamentBusyReason().Length > 0) { return C.TournamentBusyReason(); } return ""; } } public StoryPrompt QuestPrompt(string questId, string talkingToHeroId = "") { QuestState questState = Quest(questId); Campaign.QuestTemplate questTemplate = TemplateOf(questState); if (questState == null || questTemplate == null) { return null; } Campaign.QuestContext ctx = PlayerQuestContext(State.Heroes.Get(talkingToHeroId ?? "")); if (questState.Status == QuestStatus.Offered) { StoryPrompt storyPrompt = new StoryPrompt { Kind = "quest", SubjectId = questState.Id, Title = questState.Title, Speaker = questState.GiverName, SpeakerRole = GiverRole(questState) }; storyPrompt.Lines.AddRange(questTemplate.OfferLines(C, questState)); string text = QuestActionReason(); int num = ActiveQuests.Count(); List list = questTemplate.OfferOptions(C, questState, ctx); StoryOption storyOption = C.QuestDelegationSystem.OfferOption(questTemplate, questState); if (storyOption != null) { list.Add(storyOption); } foreach (StoryOption item in list) { if (item.Reason.Length == 0 && text.Length > 0) { item.Reason = text; } if (item.Reason.Length == 0 && num >= 4) { item.Reason = "You already have " + 4 + " quests under way. Finish or abandon one first."; } storyPrompt.Options.Add(item); } storyPrompt.Options.Add(new StoryOption { Id = "decline", Text = "Not now." }); storyPrompt.Note = "Reward: " + ((questState.Reward > 0) ? (questState.Reward.ToString("N0") + " denars") : "their gratitude") + " · " + QuestDurationText(questTemplate) + "."; return storyPrompt; } if (questState.Status != QuestStatus.Active || QuestDelegationSystem.IsDelegated(questState)) { return null; } StoryPrompt storyPrompt2 = questTemplate.Stage(C, questState, ctx); if (storyPrompt2 == null) { return null; } storyPrompt2.Kind = "quest"; storyPrompt2.SubjectId = questState.Id; if (storyPrompt2.Title.Length == 0) { storyPrompt2.Title = questState.Title; } string text2 = QuestActionReason(); if (text2.Length > 0) { foreach (StoryOption option in storyPrompt2.Options) { if (option.Reason.Length == 0 && option.Id != "close") { option.Reason = text2; } } } return storyPrompt2; } internal static string QuestDurationText(Campaign.QuestTemplate t) { return t.Days + " days to do it"; } internal string GiverRole(QuestState q) { if (!string.IsNullOrEmpty(q.GiverHeroId)) { Hero hero = State.Heroes.Get(q.GiverHeroId); Clan clan = State.Clans.Get(hero?.ClanId ?? ""); if (clan != null) { return "of " + clan.Name; } return ""; } NotableState notableState = State.Notables?.FirstOrDefault((NotableState x) => x.Id == q.GiverNotableId); Settlement settlement = State.Settlements.Get(q.GiverSettlementId); if (notableState != null) { return notableState.Occupation + ((settlement != null) ? (" of " + settlement.Name) : ""); } if (settlement == null) { return ""; } return "in the tavern of " + settlement.Name; } public CommandResult ChooseQuestOption(string questId, string optionId, string talkingToHeroId = "") { QuestState questState = Quest(questId); Campaign.QuestTemplate questTemplate = TemplateOf(questState); if (questState == null || questTemplate == null) { return CommandResult.Fail("That quest's gone."); } StoryPrompt storyPrompt = QuestPrompt(questId, talkingToHeroId); if (storyPrompt == null) { return CommandResult.Fail("Nothing to decide here."); } StoryOption storyOption = storyPrompt.Options.FirstOrDefault((StoryOption o) => o.Id == optionId); if (storyOption == null) { return CommandResult.Fail("That choice is not open."); } if (!storyOption.Enabled) { return CommandResult.Fail(storyOption.Reason); } Campaign.QuestContext ctx = PlayerQuestContext(State.Heroes.Get(talkingToHeroId ?? "")); CommandResult commandResult; if (questState.Status == QuestStatus.Offered) { if (optionId == "decline") { State.Quests.Quests.Remove(questState); State.Quests.GiverNextDay[GiverKey(questState)] = (State.Clock.Day / 7 + 1) * 7; State.Touch(); return CommandResult.Success("You turned the task down."); } questState.Approach = optionId; questState.AcceptedMinute = State.Clock.Minute; questState.StageMinute = State.Clock.Minute; questState.DeadlineMinute = State.Clock.Minute + (long)questTemplate.Days * 1440L; questState.Status = QuestStatus.Active; commandResult = ((optionId == "delegate") ? C.QuestDelegationSystem.Accept(questTemplate, questState) : questTemplate.Accept(C, questState, optionId, ctx)); if (!commandResult.Ok) { questState.Status = QuestStatus.Offered; questState.Approach = ""; questState.AcceptedMinute = -1L; questState.DeadlineMinute = (State.Clock.Day / 7 + 1) * 7 * 1440; return commandResult; } if (questState.Status == QuestStatus.Active) { QuestLog(questState, "Accepted: " + storyOption.Text); if (!string.IsNullOrEmpty(State.Quests.TrackedQuestId)) { QuestState questState2 = Quest(State.Quests.TrackedQuestId); if (questState2 != null && questState2.Status == QuestStatus.Active) { goto IL_028b; } } State.Quests.TrackedQuestId = questState.Id; goto IL_028b; } goto IL_02b4; } CommandResult result = questTemplate.Choose(C, questState, optionId, ctx); State.Touch(); return result; IL_028b: State.AddLog(LogCategory.Info, "Quest accepted: " + questState.Title + ".", QuestLinks(questState)); goto IL_02b4; IL_02b4: State.Touch(); return commandResult; } internal static string GiverKey(QuestState q) { if (string.IsNullOrEmpty(q.GiverHeroId)) { if (string.IsNullOrEmpty(q.GiverNotableId)) { return "tavern:" + q.GiverSettlementId; } return q.GiverNotableId; } return q.GiverHeroId; } public string AbandonQuestReason(string questId) { QuestState questState = Quest(questId); if (questState == null || questState.Status != QuestStatus.Active) { return "That quest isn't under way."; } return ""; } public CommandResult AbandonQuest(string questId) { string text = AbandonQuestReason(questId); if (text.Length > 0) { return CommandResult.Fail(text); } QuestState questState = Quest(questId); EndQuest(questState, QuestStatus.Cancelled, "You gave the task up.", 3); return CommandResult.Success("You gave up: " + questState.Title + "."); } public CommandResult TrackQuest(string questId) { if (string.IsNullOrEmpty(questId)) { State.Quests.TrackedQuestId = ""; State.Touch(); return CommandResult.Success("No quest is tracked."); } QuestState questState = Quest(questId); if (questState == null || questState.Status != QuestStatus.Active) { return CommandResult.Fail("You can only track a quest that's under way."); } State.Quests.TrackedQuestId = questState.Id; State.Touch(); return CommandResult.Success("Tracking: " + questState.Title + "."); } internal void QuestLog(QuestState q, string text) { if (q.Log == null) { q.Log = new List(); } q.Log.Add(new QuestLogLine { Minute = State.Clock.Minute, Text = text }); if (q.Log.Count > 30) { q.Log.RemoveAt(0); } } internal string[] QuestLinks(QuestState q) { return new string[4] { q.GiverSettlementId, q.GiverHeroId, q.TargetSettlementId, q.TargetHeroId }.Where((string x) => !string.IsNullOrEmpty(x)).ToArray(); } internal void EndQuest(QuestState q, QuestStatus status, string result, int relationPenalty = 0) { if (q.Status != QuestStatus.Active && q.Status != QuestStatus.Offered) { return; } if (status == QuestStatus.Succeeded) { PayQuestEscrow(q); } RefundQuestEscrow(q); q.Status = status; q.EndedMinute = State.Clock.Minute; q.Result = result; QuestLog(q, result); C.QuestDelegationSystem.Return(q); if (relationPenalty > 0) { if (!string.IsNullOrEmpty(q.GiverNotableId)) { C.AdjustNotableRelation(q.GiverNotableId, -relationPenalty, "quest " + status.ToString().ToLowerInvariant()); } else if (!string.IsNullOrEmpty(q.GiverHeroId)) { Clan clan = State.Clans.Get(q.GiverClanId); if (clan != null && !clan.IsEliminated) { C.AdjustClanRelation(State.PlayerClanId, q.GiverClanId, -relationPenalty); } } } State.Quests.GiverNextDay[GiverKey(q)] = State.Clock.Day + ((status == QuestStatus.Succeeded) ? 3 : 7); if (q.Source == QuestSource.Chain) { State.Quests.StoriesTold[q.TemplateId] = State.Clock.Day; } if (State.Quests.TrackedQuestId == q.Id) { State.Quests.TrackedQuestId = (from x in ActiveQuests where x.Id != q.Id orderby x.DeadlineMinute select x).ThenBy((QuestState x) => x.Id, StringComparer.Ordinal).FirstOrDefault()?.Id ?? ""; } string text = status switch { QuestStatus.Failed => "Quest failed", QuestStatus.Succeeded => "Quest done", _ => "Quest closed", }; string text2 = text + ": " + q.Title + ". " + result; State.AddLog((status == QuestStatus.Succeeded) ? LogCategory.Economy : LogCategory.Info, text2, QuestLinks(q)); C.Raise(CampaignEventKind.Info, text2, forcePause: false, QuestLinks(q)); PruneQuestHistory(); State.Touch(); } internal void PruneQuestHistory() { List list = (from x in State.Quests.Quests where x.Status != QuestStatus.Active && x.Status != QuestStatus.Offered && x.Escrow == 0 orderby x.EndedMinute select x).ThenBy((QuestState x) => x.Id, StringComparer.Ordinal).ToList(); for (int num = 0; num < list.Count - 40; num++) { State.Quests.Quests.Remove(list[num]); } } internal bool HoldQuestEscrow(QuestState q, long amount, Clan clan, Settlement market) { if (amount <= 0) { return true; } if (market != null) { if (market.Market == null || market.Market.Gold < amount) { return false; } market.Market.Gold -= amount; q.EscrowFrom = "market:" + market.Id; } else { if (clan == null || clan.IsEliminated || clan.Gold < amount) { return false; } State.Transact(clan, -amount, LedgerAccount.Quest, "Quest reward held: " + q.Title); q.EscrowFrom = "clan:" + clan.Id; } q.Escrow = amount; q.Reward = amount; return true; } internal bool HoldPlayerEscrow(QuestState q, long amount) { if (amount <= 0 || State.PlayerClan.Gold < amount) { return false; } State.Transact(State.PlayerClan, -amount, LedgerAccount.Quest, "Held for a quest: " + q.Title); q.EscrowFrom = "player"; q.Escrow = amount; return true; } internal void PayQuestEscrow(QuestState q) { if (q.Escrow > 0 && !(q.EscrowFrom == "player") && State.PlayerClan.Gold <= long.MaxValue - q.Escrow) { State.Transact(State.PlayerClan, q.Escrow, LedgerAccount.Quest, "Quest reward: " + q.Title); q.Escrow = 0L; } } internal void RefundQuestEscrow(QuestState q) { if (q.Escrow <= 0) { return; } string text = q.EscrowFrom ?? ""; if (text == "player") { State.Transact(State.PlayerClan, q.Escrow, LedgerAccount.Quest, "Returned from a quest: " + q.Title); q.Escrow = 0L; } else if (text.StartsWith("market:", StringComparison.Ordinal)) { Settlement settlement = State.Settlements.Get(text.Substring(7)); if (settlement?.Market != null) { settlement.Market.Gold += q.Escrow; q.Escrow = 0L; } } else if (text.StartsWith("clan:", StringComparison.Ordinal)) { Clan clan = State.Clans.Get(text.Substring(5)); if (clan != null && clan.Gold <= long.MaxValue - q.Escrow) { State.Transact(clan, q.Escrow, LedgerAccount.Quest, "Unused quest reward returned"); q.Escrow = 0L; } } } internal long MoveMarketGold(Settlement from, Settlement to, long amount) { if (from?.Market == null || to?.Market == null || amount <= 0) { return 0L; } amount = Math.Min(amount, from.Market.Gold); from.Market.Gold -= amount; to.Market.Gold += amount; return amount; } internal bool PlayerPaysMarket(Settlement s, long amount, string reason) { if (s?.Market == null || amount <= 0 || State.PlayerClan.Gold < amount) { return false; } State.Transact(State.PlayerClan, -amount, LedgerAccount.Quest, reason); s.Market.Gold += amount; return true; } internal static double Clamp100(double v) { return Math.Max(0.0, Math.Min(100.0, v)); } internal void DailyQuests() { QuestsState quests = State.Quests; if (quests == null || !quests.Started || quests.LastDay >= State.Clock.Day) { return; } quests.LastDay = State.Clock.Day; State.Touch(); quests.Quests.RemoveAll((QuestState q) => q != null && q.Status == QuestStatus.Offered && q.DeadlineMinute <= State.Clock.Minute); foreach (QuestState item in quests.Quests.Where((QuestState x) => x != null && x.Status == QuestStatus.Active).OrderBy((QuestState x) => x.Id, StringComparer.Ordinal).ToList()) { Campaign.QuestTemplate questTemplate = TemplateOf(item); if (questTemplate == null) { EndQuest(item, QuestStatus.Cancelled, "This kind of task is no longer known."); continue; } if (QuestDelegationSystem.IsDelegated(item)) { C.QuestDelegationSystem.Daily(item, questTemplate); } else { questTemplate.Daily(C, item); } if (item.Status == QuestStatus.Active) { string text = QuestParticipantsReason(item, questTemplate); if (text.Length > 0) { EndQuest(item, QuestStatus.Cancelled, text); } else if (item.DeadlineMinute <= State.Clock.Minute) { EndQuest(item, QuestStatus.Failed, "Time ran out.", 3); } } } foreach (QuestState item2 in quests.Quests.Where((QuestState x) => x != null && x.Status != QuestStatus.Active && x.Escrow > 0)) { RefundQuestEscrow(item2); } } internal string QuestParticipantsReason(QuestState q, Campaign.QuestTemplate t) { if (!string.IsNullOrEmpty(q.GiverHeroId)) { Hero hero = State.Heroes.Get(q.GiverHeroId); if (hero == null || hero.State == HeroState.Dead) { return q.GiverName + " is dead; nobody will see the task through."; } Clan clan = State.Clans.Get(hero.ClanId); if (clan == null || clan.IsEliminated) { return q.GiverName + "'s clan is no more."; } if (State.AreHostile(State.PlayerClan, clan)) { return "You are at war with " + q.GiverName + "'s realm; the task is off."; } } if (!string.IsNullOrEmpty(q.GiverNotableId)) { NotableState notableState = State.Notables?.FirstOrDefault((NotableState x) => x.Id == q.GiverNotableId); if (notableState == null || !notableState.IsAlive) { return q.GiverName + " is no longer there to see it through."; } } if (!string.IsNullOrEmpty(q.GiverSettlementId) && !State.Settlements.Contains(q.GiverSettlementId)) { return "The place is gone."; } if (!QuestDelegationSystem.IsDelegated(q)) { return t.Invalid(C, q); } return ""; } internal void HourlyQuests() { QuestsState quests = State.Quests; if (quests == null || !quests.Started) { return; } foreach (QuestState item in quests.Quests.Where((QuestState x) => x != null && x.Status == QuestStatus.Active && !QuestDelegationSystem.IsDelegated(x)).OrderBy((QuestState x) => x.Id, StringComparer.Ordinal).ToList()) { TemplateOf(item)?.Hourly(C, item); } C.HourlyDiscoveries(); } public void RecordQuestBattle(Encounter encounter, BattleResult result, BattleReport report) { if (encounter == null || result == null || report == null || !encounter.PlayerInvolved || State.Quests == null || !encounter.PartiesOn(encounter.PlayerSide).Contains(State.PlayerPartyId) || (result.Winner != WinnerSide.Attacker && result.Winner != WinnerSide.Defender)) { return; } if (result.Winner == WinnerSide.Attacker != (encounter.PlayerSide == BattleSide.Attacker)) { foreach (QuestState item in ActiveQuests.Where((QuestState x) => !QuestDelegationSystem.IsDelegated(x)).OrderBy((QuestState x) => x.Id, StringComparer.Ordinal).ToList()) { string text = TemplateOf(item)?.OnDefeat(C, item) ?? ""; if (!string.IsNullOrEmpty(text)) { report.Lines.Add(text); } } return; } BattleSide side = ((encounter.PlayerSide == BattleSide.Attacker) ? BattleSide.Defender : BattleSide.Attacker); HashSet beaten = new HashSet(encounter.PartiesOn(side), StringComparer.Ordinal); if (State.StoryEvents != null) { State.StoryEvents.LastVictoryMinute = State.Clock.Minute; } foreach (QuestState item2 in ActiveQuests.Where((QuestState x) => !QuestDelegationSystem.IsDelegated(x)).OrderBy((QuestState x) => x.Id, StringComparer.Ordinal).ToList()) { Campaign.QuestTemplate questTemplate = TemplateOf(item2); if (questTemplate != null) { string text2 = questTemplate.OnVictory(C, item2, beaten); if (!string.IsNullOrEmpty(text2)) { report.Lines.Add(text2); QuestLog(item2, text2); } } } } internal void RecordQuestRaid(Settlement village) { if (village == null || State.Quests == null) { return; } foreach (QuestState item in ActiveQuests.OrderBy((QuestState x) => x.Id, StringComparer.Ordinal).ToList()) { TemplateOf(item)?.OnRaid(C, item, village); } } public List JournalEntries(bool open) { List list = new List(); Campaign.QuestContext ctx = PlayerQuestContext(); foreach (QuestState item in State.Quests?.Quests ?? new List()) { if (item == null || item.Status == QuestStatus.Offered) { continue; } bool flag = item.Status == QuestStatus.Active; if (flag != open) { continue; } Campaign.QuestTemplate questTemplate = TemplateOf(item); JournalEntry journalEntry = new JournalEntry { Id = item.Id, Kind = "quest", Title = item.Title, GiverName = item.GiverName, Open = flag, Succeeded = (item.Status == QuestStatus.Succeeded), SourceLabel = ((item.Source == QuestSource.Lord) ? "Lord's task" : ((item.Source == QuestSource.Notable) ? "Local task" : ((item.Source == QuestSource.Chain) ? "Story" : "Discovery"))), GiverLink = ((!string.IsNullOrEmpty(item.GiverHeroId)) ? ("hero:" + item.GiverHeroId) : ((!string.IsNullOrEmpty(item.GiverNotableId)) ? ("hero:" + item.GiverNotableId) : "")), Reward = item.Reward, StartedMinute = item.AcceptedMinute, DeadlineMinute = (flag ? item.DeadlineMinute : (-1)), EndedMinute = item.EndedMinute, StatusText = (flag ? "Under way" : ((item.Status == QuestStatus.Succeeded) ? "Done" : ((item.Status == QuestStatus.Failed) ? "Failed" : "Closed"))), Tracked = (flag && State.Quests.TrackedQuestId == item.Id), CanAbandon = flag, Summary = ((!flag) ? item.Result : (questTemplate?.Summary(C, item) ?? "")), Log = (item.Log ?? new List()).ToList() }; if (questTemplate != null && flag && QuestDelegationSystem.IsDelegated(item)) { Hero hero = State.Heroes.Get(item.DelegateHeroId); journalEntry.Objectives = new List { new QuestObjective { Text = (hero?.Name ?? "Your companion") + " is seeing to it: word expected about day " + (item.DelegateDueMinute / 1440 + 1) + " (" + (int)Math.Round(item.DelegateChance * 100.0) + "% chance).", Done = false } }; journalEntry.Places = new List { hero?.SettlementId ?? "" }.Where((string x) => !string.IsNullOrEmpty(x)).ToList(); journalEntry.CanAbandon = true; } else if (questTemplate != null) { journalEntry.Objectives = questTemplate.Objectives(C, item); journalEntry.Places = (from x in questTemplate.Places(C, item) where !string.IsNullOrEmpty(x) select x).Distinct().ToList(); StoryPrompt storyPrompt = (flag ? questTemplate.Stage(C, item, ctx) : null); journalEntry.HasDecisionHere = storyPrompt != null && !storyPrompt.Optional; } list.Add(journalEntry); } foreach (ContractState c in State.Contracts ?? new List()) { if (c == null || c.Status == ContractStatus.Offered) { continue; } bool flag2 = c.Status == ContractStatus.Active; if (flag2 != open || !c.WasAccepted) { continue; } Settlement settlement = State.Settlements.Get(c.IssuerSettlementId); Settlement settlement2 = State.Settlements.Get(c.TargetSettlementId); JournalEntry journalEntry2 = new JournalEntry { Id = c.Id, Kind = "contract", Title = ((c.Kind == ContractKind.BanditBounty) ? "Bounty" : ((c.Kind == ContractKind.Delivery) ? "Delivery" : "Supply request")), SourceLabel = "Contract", GiverName = (State.Notables?.FirstOrDefault((NotableState n) => n.Id == c.IssuerNotableId)?.Name ?? settlement?.Name ?? ""), GiverLink = (string.IsNullOrEmpty(c.IssuerNotableId) ? "" : ("hero:" + c.IssuerNotableId)), Open = flag2, Succeeded = (c.Status == ContractStatus.Completed), Reward = c.Reward, DeadlineMinute = (flag2 ? c.DeadlineMinute : (-1)), StatusText = (flag2 ? "Under way" : ((c.Status == ContractStatus.Completed) ? "Done" : ((c.Status == ContractStatus.Failed) ? "Failed" : "Given up"))), Summary = c.Description, CanAbandon = flag2 }; if (Campaign.IsCargoContract(c)) { journalEntry2.Objectives.Add(new QuestObjective { Text = "Carry " + c.Quantity + " " + (TradeGoods.Get(c.GoodId)?.Name ?? c.GoodId) + " (" + Math.Min(c.Quantity, C.CargoCount(State.PlayerParty, c.GoodId)) + " aboard)", Done = (C.CargoCount(State.PlayerParty, c.GoodId) >= c.Quantity) }); journalEntry2.Objectives.Add(new QuestObjective { Text = "Deliver them to " + (settlement2?.Name ?? "the destination"), Done = (c.Status == ContractStatus.Completed) }); journalEntry2.Places.Add(c.TargetSettlementId); } else { Party party = State.Parties.Get(c.TargetPartyId); journalEntry2.Objectives.Add(new QuestObjective { Text = "Defeat " + (party?.Name ?? "the bandits") + KnownPartyWhereabouts(c.TargetPartyId), Done = (c.Progress > 0) }); journalEntry2.Objectives.Add(new QuestObjective { Text = "Return to " + (settlement?.Name ?? "the issuer"), Done = (c.Status == ContractStatus.Completed) }); if (c.Progress == 0 && party != null && State.PlayerSightings.ContainsKey(party.Id)) { journalEntry2.Places.Add(party.Id); } journalEntry2.Places.Add(c.IssuerSettlementId); } list.Add(journalEntry2); } if (!open) { return list.OrderByDescending((JournalEntry e) => e.EndedMinute).ThenBy((JournalEntry e) => e.Id, StringComparer.Ordinal).ToList(); } return list.OrderBy((JournalEntry e) => (e.DeadlineMinute >= 0) ? e.DeadlineMinute : long.MaxValue).ThenBy((JournalEntry e) => e.Id, StringComparer.Ordinal).ToList(); } internal string KnownPartyWhereabouts(string partyId) { if (string.IsNullOrEmpty(partyId) || !State.PlayerSightings.TryGetValue(partyId, out var s) || s == null) { return ""; } Settlement settlement = (from x in State.Settlements where x.Type != SettlementType.Hideout orderby Vec2.Distance(x.Position, s.Position) select x).ThenBy((Settlement x) => x.Id, StringComparer.Ordinal).FirstOrDefault(); if (s.CurrentlyVisible) { if (settlement != null) { return " (in sight, near " + settlement.Name + ")"; } return " (in sight)"; } long num = Math.Max(0L, (State.Clock.Minute - s.SeenAtMinute) / 60); return " (last seen" + ((settlement == null) ? "" : (" near " + settlement.Name)) + ", " + ((num < 1) ? "just now" : (num + "h ago")) + ")"; } public List QuestPlacesFor(string questId) { QuestState questState = Quest(questId); Campaign.QuestTemplate questTemplate = TemplateOf(questState); if (questState != null && questTemplate != null) { return (from x in questTemplate.Places(C, questState) where !string.IsNullOrEmpty(x) select x).Distinct().ToList(); } return new List(); } public List QuestsWithDecisionHere() { Campaign.QuestContext ctx = PlayerQuestContext(); return ActiveQuests.Where(delegate(QuestState q) { StoryPrompt storyPrompt = TemplateOf(q)?.Stage(C, q, ctx); return storyPrompt != null && !storyPrompt.Optional; }).OrderBy((QuestState q) => q.Id, StringComparer.Ordinal).ToList(); } internal Settlement NearestHideout(Vec2 near) { return (from s in State.Settlements.Where(delegate(Settlement s) { if (s.Type == SettlementType.Hideout && s.HideoutActive) { Clan clan = State.Clans.Get(s.BanditClanId); if (clan == null) { return false; } return clan.BanditTroops?.Count > 0; } return false; }) orderby Vec2.Distance(s.Position, near) select s).ThenBy((Settlement s) => s.Id, StringComparer.Ordinal).FirstOrDefault(); } internal Vec2 QuestSpotNear(Vec2 centre, double min, double max, RandomStream rng) { for (int i = 0; i < 80; i++) { double num = ((i < 50) ? min : (min * (double)(80 - i) / 30.0)); double num2 = rng.NextDouble() * Math.PI * 2.0; double num3 = num + rng.NextDouble() * (max - num); Vec2 p = new Vec2(centre.X + Math.Cos(num2) * num3, centre.Y + Math.Sin(num2) * num3); if (!(p.X < 1.0) && !(p.Y < 1.0) && !(p.X > Nav.WorldWidth - 1.0) && !(p.Y > Nav.WorldHeight - 1.0) && Nav.IsPassable(p) && Nav.SameComponent(p, centre) && !State.Settlements.Any((Settlement s) => Vec2.Distance(s.Position, p) < 2.5)) { return p; } } return centre; } internal Party SpawnQuestBand(Vec2 near, string name, int size, List units, RandomStream rng) { Settlement settlement = NearestHideout(near); if (settlement == null) { return null; } Clan clan = State.Clans.Get(settlement.BanditClanId); Party party = C.SpawnBanditParty(settlement, clan, rng); party.Troops.Stacks.Clear(); if (units != null && units.Count > 0) { for (int i = 0; i < size; i++) { party.Troops.Add(units[i % units.Count], 1); } } else { List weights = clan.BanditTroops.Select((WeightedUnit w) => w.Weight).ToList(); for (int num = 0; num < size; num++) { int num2 = rng.PickWeighted(weights); if (num2 >= 0) { party.Troops.Add(clan.BanditTroops[num2].Unit, 1); } } } party.Name = name; party.Position = QuestSpotNear(near, 2.5, 5.0, rng); party.NextThinkMinute = State.Clock.Minute + 360; State.PlayerSightings[party.Id] = new Sighting { PartyId = party.Id, Position = party.Position, SeenAtMinute = State.Clock.Minute, EstimatedStrength = Campaign.EstimateCount(C.PartyCombatants(party)) }; return party; } internal static bool PartyGone(Party p) { if (p != null && p.State != PartyState.Destroyed) { return p.State == PartyState.Disbanded; } return true; } internal int HandableTroops(int minTier) { return State.PlayerParty?.Troops.Stacks.Where((TroopStack s) => (C.UnitDef(s.UnitId)?.Tier ?? 1) >= minTier).Sum((TroopStack s) => s.Healthy) ?? 0; } internal List TakeTroops(int count, int minTier, TroopRoster into) { List list = new List(); Party playerParty = State.PlayerParty; foreach (TroopStack item in (from s in playerParty.Troops.Stacks where (C.UnitDef(s.UnitId)?.Tier ?? 1) >= minTier orderby C.UnitDef(s.UnitId)?.Tier ?? 1 select s).ThenBy((TroopStack s) => s.UnitId, StringComparer.Ordinal).ToList()) { if (count <= 0) { break; } int num = Math.Min(count, item.Healthy); if (num > 0) { playerParty.Troops.RemoveHealthy(item.UnitId, num); into?.Add(item.UnitId, num); for (int num2 = 0; num2 < num; num2++) { list.Add(item.UnitId); } count -= num; } } return list; } internal int JoinPlayer(string unitId, int count) { Party playerParty = State.PlayerParty; if (playerParty == null || C.UnitDef(unitId) == null) { return 0; } int num = Math.Min(Math.Max(0, C.PartySizeLimit(playerParty) - playerParty.Troops.TotalTroops - playerParty.Troops.Heroes.Count), count); if (num > 0) { playerParty.Troops.Add(unitId, num); } return num; } internal int Skill(string skill) { return State.PlayerHero?.Skill(skill) ?? 0; } } internal sealed class RaidAiSystem { private readonly Campaign C; private CampaignRules Rules => C.Rules; private CampaignState State => C.State; internal RaidAiSystem(Campaign host) { C = host; } internal void LordRaidOptions(Party party, Clan clan, double myStrength, List<(Party party, double strength, double dist)> hostiles, List options) { if (clan == null || clan.IsEliminated || clan.IsBandit) { return; } if (!hostiles.Any(((Party party, double strength, double dist) h) => myStrength / Math.Max(0.01, h.strength) < Rules.FleeStrengthRatio)) { foreach (var item in hostiles.OrderBy(((Party party, double strength, double dist) h) => h.dist).ThenBy<(Party, double, double), string>(((Party party, double strength, double dist) h) => h.party.Id, StringComparer.Ordinal)) { Party target = item.Item1; Settlement settlement = State.Settlements.Get(target.ActiveRaid?.SettlementId ?? ""); if (settlement == null || settlement.Type != SettlementType.Village || !C.IsVillageBeingRaided(settlement)) { continue; } Clan clan2 = State.Clans.Get(settlement.OwnerClanId); if (clan2 == null || State.FactionOf(clan2) != State.FactionOf(clan)) { continue; } double num = myStrength / Math.Max(0.01, item.Item2); if (num < Rules.EngageStrengthRatio || target.DisengagedUntilMinute > State.Clock.Minute) { continue; } options.Add(new Campaign.AiOption { Task = "Defend " + settlement.Name, Score = 3.0 + Math.Min(3.0, num) / 2.0, Detail = "visible raiders " + target.Name + " at " + settlement.Name, Apply = delegate { if (party.Order.Kind != OrderKind.Engage || party.Order.TargetId != target.Id) { C.SetMoveOrder(party, OrderKind.Engage, target.Position, target.Id, "defend village"); } } }); } } if (party.Food < C.DailyFoodNeed(party) * 1.5) { return; } IOrderedEnumerable orderedEnumerable = (from s in State.Settlements where s.Type == SettlementType.Village && Vec2.Distance(party.Position, s.Position) <= C.StrategicRange(20.0) orderby Vec2.Distance(party.Position, s.Position) select s).ThenBy((Settlement s) => s.Id, StringComparer.Ordinal); int num2 = 0; HashSet hashSet = new HashSet(from p in State.Parties where p.Id != party.Id && p.Order.Kind == OrderKind.Raid && p.State != PartyState.Destroyed && p.State != PartyState.Disbanded select p.Order.TargetId ?? "", StringComparer.Ordinal); foreach (Settlement item2 in orderedEnumerable) { if (hashSet.Contains(item2.Id) || C.RaidOrderReason(party, item2).Length > 0) { continue; } Settlement target2 = item2; bool flag = party.Order.Kind == OrderKind.Raid && party.Order.TargetId == target2.Id; options.Add(new Campaign.AiOption { Task = "Raid " + target2.Name, Score = (flag ? 0.8 : (0.65 - Vec2.Distance(party.Position, target2.Position) / 2000.0 - (double)num2 * 1E-06)), Detail = "hostile village " + target2.Name + "; " + C.RaidDurationMinutes(party, target2) + " minutes exposed", Apply = delegate { if (((party.Order.Kind == OrderKind.Raid && !(party.Order.TargetId != target2.Id)) || C.SetMoveOrder(party, OrderKind.Raid, target2.Position, target2.Id, "ai raid")) && party.ActiveRaid == null && !party.Order.HasPath && Vec2.Distance(party.Position, target2.Position) <= 0.01) { C.TryStartRaid(party, target2); } } }); if (++num2 >= 4) { break; } } } } internal sealed class RaidsSystem { private readonly Campaign C; private NavGrid Nav => C.Nav; private CampaignState State => C.State; internal RaidsSystem(Campaign host) { C = host; } public int RaidDefenders(Settlement settlement) { if (settlement == null) { return 0; } long num = (long)Math.Max(0, settlement.Militia) + (long)(settlement.Garrison?.TotalHealthy ?? 0); if (settlement.Garrison != null) { num += settlement.Garrison.Heroes.Distinct().Count((string id) => State.Heroes.Get(id)?.CanFight ?? false); } return (int)Math.Min(2147483647L, num); } public int RaidDurationMinutes(Party party, Settlement settlement) { return (int)Math.Max(1.0, Math.Round((double)Math.Min(1440L, 360 + 15L * (long)RaidDefenders(settlement)) * (1.0 - Math.Max(0.0, Math.Min(0.6, C.PartyPerk(party, PerkEffect.RaidSpeed)))))); } public bool IsVillageBeingRaided(Settlement settlement) { if (settlement != null) { return State.Parties.Any((Party p) => p.State == PartyState.Active && p.ActiveRaid?.SettlementId == settlement.Id && p.Order.Kind == OrderKind.Raid && p.Order.TargetId == settlement.Id && string.IsNullOrEmpty(p.EncounterId) && Vec2.Distance(p.Position, settlement.Position) <= 0.01); } return false; } internal string RaidPartyReason(Party party, bool mustBeOnMap) { if (party == null || State.Parties.Get(party.Id) != party) { return "This party is unavailable."; } if (party.Kind != PartyKind.Player && party.Kind != PartyKind.Lord) { return "Only a warband can raid."; } if (party.State != PartyState.Active && (mustBeOnMap || party.State != PartyState.InSettlement)) { return "The warband has to be free and on the map."; } if (!string.IsNullOrEmpty(party.EncounterId)) { return "Deal with the encounter first."; } Clan clan = State.Clans.Get(party.ClanId); if (clan == null || clan.IsEliminated || clan.IsBandit) { return "The warband has no active clan."; } Hero hero = State.Heroes.Get(party.LeaderHeroId); if (hero == null || !hero.CanFight || hero.ClanId != party.ClanId || !Campaign.IsPresentPartyHero(party, hero)) { return "The warband needs a fit, free leader with it."; } if (party.Id == State.PlayerPartyId) { CommandResult commandResult = C.RequireFree(); if (!commandResult.Ok) { return commandResult.Message; } if (party.ClanId != State.PlayerClanId || hero.Id != State.PlayerHeroId) { return "You have to lead the warband yourself."; } } if (C.PartyCombatants(party) < 5) { return "You need at least 5 fit fighters to raid."; } return ""; } internal string RaidTargetReason(Party party, Settlement settlement) { if (settlement == null || State.Settlements.Get(settlement.Id) != settlement) { return "Unknown village."; } if (settlement.Type != SettlementType.Village) { return "Only villages can be raided."; } Clan clan = State.Clans.Get(settlement.OwnerClanId); if (clan == null || clan.IsEliminated || !State.AreHostile(State.Clans.Get(party.ClanId), clan)) { return "You have to be at war with the owner."; } if ((settlement.VillageRecovery?.Damage ?? 0) > 0) { return "Still recovering from the last raid."; } if (settlement.Market == null || !settlement.Market.Initialized || settlement.Market.Stock == null || party.Cargo == null) { return "The village's supplies are unavailable."; } int num = RaidDefenders(settlement); if (C.PartyCombatants(party) <= num) { return "Bring more fit fighters than the village's " + num + " defenders."; } if (State.Parties.Any((Party p) => p.Id != party.Id && p.ActiveRaid?.SettlementId == settlement.Id)) { return "Someone's already raiding it."; } return ""; } public string RaidOrderReason(Party party, Settlement settlement) { string text = RaidPartyReason(party, mustBeOnMap: false); if (text.Length > 0) { return text; } text = RaidTargetReason(party, settlement); if (text.Length > 0) { return text; } if (!Nav.Reaches(party.Position, settlement.Position, 0.01)) { return "You can't get there."; } return ""; } public string RaidReason(string settlementId) { string text = C.CargoCommandReason(); if (text.Length > 0) { return text; } Party playerParty = State.PlayerParty; if (playerParty.Order.Kind == OrderKind.Raid && playerParty.Order.TargetId == settlementId) { if (playerParty.ActiveRaid != null) { return "Already raiding it."; } return "Already on the way to raid it."; } return RaidOrderReason(playerParty, State.Settlements.Get(settlementId)); } public CommandResult RaidVillage(string settlementId) { string text = RaidReason(settlementId); if (text.Length > 0) { return CommandResult.Fail(text); } Settlement settlement = State.Settlements.Require(settlementId); Party playerParty = State.PlayerParty; if (!C.SetMoveOrder(playerParty, OrderKind.Raid, settlement.Position, settlement.Id, "raid")) { return CommandResult.Fail("You can't get there."); } State.Player.WaitUntilMinute = 0L; C.UpdatePlayerTimeStates(); C.ResumeIfPaused(); State.Touch(); return CommandResult.Success("Marching to raid " + settlement.Name + "."); } public string RaidStartReason(Party party, Settlement settlement) { string text = RaidPartyReason(party, mustBeOnMap: true); if (text.Length > 0) { return text; } if (party.ActiveRaid != null) { return "This warband is already raiding."; } text = RaidTargetReason(party, settlement); if (text.Length > 0) { return text; } if (party.Order.Kind != OrderKind.Raid || party.Order.TargetId != settlement.Id) { return "Order the raid first."; } if (party.Order.HasPath || Vec2.Distance(party.Position, settlement.Position) > 0.01) { return "Get to the village first."; } return ""; } public CommandResult TryStartRaid(Party party, Settlement settlement) { string text = RaidStartReason(party, settlement); if (text.Length > 0) { return CommandResult.Fail(text); } party.ActiveRaid = new RaidState { SettlementId = settlement.Id, OwnerClanId = settlement.OwnerClanId, StartedAtMinute = State.Clock.Minute, LastProgressMinute = State.Clock.Minute, RequiredMinutes = RaidDurationMinutes(party, settlement) }; if (party.Id == State.PlayerPartyId) { C.RecordPlayerVillageRaid(settlement); NotableState notableState = C.SettlementNotable(settlement.Id); if (notableState != null) { C.AdjustNotableRelation(notableState.Id, -10, "raiding their village"); } State.Player.Activity = PlayerActivity.Raiding; } State.AddLog(LogCategory.Battle, party.Name + " began raiding " + settlement.Name + ".", party.Id, settlement.Id); State.Touch(); return CommandResult.Success("Raiding " + settlement.Name + "."); } public void CancelRaid(Party party, string reason, bool notify = true) { if (party == null || (party.ActiveRaid == null && party.Order.Kind != OrderKind.Raid)) { return; } RaidState activeRaid = party.ActiveRaid; string text = activeRaid?.SettlementId ?? party.Order.TargetId; party.ActiveRaid = null; if (party.Order.Kind == OrderKind.Raid) { party.Order = new MovementOrder(); } Settlement settlement = State.Settlements.Get(text); string text2 = party.Name + ((activeRaid == null) ? " abandoned the raid on " : " stopped raiding ") + (settlement?.Name ?? "the village") + ": " + reason + "."; State.AddLog(LogCategory.Battle, text2, party.Id, text); if (party.Id == State.PlayerPartyId) { C.UpdatePlayerTimeStates(); if (notify) { C.Raise(CampaignEventKind.Warning, text2, false, text); } } party.NextThinkMinute = Math.Min(party.NextThinkMinute, State.Clock.Minute); State.Touch(); } internal string RaidContinuationReason(Party party, Settlement settlement) { string text = RaidPartyReason(party, mustBeOnMap: true); if (text.Length > 0) { return text; } if (settlement == null || settlement.OwnerClanId != party.ActiveRaid.OwnerClanId) { return "the village changed hands"; } text = RaidTargetReason(party, settlement); if (text.Length > 0) { return text; } if (party.Order.Kind != OrderKind.Raid || party.Order.TargetId != settlement.Id || party.Order.HasPath || Vec2.Distance(party.Position, settlement.Position) > 0.01) { return "the warband left the village"; } return ""; } public void UpdateRaids(bool advanceProgress = true) { foreach (Party item in State.Parties.Where((Party p) => p.ActiveRaid == null && p.Order.Kind == OrderKind.Raid).ToList()) { string text = RaidPartyReason(item, mustBeOnMap: true); Settlement settlement = State.Settlements.Get(item.Order.TargetId); if (text.Length == 0) { text = RaidTargetReason(item, settlement); } if (text.Length > 0) { CancelRaid(item, text); } else if (advanceProgress && !item.Order.HasPath && Vec2.Distance(item.Position, settlement.Position) <= 0.01) { TryStartRaid(item, settlement); } } foreach (Party item2 in State.Parties.Where((Party p) => p.ActiveRaid != null).ToList()) { RaidState activeRaid = item2.ActiveRaid; Settlement settlement2 = State.Settlements.Get(activeRaid.SettlementId); string text2 = RaidContinuationReason(item2, settlement2); if (text2.Length > 0) { CancelRaid(item2, text2); } else { if (!advanceProgress) { continue; } long num = State.Clock.Minute - activeRaid.LastProgressMinute; if (num > 0) { activeRaid.ProgressMinutes += (int)Math.Min(num, Math.Max(0, activeRaid.RequiredMinutes - activeRaid.ProgressMinutes)); activeRaid.LastProgressMinute = State.Clock.Minute; State.Touch(); if (activeRaid.ProgressMinutes >= activeRaid.RequiredMinutes) { CompleteRaid(item2, settlement2); } } } } } internal void CompleteRaid(Party party, Settlement settlement) { if (party?.Id == State.PlayerPartyId) { C.CompanionsReactToRaid(settlement); C.TrainRoguery(40.0); } Clan clan = State.Clans.Get(party.ClanId); long num = Math.Min((long)Math.Round(100.0 * (1.0 + Math.Max(0.0, C.PartyPerk(party, PerkEffect.RaidLoot)))), Math.Min(Math.Max(0L, settlement.Market.Gold), long.MaxValue - clan.Gold)); double num2 = Math.Min(20.0, C.SettlementFood(settlement)); double num3 = party.Food + num2 - party.Food; if (double.IsInfinity(num3) || double.IsNaN(num3) || num3 < 0.0 || num3 > num2) { num3 = 0.0; } string goodId = C.PrimaryVillageGood(settlement); TradeGoodDef tradeGoodDef = TradeGoods.All.First((TradeGoodDef g) => g.Id == goodId); int num4 = C.CargoCount(party, goodId); int val = Math.Min((int)Math.Min(5.0, Math.Max(0.0, Math.Floor((C.CargoCapacity(party) - C.CargoWeight(party)) / tradeGoodDef.Weight))), Math.Min(C.MarketStock(settlement, goodId), int.MaxValue - num4)); if (num > 0) { settlement.Market.Gold -= num; State.Transact(clan, num, LedgerAccount.Loot, "Village raid at " + settlement.Name); } if (num3 > 0.0) { party.Food += C.TakeSettlementFood(settlement, num3); } val = Math.Min(val, C.MarketStock(settlement, goodId)); if (val > 0) { settlement.Market.Stock[goodId] -= val; party.Cargo[goodId] = num4 + val; } double num5 = C.SettlementFood(settlement); if (num5 > 0.0) { C.SetSettlementFood(settlement, 0.0); } C.ApplyVillageRaidDamage(settlement, party.Id == State.PlayerPartyId); if (party.Id == State.PlayerPartyId) { C.AddCrime(C.CrimeFactionOf(settlement), 18.0, "raiding " + settlement.Name, settlement.Id); } if (party.Id == State.PlayerPartyId) { C.RecordQuestRaid(settlement); } party.ActiveRaid = null; party.Order = new MovementOrder(); party.NextThinkMinute = State.Clock.Minute; string text = party.Name + " raided " + settlement.Name + ": " + num + " denars, " + num3.ToString("0.#") + " food, " + val + " " + tradeGoodDef.Name + ((num5 >= 1.0) ? ("; " + Math.Floor(num5).ToString("0") + " food burned") : "") + "."; State.AddLog(LogCategory.Battle, text, party.Id, settlement.Id); if (party.Id == State.PlayerPartyId) { State.Player.WaitUntilMinute = 0L; C.UpdatePlayerTimeStates(); C.Raise(CampaignEventKind.Info, text, true, settlement.Id); } State.Touch(); } } internal sealed class RebellionsSystem { private readonly Campaign C; private ContentDatabase Content => C.Content; private CampaignState State => C.State; public bool RebellionsEnabled => C.Settings.Rebellions; internal RebellionsSystem(Campaign host) { C = host; } public void EnsureRebellionFields() { bool flag = false; if (State.Rebellions == null) { State.Rebellions = new RebellionState(); flag = true; } RebellionState rebellions = State.Rebellions; if (rebellions.Records == null) { rebellions.Records = new List(); flag = true; } if (!rebellions.Initialized) { rebellions.Initialized = true; rebellions.LastDay = State.Clock.Day; flag = true; } foreach (Settlement settlement in State.Settlements) { if (double.IsNaN(settlement.Unrest) || double.IsInfinity(settlement.Unrest) || settlement.Unrest < 0.0) { settlement.Unrest = 0.0; flag = true; } } if (flag) { State.Touch(); } } public CommandResult SetRebellionsEnabled(bool on) { C.Settings.Rebellions = on; State.AddLog(LogCategory.Info, "Rebellions: " + (on ? "on." : "off.")); State.Touch(); return CommandResult.Success(on ? "Rebellions are on: disloyal towns and castles may rise." : "Rebellions are off: no town or castle will rise (those already in revolt carry on)."); } internal static bool Fortified(Settlement s) { if (s != null) { if (s.Type != SettlementType.Town) { return s.Type == SettlementType.Castle; } return true; } return false; } public double UnrestRate(Settlement s) { if (!C.LawAt(s, KingdomLaw.Bailiffs)) { return 1.0; } return 0.5; } public RebellionRecord RebellionOf(string clanId) { return State.Rebellions?.Records?.FirstOrDefault((RebellionRecord r) => r.ClanId == clanId); } public bool IsRebelClan(string clanId) { return RebellionOf(clanId) != null; } public string RebellionRiskReason(Settlement s) { if (!Fortified(s)) { return "Only towns and castles rise."; } Clan clan = State.Clans.Get(s.OwnerClanId); if (clan == null || clan.IsBandit || clan.IsEliminated) { return "Nobody holds it."; } if (s.Loyalty >= 25.0) { return "Loyal enough (" + 25.0.ToString("0") + " or more)."; } if (s.Unrest < 7.0) { return "Unrest is building (" + s.Unrest.ToString("0.#") + " of " + 7.0.ToString("0") + " days)."; } if (C.SiegeForSettlement(s.Id) != null) { return "Under siege."; } if (OrderKeptBy(s) != null) { return OrderKeptBy(s).Name + " keeps order there."; } if (s.Garrison.TotalHealthy >= s.Militia) { return "The garrison (" + s.Garrison.TotalHealthy + ") is a match for the militia (" + s.Militia + ")."; } if (!C.Settings.Rebellions) { return "Rebellions are off in this campaign."; } return ""; } internal Party OrderKeptBy(Settlement s) { string faction = State.FactionOf(State.Clans.Get(s.OwnerClanId)); return State.Parties.FirstOrDefault((Party p) => p.State == PartyState.InSettlement && p.CurrentSettlementId == s.Id && (p.Id == State.PlayerPartyId || ((p.Kind == PartyKind.Lord || p.Kind == PartyKind.Player) && State.FactionOfParty(p) == faction))); } internal void DailyRebellions() { RebellionState rebellions = State.Rebellions; if (rebellions == null || !rebellions.Initialized || rebellions.LastDay >= State.Clock.Day) { return; } rebellions.LastDay = State.Clock.Day; State.Touch(); RandomStream randomStream = State.Random.Get("rebellions"); foreach (Settlement item in State.Settlements.Where(Fortified).OrderBy((Settlement s) => s.Id, StringComparer.Ordinal).ToList()) { if (item.Loyalty < 25.0) { item.Unrest = Math.Min(30.0, item.Unrest + UnrestRate(item)); } else { item.Unrest = Math.Max(0.0, item.Unrest - 2.0); } if (RebellionRiskReason(item).Length <= 0 && !C.DiplomacyFactionReserved(State.FactionOf(State.Clans.Get(item.OwnerClanId))) && randomStream.Chance(0.35)) { StartRebellion(item, randomStream); } } foreach (RebellionRecord item2 in rebellions.Records.Where((RebellionRecord x) => x.Outcome == RebellionOutcome.Holding).ToList()) { AdvanceRebellion(item2); } } internal RebellionRecord StartRebellion(Settlement s, RandomStream rng) { Clan owner = State.Clans.Require(s.OwnerClanId); string text = State.FactionOf(owner); CultureDef cultureDef = Content.Cultures.Get(s.CultureId) ?? Content.Cultures.Get(owner.CultureId); string cultureId = cultureDef?.Id ?? owner.CultureId; string id; do { id = State.Ids.Allocate("clan.rebels"); } while (State.Clans.Contains(id) || State.Kingdoms.Contains(id)); Clan clan = new Clan { Id = id, Name = RebelClanName(s, cultureDef), CultureId = cultureId, KingdomId = "", Gold = 1500 + (long)Math.Max(0.0, s.Prosperity), Renown = 50.0, Influence = 0.0, Color = (cultureDef?.Color ?? "#7a2b2b"), Symbol = (cultureDef?.Symbol ?? "✊") }; State.Clans.Add(clan); HashSet taken = new HashSet(State.Heroes.Select((Hero h) => h.Name), StringComparer.Ordinal); if (State.Families != null && State.Families.ClanSurnames != null) { State.Families.ClanSurnames[clan.Id] = Wanderers.Surname(cultureId, StableHash.Fnv1a64("rebel surname|" + clan.Id)); } Hero hero = C.NewKin(clan, rng.Chance(0.7) ? HeroSex.Male : HeroSex.Female, rng.Range(28, 46), s, rng, taken, grown: true, cultureId); hero.Level = 8; clan.LeaderHeroId = hero.Id; int num = rng.Range(1, 3); for (int num2 = 0; num2 < num; num2++) { C.NewKin(clan, rng.Chance(0.6) ? HeroSex.Male : HeroSex.Female, rng.Range(19, 40), s, rng, taken, grown: true, cultureId); } int totalTroops = s.Garrison.TotalTroops; s.Garrison.Stacks.Clear(); int num3 = Math.Max(12, s.Militia); List list = cultureDef?.TownRecruits ?? new List(); int num4 = (int)Math.Round((double)num3 * 0.6); for (int num5 = 0; num5 < num4; num5++) { int num6 = ((list.Count == 0) ? (-1) : rng.PickWeighted(list.Select((WeightedUnit w) => w.Weight).ToList())); string text2 = ((num6 >= 0) ? list[num6].Unit : cultureDef?.BasicTroop); if (!string.IsNullOrEmpty(text2) && C.UnitDef(text2) != null) { s.Garrison.Add(text2, 1); } } s.Militia = Math.Max(0, s.Militia - num4); List list2 = State.Settlements.Where((Settlement x) => x.Id == s.Id || (x.Type == SettlementType.Village && x.BoundTo == s.Id && x.OwnerClanId == owner.Id)).ToList(); foreach (Settlement item in list2) { C.ChangeSettlementOwner(item, clan.Id); } s.Loyalty = 65.0; s.Security = Math.Max(30.0, s.Security); s.Unrest = 0.0; Party party = C.CreateLordParty(hero, s); foreach (TroopStack item2 in s.Garrison.Stacks.OrderByDescending((TroopStack x) => C.UnitDef(x.UnitId)?.Tier ?? 1).ThenBy((TroopStack x) => x.UnitId, StringComparer.Ordinal).ToList()) { int num7 = Math.Min(item2.Healthy, Math.Max(0, s.Garrison.TotalHealthy - num4 / 2)); if (num7 <= 0) { break; } s.Garrison.RemoveHealthy(item2.UnitId, num7); party.Troops.Add(item2.UnitId, num7); } if (C.PartyCombatants(party) < 3 && !string.IsNullOrEmpty(cultureDef?.BasicTroop)) { party.Troops.Add(cultureDef.BasicTroop, 8); } State.SetStance(clan.Id, text, Stance.War); C.AdjustClanRelation(clan.Id, owner.Id, -50); Clan clan2 = ((State.Kingdoms.Get(text) != null) ? C.ServiceRuler(text) : null); if (clan2 != null && clan2.Id != owner.Id) { C.AdjustClanRelation(clan.Id, clan2.Id, -30); } RebellionRecord rebellionRecord = new RebellionRecord { Id = State.Ids.Allocate("rebellion"), ClanId = clan.Id, SettlementId = s.Id, FormerOwnerClanId = owner.Id, FormerFactionId = text, RoseDay = State.Clock.Day, Outcome = RebellionOutcome.Holding }; State.Rebellions.Records.Add(rebellionRecord); string text3 = s.Name + " has risen against " + owner.Name + "! " + hero.Name + " leads " + clan.Name + ", who now hold " + s.Name + ((list2.Count > 1) ? " and its villages" : "") + " and are at war with " + C.DiplomacyFactionName(text) + "." + ((totalTroops > 0) ? (" The garrison of " + totalTroops + " was cut down.") : ""); State.AddLog(LogCategory.Politics, text3, s.Id, clan.Id, owner.Id); bool flag = owner.Id == State.PlayerClanId || text == State.FactionOf(State.PlayerClan); C.Raise(flag ? CampaignEventKind.Warning : CampaignEventKind.Info, text3, owner.Id == State.PlayerClanId, s.Id, clan.Id); C.OnDiplomacyChanged(); State.Touch(); return rebellionRecord; } internal string RebelClanName(Settlement s, CultureDef culture) { string name = s.Name + " Rebels"; int num = 2; while (State.Clans.Any((Clan c) => c.Name == name)) { name = s.Name + " Rebels " + num; num++; } return name; } internal void AdvanceRebellion(RebellionRecord record) { Clan clan = State.Clans.Get(record.ClanId); if (clan == null || clan.IsEliminated) { EndRebellion(record, RebellionOutcome.Crushed, ""); } else if (!string.IsNullOrEmpty(clan.KingdomId)) { EndRebellion(record, RebellionOutcome.JoinedKingdom, clan.KingdomId); } else { if (C.DiplomacyFactionReserved(clan.Id) || C.DiplomacyFactionReserved(record.FormerFactionId)) { return; } if (!State.Settlements.Any((Settlement s) => Fortified(s) && s.OwnerClanId == clan.Id) && SiegeForClan(clan.Id) == null) { CrushRebellion(record, clan); return; } long num = State.Clock.Day - record.RoseDay; if (num >= 30) { Settlement home = State.Settlements.Where((Settlement s) => Fortified(s) && s.OwnerClanId == clan.Id).OrderBy((Settlement s) => s.Id, StringComparer.Ordinal).FirstOrDefault(); Kingdom kingdom = (from k in State.Kingdoms where !k.IsEliminated && k.CultureId == clan.CultureId && k.Id != record.FormerFactionId && k.RulerClanId != State.PlayerClanId && C.LivingDiplomacyRuler(k.Id) != null && !C.DiplomacyFactionReserved(k.Id) orderby (home != null) ? (from s in State.Settlements where Fortified(s) && State.Clans.Get(s.OwnerClanId)?.KingdomId == k.Id select Vec2.Distance(s.Position, home.Position)).DefaultIfEmpty(double.MaxValue).Min() : 0.0 select k).ThenBy((Kingdom k) => k.Id, StringComparer.Ordinal).FirstOrDefault(); if (kingdom != null) { C.ClearClanIndependentDiplomacy(clan.Id); clan.KingdomId = kingdom.Id; clan.Influence = 0.0; C.RecordClanAllegiance(clan, "", kingdom.RulerClanId, ClanAllegianceChange.Swore, 0L); C.AdjustClanRelation(clan.Id, kingdom.RulerClanId, 20); string text = clan.Name + " of " + (home?.Name ?? "the rebellion") + " swore fealty to " + kingdom.Name + ", bringing " + (home?.Name ?? "their holdings") + " into the realm" + (State.AtWar(kingdom.Id, record.FormerFactionId) ? (", already at war with " + C.DiplomacyFactionName(record.FormerFactionId) + ".") : "."); State.AddLog(LogCategory.Politics, text, clan.Id, kingdom.Id); C.Raise(CampaignEventKind.Info, text, false, clan.Id, kingdom.Id); EndRebellion(record, RebellionOutcome.JoinedKingdom, kingdom.Id); C.OnDiplomacyChanged(); return; } } if (num >= 60 && record.FormerFactionId != State.FactionOf(State.PlayerClan) && State.AtWar(clan.Id, record.FormerFactionId)) { State.SetStance(clan.Id, record.FormerFactionId, Stance.Peace); C.AddDiplomacyTruce(clan.Id, record.FormerFactionId, "", "", 0L); string text2 = C.DiplomacyFactionName(record.FormerFactionId) + " recognised " + clan.Name + " after " + num + " days of rebellion; they are at peace."; State.AddLog(LogCategory.Politics, text2, clan.Id, record.FormerFactionId); EndRebellion(record, RebellionOutcome.Recognised, ""); C.OnDiplomacyChanged(); } } } internal SiegeState SiegeForClan(string clanId) { return State.Sieges.FirstOrDefault((SiegeState s) => s.Stage != SiegeStage.Ended && State.Settlements.Get(s.SettlementId)?.OwnerClanId == clanId); } internal void EndRebellion(RebellionRecord record, RebellionOutcome outcome, string kingdomId) { record.Outcome = outcome; record.EndedDay = State.Clock.Day; record.KingdomId = kingdomId ?? ""; State.Touch(); } internal void CrushRebellion(RebellionRecord record, Clan clan) { foreach (Settlement item in State.Settlements.Where((Settlement s) => s.OwnerClanId == clan.Id && !Fortified(s)).ToList()) { Settlement settlement = State.Settlements.Get(item.BoundTo); Clan clan2 = State.Clans.Get(settlement?.OwnerClanId ?? ""); if (clan2 == null || clan2.IsEliminated || clan2.IsBandit || clan2.Id == clan.Id) { clan2 = State.Clans.Get(record.FormerOwnerClanId); } if (clan2 != null && !clan2.IsEliminated && !clan2.IsBandit) { C.ChangeSettlementOwner(item, clan2.Id); } } foreach (Party item2 in State.Parties.Where((Party p) => p.ClanId == clan.Id && p.Kind == PartyKind.Lord && p.State != PartyState.Destroyed && p.State != PartyState.Disbanded && string.IsNullOrEmpty(p.EncounterId)).ToList()) { C.DisbandLordParty(item2, "the rebellion was crushed"); } foreach (Hero item3 in State.Heroes.Where((Hero h) => h.ClanId == clan.Id && (h.State == HeroState.Active || h.State == HeroState.Inactive)).ToList()) { C.HeroDies(item3, "in exile"); } clan.IsEliminated = true; C.ClearClanIndependentDiplomacy(clan.Id); string text = "The rebellion of " + (State.Settlements.Get(record.SettlementId)?.Name ?? clan.Name) + " has been crushed; " + clan.Name + " are no more. Their surviving lords fled into exile."; State.AddLog(LogCategory.Politics, text, clan.Id, record.SettlementId); C.Raise(CampaignEventKind.Info, text, false, record.SettlementId); EndRebellion(record, RebellionOutcome.Crushed, ""); C.OnDiplomacyChanged(); } public CommandResult DeveloperStartRebellion(string settlementId) { string text = C.DeveloperCampaignReason(); if (text.Length > 0) { return CommandResult.Fail(text); } Settlement settlement = State.Settlements.Get(settlementId); if (!Fortified(settlement)) { return CommandResult.Fail("Choose a town or castle."); } Clan clan = State.Clans.Get(settlement.OwnerClanId); if (clan == null || clan.IsBandit || clan.IsEliminated) { return CommandResult.Fail("Nobody holds " + settlement.Name + "."); } if (C.SiegeForSettlement(settlement.Id) != null) { return CommandResult.Fail(settlement.Name + " is under siege."); } if (State.PlayerParty?.CurrentSettlementId == settlement.Id && State.PlayerParty.State == PartyState.InSettlement) { return CommandResult.Fail("Leave " + settlement.Name + " first."); } if (C.DiplomacyFactionReserved(State.FactionOf(clan))) { return CommandResult.Fail("Wait for " + clan.Name + "'s battles to finish."); } if (State.Rebellions == null || !State.Rebellions.Initialized) { EnsureRebellionFields(); } RebellionRecord rebellionRecord = StartRebellion(settlement, State.Random.Get("rebellions")); return CommandResult.Success("Developer: " + settlement.Name + " rose; " + State.Clans.Get(rebellionRecord.ClanId).Name + " hold it."); } } internal sealed class RescuedTroopsSystem { private readonly Campaign C; private CampaignState State => C.State; internal RescuedTroopsSystem(Campaign host) { C = host; } internal string RescuedTroopActionReason(string encounterId, string unitId, int count) { BattleReport lastReport = State.Player.LastReport; if (lastReport == null || State.Player.LastReportSeen || string.IsNullOrEmpty(encounterId) || lastReport.EncounterId != encounterId || !State.CommittedEncounters.Contains(encounterId)) { return "That offer's gone."; } if (!lastReport.PlayerWon || lastReport.PlayerCaptured || (lastReport.EndKind != BattleEndKind.Victory && lastReport.EndKind != BattleEndKind.Surrender)) { return "This battle has no rescue offer."; } if (RescueValidation.Check(State).Count > 0) { return "This battle has invalid rescue records."; } CommandResult commandResult = C.RequireFree(); if (!commandResult.Ok) { return commandResult.Message; } Party playerParty = State.PlayerParty; Hero hero = State.PlayerHero; if (playerParty.State != PartyState.Active || playerParty.ClanId != State.PlayerClanId || State.PlayerClan == null || hero == null || hero.State != HeroState.Active || !Campaign.IsPresentPartyHero(playerParty, hero) || playerParty.Troops.Heroes.Count((string id) => id == hero.Id) != 1) { return "You have to be with your warband to decide."; } if (!string.IsNullOrEmpty(State.Player.PendingEncounterId) || !string.IsNullOrEmpty(playerParty.EncounterId) || C.MilitaryPartyReserved(playerParty.Id)) { return "Deal with the encounter first."; } if (lastReport.RescueMinute != State.Clock.Minute || !RescueFinitePosition(lastReport.RescuePosition) || !RescueFinitePosition(playerParty.Position) || Vec2.Distance(lastReport.RescuePosition, playerParty.Position) > 0.01) { return "The rescued troops have moved on."; } if (count <= 0) { return "Pick at least one."; } if (string.IsNullOrEmpty(unitId) || C.UnitDef(unitId) == null) { return "Unknown rescued troop type."; } string text = RescueRosterReason(lastReport.RescuedTroops, rescued: true); if (text.Length > 0) { return text; } long num = lastReport.RescuedTroops.Stacks.Sum((TroopStack s) => (long)s.Healthy + (long)s.Wounded); if (lastReport.RescuedRecruited < 0 || lastReport.RescuedReleased < 0 || num + lastReport.RescuedRecruited + lastReport.RescuedReleased > int.MaxValue) { return "The rescue offer has invalid totals."; } TroopStack troopStack = lastReport.RescuedTroops.Find(unitId); if (troopStack != null && troopStack.Total >= count) { return ""; } return "Not that many of that type left."; } internal static bool RescueFinitePosition(Vec2 position) { if (!double.IsNaN(position.X) && !double.IsInfinity(position.X) && !double.IsNaN(position.Y)) { return !double.IsInfinity(position.Y); } return false; } internal string RescueRosterReason(TroopRoster roster, bool rescued) { if (roster?.Stacks == null || roster.Heroes == null || (rescued && roster.Heroes.Count != 0)) { return "Invalid rescued troop roster."; } HashSet hashSet = new HashSet(StringComparer.Ordinal); long num = 0L; foreach (TroopStack stack in roster.Stacks) { if (stack == null || string.IsNullOrEmpty(stack.UnitId) || C.UnitDef(stack.UnitId) == null || !hashSet.Add(stack.UnitId) || stack.Healthy < 0 || stack.Wounded < 0 || stack.Xp < 0 || (long)stack.Healthy + (long)stack.Wounded <= 0 || double.IsNaN(stack.PrisonerRecruitment) || double.IsInfinity(stack.PrisonerRecruitment) || stack.PrisonerRecruitment != 0.0) { return "The troop roster has invalid counts or training records."; } num += (long)stack.Healthy + (long)stack.Wounded; if (num > int.MaxValue) { return "The troop roster exceeds its supported capacity."; } } return ""; } public string RescuedTroopRecruitmentReason(string encounterId, string unitId, int count) { string text = RescuedTroopActionReason(encounterId, unitId, count); if (text.Length > 0) { return text; } UnitDef unitDef = C.UnitDef(unitId); if (unitDef.Rarity == UnitRarity.Unique || unitDef.Access == null || !unitDef.Access.Any((AccessKind a) => a == AccessKind.VillageRecruit || a == AccessKind.TownRecruit || a == AccessKind.Upgrade || a == AccessKind.Mercenary || a == AccessKind.Bandit)) { return "These troops can't join an ordinary warband."; } Party playerParty = State.PlayerParty; text = RescueRosterReason(playerParty.Troops, rescued: false); if (text.Length > 0) { return text; } if ((long)playerParty.Troops.TotalTroops + (long)count > C.PartySizeLimit(playerParty)) { return "Not enough room in your party."; } TroopStack source = State.Player.LastReport.RescuedTroops.Find(unitId); TroopStack troopStack = playerParty.Troops.Find(unitId); int num = RescuedTroopXp(source, count); if ((long)(troopStack?.Xp ?? 0) + (long)num > int.MaxValue || (long)(troopStack?.Total ?? 0) + (long)count > int.MaxValue) { return "Your troop stack cannot hold that much training or manpower."; } return ""; } internal static int RescuedTroopXp(TroopStack source, int count) { return source.Xp - (int)Math.Round((double)source.Xp * (double)(source.Total - count) / (double)source.Total); } public CommandResult RecruitRescuedTroops(string encounterId, string unitId, int count) { string text = RescuedTroopRecruitmentReason(encounterId, unitId, count); if (text.Length > 0) { return CommandResult.Fail(text); } BattleReport lastReport = State.Player.LastReport; TroopStack troopStack = lastReport.RescuedTroops.Find(unitId); int num = Math.Min(count, troopStack.Healthy); int wounded = count - num; int xp = RescuedTroopXp(troopStack, count); lastReport.RescuedTroops.Remove(unitId, count); State.PlayerParty.Troops.Add(unitId, num, wounded, xp); lastReport.RescuedRecruited += count; State.Touch(); return CommandResult.Success($"{count} rescued {C.UnitDef(unitId).Name} joined your warband."); } public string RescuedTroopReleaseReason(string encounterId, string unitId, int count) { return RescuedTroopActionReason(encounterId, unitId, count); } public CommandResult ReleaseRescuedTroops(string encounterId, string unitId, int count) { string text = RescuedTroopReleaseReason(encounterId, unitId, count); if (text.Length > 0) { return CommandResult.Fail(text); } BattleReport lastReport = State.Player.LastReport; lastReport.RescuedTroops.Remove(unitId, count); lastReport.RescuedReleased += count; State.Touch(); return CommandResult.Success($"Released {count} rescued {C.UnitDef(unitId).Name}."); } } public sealed class ScoutOffer { public int Index; public string Name = ""; public int Rating; public long Price; } internal sealed class ScoutingSystem { private readonly Campaign C; internal const int OffersPerTavern = 3; internal const int MaximumRating = 5; internal const int MaximumMissions = 6; internal const double ScoutSpeed = 7.0; internal const double WatchHours = 6.0; private static readonly long[] Prices = new long[6] { 0L, 45L, 110L, 200L, 320L, 480L }; private static readonly double[] Spread = new double[6] { 0.0, 0.45, 0.3, 0.18, 0.1, 0.04 }; private CampaignState State => C.State; private long Week => State.Clock.Day / 7; internal ScoutingSystem(Campaign host) { C = host; } internal void EnsureScoutingFields() { if (State.Scouting == null) { State.Scouting = new ScoutingState(); } ScoutingState scouting = State.Scouting; if (scouting.Missions == null) { scouting.Missions = new List(); } if (scouting.Reports == null) { scouting.Reports = new SortedDictionary(StringComparer.Ordinal); } if (scouting.Hired == null) { scouting.Hired = new SortedSet(StringComparer.Ordinal); } foreach (ScoutReportState item in scouting.Reports.Values.Concat(scouting.Missions.Select((ScoutMissionState m) => m.Report))) { if (item != null && item.Units == null) { item.Units = new List(); } } } private static string OfferKey(string townId, long week, int index) { return townId + "|" + week.ToString(CultureInfo.InvariantCulture) + "|" + index.ToString(CultureInfo.InvariantCulture); } private RandomStream Stream(string name) { return new RandomStream("scouting|" + name, StableHash.Fnv1a64(State.CampaignId ?? "")); } public List ScoutOffers(Settlement town) { List list = new List(); if (town == null || town.Type != SettlementType.Town) { return list; } long week = Week; RandomStream randomStream = Stream(town.Id + "|" + week.ToString(CultureInfo.InvariantCulture)); HashSet hashSet = new HashSet(StringComparer.Ordinal); for (int i = 0; i < 3; i++) { int num = 1 + randomStream.PickWeighted(new double[5] { 20.0, 30.0, 28.0, 15.0, 7.0 }); HeroSex sex = ((!randomStream.Chance(0.3)) ? HeroSex.Male : HeroSex.Female); string text = Families.Name(town.CultureId, sex, "", randomStream, hashSet); hashSet.Add(text); long price = (long)Math.Round((double)Prices[num] * randomStream.Range(0.9, 1.15) / 5.0) * 5; if (!State.Scouting.Hired.Contains(OfferKey(town.Id, week, i))) { list.Add(new ScoutOffer { Index = i, Name = text, Rating = num, Price = price }); } } return list; } public IEnumerable ScoutTargets() { return (from s in State.Settlements where (s.Type == SettlementType.Town || s.Type == SettlementType.Castle) && !IsOwnRealm(s) orderby Vec2.Distance(s.Position, State.PlayerParty?.Position ?? s.Position) select s).ThenBy((Settlement s) => s.Id, StringComparer.Ordinal); } private bool IsOwnRealm(Settlement s) { Clan clan = State.Clans.Get(s.OwnerClanId); if (clan != null) { return State.FactionOf(clan) == State.FactionOf(State.PlayerClan); } return false; } private Settlement Tavern() { Settlement settlement = C.CurrentSettlement(); if (settlement == null || settlement.Type != SettlementType.Town) { return null; } return settlement; } public string ScoutHireReason(int index, string targetId) { CommandResult commandResult = C.RequireFree(); if (!commandResult.Ok) { return commandResult.Message; } Settlement settlement = Tavern(); if (settlement == null) { return "Scouts are hired in a town's tavern."; } ScoutOffer scoutOffer = ScoutOffers(settlement).FirstOrDefault((ScoutOffer o) => o.Index == index); if (scoutOffer == null) { return "That scout has already been hired."; } Settlement target = State.Settlements.Get(targetId ?? ""); if (target == null) { return "Choose a town or castle to scout."; } if (target.Type != SettlementType.Town && target.Type != SettlementType.Castle) { return "Scouts look over towns and castles."; } if (IsOwnRealm(target)) { return target.Name + " is your own realm's; its stewards can tell you all about it."; } if (State.Scouting.Missions.Count((ScoutMissionState m) => m.TargetId == target.Id) > 0) { return "A scout is already on the way to " + target.Name + "."; } if (State.Scouting.Missions.Count >= 6) { return "You already have " + 6 + " scouts out."; } if (State.PlayerClan.Gold < scoutOffer.Price) { return "You need " + scoutOffer.Price.ToString("N0", CultureInfo.InvariantCulture) + " denars."; } return ""; } public long ScoutTravelMinutes(Settlement from, Settlement target) { if (from != null && target != null) { return (long)Math.Ceiling(Vec2.Distance(from.Position, target.Position) / 7.0 * 60.0); } return 0L; } public CommandResult HireScout(int index, string targetId) { string text = ScoutHireReason(index, targetId); if (text.Length > 0) { return CommandResult.Fail(text); } Settlement settlement = Tavern(); ScoutOffer scoutOffer = ScoutOffers(settlement).First((ScoutOffer o) => o.Index == index); Settlement settlement2 = State.Settlements.Get(targetId); long minute = State.Clock.Minute; long num = Math.Max(60L, ScoutTravelMinutes(settlement, settlement2)); ScoutMissionState scoutMissionState = new ScoutMissionState { Id = State.Ids.Allocate("scout"), ScoutName = scoutOffer.Name, Rating = scoutOffer.Rating, Price = scoutOffer.Price, TownId = settlement.Id, TargetId = settlement2.Id, HiredMinute = minute, ObserveMinute = minute + num + 360, ReturnMinute = minute + num * 2 + 360 }; State.Transact(State.PlayerClan, -scoutOffer.Price, LedgerAccount.Scouting, "Scout sent to " + settlement2.Name); State.Scouting.Missions.Add(scoutMissionState); string week = "|" + Week.ToString(CultureInfo.InvariantCulture) + "|"; State.Scouting.Hired.RemoveWhere((string k) => !k.Contains(week)); State.Scouting.Hired.Add(OfferKey(settlement.Id, Week, index)); string text2 = scoutOffer.Name + " rides for " + settlement2.Name + ". Expect word in about " + Hours(scoutMissionState.ReturnMinute - minute) + "."; State.AddLog(LogCategory.Info, text2, settlement2.Id); State.Touch(); return CommandResult.Success(text2); } private static string Hours(long minutes) { long num = Math.Max(1L, (minutes + 59) / 60); if (num >= 48) { return (num + 12) / 24 + " days"; } return num + " hours"; } public ScoutReportState ScoutReport(string settlementId) { if (!State.Scouting.Reports.TryGetValue(settlementId ?? "", out var value)) { return null; } return value; } internal void HourlyScouting() { List missions = State.Scouting.Missions; if (missions.Count == 0) { return; } long minute = State.Clock.Minute; foreach (ScoutMissionState item in missions.ToList()) { Settlement settlement = State.Settlements.Get(item.TargetId); if (settlement == null) { missions.Remove(item); State.Touch(); continue; } if (item.Report == null && minute >= item.ObserveMinute) { item.Report = Observe(item, settlement); State.Touch(); } if (item.Report != null && minute >= item.ReturnMinute) { item.Report.DeliveredMinute = minute; State.Scouting.Reports[settlement.Id] = item.Report; missions.Remove(item); string text = item.ScoutName + " is back from " + settlement.Name + ": " + Summary(item.Report) + "."; State.AddLog(LogCategory.Info, text, settlement.Id); C.Raise(CampaignEventKind.Info, text, false, settlement.Id); State.Touch(); } } } public static string Range(int low, int high) { if (low != high) { return low.ToString("N0", CultureInfo.InvariantCulture) + "–" + high.ToString("N0", CultureInfo.InvariantCulture); } return low.ToString("N0", CultureInfo.InvariantCulture); } public static string Summary(ScoutReportState r) { return "about " + Range(r.DefendersLow, r.DefendersHigh) + " defenders, " + Range(r.FoodLow, r.FoodHigh) + " food, walls level " + r.WallLevel; } internal ScoutReportState Observe(ScoutMissionState m, Settlement s) { RandomStream randomStream = Stream("report|" + m.Id); int num = Math.Max(1, Math.Min(5, m.Rating)); ScoutReportState scoutReportState = new ScoutReportState { SettlementId = s.Id, ScoutName = m.ScoutName, Rating = num, ObservedMinute = State.Clock.Minute }; Estimate(C.SettlementFood(s), num, randomStream, out scoutReportState.FoodLow, out scoutReportState.FoodHigh); Estimate(C.SiegeDefenders(s), num, randomStream, out scoutReportState.DefendersLow, out scoutReportState.DefendersHigh); Dictionary counts = new Dictionary(StringComparer.Ordinal); foreach (KeyValuePair> item in C.MilitiaTroops(s, s.Militia, 0)) { Count(item.Key, item.Value.Key); } foreach (TroopStack stack in s.Garrison.Stacks) { Count(stack.UnitId, stack.Healthy); } foreach (Party item2 in C.SiegeResidentDefenders(s)) { foreach (TroopStack stack2 in item2.Troops.Stacks) { Count(stack2.UnitId, stack2.Healthy); } } List> source = (from e in counts where C.UnitDef(e.Key) != null orderby e.Value descending select e).ThenBy, string>((KeyValuePair e) => e.Key, StringComparer.Ordinal).ToList(); foreach (KeyValuePair item3 in source.Take(num + 1)) { ScoutedUnitState scoutedUnitState = new ScoutedUnitState { UnitId = item3.Key }; Estimate(item3.Value, num, randomStream, out scoutedUnitState.Low, out scoutedUnitState.High); scoutReportState.Units.Add(scoutedUnitState); } long num2 = source.Skip(num + 1).Sum((KeyValuePair e) => e.Value); if (num2 > 0) { Estimate(num2, num, randomStream, out scoutReportState.OthersLow, out scoutReportState.OthersHigh); } int num3 = C.WallLevel(s); if (num <= 2 && randomStream.Chance((num == 1) ? 0.35 : 0.2)) { num3 += (randomStream.Chance(0.5) ? 1 : (-1)); } scoutReportState.WallLevel = Math.Max(1, Math.Min(3, num3)); return scoutReportState; void Count(string unitId, long n) { if (!string.IsNullOrEmpty(unitId) && n > 0) { counts.TryGetValue(unitId, out var value); counts[unitId] = value + n; } } } private static void Estimate(double truth, int rating, RandomStream rng, out int low, out int high) { truth = Math.Max(0.0, truth); double num = 2.0 * Spread[rating] * truth; double num2 = ((rating <= 2) ? rng.Range(-0.25, 1.25) : rng.NextDouble()); double num3 = truth - num * num2; low = (int)Math.Max(0.0, Math.Round(num3)); high = (int)Math.Max(low, Math.Round(num3 + num)); } } internal sealed class ServiceSystem { private readonly Campaign C; private CampaignState State => C.State; internal ServiceSystem(Campaign host) { C = host; } public void EnsureServiceFields() { bool flag = false; if (State.ClanService == null) { State.ClanService = new ClanServiceState(); flag = true; } ClanServiceState clanService = State.ClanService; if (!clanService.Initialized) { clanService.Initialized = true; clanService.KingdomId = State.PlayerClan?.KingdomId ?? ""; clanService.Kind = ((clanService.KingdomId.Length != 0) ? ((State.Kingdoms.Get(clanService.KingdomId)?.RulerClanId == State.PlayerClanId) ? ClanServiceKind.Ruler : ClanServiceKind.Vassal) : ClanServiceKind.Independent); clanService.StartedDay = State.Clock.Day; clanService.EndsDay = -1L; clanService.LastPaidDay = State.Clock.Day; clanService.LastPayment = 0L; flag = true; } if (flag) { State.Touch(); } } public Clan ServiceRuler(string kingdomId) { Kingdom kingdom = State.Kingdoms.Get(kingdomId); Clan clan = ((kingdom == null) ? null : State.Clans.Get(kingdom.RulerClanId)); if (kingdom != null && !kingdom.IsEliminated && clan != null && !clan.IsEliminated && !clan.IsBandit && !(clan.KingdomId != kingdom.Id)) { return clan; } return null; } public IEnumerable ServiceHoldings() { return State.Settlements.Where((Settlement s) => s.Type != SettlementType.Hideout && s.OwnerClanId == State.PlayerClanId).OrderBy((Settlement s) => s.Id, StringComparer.Ordinal); } public string ServiceJoinReason(string kingdomId, bool asVassal) { string text = C.CargoCommandReason(); if (text.Length > 0) { return text; } ClanServiceState clanService = State.ClanService; if (clanService == null || !clanService.Initialized) { return "Clan service is unavailable."; } if (State.PlayerClan.IsEliminated || State.PlayerClan.IsBandit) { return "Your clan can't serve a kingdom."; } if (!string.IsNullOrEmpty(State.Player.PendingEncounterId) || !string.IsNullOrEmpty(State.PlayerParty.EncounterId) || C.DiplomacyFactionReserved(State.FactionOf(State.PlayerClan)) || C.DiplomacyFactionReserved(kingdomId)) { return "Wait for the fighting involving your warbands to finish."; } if (clanService.Kind == ClanServiceKind.Ruler) { return "A ruling clan can't serve another kingdom."; } if (clanService.Kind == ClanServiceKind.Independent && C.HasIndependentDiplomacyObligations()) { return "Settle your own wars and let your truces run out first."; } Clan clan = ServiceRuler(kingdomId); if (clan == null || clan.Id == State.PlayerClanId) { return "This kingdom has no ruling clan."; } Hero hero = State.Heroes.Get(clan.LeaderHeroId); if (hero == null || hero.State == HeroState.Dead || hero.State == HeroState.Inactive || hero.ClanId != clan.Id) { return "Their ruling clan needs a living leader first."; } if (clanService.Kind == ClanServiceKind.Vassal) { return "Leave your current kingdom first."; } if (clanService.Kind == ClanServiceKind.Mercenary && (!asVassal || clanService.KingdomId != kingdomId)) { return "Finish or leave your mercenary contract first."; } if (State.PlayerClan.KingdomId != clanService.KingdomId) { return "Your allegiance just changed; wait until tomorrow."; } if (asVassal && State.PlayerClan.Renown < 100.0) { return "Earn " + 100 + " renown before swearing vassalage."; } if (!asVassal && ServiceHoldings().Any()) { return "Only landless clans can be mercenaries."; } Settlement settlement = C.CompanionMeetingSettlement(townOnly: false); if (settlement == null || (settlement.Type != SettlementType.Town && settlement.Type != SettlementType.Castle) || Vec2.Distance(State.PlayerParty.Position, settlement.Position) > 0.01 || State.Clans.Get(settlement.OwnerClanId)?.KingdomId != kingdomId) { return "Go to a friendly town or castle of this kingdom."; } if (State.AreHostile(State.PlayerClan, clan)) { return "You can't serve an enemy kingdom."; } return ""; } public CommandResult JoinKingdomService(string kingdomId, bool asVassal) { string text = ServiceJoinReason(kingdomId, asVassal); if (text.Length > 0) { return CommandResult.Fail(text); } ClanServiceState clanService = State.ClanService; clanService.Kind = ((!asVassal) ? ClanServiceKind.Mercenary : ClanServiceKind.Vassal); clanService.KingdomId = kingdomId; clanService.StartedDay = State.Clock.Day; clanService.EndsDay = (asVassal ? (-1) : (State.Clock.Day + 7)); clanService.LastPaidDay = State.Clock.Day; clanService.LastPayment = 0L; State.PlayerClan.KingdomId = kingdomId; string name = State.Kingdoms.Require(kingdomId).Name; State.AddLog(LogCategory.Politics, asVassal ? (State.PlayerClan.Name + " swore vassalage to " + name + ".") : (State.PlayerClan.Name + " entered " + 7 + " days of mercenary service for " + name + "."), kingdomId, State.PlayerClanId); C.OnPlayerAllegianceChanged(); C.TrainDiplomacy(40.0); State.Touch(); return CommandResult.Success(asVassal ? "Oath sworn. Your clan now shares this kingdom's wars." : ("Contract signed. Up to " + 50L + " denars per day, paid from the ruler's treasury.")); } public string LeaveServiceReason(bool relinquishFiefs) { string text = C.CargoCommandReason(); if (text.Length > 0) { return text; } ClanServiceState clanService = State.ClanService; if (clanService == null || !clanService.Initialized || clanService.Kind == ClanServiceKind.Independent) { return "You're already independent."; } if (!string.IsNullOrEmpty(State.Player.PendingEncounterId) || !string.IsNullOrEmpty(State.PlayerParty.EncounterId) || C.DiplomacyFactionReserved(State.FactionOf(State.PlayerClan))) { return "Wait for the fighting involving your warbands to finish."; } if (State.PlayerClan.KingdomId != clanService.KingdomId) { return "Your allegiance just changed; wait until tomorrow."; } Kingdom kingdom = State.Kingdoms.Get(clanService.KingdomId); if (clanService.Kind == ClanServiceKind.Ruler || (kingdom != null && kingdom.RulerClanId == State.PlayerClanId)) { return "A ruling clan can't leave its own kingdom."; } bool flag = ServiceHoldings().Any(); if (flag && !relinquishFiefs) { return "Confirm handing back all your fiefs, with their garrisons and prisoners, first."; } if (flag && ServiceRuler(clanService.KingdomId) == null) { return "There's nobody to hand your fiefs to."; } return ""; } public CommandResult LeaveService(bool relinquishFiefs) { string text = LeaveServiceReason(relinquishFiefs); if (text.Length > 0) { return CommandResult.Fail(text); } List list = ServiceHoldings().ToList(); Clan clan = ServiceRuler(State.ClanService.KingdomId); foreach (Settlement item in list) { C.ChangeSettlementOwner(item, clan.Id); } string kingdomId = State.ClanService.KingdomId; BecomeIndependent(); State.AddLog(LogCategory.Politics, State.PlayerClan.Name + " left " + (State.Kingdoms.Get(kingdomId)?.Name ?? "kingdom service") + ((list.Count > 0) ? ("; " + list.Count + " fiefs, their garrisons and prisoners were returned to the ruler.") : ".") + " Kingdom influence was relinquished.", kingdomId, State.PlayerClanId); C.OnPlayerAllegianceChanged(); State.Touch(); return CommandResult.Success((list.Count > 0) ? "Independent. Fiefs handed back, influence gone." : "Independent. Kingdom influence relinquished."); } internal void BecomeIndependent() { State.PlayerClan.KingdomId = ""; State.PlayerClan.Influence = 0.0; ClanServiceState clanService = State.ClanService; clanService.Kind = ClanServiceKind.Independent; clanService.KingdomId = ""; clanService.StartedDay = State.Clock.Day; clanService.EndsDay = -1L; clanService.LastPaidDay = State.Clock.Day; clanService.LastPayment = 0L; } public void DailyService() { ClanServiceState clanService = State.ClanService; if (clanService == null || !clanService.Initialized || clanService.Kind == ClanServiceKind.Independent || State.PlayerClan == null) { return; } string kingdomId = clanService.KingdomId; Clan clan = ServiceRuler(kingdomId); if (clan == null || State.PlayerClan.IsEliminated || State.PlayerClan.KingdomId != kingdomId) { BecomeIndependent(); State.AddLog(LogCategory.Politics, "Your service ended: the allegiance couldn't hold. You keep what's left of your holdings.", kingdomId, State.PlayerClanId); C.Raise(CampaignEventKind.Warning, "Service ended. You're independent and keep what's left of your holdings.", false, State.PlayerClanId); C.OnPlayerAllegianceChanged(); State.Touch(); } else { if (clanService.Kind != ClanServiceKind.Mercenary || clanService.LastPaidDay >= State.Clock.Day) { return; } clanService.LastPaidDay = State.Clock.Day; clanService.LastPayment = 0L; if (State.Clock.Day <= clanService.EndsDay) { long num = Math.Min(50L, Math.Min(Math.Max(0L, clan.Gold), long.MaxValue - State.PlayerClan.Gold)); if (num > 0) { State.Transact(clan, -num, LedgerAccount.Other, "Mercenary retainer: " + State.PlayerClan.Name); State.Transact(State.PlayerClan, num, LedgerAccount.Other, "Mercenary retainer: " + State.Kingdoms.Require(kingdomId).Name); clanService.LastPayment = num; } if (num < 50) { State.AddLog(LogCategory.Economy, "Mercenary retainer paid " + num + " of " + 50L + " denars; what's unpaid is just lost.", kingdomId, clan.Id); } } if (State.Clock.Day >= clanService.EndsDay) { BecomeIndependent(); State.AddLog(LogCategory.Politics, "Mercenary service for " + State.Kingdoms.Require(kingdomId).Name + " ended. Your clan is independent again.", kingdomId, State.PlayerClanId); C.Raise(CampaignEventKind.Info, "Your mercenary contract has run out. You're independent again.", false, State.PlayerClanId); C.OnPlayerAllegianceChanged(); } State.Touch(); } } } internal sealed class SettlementBudgetsSystem { private readonly Campaign C; public static readonly long[] WageLimitSteps = new long[7] { 0L, 25L, 50L, 100L, 200L, 400L, 800L }; public static readonly long[] GovernorBudgetSteps = new long[6] { 0L, 25L, 50L, 100L, 200L, 400L }; private CampaignState State => C.State; private CampaignRules Rules => C.Rules; internal SettlementBudgetsSystem(Campaign host) { C = host; } public void EnsureBudgetFields() { bool flag = false; foreach (Settlement settlement in State.Settlements) { SettlementManagementState management = settlement.Management; if (management != null) { if (management.ProjectQueue == null) { management.ProjectQueue = new List(); flag = true; } if (management.GarrisonWageLimit < 0) { management.GarrisonWageLimit = 0L; flag = true; } if (management.GovernorBudget < 0) { management.GovernorBudget = 0L; flag = true; } if (double.IsNaN(management.Hardship) || management.Hardship < 0.0 || management.Hardship > 100.0) { management.Hardship = Math.Max(0.0, Math.Min(100.0, double.IsNaN(management.Hardship) ? 0.0 : management.Hardship)); flag = true; } } } if (flag) { State.Touch(); } } public static int ProjectMaxLevel(string id) { if (!(id == "project.walls")) { return 3; } return 3; } internal bool OwnsProject(Settlement s) { if (s?.Management != null && s.Management.OwnerClanId == s.OwnerClanId && s.Management.ProjectOwnerClanId == s.OwnerClanId) { return !string.IsNullOrEmpty(s.Management.ProjectId); } return false; } public int PlannedProjectLevel(Settlement s, string id) { if (s?.Management == null) { return 0; } int num = C.ProjectLevel(s, id); if (OwnsProject(s) && s.Management.ProjectId == id) { num++; } return num + (s.Management.ProjectQueue?.Count((string q) => q == id) ?? 0); } public string QueueProjectReason(string id) { string text = C.SettlementManagementReason(); if (text.Length > 0) { return text; } if (!GovernanceSystem.IsSettlementProject(id)) { return "Unknown settlement project."; } Settlement settlement = C.CurrentSettlement(); if (id == "project.granary" && settlement.Type != SettlementType.Town) { return "Granaries cut how much townsfolk eat. Towns only."; } List list = settlement.Management.ProjectQueue ?? new List(); if (settlement.Management.OwnerClanId == settlement.OwnerClanId && list.Count >= 3) { return "The queue holds " + 3 + " projects."; } if (PlannedProjectLevel(settlement, id) >= ProjectMaxLevel(id)) { return "Already planned up to its highest level."; } return ""; } public CommandResult QueueSettlementProject(string id) { string text = QueueProjectReason(id); if (text.Length > 0) { return CommandResult.Fail(text); } Settlement settlement = C.CurrentSettlement(); C.SyncSettlementManagementOwner(settlement); SettlementManagementState management = settlement.Management; if (management.ProjectQueue == null) { management.ProjectQueue = new List(); } management.ProjectQueue.Add(id); management.QueueWaitingDay = -1L; string text2 = ""; if (!OwnsProject(settlement) && StartNextQueuedProject(settlement)) { text2 = " Work starts at once."; } State.AddLog(LogCategory.Economy, C.ProjectName(id) + " queued at " + settlement.Name + "." + text2, settlement.Id); State.Touch(); return CommandResult.Success((text2.Length > 0) ? (C.ProjectName(id) + " started from the queue: " + QueuedProjectCost(settlement, id).ToString("N0") + " denars paid.") : (C.ProjectName(id) + " queued. It is paid for when work starts.")); } public string RemoveQueuedProjectReason(int index) { string text = C.SettlementManagementReason(); if (text.Length > 0) { return text; } List projectQueue = C.CurrentSettlement().Management.ProjectQueue; if (projectQueue == null || index < 0 || index >= projectQueue.Count) { return "Nothing is queued there."; } return ""; } public CommandResult RemoveQueuedProject(int index) { string text = RemoveQueuedProjectReason(index); if (text.Length > 0) { return CommandResult.Fail(text); } Settlement settlement = C.CurrentSettlement(); string id = settlement.Management.ProjectQueue[index]; settlement.Management.ProjectQueue.RemoveAt(index); State.AddLog(LogCategory.Economy, C.ProjectName(id) + " taken out of the queue at " + settlement.Name + ".", settlement.Id); State.Touch(); return CommandResult.Success(C.ProjectName(id) + " removed from the queue. Nothing had been paid."); } public long MaterialsCost(Settlement s, string goodId, int count) { if (count <= 0) { return 0L; } long num = 2 * Math.Max(1L, TradeGoods.Get(goodId)?.BasePrice ?? 10); int num2 = LocalMaterials(s, goodId, count); long num3 = 0L; int num4 = C.MarketStock(s, goodId); for (int i = 0; i < num2; i++) { num3 += C.CommodityPrice(s, goodId, buying: true, num4 - i); } return num3 + (count - num2) * num; } internal int LocalMaterials(Settlement s, string goodId, int count) { if (s == null || s.Type != SettlementType.Town || s.Market?.Stock == null || !s.Market.Initialized) { return 0; } return Math.Max(0, Math.Min(count, C.MarketStock(s, goodId))); } public long QueuedProjectCost(Settlement s, string id) { return C.ProjectCost(id) + MaterialsCost(s, "good.timber", C.ProjectTimber(id)) + MaterialsCost(s, "good.tools", C.ProjectTools(id)); } internal bool StartNextQueuedProject(Settlement s) { SettlementManagementState settlementManagementState = s?.Management; if (settlementManagementState == null || settlementManagementState.ProjectQueue == null || settlementManagementState.ProjectQueue.Count == 0 || OwnsProject(s)) { return false; } if (settlementManagementState.OwnerClanId != s.OwnerClanId) { return false; } bool result = false; while (settlementManagementState.ProjectQueue.Count > 0) { string text = settlementManagementState.ProjectQueue[0]; if (GovernanceSystem.IsSettlementProject(text) && C.ProjectLevel(s, text) < ProjectMaxLevel(text) && (text != "project.granary" || s.Type == SettlementType.Town)) { break; } settlementManagementState.ProjectQueue.RemoveAt(0); result = true; } if (settlementManagementState.ProjectQueue.Count == 0) { return result; } string text2 = settlementManagementState.ProjectQueue[0]; Clan clan = State.Clans.Get(s.OwnerClanId); long num = QueuedProjectCost(s, text2); if (clan == null || clan.Gold < num) { if (settlementManagementState.QueueWaitingDay < 0) { settlementManagementState.QueueWaitingDay = State.Clock.Day; State.AddLog(LogCategory.Economy, "The build queue at " + s.Name + " is waiting for money: " + C.ProjectName(text2) + " needs " + num.ToString("N0") + " denars.", s.Id); if (clan != null && clan.IsPlayerClan) { C.Raise(CampaignEventKind.Info, "The build queue at " + s.Name + " is waiting: " + C.ProjectName(text2) + " needs " + num.ToString("N0") + " denars.", false, s.Id); } } return true; } (string, int)[] array = new(string, int)[2] { ("good.timber", C.ProjectTimber(text2)), ("good.tools", C.ProjectTools(text2)) }; for (int i = 0; i < array.Length; i++) { (string, int) tuple = array[i]; string item = tuple.Item1; int item2 = tuple.Item2; int num2 = LocalMaterials(s, item, item2); if (num2 > 0) { int num3 = C.MarketStock(s, item); long num4 = 0L; for (int j = 0; j < num2; j++) { num4 += C.CommodityPrice(s, item, buying: true, num3 - j); } s.Market.Stock[item] = num3 - num2; if (s.Market.Gold < 5000) { s.Market.Gold += Math.Min(num4, 5000 - s.Market.Gold); } } } State.Transact(clan, -num, LedgerAccount.Upgrade, "Construction (queued): " + C.ProjectName(text2) + " at " + s.Name); settlementManagementState.ProjectQueue.RemoveAt(0); settlementManagementState.ProjectId = text2; settlementManagementState.ProjectRemainingDays = Campaign.ProjectDays(text2); settlementManagementState.ProjectOwnerClanId = s.OwnerClanId; settlementManagementState.QueueWaitingDay = -1L; settlementManagementState.LastDay = Math.Max(settlementManagementState.LastDay, State.Clock.Day); State.AddLog(LogCategory.Economy, "Construction started from the queue: " + C.ProjectName(text2) + " at " + s.Name + " (" + num.ToString("N0") + " denars with materials).", s.Id); State.Touch(); return true; } public string BudgetReason() { return C.SettlementManagementReason(); } public CommandResult SetGarrisonWageLimit(long limit) { string text = BudgetReason(); if (text.Length > 0) { return CommandResult.Fail(text); } if (limit < 0) { return CommandResult.Fail("A wage limit can't be negative."); } Settlement settlement = C.CurrentSettlement(); C.SyncSettlementManagementOwner(settlement); settlement.Management.GarrisonWageLimit = limit; if (limit == 0L && C.GarrisonOrders(settlement).Target <= 0) { settlement.Management.GarrisonAutoRecruit = false; } State.AddLog(LogCategory.Economy, "Garrison wages at " + settlement.Name + ((limit == 0L) ? " are no longer limited." : (" are limited to " + limit + " denars a day.")), settlement.Id); State.Touch(); return CommandResult.Success((limit == 0L) ? "No wage limit." : ("Garrison wages limited to " + limit + " a day. Troops over the limit go home at dawn.")); } public string GarrisonAutoRecruitReason(bool on) { string text = BudgetReason(); if (text.Length > 0) { return text; } Settlement settlement = C.CurrentSettlement(); if (on && settlement.Management.GarrisonWageLimit <= 0 && C.GarrisonOrders(settlement).Target <= 0) { return "Set a wage limit or a target size (Garrison tab) first: volunteers are taken on up to it."; } return ""; } public CommandResult SetGarrisonAutoRecruit(bool on) { string text = GarrisonAutoRecruitReason(on); if (text.Length > 0) { return CommandResult.Fail(text); } Settlement settlement = C.CurrentSettlement(); C.SyncSettlementManagementOwner(settlement); settlement.Management.GarrisonAutoRecruit = on; State.Touch(); return CommandResult.Success(on ? "The garrison takes on volunteers each dawn, up to its wage limit and target size." : "The garrison no longer recruits on its own."); } public CommandResult SetGovernorBudget(long budget) { string text = BudgetReason(); if (text.Length > 0) { return CommandResult.Fail(text); } if (budget < 0) { return CommandResult.Fail("A budget can't be negative."); } Settlement settlement = C.CurrentSettlement(); C.SyncSettlementManagementOwner(settlement); settlement.Management.GovernorBudget = budget; State.AddLog(LogCategory.Economy, "The governor's budget at " + settlement.Name + " is now " + budget + " denars a day.", settlement.Id); State.Touch(); return CommandResult.Success((budget == 0L) ? "The governor spends nothing on relief." : ("The governor may spend up to " + budget + " a day on relief.")); } internal double GarrisonWagePerHead(Settlement s, string unitId) { return (C.UnitDef(unitId)?.DailyWage ?? 0.0) * Rules.GarrisonWageFactor * C.LawGarrisonWageFactor(s); } internal int EnforceGarrisonWageLimit(Settlement s) { SettlementManagementState management = s.Management; if (management.GarrisonWageLimit <= 0 || management.OwnerClanId != s.OwnerClanId || C.IsSettlementBesieged(s)) { return 0; } if (C.GarrisonDailyWages(s) <= (double)management.GarrisonWageLimit) { return 0; } int num = 0; foreach (TroopStack item in (from st in s.Garrison.Stacks orderby GarrisonWagePerHead(s, st.UnitId) descending, C.UnitDef(st.UnitId)?.Tier ?? 0 descending select st).ThenBy((TroopStack st) => st.UnitId, StringComparer.Ordinal).ToList()) { double num2 = GarrisonWagePerHead(s, item.UnitId); if (!(num2 <= 0.0)) { while (item.Total > 0 && C.GarrisonDailyWages(s) > (double)management.GarrisonWageLimit) { int val = (int)Math.Ceiling((C.GarrisonDailyWages(s) - (double)management.GarrisonWageLimit) / num2); int count = Math.Max(1, Math.Min(item.Total, val)); num += s.Garrison.Remove(item.UnitId, count, woundedFirst: true); } if (C.GarrisonDailyWages(s) <= (double)management.GarrisonWageLimit) { break; } } } s.Garrison.Prune(); if (num > 0) { string text = num + " soldiers of the garrison of " + s.Name + " were sent home to keep its wages within " + management.GarrisonWageLimit + " a day."; State.AddLog(LogCategory.Economy, text, s.Id); if (s.OwnerClanId == State.PlayerClanId) { C.Raise(CampaignEventKind.Info, text, false, s.Id); } } return num; } internal long SpendGovernorBudget(Settlement s) { SettlementManagementState management = s.Management; if (management.GovernorSpendDay != State.Clock.Day) { management.GovernorSpendDay = State.Clock.Day; management.GovernorSpentToday = 0L; } if (management.GovernorBudget <= 0 || !C.GovernorActive(s) || management.OwnerClanId != s.OwnerClanId) { return 0L; } Clan clan = State.Clans.Get(s.OwnerClanId); if (clan == null) { return 0L; } long num = Math.Min(management.GovernorBudget - management.GovernorSpentToday, Math.Max(0L, clan.Gold)); if (num <= 0) { return 0L; } long num2 = 0L; string text = ""; if (!C.IsSettlementBesieged(s) && s.Market?.Stock != null) { double num3 = Math.Max(1.0, C.SettlementFoodNeed(s)); double val = Math.Min(C.FoodCapacity(s) - C.SettlementFood(s), 10.0 * num3 - C.SettlementFood(s)); long num4 = ImportedFoodPrice(); int num5 = (int)Math.Min(Math.Floor(Math.Max(0.0, val)), num / num4); if (num5 > 0) { double a = C.AddSettlementFood(s, "good.grain", num5); long num6 = (long)Math.Ceiling(a) * num4; if (num6 > 0) { num2 += num6; text = Math.Round(a) + " grain"; } } } long num7 = 0L; if (s.Type == SettlementType.Town && management.Hardship > 0.0) { num7 = Math.Min(num - num2, (long)Math.Ceiling(management.Hardship * 4.0)); if (num7 > 0) { management.Hardship = Math.Max(0.0, management.Hardship - (double)num7 / 4.0); num2 += num7; } } if (num2 <= 0) { return 0L; } State.Transact(clan, -num2, LedgerAccount.Other, "Governor's relief at " + s.Name); management.GovernorSpentToday += num2; Hero hero = C.SettlementGovernor(s); if (hero != null) { C.GrantSkillExperience(hero, "stewardship", Math.Min(40.0, (double)num2 / 10.0)); } State.AddLog(LogCategory.Economy, (hero?.Name ?? "The governor") + " spent " + num2 + " denars at " + s.Name + " on " + ((text.Length > 0) ? (text + ((num7 > 0) ? " and alms" : "")) : "alms and public works") + ".", s.Id); return num2; } internal long ImportedFoodPrice() { return (long)Math.Ceiling((double)Math.Max(1L, TradeGoods.Get("good.grain")?.BasePrice ?? 10) * 1.5); } public static string HardshipTier(double hardship) { if (!(hardship >= 75.0)) { if (!(hardship >= 50.0)) { if (!(hardship >= 25.0)) { return "Getting by"; } return "Strained"; } return "Suffering"; } return "Desperate"; } public static string HardshipEffects(double hardship) { if (!(hardship >= 75.0)) { if (!(hardship >= 50.0)) { if (!(hardship >= 25.0)) { return "No effect."; } return "Loyalty −0.5 a day; taxes −10%."; } return "Loyalty −1, prosperity −1 and security −0.5 a day; taxes −20%."; } return "Loyalty −2, prosperity −3 and security −1 a day; taxes −35%; riots break out when loyalty is under 50."; } public StatForecast HardshipPressure(Settlement s) { StatForecast statForecast = new StatForecast { Current = (s?.Management?.Hardship).GetValueOrDefault() }; if (s == null || s.Type != SettlementType.Town || s.Management == null) { return statForecast; } FoodForecast foodForecast = C.SettlementFoodForecast(s); double num = Math.Max(1.0, foodForecast.Consumption); if (foodForecast.Starving || C.SettlementFood(s) <= 0.0) { statForecast.Add("Hunger", 40.0); } else if (C.SettlementFood(s) < num * 5.0) { statForecast.Add("Food running low", 15.0); } if (C.IsSettlementBesieged(s)) { statForecast.Add("Under siege", 30.0); } double num2 = 0.0; foreach (Settlement item in C.BoundVillages(s)) { int num3 = Math.Max(0, Math.Min(100, item.VillageRecovery?.Damage ?? 0)); if (C.IsVillageBeingRaided(item)) { num2 += 8.0; } else if (num3 > 0) { num2 += (double)(8 * num3) / 100.0; } } statForecast.Add("Refugees from raided villages", num2); if (s.Security < 25.0) { statForecast.Add("Lawlessness", 15.0); } else if (s.Security < 40.0) { statForecast.Add("Crime", 5.0); } switch (C.GovernanceSystem.EffectiveSettlementPolicy(s)) { case TaxPolicy.Levy: statForecast.Add("Tax levy", 10.0); break; case TaxPolicy.Relief: statForecast.Add("Tax relief", -10.0); break; } if (s.Prosperity < 800.0) { statForecast.Add("Poverty", 20.0); } else if (s.Prosperity < 1500.0) { statForecast.Add("Poverty", 10.0); } if (C.RealmPolicyAt(s) == RealmPolicy.WarLevy) { statForecast.Add("War levy", 5.0); } statForecast.Change = Math.Max(0.0, Math.Min(100.0, statForecast.Change)); return statForecast; } public double HardshipChange(Settlement s) { if (s == null || s.Type != SettlementType.Town || s.Management == null) { return 0.0; } double change = HardshipPressure(s).Change; double hardship = s.Management.Hardship; if (!(change > hardship)) { return 0.0 - Math.Min(3.0, hardship - change); } return Math.Min(5.0, change - hardship); } internal double Hardship(Settlement s) { if (s == null || s.Type != SettlementType.Town) { return 0.0; } return s.Management?.Hardship ?? 0.0; } public double HardshipTaxFactor(Settlement s) { double num = Hardship(s); if (!(num >= 75.0)) { if (!(num >= 50.0)) { if (!(num >= 25.0)) { return 1.0; } return 0.9; } return 0.8; } return 0.65; } internal double HardshipLoyalty(Settlement s) { double num = Hardship(s); if (!(num >= 75.0)) { if (!(num >= 50.0)) { if (!(num >= 25.0)) { return 0.0; } return -0.5; } return -1.0; } return -2.0; } internal double HardshipProsperity(Settlement s) { double num = Hardship(s); return (num >= 75.0) ? (-3) : ((num >= 50.0) ? (-1) : 0); } internal double HardshipSecurity(Settlement s) { double num = Hardship(s); if (!(num >= 75.0)) { if (!(num >= 50.0)) { return 0.0; } return -0.5; } return -1.0; } internal void UpdateHardship(Settlement s) { SettlementManagementState settlementManagementState = s?.Management; if (settlementManagementState == null || s.Type != SettlementType.Town || settlementManagementState.HardshipDay >= State.Clock.Day) { return; } settlementManagementState.HardshipDay = State.Clock.Day; double hardship = settlementManagementState.Hardship; settlementManagementState.Hardship = Math.Max(0.0, Math.Min(100.0, settlementManagementState.Hardship + HardshipChange(s))); string text = HardshipTier(hardship); string text2 = HardshipTier(settlementManagementState.Hardship); if (text != text2 && s.OwnerClanId == State.PlayerClanId) { string text3 = ((settlementManagementState.Hardship > hardship) ? ("Life in " + s.Name + " is getting harder: its people are " + text2.ToLowerInvariant() + ".") : ("Life in " + s.Name + " is easing: its people are " + ((text2 == "Getting by") ? "getting by again" : text2.ToLowerInvariant()) + ".")); State.AddLog(LogCategory.Economy, text3, s.Id); C.Raise(CampaignEventKind.Info, text3, false, s.Id); } if (settlementManagementState.Hardship >= 75.0 && s.Loyalty < 50.0 && State.Clock.Day - settlementManagementState.LastRiotDay >= 7) { SiegeState siegeState = C.SiegeForSettlement(s.Id); if ((siegeState == null || siegeState.Stage != SiegeStage.Assault) && State.Random.Get("hardship").Chance(0.2)) { Riot(s); } } } internal void Riot(Settlement s) { s.Management.LastRiotDay = State.Clock.Day; s.Security = Math.Max(0.0, s.Security - 10.0); s.Loyalty = Math.Max(0.0, s.Loyalty - 5.0); long num = 0L; if (s.Market != null) { num = s.Market.Gold * 15 / 100; s.Market.Gold -= num; } double a = C.TakeSettlementFood(s, C.SettlementFood(s) * 0.1); int num2 = s.Militia / 10; s.Militia -= num2; string text = "Riots in " + s.Name + "! The hungry and the desperate took to the streets: " + Math.Round(a) + " food and " + num + " denars from the market were lost, and " + num2 + " militiamen went home."; State.AddLog(LogCategory.Warning, text, s.Id); if (s.OwnerClanId == State.PlayerClanId) { C.Raise(CampaignEventKind.Warning, text, false, s.Id); } } internal void DailyBudgets(Settlement s) { if (s?.Management == null || s.Type == SettlementType.Hideout || s.Type == SettlementType.Village) { return; } SettlementManagementState management = s.Management; if (management.LastGarrisonBudgetDay < State.Clock.Day) { management.LastGarrisonBudgetDay = State.Clock.Day; if (string.IsNullOrEmpty(management.ProjectId) || !OwnsProject(s)) { StartNextQueuedProject(s); } EnforceGarrisonWageLimit(s); C.GarrisonsSystem.AutoRecruit(s); C.GarrisonsSystem.DailyGarrison(s); SpendGovernorBudget(s); UpdateHardship(s); } } } internal sealed class SettlementFoodSystem { private readonly Campaign C; private static string[] FoodGoods => Campaign.FoodGoods; private CampaignRules Rules => C.Rules; private CampaignState State => C.State; internal SettlementFoodSystem(Campaign host) { C = host; } public static bool IsFoodGood(string goodId) { TradeGoodDef tradeGoodDef = TradeGoods.Get(goodId ?? ""); if (tradeGoodDef == null) { return false; } return tradeGoodDef.Category == GoodCategory.Food; } internal static double FoodPartOf(Settlement s) { if (s != null && !double.IsNaN(s.FoodPart) && !double.IsInfinity(s.FoodPart)) { return Math.Max(0.0, Math.Min(1.0, s.FoodPart)); } return 0.0; } public double SettlementFood(Settlement s) { if (s?.Market?.Stock == null || s.Type == SettlementType.Hideout) { return 0.0; } long num = 0L; string[] foodGoods = FoodGoods; foreach (string goodId in foodGoods) { num += C.MarketStock(s, goodId); } return (double)num + FoodPartOf(s); } public string SettlementFoodBreakdown(Settlement s) { List list = (from g in FoodGoods where C.MarketStock(s, g) > 0 select C.MarketStock(s, g) + " " + TradeGoods.Get(g).Name).ToList(); if (list.Count != 0) { return string.Join(", ", list); } return "no food goods"; } public string VillageFoodGood(Settlement village) { string text = C.PrimaryVillageGood(village); if (IsFoodGood(text)) { return text; } if (!(text == "good.hides") && !(text == "good.wool")) { return "good.grain"; } return "good.meat"; } public List HomeFoods(Settlement s) { List list = new List(); if (s == null || s.Type == SettlementType.Hideout) { return list; } if (s.Type == SettlementType.Village) { list.Add(VillageFoodGood(s)); return list; } list.Add("good.grain"); foreach (Settlement item2 in C.BoundVillages(s)) { string item = VillageFoodGood(item2); if (!list.Contains(item)) { list.Add(item); } } return list; } public static double OpeningFood(Settlement s) { if (s == null || s.Type != SettlementType.Town) { if (s == null || s.Type != SettlementType.Castle) { if (s == null || s.Type != SettlementType.Village) { return 0.0; } return 120.0; } return 200.0; } return 450.0; } internal double AddSettlementFood(Settlement s, string goodId, double amount) { if (s?.Market?.Stock == null || s.Type == SettlementType.Hideout || !(amount > 0.0) || double.IsInfinity(amount) || !IsFoodGood(goodId)) { return 0.0; } double num = SettlementFood(s); double num2 = FoodPartOf(s); double num3 = num2 + amount; double num4 = Math.Floor(num3); long num5 = (long)Math.Min(num4, 2147483647.0); foreach (string item in FoodDestinations(s, goodId)) { if (num5 <= 0) { break; } int num6 = C.MarketStock(s, item); long num7 = Math.Min(num5, Math.Max(0, 500 - num6)); if (num7 > 0) { s.Market.Stock[item] = (int)(num6 + num7); num5 -= num7; } } s.FoodPart = ((num5 > 0) ? Math.Max(num2, num3 - num4) : (num3 - num4)); State.Touch(); return Math.Max(0.0, SettlementFood(s) - num); } internal List FoodDestinations(Settlement s, string first) { List home = HomeFoods(s); List list = new List(); list.Add(first); list.AddRange((from g in home where g != first orderby C.MarketStock(s, g) select g).ThenBy((string g) => g, StringComparer.Ordinal)); list.AddRange((from g in FoodGoods where g != first && !home.Contains(g) orderby C.MarketStock(s, g) select g).ThenBy((string g) => g, StringComparer.Ordinal)); return list; } internal double SpreadSettlementFood(Settlement s, IReadOnlyList goods, double amount) { if (goods == null || goods.Count == 0 || !(amount > 0.0)) { return 0.0; } double num = 0.0; foreach (string good in goods) { num += AddSettlementFood(s, good, amount / (double)goods.Count); } return num; } internal string CheapestFood(Settlement s, out long price) { string text = null; price = 0L; string[] foodGoods = FoodGoods; foreach (string text2 in foodGoods) { int num = C.MarketStock(s, text2); if (num > 0) { long num2 = C.CommodityPrice(s, text2, buying: true, num); if (text == null || num2 < price) { text = text2; price = num2; } } } return text; } internal double TakeSettlementFood(Settlement s, double amount, out long value) { value = 0L; if (s?.Market?.Stock == null || s.Type == SettlementType.Hideout || !(amount > 0.0)) { return 0.0; } amount = Math.Min(amount, SettlementFood(s)); double num = FoodPartOf(s); double num2 = Math.Min(num, amount); double num3 = amount - num2; num -= num2; while (num3 > 1E-09) { long price; string text = CheapestFood(s, out price); if (text == null) { break; } s.Market.Stock[text] = C.MarketStock(s, text) - 1; value = ((value > long.MaxValue - price) ? long.MaxValue : (value + price)); double num4 = Math.Min(1.0, num3); num2 += num4; num3 -= num4; num += 1.0 - num4; } s.FoodPart = Math.Max(0.0, Math.Min(1.0, num)); State.Touch(); return num2; } internal double TakeSettlementFood(Settlement s, double amount) { long value; return TakeSettlementFood(s, amount, out value); } public double FoodPrice(Settlement s) { if (s == null) { return Rules.FoodPrice; } long price; return (CheapestFood(s, out price) != null) ? price : C.CommodityPrice(s, "good.grain", buying: true, 0); } public void SetSettlementFood(Settlement s, double amount) { if (s?.Market?.Stock != null) { string[] foodGoods = FoodGoods; foreach (string key in foodGoods) { s.Market.Stock.Remove(key); } s.FoodPart = 0.0; s.FoodStock = 0.0; s.FoodInMarket = true; if (amount > 0.0) { AddSettlementFood(s, HomeFoods(s).FirstOrDefault() ?? "good.grain", amount); } State.Touch(); } } internal bool EnsureSettlementFood() { bool result = false; foreach (Settlement settlement in State.Settlements) { if (!settlement.FoodInMarket) { result = true; settlement.FoodInMarket = true; double amount = ((double.IsNaN(settlement.FoodStock) || double.IsInfinity(settlement.FoodStock)) ? 0.0 : Math.Max(0.0, settlement.FoodStock)); settlement.FoodStock = 0.0; settlement.FoodPart = FoodPartOf(settlement); if (settlement.Type != SettlementType.Hideout && settlement.Market?.Stock != null) { List goods = HomeFoods(settlement); SpreadSettlementFood(settlement, goods, amount); SpreadSettlementFood(settlement, goods, OpeningFood(settlement) - SettlementFood(settlement)); } } } return result; } } internal sealed class SettlementStatsSystem { private readonly Campaign C; private CampaignRules Rules => C.Rules; private CampaignState State => C.State; internal SettlementStatsSystem(Campaign host) { C = host; } public IEnumerable BoundVillages(Settlement fief) { if (fief != null) { return State.Settlements.Where((Settlement v) => v.Type == SettlementType.Village && v.BoundTo == fief.Id).OrderBy((Settlement v) => v.Id, StringComparer.Ordinal); } return Enumerable.Empty(); } public Settlement BoundFief(Settlement village) { if (village == null || village.Type != SettlementType.Village || string.IsNullOrEmpty(village.BoundTo)) { return null; } Settlement settlement = State.Settlements.Get(village.BoundTo); if (settlement == null || (settlement.Type != SettlementType.Town && settlement.Type != SettlementType.Castle)) { return null; } return settlement; } public static double HearthFactor(Settlement village) { if (village != null) { return Math.Max(0.2, Math.Min(3.0, village.Prosperity / 500.0)); } return 0.0; } public VillageProductDef VillageProduct(Settlement village) { if (village == null || village.Type != SettlementType.Village) { return null; } return VillageProducts.Get(C.PrimaryVillageGood(village)); } public double VillageFoodToFief(Settlement village) { if (village == null || village.Type != SettlementType.Village) { return 0.0; } return Math.Max(1.0, VillageProduct(village)?.FoodPerDay ?? 1.0) * HearthFactor(village) * C.VillageOutputFactor(village); } public double FieldsWorked(Settlement fief) { List list = BoundVillages(fief).ToList(); if (list.Count != 0) { return list.Average((Settlement v) => C.VillageOutputFactor(v)); } return 1.0; } public bool VillageSuppliesFief(Settlement village, Settlement fief) { if (village == null || fief == null || village.BoundTo != fief.Id || C.IsSettlementBesieged(fief)) { return false; } return !State.AreHostile(State.Clans.Get(village.OwnerClanId), State.Clans.Get(fief.OwnerClanId)); } public double FoodCapacity(Settlement s) { if (s != null && s.Type == SettlementType.Town) { return 600.0 + 120.0 * (double)Math.Max(0, Math.Min(3, s.Management?.GranaryLevel ?? 0)); } if (s == null || s.Type != SettlementType.Castle) { if (s == null || s.Type != SettlementType.Village) { return 0.0; } return 200.0; } return 300.0; } public double CivilianFoodBase(Settlement s) { if (s == null || s.Type != SettlementType.Town) { if (s == null || s.Type != SettlementType.Castle) { return 0.0; } return 1.0; } return 3.0 * Math.Max(0.0, s.Prosperity) / 900.0; } public double SettlementCivilianFood(Settlement s) { return C.SettlementFoodConsumption(s, CivilianFoodBase(s)); } public double SettlementMouths(Settlement s) { if (s != null) { return (double)((long)s.Militia + (long)s.WoundedMilitia) + s.Garrison.Stacks.Sum((TroopStack st) => (double)st.Total * (C.UnitDef(st.UnitId)?.FoodUse ?? 1.0)); } return 0.0; } public double SoldierFood(Settlement s) { return SettlementMouths(s) * Rules.FoodPerTroopPerDay * 0.6; } public double SettlementFoodNeed(Settlement s) { return C.SettlementFoodConsumption(s, Math.Max(1.0, CivilianFoodBase(s) + SoldierFood(s))); } public FoodForecast SettlementFoodForecast(Settlement s) { FoodForecast foodForecast = new FoodForecast(); if (s == null || (s.Type != SettlementType.Town && s.Type != SettlementType.Castle)) { return foodForecast; } foodForecast.Stock = C.SettlementFood(s); foodForecast.Capacity = FoodCapacity(s); foodForecast.Besieged = C.IsSettlementBesieged(s); if (!foodForecast.Besieged) { double num = FieldsWorked(s); double amount = ((s.Type == SettlementType.Town) ? 4.0 : 2.0) * num; foodForecast.Sources.Add(new FoodSource { Label = ((s.Type == SettlementType.Town) ? "Town fields" : "Castle lands") + ((num < 0.999) ? " (raided villages)" : ""), GoodId = "good.grain", Amount = amount }); foreach (Settlement item in BoundVillages(s)) { if (VillageSuppliesFief(item, s)) { foodForecast.Sources.Add(new FoodSource { Label = item.Name, GoodId = C.VillageFoodGood(item), Amount = VillageFoodToFief(item) }); } } foreach (FoodSource source in foodForecast.Sources) { foodForecast.Add(source.Label, source.Amount); foodForecast.Supply += source.Amount; } } else { foodForecast.Lines.Add(new StatLine { Label = "Under siege: no supplies reach the stores", Value = 0.0 }); } double num2 = CivilianFoodBase(s); double num3 = SoldierFood(s); double num4 = Math.Max(1.0, num2 + num3); foodForecast.Consumption = C.SettlementFoodConsumption(s, num4); foodForecast.CivilianConsumption = foodForecast.Consumption * num2 / num4; foodForecast.Add((s.Type == SettlementType.Town) ? "Townsfolk" : "Castle household", 0.0 - num2); foodForecast.Add("Garrison and militia", 0.0 - num3); foodForecast.Add("Minimum upkeep", 0.0 - (num4 - num2 - num3)); foodForecast.Add("Granary", num4 - foodForecast.Consumption); double num5 = foodForecast.Supply - foodForecast.Consumption; foodForecast.SupplyStored = foodForecast.Supply; if (num5 > 0.0) { double num6 = Math.Max(0.0, foodForecast.Capacity - foodForecast.Stock); if (num5 > num6) { foodForecast.Add("Stores full", num6 - num5); foodForecast.SupplyStored -= num5 - num6; num5 = num6; } } foodForecast.Change = Math.Max(0.0 - foodForecast.Stock, num5); return foodForecast; } public StatForecast SettlementProsperityForecast(Settlement s) { if (s != null && s.Type == SettlementType.Village) { return VillageHearthForecast(s); } StatForecast statForecast = new StatForecast { Current = (s?.Prosperity ?? 0.0) }; if (s == null || (s.Type != SettlementType.Town && s.Type != SettlementType.Castle)) { return statForecast; } double num = ((s.Type == SettlementType.Castle) ? 0.5 : 1.0); FoodForecast foodForecast = SettlementFoodForecast(s); if (foodForecast.Starving) { statForecast.Add("Starvation", -10.0 * num); } else { double num2 = foodForecast.Supply - foodForecast.Consumption; statForecast.Add((num2 >= 0.0) ? "Food surplus" : "Shrinking food stores", num * ((num2 >= 0.0) ? Math.Min(1.0, num2 / 2.0) : Math.Max(-2.0, num2 / 2.0))); } statForecast.Add("Security", num * (s.Security - 50.0) / 50.0); double num3 = 0.0; foreach (Settlement item in BoundVillages(s)) { int num4 = Math.Max(0, Math.Min(100, item.VillageRecovery?.Damage ?? 0)); if (C.IsVillageBeingRaided(item)) { statForecast.Add(item.Name + " is being raided", -2.0 * num); continue; } if (num4 > 0) { statForecast.Add(item.Name + " is recovering from a raid", -2.0 * num * (double)num4 / 100.0); continue; } VillageProductDef villageProductDef = VillageProduct(item); if ((villageProductDef == null || !villageProductDef.FoodVillage) && VillageSuppliesFief(item, s)) { num3 += 0.25 * num; } } statForecast.Add("Trade with villages", num3); if (foodForecast.Besieged) { statForecast.Add("Under siege", -2.0 * num); } C.AddLawProsperity(statForecast, s); C.AddPactProsperity(statForecast, s); statForecast.Add("Hardship (" + Campaign.HardshipTier(s.Management?.Hardship ?? 0.0).ToLowerInvariant() + ")", C.HardshipProsperity(s)); statForecast.Add("Perks", C.SettlementPerk(s, PerkEffect.Prosperity)); statForecast.Bound(100.0, 10000.0); return statForecast; } public StatForecast VillageHearthForecast(Settlement village) { StatForecast statForecast = new StatForecast { Current = (village?.Prosperity ?? 0.0) }; if (village == null || village.Type != SettlementType.Village || C.IsVillageBeingRaided(village)) { return statForecast; } if ((village.VillageRecovery?.Damage ?? 0) > 0) { statForecast.Add("Recovering from a raid", -0.5); } else { statForecast.Add("Growth", 0.5); statForecast.Add("Security", (village.Security - 50.0) / 100.0); C.AddLawProsperity(statForecast, village); statForecast.Add("Perks", C.SettlementPerk(village, PerkEffect.Prosperity)); } statForecast.Bound(100.0, 2000.0); return statForecast; } public double MilitiaTarget(Settlement s) { if (s == null) { return 0.0; } double num = ((s.Type == SettlementType.Town) ? 10.0 : ((s.Type == SettlementType.Castle) ? 9.0 : ((s.Type == SettlementType.Village) ? 40.0 : 0.0))); double num2 = ((s.Type == SettlementType.Village) ? 1.0 : Campaign.MilitiaTradition(s.Id)); if (!(num <= 0.0)) { return Math.Max(0.0, s.Prosperity) / num * num2 * C.LawMilitiaFactor(s); } return 0.0; } public StatForecast SettlementMilitiaForecast(Settlement s) { StatForecast statForecast = new StatForecast { Current = (s?.Militia ?? 0) }; if (s == null || s.Type == SettlementType.Hideout) { return statForecast; } if (s.Type != SettlementType.Village && SettlementFoodForecast(s).Starving && !C.IsSettlementBesieged(s)) { if (s.Militia > 0) { statForecast.Add("Hunger", -Math.Max(1, s.Militia / 20)); } return statForecast; } Settlement settlement = BoundFief(s); if (C.IsSettlementBesieged(s) || C.IsVillageBeingRaided(s) || (settlement != null && C.IsSettlementBesieged(settlement))) { return statForecast; } long num = (long)s.Militia + (long)s.WoundedMilitia; double num2 = MilitiaTarget(s); if ((double)(num + 1) <= num2) { statForecast.Add("Volunteers", 1.0 + Math.Floor((num2 - (double)num - 1.0) / 20.0)); } else if ((double)num > num2 + 1.0 && s.Militia > 0) { statForecast.Add("Too many for the settlement's size", 0.0 - Math.Min(s.Militia, 1.0 + Math.Floor(((double)num - num2 - 1.0) / 20.0))); } if ((double)(num + 1) <= num2) { statForecast.Add("Perks", C.SettlementPerk(s, PerkEffect.Militia)); } return statForecast; } public int WallLevel(Settlement s) { if (s != null && (s.Type == SettlementType.Town || s.Type == SettlementType.Castle)) { return Math.Max(1, Math.Min(3, s.WallLevel)); } return 0; } public double SiegeWallMaxHealth(SiegeState siege) { return SiegeWorksRules.WallMaxHealthFor(WallLevel(State.Settlements.Get(siege?.SettlementId ?? ""))); } public void DailySettlementStats() { bool flag = false; foreach (Settlement settlement in State.Settlements) { if (settlement.Type == SettlementType.Hideout || settlement.StatsDay >= State.Clock.Day) { continue; } settlement.StatsDay = State.Clock.Day; flag = true; SiegeState siegeState = C.SiegeForSettlement(settlement.Id); if (siegeState != null && siegeState.Stage == SiegeStage.Assault) { continue; } StatForecast statForecast = SettlementProsperityForecast(settlement); StatForecast statForecast2 = SettlementMilitiaForecast(settlement); if (settlement.Type == SettlementType.Town || settlement.Type == SettlementType.Castle) { FoodForecast foodForecast = SettlementFoodForecast(settlement); if (!foodForecast.Besieged) { FeedSettlement(settlement, foodForecast); if (foodForecast.Starving) { Starve(settlement); } else { settlement.StarvingDays = 0; } } } settlement.Prosperity += statForecast.Change; settlement.Militia = (int)Math.Max(0L, Math.Min(2147483647L - (long)settlement.WoundedMilitia, settlement.Militia + (long)Math.Round(statForecast2.Change))); } if (flag) { State.Touch(); } } internal void FeedSettlement(Settlement s, FoodForecast food) { double num = ((food.Supply > 1E-09) ? Math.Max(0.0, Math.Min(1.0, food.SupplyStored / food.Supply)) : 0.0); foreach (FoodSource source in food.Sources) { C.AddSettlementFood(s, source.GoodId, source.Amount * num); } C.TakeSettlementFood(s, food.CivilianConsumption, out var value); C.TakeSettlementFood(s, food.Consumption - food.CivilianConsumption); MarketState market = s.Market; if (s.Type == SettlementType.Town && value > 0 && market != null && market.Gold < 5000) { market.Gold += Math.Min(value, 5000 - market.Gold); } } internal void Starve(Settlement s) { if (s.StarvingDays < int.MaxValue) { s.StarvingDays++; } foreach (TroopStack item in s.Garrison.Stacks.ToList()) { if (item.Healthy > 0) { s.Garrison.Wound(item.UnitId, Math.Max(1, item.Healthy / 20)); } } s.Security = Math.Max(0.0, s.Security - 1.0); if (s.StarvingDays == 1) { State.AddLog(LogCategory.Warning, s.Name + " has run out of food; its people go hungry.", s.Id); if (s.OwnerClanId == State.PlayerClanId) { C.Raise(CampaignEventKind.Info, s.Name + " has run out of food.", false, s.Id); } } } } internal sealed class SiegeAiSystem { private readonly Campaign C; private CampaignState State => C.State; internal SiegeAiSystem(Campaign host) { C = host; } internal void LordSiegeOptions(Party party, Clan clan, double strength, List<(Party party, double strength, double dist)> hostiles, List options) { if (clan == null || clan.IsPlayerClan || C.MilitaryPartyFor(party) != null) { return; } SiegeState camp = State.Sieges.FirstOrDefault((SiegeState s) => s.BesiegerPartyId == party.Id && s.Stage != SiegeStage.Ended); if (camp != null) { Settlement settlement = State.Settlements.Get(camp.SettlementId); if (settlement == null) { return; } if (party.Food <= 0.0 || strength < C.SiegeDefenderStrength(settlement) * 0.8) { options.Add(new Campaign.AiOption { Task = "Lift siege", Score = 3.0, Detail = "insufficient supplies or strength", Apply = delegate { C.EndSiege(camp, "The besiegers withdrew to recover."); } }); return; } options.Add(new Campaign.AiOption { Task = "Besiege " + settlement.Name, Score = 2.4, Detail = ((camp.Stage == SiegeStage.Ready) ? "building siege engines and bombarding defenses" : "preparing camp; exposed to relief"), Apply = delegate { C.PlanAiSiegeWorks(camp); if (camp.Stage == SiegeStage.Ready && C.AiSiegeWorksReady(camp) && C.SiegeCampReason(camp, ready: true).Length == 0) { C.BeginSiegeAssault(camp); } } }); return; } foreach (SiegeState item in State.Sieges.Where((SiegeState s) => s.Stage == SiegeStage.Preparing || s.Stage == SiegeStage.Ready)) { Party target = State.Parties.Get(item.BesiegerPartyId); Settlement settlement2 = State.Settlements.Get(item.SettlementId); if (target != null && settlement2 != null && !(State.FactionOf(clan) != State.FactionOf(State.Clans.Get(settlement2.OwnerClanId))) && C.IsInterceptable(target) && C.CanSee(party, target) && State.AreHostile(party, target) && !(strength < C.PartyStrength(target) * 0.9)) { options.Add(new Campaign.AiOption { Task = "Relieve " + settlement2.Name, Score = 2.8, Detail = "visible enemy siege camp", Apply = delegate { C.SetMoveOrder(party, OrderKind.Engage, target.Position, target.Id, "relieve siege"); } }); } } if (party.Order.Kind == OrderKind.Raid || party.ActiveRaid != null || C.PartyCombatants(party) < 15 || party.Food < C.DailyFoodNeed(party) * 5.0 || hostiles.Any(((Party party, double strength, double dist) h) => h.strength > strength * 0.8) || State.Sieges.Any((SiegeState s) => s.Stage != SiegeStage.Ended && State.Parties.Get(s.BesiegerPartyId)?.ClanId == clan.Id)) { return; } foreach (Settlement target2 in from s in State.Settlements where (s.Type == SettlementType.Town || s.Type == SettlementType.Castle) && Vec2.Distance(s.Position, party.Position) <= C.StrategicRange(18.0) orderby Vec2.Distance(s.Position, party.Position), s.Id select s) { if (!(strength < C.SiegeDefenderStrength(target2) * 1.35) && C.SiegeOrderReason(party, target2).Length <= 0) { options.Add(new Campaign.AiOption { Task = "Besiege " + target2.Name, Score = ((Vec2.Distance(party.Position, target2.Position) <= 0.01) ? 0.7 : 0.6), Detail = "nearby hostile fort; supplies and military advantage", Apply = delegate { C.OrderSiege(party, target2); } }); break; } } } } internal sealed class SiegeBattlesSystem { private readonly Campaign C; private ContentDatabase Content => C.Content; private NavGrid Nav => C.Nav; private CampaignRules Rules => C.Rules; private CampaignState State => C.State; internal SiegeBattlesSystem(Campaign host) { C = host; } public CommandResult BeginSiegeAssault(SiegeState siege) { return CreateSiegeEncounter(siege, surrender: false); } public CommandResult SurrenderSiegeDefenders(SiegeState siege) { return CreateSiegeEncounter(siege, surrender: true); } internal CommandResult CreateSiegeEncounter(SiegeState siege, bool surrender) { if (siege == null || State.Sieges == null || !State.Sieges.Contains(siege) || siege.Stage != SiegeStage.Ready) { return CommandResult.Fail("The siege isn't ready for an assault."); } string text = (surrender ? C.SurrenderCampReason(siege) : C.SiegeCampReason(siege, ready: true)); if (text.Length > 0) { return CommandResult.Fail(text); } if (!Enum.IsDefined(typeof(SiegeCapturePolicy), siege.CapturePolicy)) { return CommandResult.Fail("Unknown occupation policy."); } Settlement settlement = State.Settlements.Get(siege.SettlementId); Party party = State.Parties.Get(siege.BesiegerPartyId); if (settlement == null || settlement.OwnerClanId != siege.OwnerClanId || (settlement.Type != SettlementType.Town && settlement.Type != SettlementType.Castle)) { return CommandResult.Fail("The place has changed hands."); } Clan clan = State.Clans.Get(siege.OwnerClanId); Clan clan2 = ((party == null) ? null : State.Clans.Get(party.ClanId)); if (party == null || party.State != PartyState.Active || C.MilitaryPartyReserved(party.Id) || !string.IsNullOrEmpty(party.EncounterId) || C.PartyCombatants(party) == 0 || Vec2.Distance(party.Position, settlement.Position) > Rules.ContactRadius || clan == null || clan2 == null || !State.AreHostile(clan2, clan)) { return CommandResult.Fail("A free hostile warband must hold the siege camp."); } if (settlement.Garrison == null || settlement.Garrison.Heroes.Count != 0 || settlement.Militia < 0 || settlement.WoundedMilitia < 0 || (long)settlement.Militia + (long)settlement.WoundedMilitia > int.MaxValue) { return CommandResult.Fail("The settlement's defender records cannot be reserved."); } string id = Content.Cultures.Get(settlement.CultureId)?.BasicTroop ?? ""; if ((settlement.Militia > 0 || settlement.WoundedMilitia > 0) && C.UnitDef(id) == null) { return CommandResult.Fail("The settlement has no valid militia troop definition."); } Party playerParty = State.PlayerParty; if (surrender && playerParty != null && playerParty.Id != party.Id && !C.MilitaryPartyReserved(playerParty.Id) && string.IsNullOrEmpty(playerParty.EncounterId) && playerParty.DisengagedUntilMinute <= State.Clock.Minute && C.PartyCombatants(playerParty) > 0 && State.FactionOf(State.Clans.Get(playerParty.ClanId)) == State.FactionOf(clan) && State.AreHostile(playerParty, party) && ((playerParty.State == PartyState.InSettlement && playerParty.CurrentSettlementId == settlement.Id) || (playerParty.State == PartyState.Active && Vec2.Distance(playerParty.Position, settlement.Position) <= Rules.JoinBattleRadius))) { return CommandResult.Fail("The player must decide whether to surrender their defense."); } Encounter encounter = new Encounter { Id = State.Ids.Allocate("enc"), CreatedAtMinute = State.Clock.Minute, Kind = EncounterKind.Siege, Position = settlement.Position, SiegeId = siege.Id, InitiatorPartyId = party.Id, Biome = Nav.TerrainAt(settlement.Position).Biome }; TroopRoster keepTroops = ((surrender || siege.NoKeepBattle) ? new TroopRoster() : C.SiegeSortiesSystem.KeepGuard(settlement)); Party party2 = SiegeDefender(settlement, "garrison", settlement.Garrison); Party party3 = SiegeDefender(settlement, "militia", new TroopRoster()); foreach (KeyValuePair> item in C.MilitiaTroops(settlement, settlement.Militia, settlement.WoundedMilitia)) { party3.Troops.Add(item.Key, item.Value.Key, item.Value.Value); } settlement.Garrison = new TroopRoster(); settlement.Militia = 0; settlement.WoundedMilitia = 0; State.Parties.Add(party2); State.Parties.Add(party3); encounter.AttackerParties.Add(party.Id); encounter.DefenderParties.Add(party2.Id); encounter.DefenderParties.Add(party3.Id); foreach (Party item2 in State.Parties.OrderBy((Party p) => p.Id, StringComparer.Ordinal)) { if (item2.Id == party.Id || item2.Kind == PartyKind.SiegeDefender || C.MilitaryPartyReserved(item2.Id) || !string.IsNullOrEmpty(item2.EncounterId) || item2.DisengagedUntilMinute > State.Clock.Minute || C.PartyCombatants(item2) == 0 || ((item2.State != PartyState.InSettlement || !(item2.CurrentSettlementId == settlement.Id)) && (!C.IsInterceptable(item2) || Vec2.Distance(item2.Position, settlement.Position) > Rules.JoinBattleRadius))) { continue; } Clan clan3 = State.Clans.Get(item2.ClanId); if (clan3 != null) { if (State.AreAllied(item2, party) && State.AreHostile(clan3, clan)) { encounter.AttackerParties.Add(item2.Id); } else if (State.FactionOf(clan3) == State.FactionOf(clan) && State.AreHostile(item2, party)) { encounter.DefenderParties.Add(item2.Id); } } } C.SiegeSortiesSystem.AddGuards(encounter, settlement, BattleSide.Defender, party2, party); siege.Stage = SiegeStage.Assault; siege.KeepTroops = keepTroops; siege.KeepStage = (siege.KeepPending = false); siege.KeepPartyId = ""; siege.EncounterId = encounter.Id; siege.GarrisonPartyId = party2.Id; siege.MilitiaPartyId = party3.Id; State.Encounters.Add(encounter); foreach (string allParty in encounter.AllParties) { Party party4 = State.Parties.Require(allParty); C.CancelRaid(party4, "joined a settlement assault", notify: false); party4.State = PartyState.Engaged; party4.EncounterId = encounter.Id; } encounter.PlayerInvolved = encounter.AllParties.Contains(State.PlayerPartyId); if (encounter.PlayerInvolved) { encounter.PlayerSide = encounter.SideOf(State.PlayerPartyId); State.Player.PendingEncounterId = encounter.Id; State.Player.Activity = PlayerActivity.InEncounter; C.NoteHeroesMet(); } State.Touch(); if (surrender) { BattleManifest battleManifest = C.BeginAttempt(encounter, 0); BattleResult battleResult = new BattleResult { CampaignId = State.CampaignId, EncounterId = encounter.Id, AttemptId = encounter.CurrentAttemptId, ExpectedRevision = encounter.ExpectedRevision, EndKind = BattleEndKind.Surrender, Winner = WinnerSide.Attacker, LosingSide = BattleSide.Defender, Simulated = true }; foreach (Combatant combatant in battleManifest.Combatants) { battleResult.Outcomes.Add(new CombatantResult { Id = combatant.Id, Outcome = CombatOutcome.Unhurt }); } CommitResult commitResult = OutcomeCommitter.Commit(C, battleResult); if (!commitResult.Success) { return CommandResult.Fail(commitResult.Error); } return CommandResult.Success("The defenders surrendered."); } if (encounter.PlayerInvolved) { C.Raise(CampaignEventKind.EncounterStarted, "The assault on " + settlement.Name + " is ready. Use prepared breaches and towers, or batter the central gate.", true, encounter.Id, settlement.Id); } else { C.ResolveAiEncounter(encounter); } return CommandResult.Success(); } internal Party SiegeDefender(Settlement settlement, string name, TroopRoster roster) { return new Party { Id = State.Ids.Allocate("siege-defender"), Name = settlement.Name + " " + name, Kind = PartyKind.SiegeDefender, ClanId = settlement.OwnerClanId, HomeSettlementId = settlement.Id, Position = settlement.Position, Troops = roster, AiFrozen = true, CreatedAtMinute = State.Clock.Minute }; } public string SiegeBattleValidation(Encounter enc) { if (enc == null) { return "The assault encounter is missing."; } if (string.IsNullOrEmpty(enc.SiegeId)) { if (enc.Kind != EncounterKind.Siege) { return ""; } return "The assault has no siege record."; } SiegeState siegeState = State.Sieges?.FirstOrDefault((SiegeState s) => s.Id == enc.SiegeId); if (siegeState == null || siegeState.Stage != SiegeStage.Assault || siegeState.EncounterId != enc.Id || enc.Kind != EncounterKind.Siege) { return "The assault is no longer reserved by this siege."; } Settlement settlement = State.Settlements.Get(siegeState.SettlementId); Party party = State.Parties.Get(siegeState.BesiegerPartyId); Clan clan = State.Clans.Get(siegeState.OwnerClanId); Clan clan2 = ((party == null) ? null : State.Clans.Get(party.ClanId)); if (settlement == null || settlement.OwnerClanId != siegeState.OwnerClanId || clan2 == null || clan == null || !State.AreHostile(clan2, clan) || !enc.AttackerParties.Contains(siegeState.BesiegerPartyId) || enc.InitiatorPartyId != siegeState.BesiegerPartyId) { return "The siege ownership or belligerents changed before the result was committed."; } if (!settlement.Garrison.IsEmpty || settlement.Militia != 0 || settlement.WoundedMilitia != 0) { return "The settlement defenders changed while the assault was reserved."; } if (!siegeState.KeepStage && siegeState.GarrisonPartyId == siegeState.MilitiaPartyId) { return "The assault has duplicate defender records."; } if (enc.IsKeepBattle != siegeState.KeepStage) { return "The assault is no longer reserved by this siege."; } string[] array = ((!siegeState.KeepStage) ? new string[2] { siegeState.GarrisonPartyId, siegeState.MilitiaPartyId } : new string[1] { siegeState.KeepPartyId }); foreach (string text in array) { Party party2 = State.Parties.Get(text); if (party2 == null || party2.Kind != PartyKind.SiegeDefender || party2.ClanId != siegeState.OwnerClanId || party2.HomeSettlementId != siegeState.SettlementId || !enc.DefenderParties.Contains(text) || party2.Troops.Heroes.Count != 0) { return "The reserved settlement defenders are missing or changed."; } } foreach (string id in enc.AllParties) { Party party3 = State.Parties.Get(id); if (party3 == null || party3.State != PartyState.Engaged || party3.EncounterId != enc.Id) { return "An assault participant is no longer reserved for this battle."; } if (enc.Manifest != null) { List fighters = enc.Manifest.Combatants.Where((Combatant c) => c.PartyId == id).ToList(); if (fighters.Any((Combatant c) => c.Side != enc.SideOf(id)) || (from c in fighters where !c.IsHero group c by c.UnitId).Any((IGrouping g) => party3.Troops.Healthy(g.Key) != g.Count()) || party3.Troops.Stacks.Any((TroopStack st) => fighters.Count((Combatant c) => !c.IsHero && c.UnitId == st.UnitId) != st.Healthy) || fighters.Where((Combatant c) => c.IsHero).Any(delegate(Combatant c) { if (party3.Troops.Heroes.Contains(c.HeroId)) { Hero hero = State.Heroes.Get(c.HeroId); if (hero == null) { return true; } return !hero.CanFight; } return true; }) || party3.Troops.Heroes.Any(delegate(string heroId) { Hero hero = State.Heroes.Get(heroId); return hero != null && hero.CanFight && fighters.Count((Combatant c) => c.HeroId == heroId) != 1; })) { return "An assault roster changed after battle preparation."; } } } return ""; } public void CancelSiegeBattle(Encounter enc) { SiegeState siegeState = State.Sieges?.FirstOrDefault((SiegeState s) => s.Id == enc.SiegeId); if (siegeState != null && siegeState.Stage == SiegeStage.Assault && !(siegeState.EncounterId != enc.Id)) { RestoreSiegeDefenders(siegeState, captured: false, null); RestoreSiegeResidents(enc, siegeState, captured: false); C.EndSiege(siegeState, "The assault was abandoned."); } } public void CompleteSiegeBattle(Encounter enc, BattleResult result, BattleReport report) { if (string.IsNullOrEmpty(enc.SiegeId)) { return; } SiegeState siegeState = State.Sieges?.FirstOrDefault((SiegeState s) => s.Id == enc.SiegeId); if (siegeState == null || siegeState.Stage != SiegeStage.Assault || siegeState.EncounterId != enc.Id) { return; } Party party = State.Parties.Get(siegeState.BesiegerPartyId); Hero hero = ((party == null) ? null : State.Heroes.Get(party.LeaderHeroId)); bool flag = result.Winner == WinnerSide.Attacker && (result.EndKind == BattleEndKind.Victory || result.EndKind == BattleEndKind.Surrender) && party != null && party.State == PartyState.Active && C.PartyCombatants(party) > 0 && hero != null && hero.State == HeroState.Active && hero.PartyId == party.Id; if (flag && !enc.IsKeepBattle && result.EndKind != BattleEndKind.Surrender && siegeState.KeepTroops != null && siegeState.KeepTroops.TotalHealthy > 0) { Party party2 = State.Parties.Get(siegeState.GarrisonPartyId); if (party2 != null) { foreach (TroopStack item in party2.Troops.Stacks.Where((TroopStack x) => x.Healthy > 0).ToList()) { SiegeSortiesSystem.MoveHealthy(party2.Troops, siegeState.KeepTroops, item.UnitId, item.Healthy); } } TroopRoster keepTroops = siegeState.KeepTroops; siegeState.KeepTroops = new TroopRoster(); RestoreSiegeDefenders(siegeState, captured: true, report); siegeState.KeepTroops = keepTroops; RestoreSiegeResidents(enc, siegeState, captured: true); siegeState.KeepAttackerIds = enc.AttackerParties.ToList(); siegeState.KeepPending = true; report?.Lines.Add("The walls are taken. " + keepTroops.TotalHealthy + " defenders fell back to the keep."); } else { RestoreSiegeDefenders(siegeState, flag, report); RestoreSiegeResidents(enc, siegeState, flag); if (flag) { C.CaptureSiegeSettlement(siegeState, report); } else { C.EndSiege(siegeState, enc.IsKeepBattle ? "The defenders held the keep." : "The defenders held the settlement."); } } } internal void RestoreSiegeResidents(Encounter enc, SiegeState siege, bool captured) { foreach (string allParty in enc.AllParties) { Party party = State.Parties.Get(allParty); if (party != null && !(party.CurrentSettlementId != siege.SettlementId)) { if (party.State == PartyState.Active && !captured) { party.State = PartyState.InSettlement; } else { party.CurrentSettlementId = ""; } if (party.Id == State.PlayerPartyId && captured) { State.Player.MenuSettlementId = ""; } } } } internal void RestoreSiegeDefenders(SiegeState siege, bool captured, BattleReport report) { Settlement settlement = State.Settlements.Require(siege.SettlementId); if (siege.KeepTroops != null && siege.KeepTroops.TotalTroops > 0) { if (!captured) { foreach (TroopStack stack in siege.KeepTroops.Stacks) { settlement.Garrison.Add(stack.UnitId, stack.Healthy, stack.Wounded, stack.Xp); } } else { report?.Lines.Add(siege.KeepTroops.TotalTroops + " of the keep's guard scattered after the capture."); } } siege.KeepTroops = new TroopRoster(); siege.KeepStage = (siege.KeepPending = false); siege.KeepAttackerIds.Clear(); string[] array = new string[3] { siege.GarrisonPartyId, siege.MilitiaPartyId, siege.KeepPartyId }; foreach (string text in array) { Party party = State.Parties.Get(text); if (party == null) { continue; } if (!captured) { if (text == siege.GarrisonPartyId || text == siege.KeepPartyId) { foreach (TroopStack stack2 in party.Troops.Stacks) { settlement.Garrison.Add(stack2.UnitId, stack2.Healthy, stack2.Wounded, stack2.Xp); } } else { settlement.Militia += party.Troops.TotalHealthy; settlement.WoundedMilitia += party.Troops.TotalWounded; } } else if (party.Troops.TotalTroops > 0) { report?.Lines.Add(party.Troops.TotalTroops + " surviving " + party.Name + " troops scattered after the capture."); } foreach (TroopStack stack3 in party.Prisoners.Stacks) { settlement.Prisoners.Add(stack3.UnitId, stack3.Healthy, stack3.Wounded, stack3.Xp); } foreach (string hero2 in party.Prisoners.Heroes) { Hero hero = State.Heroes.Get(hero2); if (hero != null) { if (!settlement.Prisoners.Heroes.Contains(hero2)) { settlement.Prisoners.Heroes.Add(hero2); } hero.CaptorPartyId = ""; hero.CaptorSettlementId = settlement.Id; if (hero.IsPlayer) { State.Player.CaptorPartyId = ""; State.Player.CaptorSettlementId = settlement.Id; } } } foreach (KeyValuePair item in party.Cargo) { settlement.Market.Stock.TryGetValue(item.Key, out var value); settlement.Market.Stock[item.Key] = (int)Math.Min(500L, Math.Max(0L, (long)value + (long)item.Value)); } C.AddSettlementFood(settlement, "good.grain", party.Food); if (party.Equipment != null && party.Equipment.Count > 0) { if (settlement.Market.EquipmentStock == null) { settlement.Market.EquipmentStock = new SortedDictionary(StringComparer.Ordinal); } settlement.Market.EquipmentInitialized = true; int num = 0; foreach (KeyValuePair item2 in party.Equipment) { int num2 = C.EquipmentStock(settlement, item2.Key); OwnedItemInfo ownedItemInfo = C.ItemInfo(item2.Key); int num3 = ((ownedItemInfo != null && ownedItemInfo.Shoppable) ? Math.Min(Math.Max(0, item2.Value), Math.Max(0, ownedItemInfo.Limit - num2)) : 0); settlement.Market.EquipmentStock[item2.Key] = num2 + num3; num += item2.Value - num3; } party.Equipment.Clear(); if (num > 0) { report?.Lines.Add(num + " loose equipment items were abandoned after the siege."); } } Clan clan = State.Clans.Get(siege.OwnerClanId); if (clan != null && party.Gold > 0) { State.Transact(clan, party.Gold, LedgerAccount.Loot, "Settlement defenders' spoils"); } State.PlayerSightings.Remove(text); State.Parties.Remove(text); } siege.GarrisonPartyId = ""; siege.MilitiaPartyId = ""; siege.KeepPartyId = ""; siege.EncounterId = ""; } } internal sealed class SiegeCaptureSystem { private readonly Campaign C; private CampaignState State => C.State; internal SiegeCaptureSystem(Campaign host) { C = host; } internal void CaptureSiegeSettlement(SiegeState siege, BattleReport report) { if (siege == null || !State.Sieges.Contains(siege) || siege.Stage != SiegeStage.Assault || !string.IsNullOrEmpty(siege.GarrisonPartyId) || !string.IsNullOrEmpty(siege.MilitiaPartyId) || report == null || !State.CommittedEncounters.Contains(report.EncounterId) || report.Winner != WinnerSide.Attacker || (report.EndKind != BattleEndKind.Victory && report.EndKind != BattleEndKind.Surrender)) { return; } Encounter encounter = State.Encounters.Get(report.EncounterId); if (encounter == null || encounter.SiegeId != siege.Id || encounter.Phase != EncounterPhase.Committed || encounter.InitiatorPartyId != siege.BesiegerPartyId) { return; } Settlement settlement = State.Settlements.Get(siege.SettlementId); Party party = State.Parties.Get(siege.BesiegerPartyId); Clan clan = ((party == null) ? null : State.Clans.Get(party.ClanId)); if (settlement == null || settlement.OwnerClanId != siege.OwnerClanId || clan == null || clan.IsEliminated || clan.IsBandit || party.State != PartyState.Active || C.PartyCombatants(party) <= 0) { C.EndSiege(siege, "Nobody left alive could take the place."); return; } if (settlement.Garrison.TotalTroops > 0) { report.Lines.Add(settlement.Garrison.TotalTroops + " remaining defenders dispersed from " + settlement.Name + "."); } settlement.Garrison = new TroopRoster(); settlement.Militia = 0; settlement.WoundedMilitia = 0; List list = State.Settlements.Where((Settlement s) => s.Id == settlement.Id || (s.Type == SettlementType.Village && s.BoundTo == settlement.Id && s.OwnerClanId == siege.OwnerClanId)).ToList(); C.RecordWarCapture(State.FactionOf(clan), State.FactionOf(State.Clans.Get(siege.OwnerClanId)), settlement.Id); foreach (Settlement item in list) { C.ChangeSettlementOwner(item, clan.Id); foreach (string item2 in item.Prisoners.Heroes.ToList()) { Hero hero = State.Heroes.Get(item2); Clan clan2 = ((hero == null) ? null : State.Clans.Get(hero.ClanId)); if (clan2 != null && !State.AreHostile(clan, clan2)) { OutcomeCommitter.ReleaseHero(C, hero, "liberated when " + item.Name + " changed hands"); } } } bool flag = siege.CapturePolicy == SiegeCapturePolicy.Pillage; long num = 0L; if (flag) { num = Math.Min(300L, Math.Min(Math.Max(0L, settlement.Market.Gold / 4), long.MaxValue - clan.Gold)); settlement.Market.Gold -= num; if (num > 0) { State.Transact(clan, num, LedgerAccount.Loot, "Pillaged " + settlement.Name); } settlement.Prosperity = Math.Max(0.0, settlement.Prosperity * 0.85); } settlement.Loyalty = Math.Max(0.0, settlement.Loyalty - (double)(flag ? 30 : 10)); settlement.Security = Math.Max(0.0, settlement.Security - (double)(flag ? 20 : 5)); string text = clan.Name + " captured " + settlement.Name + ((list.Count > 1) ? (" and " + (list.Count - 1) + " bound villages") : "") + "."; report.Lines.Add(text); report.Lines.Add(flag ? ("Pillage transferred " + num + " denars from the local market; prosperity, loyalty and security fell.") : "Occupied. The market keeps its money and goods; loyalty and security fell."); C.QueueCapturedFiefCouncil(siege, clan, settlement); C.EndSiege(siege, text); C.OnDiplomacyChanged(); C.Raise(CampaignEventKind.Info, text, clan.Id == State.PlayerClanId, settlement.Id, clan.Id); State.Touch(); } } internal sealed class SiegeSortiesSystem { public const string Sally = "sally"; public const string BreakOut = "breakout"; public const string BreakIn = "breakin"; public const int KeepGuardMinimum = 5; public const int KeepGuardMaximum = 24; public const int KeepBattleBudget = 60; public const double KeepGuardShare = 0.15; public const double AiSallyStrengthRatio = 1.4; public const double AiSallyChance = 0.5; public const int SortieDisengageHours = 4; private readonly Campaign C; private NavGrid Nav => C.Nav; private CampaignRules Rules => C.Rules; private CampaignState State => C.State; internal SiegeSortiesSystem(Campaign host) { C = host; } internal SiegeState SiegeOf(Encounter enc) { if (enc != null && !string.IsNullOrEmpty(enc.SortieSiegeId)) { return State.Sieges?.FirstOrDefault((SiegeState s) => s.Id == enc.SortieSiegeId); } return null; } private SiegeState OpenSiege(Settlement s) { SiegeState siegeState = ((s == null) ? null : C.SiegeForSettlement(s.Id)); if (siegeState == null || siegeState.Stage == SiegeStage.Marching || siegeState.Stage == SiegeStage.Assault || siegeState.Stage == SiegeStage.Ended) { return null; } if (!string.IsNullOrEmpty(siegeState.SortieEncounterId)) { return null; } return siegeState; } private Party Besieger(SiegeState siege) { return State.Parties.Get(siege?.BesiegerPartyId ?? ""); } internal bool ShutOut(Party p, Settlement s) { SiegeState siegeState = ((s == null) ? null : C.SiegeForSettlement(s.Id)); if (siegeState == null || siegeState.Stage == SiegeStage.Marching || siegeState.Stage == SiegeStage.Ended) { return false; } Party party = Besieger(siegeState); if (party != null) { return State.AreHostile(p, party); } return false; } public string SallyReason() { string text = C.CargoCommandReason(); if (text.Length > 0) { return text; } Party playerParty = State.PlayerParty; Settlement settlement = ((playerParty == null || playerParty.State != PartyState.InSettlement) ? null : State.Settlements.Get(playerParty.CurrentSettlementId)); if (settlement == null) { return "You have to be inside a besieged town or castle."; } SiegeState siegeState = C.SiegeForSettlement(settlement.Id); if (siegeState == null || siegeState.Stage == SiegeStage.Marching || siegeState.Stage == SiegeStage.Ended) { return settlement.Name + " isn't under siege."; } if (siegeState.Stage == SiegeStage.Assault) { return "The assault is under way."; } if (!string.IsNullOrEmpty(siegeState.SortieEncounterId)) { return "Someone is already fighting outside the walls."; } Party party = Besieger(siegeState); if (party == null || party.State != PartyState.Active || !string.IsNullOrEmpty(party.EncounterId) || C.MilitaryPartyReserved(party.Id)) { return "The besiegers are busy elsewhere."; } Clan clan = State.Clans.Get(settlement.OwnerClanId); if (State.FactionOf(State.PlayerClan) != State.FactionOf(clan)) { return "Only the realm's own warbands lead a sally from " + settlement.Name + "."; } if (!State.AreHostile(playerParty, party)) { return "You aren't at war with the besiegers."; } if (C.PartyCombatants(playerParty) == 0) { return "Nobody in your party is fit to fight."; } return ""; } public CommandResult SallyOut() { string text = SallyReason(); if (text.Length > 0) { return CommandResult.Fail(text); } Settlement s = State.Settlements.Require(State.PlayerParty.CurrentSettlementId); if (StartSally(OpenSiegeOrAny(s), State.PlayerParty) != null) { return CommandResult.Success("You lead a sally against the siege camp."); } return CommandResult.Fail("The sally couldn't be made ready."); } private SiegeState OpenSiegeOrAny(Settlement s) { return OpenSiege(s) ?? C.SiegeForSettlement(s.Id); } public string BreakOutReason() { string text = C.CargoCommandReason(); if (text.Length > 0) { return text; } Party playerParty = State.PlayerParty; Settlement settlement = ((playerParty == null || playerParty.State != PartyState.InSettlement) ? null : State.Settlements.Get(playerParty.CurrentSettlementId)); if (settlement == null) { return "You're not in a settlement."; } if (!ShutOut(playerParty, settlement)) { return settlement.Name + " isn't besieged by your enemies: you can leave as you like."; } SiegeState siegeState = C.SiegeForSettlement(settlement.Id); if (siegeState.Stage == SiegeStage.Assault) { return "The assault is under way."; } if (!string.IsNullOrEmpty(siegeState.SortieEncounterId)) { return "Someone is already fighting outside the walls."; } Party party = Besieger(siegeState); if (party.State != PartyState.Active || !string.IsNullOrEmpty(party.EncounterId) || C.MilitaryPartyReserved(party.Id)) { return "The besiegers are busy elsewhere."; } if (C.PartyCombatants(playerParty) == 0) { return "Nobody in your party is fit to fight."; } Party party2 = C.ArmyHead(playerParty); if (party2 != null && party2.Id != playerParty.Id) { return "Your army is staying here: " + C.MarchingWithArmyReason(); } return ""; } public CommandResult BreakOutOfSettlement() { string text = BreakOutReason(); if (text.Length > 0) { return CommandResult.Fail(text); } Settlement settlement = State.Settlements.Require(State.PlayerParty.CurrentSettlementId); SiegeState siege = C.SiegeForSettlement(settlement.Id); if (StartPicketFight(siege, State.PlayerParty, "breakout") != null) { return CommandResult.Success("You make for the besiegers' lines."); } LeaveFreely(State.PlayerParty, settlement); return CommandResult.Success("You slipped out of " + settlement.Name + "."); } public string BreakInReason(string settlementId) { string text = C.CargoCommandReason(); if (text.Length > 0) { return text; } Party playerParty = State.PlayerParty; Settlement settlement = State.Settlements.Get(settlementId ?? ""); if (playerParty == null || settlement == null || (settlement.Type != SettlementType.Town && settlement.Type != SettlementType.Castle)) { return "There's nowhere to break into."; } if (playerParty.State != PartyState.Active || !string.IsNullOrEmpty(playerParty.EncounterId) || C.MilitaryPartyReserved(playerParty.Id) || State.Player.Activity == PlayerActivity.Captive) { return "Deal with your own encounter first."; } if (!ShutOut(playerParty, settlement)) { return settlement.Name + " isn't besieged by your enemies."; } SiegeState siegeState = C.SiegeForSettlement(settlement.Id); if (siegeState.Stage == SiegeStage.Assault) { return "The assault is under way."; } if (!string.IsNullOrEmpty(siegeState.SortieEncounterId)) { return "Someone is already fighting outside the walls."; } if (State.AreHostile(State.PlayerClan, State.Clans.Get(settlement.OwnerClanId))) { return settlement.Name + " won't open its gates to you."; } if (Vec2.Distance(playerParty.Position, settlement.Position) > Rules.JoinBattleRadius) { return "Get closer to " + settlement.Name + " first."; } Party party = Besieger(siegeState); if (party.State != PartyState.Active || !string.IsNullOrEmpty(party.EncounterId) || C.MilitaryPartyReserved(party.Id)) { return "The besiegers are busy elsewhere."; } if (C.PartyCombatants(playerParty) == 0) { return "Nobody in your party is fit to fight."; } Party party2 = C.ArmyHead(playerParty); if (party2 != null && party2.Id != playerParty.Id) { return "Your army decides where it goes: " + C.MarchingWithArmyReason(); } return ""; } public CommandResult BreakIntoSettlement(string settlementId) { string text = BreakInReason(settlementId); if (text.Length > 0) { return CommandResult.Fail(text); } Settlement settlement = State.Settlements.Require(settlementId); SiegeState siege = C.SiegeForSettlement(settlement.Id); C.ClearOrder(State.PlayerParty); if (StartPicketFight(siege, State.PlayerParty, "breakin") != null) { return CommandResult.Success("You charge the besiegers' lines."); } EnterFreely(State.PlayerParty, settlement); return CommandResult.Success("You slipped into " + settlement.Name + "."); } private Encounter NewEncounter(SiegeState siege, Settlement s, string sortie, string initiatorId) { return new Encounter { Id = State.Ids.Allocate("enc"), CreatedAtMinute = State.Clock.Minute, Kind = EncounterKind.FieldBattle, Position = s.Position, Biome = Nav.TerrainAt(s.Position).Biome, InitiatorPartyId = initiatorId, SortieSiegeId = siege.Id, Sortie = sortie }; } internal static int MoveHealthy(TroopRoster from, TroopRoster to, string unitId, int count) { int num = from.Find(unitId)?.Xp ?? 0; int num2 = from.RemoveHealthy(unitId, count); int num3 = from.Find(unitId)?.Xp ?? 0; if (num2 > 0) { to.Add(unitId, num2, 0, Math.Max(0, num - num3)); } return num2; } private Party Proxy(Settlement s, string clanId, string name, TroopRoster roster) { return new Party { Id = State.Ids.Allocate("siege-defender"), Name = name, Kind = PartyKind.SiegeDefender, ClanId = clanId, HomeSettlementId = s.Id, Position = s.Position, Troops = roster, AiFrozen = true, CreatedAtMinute = State.Clock.Minute }; } private void Reserve(Encounter enc) { foreach (string allParty in enc.AllParties) { Party party = State.Parties.Require(allParty); C.CancelRaid(party, "joined a fight at a siege", notify: false); party.State = PartyState.Engaged; party.EncounterId = enc.Id; } } internal void AddGuards(Encounter enc, Settlement s, BattleSide settlementSide, Party settlementLead, Party campLead) { foreach (Party item in State.Parties.Where((Party p) => p.Kind == PartyKind.Garrison).OrderBy((Party p) => p.Id, StringComparer.Ordinal).ToList()) { if (enc.AllParties.Contains(item.Id)) { continue; } string text = C.GarrisonsSystem.SiegeCall(item, s); if (text.Length == 0) { continue; } BattleSide battleSide; if (text == "defend") { battleSide = settlementSide; } else if (enc.AttackerParties.Contains(text)) { battleSide = BattleSide.Attacker; } else { if (!enc.DefenderParties.Contains(text)) { continue; } battleSide = BattleSide.Defender; } bool flag = battleSide == settlementSide; Party party = (flag ? settlementLead : campLead); Party party2 = (flag ? campLead : settlementLead); Clan clan = State.Clans.Get(item.ClanId); if (clan == null || party2 == null || !State.AreHostile(item, party2)) { continue; } bool num; if (!flag) { if (party == null) { continue; } num = !State.AreAllied(item, party); } else { num = State.FactionOf(clan) != State.FactionOf(State.Clans.Get(s.OwnerClanId)); } if (!num) { enc.PartiesOn(battleSide).Add(item.Id); C.GarrisonsSystem.BringToSiege(item, s); } } } private void Involve(Encounter enc, string text, params string[] refs) { enc.PlayerInvolved = enc.AllParties.Contains(State.PlayerPartyId); if (enc.PlayerInvolved) { enc.PlayerSide = enc.SideOf(State.PlayerPartyId); State.Player.PendingEncounterId = enc.Id; State.Player.Activity = PlayerActivity.InEncounter; State.Player.WaitUntilMinute = 0L; C.NoteHeroesMet(); C.Raise(CampaignEventKind.EncounterStarted, text, forcePause: true, refs); } } internal Encounter StartSally(SiegeState siege, Party leader) { Settlement settlement = State.Settlements.Get(siege?.SettlementId ?? ""); Party party = Besieger(siege); if (settlement == null || party == null) { return null; } Clan b = State.Clans.Get(settlement.OwnerClanId); TroopRoster troopRoster = new TroopRoster(); foreach (TroopStack item in settlement.Garrison.Stacks.OrderBy((TroopStack x) => x.UnitId, StringComparer.Ordinal).ToList()) { MoveHealthy(settlement.Garrison, troopRoster, item.UnitId, item.Healthy); } Party party2 = null; if (troopRoster.TotalHealthy > 0) { party2 = Proxy(settlement, settlement.OwnerClanId, settlement.Name + " sally", troopRoster); State.Parties.Add(party2); } Encounter encounter = NewEncounter(siege, settlement, "sally", leader?.Id ?? party2?.Id ?? ""); if (leader != null) { encounter.AttackerParties.Add(leader.Id); } if (party2 != null) { encounter.AttackerParties.Add(party2.Id); } foreach (Party item2 in C.SiegeResidentDefenders(settlement).OrderBy((Party p) => p.Id, StringComparer.Ordinal).ToList()) { if (!encounter.AllParties.Contains(item2.Id) && !C.MilitaryPartyReserved(item2.Id) && string.IsNullOrEmpty(item2.EncounterId) && C.PartyCombatants(item2) != 0 && State.AreHostile(item2, party) && (!(item2.Id == State.PlayerPartyId) || !(leader?.Id != item2.Id))) { encounter.AttackerParties.Add(item2.Id); } } if (encounter.AttackerParties.Count == 0) { if (party2 != null) { ReturnToSettlement(party2, settlement, null); } return null; } if (string.IsNullOrEmpty(encounter.InitiatorPartyId)) { encounter.InitiatorPartyId = encounter.AttackerParties[0]; } encounter.DefenderParties.Add(party.Id); foreach (Party item3 in State.Parties.OrderBy((Party p) => p.Id, StringComparer.Ordinal)) { if (!encounter.AllParties.Contains(item3.Id) && item3.Kind != PartyKind.SiegeDefender && item3.Kind != PartyKind.Garrison && C.IsInterceptable(item3) && !C.MilitaryPartyReserved(item3.Id) && item3.DisengagedUntilMinute <= State.Clock.Minute && C.PartyCombatants(item3) != 0 && !(Vec2.Distance(item3.Position, settlement.Position) > Rules.JoinBattleRadius)) { Clan clan = State.Clans.Get(item3.ClanId); if (clan != null && (!(item3.Id == State.PlayerPartyId) || State.AreAllied(item3, party)) && State.AreAllied(item3, party) && State.AreHostile(clan, b)) { encounter.DefenderParties.Add(item3.Id); } } } AddGuards(encounter, settlement, BattleSide.Attacker, party2 ?? State.Parties.Get(encounter.AttackerParties[0]), party); siege.Sortie = "sally"; siege.SortieEncounterId = encounter.Id; siege.SortiePartyId = party2?.Id ?? ""; State.Encounters.Add(encounter); Reserve(encounter); State.AddLog(LogCategory.Battle, "The defenders of " + settlement.Name + " sallied out against " + party.Name + "'s camp.", settlement.Id, party.Id); Involve(encounter, (encounter.PlayerSide == BattleSide.Attacker) ? ("You lead the sally out of " + settlement.Name + " against the siege camp.") : ("The garrison of " + settlement.Name + " sallies out against your camp!"), encounter.Id, settlement.Id); State.Touch(); if (!encounter.PlayerInvolved) { C.ResolveAiEncounter(encounter); } return encounter; } internal int PicketSize(Party besieger, Party breaker) { return Math.Min(besieger.Troops.TotalHealthy, Math.Max(5, (int)Math.Ceiling((double)C.PartyCombatants(breaker) * 1.2) + 3)); } internal Encounter StartPicketFight(SiegeState siege, Party breaker, string sortie) { Settlement settlement = State.Settlements.Get(siege?.SettlementId ?? ""); Party party = Besieger(siege); if (settlement == null || party == null) { return null; } int size = PicketSize(party, breaker); if (size <= 0) { return null; } TroopRoster troopRoster = new TroopRoster(); List source = party.Troops.Stacks.Where((TroopStack x) => x.Healthy > 0).OrderBy((TroopStack x) => x.UnitId, StringComparer.Ordinal).ToList(); int total = source.Sum((TroopStack x) => x.Healthy); List<(string, int, int)> list = source.Select((TroopStack x) => (UnitId: x.UnitId, n: (int)Math.Floor((double)x.Healthy * (double)size / (double)total), have: x.Healthy)).ToList(); int num = size - list.Sum<(string, int, int)>(((string UnitId, int n, int have) x) => x.n); int num2 = 0; while (num > 0 && num2 < list.Count * 2) { int index = num2 % list.Count; if (list[index].Item2 < list[index].Item3) { list[index] = (list[index].Item1, list[index].Item2 + 1, list[index].Item3); num--; } num2++; } foreach (var item in list.Where<(string, int, int)>(((string UnitId, int n, int have) x) => x.n > 0)) { MoveHealthy(party.Troops, troopRoster, item.Item1, item.Item2); } if (troopRoster.TotalHealthy == 0) { return null; } Party party2 = Proxy(settlement, party.ClanId, party.Name + " pickets", troopRoster); State.Parties.Add(party2); Encounter encounter = NewEncounter(siege, settlement, sortie, breaker.Id); encounter.AttackerParties.Add(breaker.Id); encounter.DefenderParties.Add(party2.Id); if (sortie == "breakin") { AddGuards(encounter, settlement, BattleSide.Attacker, breaker, party); } siege.Sortie = sortie; siege.SortieEncounterId = encounter.Id; siege.SortiePartyId = party2.Id; State.Encounters.Add(encounter); Reserve(encounter); Involve(encounter, (sortie == "breakout") ? ("You make for the lines round " + settlement.Name + ": " + party2.Name + " stand in the way.") : ("You charge the lines round " + settlement.Name + ": " + party2.Name + " stand in the way."), encounter.Id, settlement.Id); State.Touch(); if (!encounter.PlayerInvolved) { C.ResolveAiEncounter(encounter); } return encounter; } internal void ReturnToSettlement(Party proxy, Settlement s, BattleReport report) { foreach (TroopStack stack in proxy.Troops.Stacks) { s.Garrison.Add(stack.UnitId, stack.Healthy, stack.Wounded, stack.Xp); } foreach (TroopStack stack2 in proxy.Prisoners.Stacks) { s.Prisoners.Add(stack2.UnitId, stack2.Healthy, stack2.Wounded, stack2.Xp); } foreach (string hero2 in proxy.Prisoners.Heroes) { Hero hero = State.Heroes.Get(hero2); if (hero != null) { if (!s.Prisoners.Heroes.Contains(hero2)) { s.Prisoners.Heroes.Add(hero2); } hero.CaptorPartyId = ""; hero.CaptorSettlementId = s.Id; if (hero.IsPlayer) { State.Player.CaptorPartyId = ""; State.Player.CaptorSettlementId = s.Id; } } } foreach (KeyValuePair item in proxy.Cargo) { s.Market.Stock.TryGetValue(item.Key, out var value); s.Market.Stock[item.Key] = (int)Math.Min(500L, Math.Max(0L, (long)value + (long)item.Value)); } if (proxy.Food > 0.0) { C.AddSettlementFood(s, "good.grain", proxy.Food); } Clan clan = State.Clans.Get(s.OwnerClanId); if (clan != null && proxy.Gold > 0) { State.Transact(clan, proxy.Gold, LedgerAccount.Loot, "Siege defenders' spoils"); } Drop(proxy, report); } internal void ReturnToCamp(Party proxy, Party besieger, BattleReport report) { if (besieger == null || besieger.State == PartyState.Destroyed || besieger.State == PartyState.Disbanded) { foreach (string item in proxy.Prisoners.Heroes.ToList()) { OutcomeCommitter.ReleaseHero(C, State.Heroes.Get(item), "the besiegers' camp was gone"); } if (proxy.Troops.TotalTroops > 0) { report?.Lines.Add(proxy.Troops.TotalTroops + " of " + proxy.Name + " scattered: their camp was gone."); } Drop(proxy, report); return; } foreach (TroopStack stack in proxy.Troops.Stacks) { besieger.Troops.Add(stack.UnitId, stack.Healthy, stack.Wounded, stack.Xp); } foreach (TroopStack stack2 in proxy.Prisoners.Stacks) { besieger.Prisoners.Add(stack2.UnitId, stack2.Healthy, stack2.Wounded, stack2.Xp); } foreach (string hero2 in proxy.Prisoners.Heroes) { Hero hero = State.Heroes.Get(hero2); if (hero != null) { if (!besieger.Prisoners.Heroes.Contains(hero2)) { besieger.Prisoners.Heroes.Add(hero2); } hero.CaptorPartyId = besieger.Id; hero.CaptorSettlementId = ""; if (hero.IsPlayer) { State.Player.CaptorPartyId = besieger.Id; State.Player.CaptorSettlementId = ""; } } } foreach (KeyValuePair item2 in proxy.Cargo) { besieger.Cargo[item2.Key] = (besieger.Cargo.TryGetValue(item2.Key, out var value) ? value : 0) + item2.Value; } besieger.Food += proxy.Food; Clan clan = State.Clans.Get(besieger.ClanId); if (proxy.Gold > 0) { if (clan != null && !clan.IsBandit) { State.Transact(clan, proxy.Gold, LedgerAccount.Loot, "Pickets' spoils"); } else { besieger.Gold += proxy.Gold; } } Drop(proxy, report); } private void Drop(Party proxy, BattleReport report) { if (proxy.Equipment != null && proxy.Equipment.Count > 0) { int num = proxy.Equipment.Values.Sum(); proxy.Equipment.Clear(); if (num > 0) { report?.Lines.Add(num + " loose equipment items were abandoned after the fight."); } } proxy.Troops.Stacks.Clear(); proxy.Prisoners.Stacks.Clear(); proxy.Prisoners.Heroes.Clear(); State.PlayerSightings.Remove(proxy.Id); State.Parties.Remove(proxy.Id); } private void BackInside(Party p, Settlement s) { if (p == null || p.State != PartyState.Active || p.Kind == PartyKind.SiegeDefender || p.Kind == PartyKind.Garrison) { return; } if (p.Id == State.PlayerPartyId) { if (State.Player.Activity == PlayerActivity.Captive) { return; } Hero playerHero = State.PlayerHero; if (playerHero == null || playerHero.State != HeroState.Active) { return; } } p.State = PartyState.InSettlement; p.CurrentSettlementId = s.Id; p.Position = s.Position; C.ClearOrder(p); if (p.Id == State.PlayerPartyId) { State.Player.MenuSettlementId = s.Id; if (State.Player.Activity == PlayerActivity.Idle || State.Player.Activity == PlayerActivity.InEncounter) { State.Player.Activity = PlayerActivity.InSettlement; } } } private void LeaveFreely(Party p, Settlement s) { C.LeaveSettlementInternal(p); p.Position = s.Position; p.DisengagedUntilMinute = State.Clock.Minute + 240; C.UpdatePlayerTimeStates(); State.Touch(); } private void EnterFreely(Party p, Settlement s) { p.State = PartyState.InSettlement; p.CurrentSettlementId = s.Id; p.Position = s.Position; C.ClearOrder(p); if (p.Id == State.PlayerPartyId) { State.Player.MenuSettlementId = s.Id; State.Player.KeepAccessSettlementId = ""; State.Player.Activity = PlayerActivity.InSettlement; C.RefreshContractOffers(); C.UpdatePlayerTimeStates(); } State.Touch(); } internal void Complete(Encounter enc, BattleResult result, BattleReport report) { SiegeState siegeState = SiegeOf(enc); if (siegeState == null || siegeState.SortieEncounterId != enc.Id) { return; } Settlement settlement = State.Settlements.Get(siegeState.SettlementId); Party besieger = Besieger(siegeState); Party party = State.Parties.Get(siegeState.SortiePartyId); bool flag = result.Winner == WinnerSide.Attacker && result.EndKind != BattleEndKind.MutualDestruction; string sortie = siegeState.Sortie; siegeState.Sortie = (siegeState.SortieEncounterId = (siegeState.SortiePartyId = "")); if (sortie == "sally") { if (party != null && settlement != null) { ReturnToSettlement(party, settlement, report); } foreach (string attackerParty in enc.AttackerParties) { BackInside(State.Parties.Get(attackerParty), settlement); } if (flag) { report?.Lines.Add("The sally broke the siege of " + settlement?.Name + "."); C.EndSiege(siegeState, "The defenders sallied out and broke the siege."); } else { BattleManifest manifest = enc.Manifest; int num = manifest?.OnSide(BattleSide.Defender).Count() ?? 0; int num2 = manifest?.OnSide(BattleSide.Defender).Count((Combatant c) => result.Outcomes.Any((CombatantResult o) => o.Id == c.Id && o.Outcome == CombatOutcome.Downed)) ?? 0; double num3 = ((num == 0) ? 0.0 : Math.Min(0.6, (double)num2 / (double)num)); int num4 = 0; foreach (SiegeEngineState item in siegeState.Works?.Attackers.Where((SiegeEngineState e) => e.IsOperational) ?? Enumerable.Empty()) { item.Health = Math.Max(0.0, item.Health - item.MaxHealth * num3); if (item.Health <= 0.0) { num4++; } } if (num4 > 0) { report?.Lines.Add(num4 + " siege engine" + ((num4 == 1) ? " was" : "s were") + " wrecked in the sally."); } report?.Lines.Add("The sally was beaten back behind the walls of " + settlement?.Name + "."); } } else { if (party != null) { ReturnToCamp(party, besieger, report); } Party breaker = State.Parties.Get(enc.InitiatorPartyId); if (sortie == "breakout") { if (flag && breaker != null && breaker.State == PartyState.Active && settlement != null) { breaker.CurrentSettlementId = ""; breaker.Position = settlement.Position; breaker.DisengagedUntilMinute = State.Clock.Minute + 240; if (breaker.Id == State.PlayerPartyId) { State.Player.MenuSettlementId = ""; } report?.Lines.Add("You broke out of " + settlement.Name + "."); } else { BackInside(breaker, settlement); report?.Lines.Add("You were driven back into " + settlement?.Name + "."); } } else if (flag && breaker != null && breaker.State == PartyState.Active && settlement != null && !State.AreHostile(State.Clans.Get(breaker.ClanId), State.Clans.Get(settlement.OwnerClanId))) { EnterFreely(breaker, settlement); foreach (string item2 in enc.AttackerParties.Where((string id) => id != breaker.Id)) { Party party2 = State.Parties.Get(item2); if (party2 != null) { party2.Position = settlement.Position; } } report?.Lines.Add("You fought your way into " + settlement.Name + "."); } else { report?.Lines.Add("The besiegers held you off from " + settlement?.Name + "."); } } State.Touch(); } internal void Cancel(Encounter enc) { SiegeState siegeState = SiegeOf(enc); if (siegeState == null || siegeState.SortieEncounterId != enc.Id) { return; } Settlement settlement = State.Settlements.Get(siegeState.SettlementId); Party party = State.Parties.Get(siegeState.SortiePartyId); string sortie = siegeState.Sortie; siegeState.Sortie = (siegeState.SortieEncounterId = (siegeState.SortiePartyId = "")); if (party != null) { if (sortie == "sally" && settlement != null) { ReturnToSettlement(party, settlement, null); } else { ReturnToCamp(party, Besieger(siegeState), null); } } if (sortie == "sally" || sortie == "breakout") { foreach (string attackerParty in enc.AttackerParties) { BackInside(State.Parties.Get(attackerParty), settlement); } } State.Touch(); } internal void DailyAiSallies() { foreach (SiegeState item in (State.Sieges ?? new List()).Where((SiegeState x) => x.Stage == SiegeStage.Ready || x.Stage == SiegeStage.Preparing).ToList()) { Settlement settlement = State.Settlements.Get(item.SettlementId); if (settlement == null || OpenSiege(settlement) != item) { continue; } Party playerParty = State.PlayerParty; if (playerParty != null && playerParty.State == PartyState.InSettlement && playerParty.CurrentSettlementId == settlement.Id) { continue; } Party besieger = Besieger(item); if (besieger != null && besieger.State == PartyState.Active && string.IsNullOrEmpty(besieger.EncounterId) && !C.MilitaryPartyReserved(besieger.Id) && settlement.Garrison.TotalHealthy >= 10) { double num = settlement.Garrison.Stacks.Sum((TroopStack x) => (double)x.Healthy * C.UnitPower(x.UnitId)) + (from p in C.SiegeResidentDefenders(settlement) where p.Id != State.PlayerPartyId && State.AreHostile(p, besieger) select p).Sum((Func)C.PartyStrength); double num2 = C.SiegesSystem.SiegeBesiegerStrength(item); if (!(num2 <= 0.0) && !(num < num2 * 1.4) && State.Random.Get("siege.sally").Chance(0.5)) { StartSally(item, null); } } } } internal TroopRoster KeepGuard(Settlement s) { TroopRoster troopRoster = new TroopRoster(); int totalHealthy = s.Garrison.TotalHealthy; int num = C.SiegeDefenders(s); int num2 = Math.Min(24, Math.Max(5, (int)Math.Round((double)num * 0.15))); if (totalHealthy < num2 + 3) { return troopRoster; } foreach (TroopStack item in (from x in s.Garrison.Stacks where x.Healthy > 0 orderby C.UnitDef(x.UnitId)?.Tier ?? 1 descending select x).ThenBy((TroopStack x) => x.UnitId, StringComparer.Ordinal).ToList()) { if (num2 <= 0) { break; } num2 -= MoveHealthy(s.Garrison, troopRoster, item.UnitId, Math.Min(num2, item.Healthy)); } return troopRoster; } internal void StartPendingKeepBattles() { foreach (SiegeState item in (State.Sieges ?? new List()).Where((SiegeState x) => x.KeepPending).ToList()) { item.KeepPending = false; Settlement settlement = State.Settlements.Get(item.SettlementId); Party party = Besieger(item); Clan clan = State.Clans.Get(item.OwnerClanId); Hero hero = ((party == null) ? null : State.Heroes.Get(party.LeaderHeroId)); if (settlement == null || clan == null || party == null || party.State != PartyState.Active || C.PartyCombatants(party) <= 0 || hero == null || hero.State != HeroState.Active || !(hero.PartyId == party.Id) || !(settlement.OwnerClanId == item.OwnerClanId) || !State.AreHostile(State.Clans.Get(party.ClanId), clan) || item.KeepTroops.TotalHealthy <= 0) { C.SiegeBattlesSystem.RestoreSiegeDefenders(item, captured: false, null); C.EndSiege(item, "The defenders held the keep."); continue; } Party party2 = Proxy(settlement, settlement.OwnerClanId, settlement.Name + " keep guard", item.KeepTroops); item.KeepTroops = new TroopRoster(); State.Parties.Add(party2); Encounter encounter = new Encounter { Id = State.Ids.Allocate("enc"), CreatedAtMinute = State.Clock.Minute, Kind = EncounterKind.Siege, Position = settlement.Position, SiegeId = item.Id, SiegeStage = "keep", InitiatorPartyId = party.Id, Biome = Nav.TerrainAt(settlement.Position).Biome }; encounter.AttackerParties.Add(party.Id); foreach (string keepAttackerId in item.KeepAttackerIds) { Party party3 = State.Parties.Get(keepAttackerId); if (party3 != null && !encounter.AttackerParties.Contains(keepAttackerId) && party3.State == PartyState.Active && string.IsNullOrEmpty(party3.EncounterId) && !C.MilitaryPartyReserved(party3.Id) && C.PartyCombatants(party3) != 0 && !(Vec2.Distance(party3.Position, settlement.Position) > Rules.JoinBattleRadius)) { Clan clan2 = State.Clans.Get(party3.ClanId); if (clan2 != null && State.AreHostile(clan2, clan)) { encounter.AttackerParties.Add(keepAttackerId); } } } encounter.DefenderParties.Add(party2.Id); item.KeepAttackerIds.Clear(); item.KeepPartyId = party2.Id; item.KeepStage = true; item.EncounterId = encounter.Id; State.Encounters.Add(encounter); Reserve(encounter); State.AddLog(LogCategory.Battle, "The walls of " + settlement.Name + " fell; " + party2.Troops.TotalHealthy + " of its defenders hold out in the keep.", settlement.Id, party.Id); Involve(encounter, "The walls of " + settlement.Name + " are yours, but " + party2.Troops.TotalHealthy + " defenders hold the keep. Take it, and the place is yours.", encounter.Id, settlement.Id); State.Touch(); if (!encounter.PlayerInvolved) { C.ResolveAiEncounter(encounter); } } } } internal sealed class SiegesSystem { private readonly Campaign C; private ContentDatabase Content => C.Content; private NavGrid Nav => C.Nav; private CampaignRules Rules => C.Rules; private CampaignState State => C.State; public SiegeState PlayerSiege => State.Sieges?.FirstOrDefault((SiegeState s) => s.Stage != SiegeStage.Ended && s.BesiegerPartyId == State.PlayerPartyId); internal SiegesSystem(Campaign host) { C = host; } public SiegeState SiegeForSettlement(string id) { return State.Sieges?.FirstOrDefault((SiegeState s) => s.Stage != SiegeStage.Ended && s.SettlementId == id); } public bool IsSettlementBesieged(Settlement settlement) { SiegeState siegeState = SiegeForSettlement(settlement?.Id); if (siegeState != null) { return siegeState.Stage != SiegeStage.Marching; } return false; } public void EnsureSiegeFields() { if (State.Sieges == null) { State.Sieges = new List(); State.Touch(); } foreach (SiegeState item in State.Sieges.Where((SiegeState s) => s != null && s.Works == null && s.Stage != SiegeStage.Assault && s.Stage != SiegeStage.Ended)) { item.Works = SiegeWorksRules.Create(C.WallLevel(State.Settlements.Get(item.SettlementId ?? ""))); State.Touch(); } } public IEnumerable SiegeResidentDefenders(Settlement settlement) { return State.ActiveParties.Where((Party p) => p.Kind != PartyKind.SiegeDefender && p.State == PartyState.InSettlement && p.CurrentSettlementId == settlement.Id && Vec2.Distance(p.Position, settlement.Position) <= 0.01 && State.FactionOfParty(p) == State.FactionOf(State.Clans.Get(settlement.OwnerClanId))); } public int SiegeDefenders(Settlement settlement) { if (settlement == null) { return 0; } long num = (long)Math.Max(0, settlement.Militia) + (long)settlement.Garrison.TotalHealthy + settlement.Garrison.Heroes.Count((string id2) => State.Heroes.Get(id2)?.CanFight ?? false); num += SiegeResidentDefenders(settlement).Sum((Func)((Party p) => C.PartyCombatants(p))); SiegeState siegeState = SiegeForSettlement(settlement.Id); if (siegeState != null && siegeState.Stage == SiegeStage.Assault) { string[] array = new string[3] { siegeState.GarrisonPartyId, siegeState.MilitiaPartyId, siegeState.KeepPartyId }; foreach (string id in array) { Party party = State.Parties.Get(id); if (party != null) { num += C.PartyCombatants(party); } } num += siegeState.KeepTroops?.TotalHealthy ?? 0; } if (siegeState != null && siegeState.Sortie == "sally") { Party party2 = State.Parties.Get(siegeState.SortiePartyId); if (party2 != null) { num += C.PartyCombatants(party2); } } return (int)Math.Min(2147483647L, num); } internal double MilitiaPower(Settlement settlement) { List source = DefenderTroops.Line(Content, settlement.CultureId); double num = source.Sum((WeightedUnit w) => w.Weight); if (!(num <= 0.0)) { return source.Sum((WeightedUnit w) => w.Weight * C.UnitPower(w.Unit)) / num; } return C.UnitPower(Content.Cultures.Get(settlement.CultureId)?.BasicTroop); } internal List>> MilitiaTroops(Settlement settlement, int healthy, int wounded) { List list = DefenderTroops.Line(Content, settlement.CultureId); if (list.Count == 0) { list.Add(new WeightedUnit { Unit = (Content.Cultures.Get(settlement.CultureId)?.BasicTroop ?? ""), Weight = 1.0 }); } Dictionary h = DefenderTroops.Split(list, Math.Max(0, healthy)).ToDictionary((KeyValuePair e) => e.Key, (KeyValuePair e) => e.Value); Dictionary w = DefenderTroops.Split(list, Math.Max(0, wounded)).ToDictionary((KeyValuePair e) => e.Key, (KeyValuePair e) => e.Value); int value; int value2; return (from u in list select u.Unit into id where h.ContainsKey(id) || w.ContainsKey(id) select new KeyValuePair>(id, new KeyValuePair(h.TryGetValue(id, out value) ? value : 0, w.TryGetValue(id, out value2) ? value2 : 0))).ToList(); } public double SiegeDefenderStrength(Settlement settlement) { if (settlement != null) { return (double)Math.Max(0, settlement.Militia) * MilitiaPower(settlement) + settlement.Garrison.Stacks.Sum((TroopStack s) => (double)s.Healthy * C.UnitPower(s.UnitId)) + settlement.Garrison.Heroes.Sum((string id) => C.HeroPower(State.Heroes.Get(id))) + SiegeResidentDefenders(settlement).Sum((Func)C.PartyStrength); } return 0.0; } public double SiegeBesiegerStrength(SiegeState siege) { Party party = State.Parties.Get(siege?.BesiegerPartyId); if (party == null) { return 0.0; } return State.ActiveParties.Where((Party p) => p.Kind != PartyKind.SiegeDefender && p.State == PartyState.Active && (p.Id == party.Id || (State.AreAllied(p, party) && !C.MilitaryPartyReserved(p.Id) && string.IsNullOrEmpty(p.EncounterId) && p.DisengagedUntilMinute <= State.Clock.Minute && Vec2.Distance(p.Position, party.Position) <= Rules.JoinBattleRadius))).Sum((Func)C.PartyStrength); } internal string SiegePartyReason(Party party) { if (party == null || State.Parties.Get(party.Id) != party || (party.Kind != PartyKind.Player && party.Kind != PartyKind.Lord)) { return "Only a field warband can lay siege."; } if ((party.State != PartyState.Active && party.State != PartyState.InSettlement) || C.MilitaryPartyReserved(party.Id) || !string.IsNullOrEmpty(party.EncounterId)) { return "Deal with this warband's encounter first."; } Clan clan = State.Clans.Get(party.ClanId); Hero hero = State.Heroes.Get(party.LeaderHeroId); if (clan == null || clan.IsBandit || clan.IsEliminated || hero == null || !hero.CanFight || hero.ClanId != clan.Id || !Campaign.IsPresentPartyHero(party, hero)) { return "The siege needs a fit clan commander."; } if (party.Id == State.PlayerPartyId && (State.PlayerHeroId != hero.Id || State.PlayerClanId != clan.Id)) { return "You have to lead your own warband."; } if (party.ClanId == State.PlayerClanId && State.ClanService.Kind == ClanServiceKind.Mercenary) { return "A mercenary doesn't get to keep what it captures."; } if (C.PartyCombatants(party) < 5) { return "Bring at least 5 fit fighters."; } return ""; } public string SiegeOrderReason(Party party, Settlement settlement) { string text = SiegePartyReason(party); if (text.Length > 0) { return text; } if (settlement == null || State.Settlements.Get(settlement.Id) != settlement || (settlement.Type != SettlementType.Town && settlement.Type != SettlementType.Castle)) { return "Only towns and castles can be besieged."; } Clan clan = State.Clans.Get(settlement.OwnerClanId); if (clan == null || clan.IsEliminated || clan.IsBandit || !State.AreHostile(State.Clans.Get(party.ClanId), clan)) { return "You have to be at war with the owner."; } if (SiegeForSettlement(settlement.Id) != null) { return "Someone's already ordered to besiege it."; } if (Content.Cultures.Get(settlement.CultureId) == null || C.UnitDef(Content.Cultures.Get(settlement.CultureId).BasicTroop) == null) { return "The settlement's militia blueprint is unavailable."; } if (SiegeResidentDefenders(settlement).Any((Party p) => C.MilitaryPartyReserved(p.Id) || !string.IsNullOrEmpty(p.EncounterId))) { return "The defenders are already fighting someone."; } if (!Nav.Reaches(party.Position, settlement.Position, 0.01)) { return "You can't get there."; } return ""; } public string SiegeReason(string settlementId) { string text = C.CargoCommandReason(); if (text.Length <= 0) { return SiegeOrderReason(State.PlayerParty, State.Settlements.Get(settlementId)); } return text; } public CommandResult BesiegeSettlement(string settlementId) { string text = SiegeReason(settlementId); if (text.Length > 0) { return CommandResult.Fail(text); } CommandResult commandResult = OrderSiege(State.PlayerParty, State.Settlements.Require(settlementId)); if (commandResult.Ok) { State.Player.WaitUntilMinute = 0L; C.UpdatePlayerTimeStates(); C.ResumeIfPaused(); } return commandResult; } public CommandResult OrderSiege(Party party, Settlement settlement) { string text = SiegeOrderReason(party, settlement); if (text.Length > 0) { return CommandResult.Fail(text); } if (!C.SetMoveOrder(party, OrderKind.Besiege, settlement.Position, settlement.Id, "siege")) { return CommandResult.Fail("No route to the settlement."); } SiegeState item = new SiegeState { Id = State.Ids.Allocate("siege"), SettlementId = settlement.Id, BesiegerPartyId = party.Id, OwnerClanId = settlement.OwnerClanId, StartedMinute = State.Clock.Minute, LastProcessedMinute = State.Clock.Minute, LastSupplyDay = State.Clock.Day, Stage = SiegeStage.Marching, Works = SiegeWorksRules.Create(C.WallLevel(settlement)) }; State.Sieges.Add(item); PruneSieges(); State.AddLog(LogCategory.Battle, party.Name + " marched to besiege " + settlement.Name + ".", settlement.Id, party.Id); State.Touch(); return CommandResult.Success("Marching to besiege " + settlement.Name + "."); } internal string SiegeCampReason(SiegeState siege, bool ready) { if (siege == null || siege.Stage == SiegeStage.Ended) { return "There is no active siege."; } string text = SiegePartyReason(State.Parties.Get(siege.BesiegerPartyId)); if (text.Length > 0) { return text; } Party party = State.Parties.Require(siege.BesiegerPartyId); Settlement settlement = State.Settlements.Get(siege.SettlementId); if (settlement == null || settlement.OwnerClanId != siege.OwnerClanId || !State.AreHostile(State.Clans.Get(party.ClanId), State.Clans.Get(settlement.OwnerClanId))) { return "The owner or the diplomacy changed."; } if (siege.Stage == SiegeStage.Assault) { return "Resolve the assault first."; } if (!string.IsNullOrEmpty(siege.SortieEncounterId)) { return "Deal with the fighting outside the walls first."; } if (party.State != PartyState.Active || party.Order.Kind != OrderKind.Besiege || party.Order.TargetId != settlement.Id || Vec2.Distance(party.Position, settlement.Position) > 0.01) { return "Reach the siege camp first."; } if (ready && (siege.Stage != SiegeStage.Ready || siege.PreparationMinutes < 360.0)) { return "Make camp first: six hours."; } if (SiegeResidentDefenders(settlement).Any((Party p) => C.MilitaryPartyReserved(p.Id) || !string.IsNullOrEmpty(p.EncounterId))) { return "Wait for the defenders' fight to finish."; } return ""; } public string SiegeAssaultReason() { string text = C.CargoCommandReason(); if (text.Length <= 0) { return SiegeCampReason(PlayerSiege, ready: true); } return text; } public CommandResult AssaultSettlement(SiegeCapturePolicy policy) { string text = SiegeAssaultReason(); if (!Enum.IsDefined(typeof(SiegeCapturePolicy), policy)) { text = "Unknown occupation policy."; } if (text.Length > 0) { return CommandResult.Fail(text); } SiegeState playerSiege = PlayerSiege; SiegeCapturePolicy capturePolicy = playerSiege.CapturePolicy; playerSiege.CapturePolicy = policy; CommandResult commandResult = C.BeginSiegeAssault(playerSiege); if (!commandResult.Ok) { playerSiege.CapturePolicy = capturePolicy; } return commandResult; } internal string SurrenderCampReason(SiegeState siege) { string text = SiegeCampReason(siege, ready: true); if (text.Length > 0) { return text; } Settlement settlement = State.Settlements.Require(siege.SettlementId); if (SiegeDefenders(settlement) == 0) { return ""; } if (State.Clock.Minute - siege.StartedMinute < 1440 || C.SettlementFood(settlement) > 1E-06 || SiegeBesiegerStrength(siege) < 2.0 * SiegeDefenderStrength(settlement)) { return "They refuse. Hold the camp a day, starve them out and bring twice their strength."; } return ""; } public string SiegeSurrenderReason() { string text = C.CargoCommandReason(); if (text.Length <= 0) { return SurrenderCampReason(PlayerSiege); } return text; } public CommandResult DemandSiegeSurrender(SiegeCapturePolicy policy) { string text = SiegeSurrenderReason(); if (!Enum.IsDefined(typeof(SiegeCapturePolicy), policy)) { text = "Unknown occupation policy."; } if (text.Length > 0) { return CommandResult.Fail(text); } SiegeState playerSiege = PlayerSiege; SiegeCapturePolicy capturePolicy = playerSiege.CapturePolicy; playerSiege.CapturePolicy = policy; CommandResult commandResult = C.SurrenderSiegeDefenders(playerSiege); if (!commandResult.Ok) { playerSiege.CapturePolicy = capturePolicy; } return commandResult; } public CommandResult AbandonSiege() { string text = C.CargoCommandReason(); if (text.Length > 0) { return CommandResult.Fail(text); } SiegeState playerSiege = PlayerSiege; if (playerSiege == null) { return CommandResult.Fail("There is no active siege."); } if (playerSiege.Stage == SiegeStage.Assault || C.MilitaryPartyReserved(playerSiege.BesiegerPartyId) || !string.IsNullOrEmpty(playerSiege.SortieEncounterId)) { return CommandResult.Fail("Deal with the encounter first."); } EndSiege(playerSiege, "The besiegers withdrew."); return CommandResult.Success("Siege lifted. The owner keeps the place."); } public void EndPartySiege(Party party, string reason) { foreach (SiegeState item in State.Sieges.Where((SiegeState s) => s.BesiegerPartyId == party.Id && s.Stage != SiegeStage.Ended && s.Stage != SiegeStage.Assault).ToList()) { EndSiege(item, reason); } } public void EndSiege(SiegeState siege, string reason) { if (siege != null && siege.Stage != SiegeStage.Ended && (siege.Stage != SiegeStage.Assault || (string.IsNullOrEmpty(siege.GarrisonPartyId) && string.IsNullOrEmpty(siege.MilitiaPartyId) && string.IsNullOrEmpty(siege.KeepPartyId) && !siege.KeepPending)) && string.IsNullOrEmpty(siege.SortieEncounterId)) { siege.Stage = SiegeStage.Ended; siege.EndedMinute = State.Clock.Minute; siege.LastProcessedMinute = State.Clock.Minute; siege.Result = reason; Party party = State.Parties.Get(siege.BesiegerPartyId); if (party != null && party.Order.Kind == OrderKind.Besiege && party.Order.TargetId == siege.SettlementId) { party.Order = new MovementOrder(); } if (party != null) { party.NextThinkMinute = State.Clock.Minute; } RefreshSiegeAccess(); State.AddLog(LogCategory.Battle, "Siege of " + (State.Settlements.Get(siege.SettlementId)?.Name ?? siege.SettlementId) + ": " + reason, siege.SettlementId, siege.BesiegerPartyId); C.UpdatePlayerTimeStates(); if (siege.BesiegerPartyId == State.PlayerPartyId) { C.Raise(CampaignEventKind.Info, reason, false, siege.SettlementId); } State.Touch(); } } internal void PruneSieges() { foreach (SiegeState item in (from s in State.Sieges where s.Stage == SiegeStage.Ended orderby s.EndedMinute descending, s.Id select s).Skip(24).ToList()) { State.Sieges.Remove(item); } } public void UpdateSieges(bool advanceProgress = true) { foreach (SiegeState item in State.Sieges.Where((SiegeState s) => s.Stage != SiegeStage.Ended && s.Stage != SiegeStage.Assault).ToList()) { if (!string.IsNullOrEmpty(item.SortieEncounterId)) { continue; } Party party = State.Parties.Get(item.BesiegerPartyId); Settlement settlement = State.Settlements.Get(item.SettlementId); if (party == null || SiegePartyReason(party).Length > 0 || settlement == null || settlement.OwnerClanId != item.OwnerClanId || !State.AreHostile(State.Clans.Get(party.ClanId), State.Clans.Get(settlement.OwnerClanId)) || party.Order.Kind != OrderKind.Besiege || party.Order.TargetId != settlement.Id) { EndSiege(item, "The siege couldn't go on."); } else { if (!advanceProgress) { continue; } if (item.Stage != SiegeStage.Marching && Vec2.Distance(party.Position, settlement.Position) > 0.01) { EndSiege(item, "The besiegers left their camp."); continue; } long num = Math.Max(0L, State.Clock.Minute - item.LastProcessedMinute); if (num == 0L && item.Stage != SiegeStage.Marching) { continue; } item.LastProcessedMinute = State.Clock.Minute; if (item.Stage == SiegeStage.Marching) { if (!(Vec2.Distance(party.Position, settlement.Position) > 0.01)) { item.Stage = SiegeStage.Preparing; item.StartedMinute = State.Clock.Minute; item.LastSupplyDay = State.Clock.Day; party.Order.Path.Clear(); party.Order.PathIndex = 0; State.AddLog(LogCategory.Battle, party.Name + " established a siege camp at " + settlement.Name + ".", settlement.Id, party.Id); if (party.Id == State.PlayerPartyId || State.FactionOf(State.PlayerClan) == State.FactionOf(State.Clans.Get(settlement.OwnerClanId))) { C.Raise(CampaignEventKind.Warning, settlement.Name + " is under siege.", true, settlement.Id, party.Id); } State.Touch(); } continue; } double elapsed = num; if (item.Stage == SiegeStage.Preparing) { elapsed = Math.Max(0.0, (double)num - (360.0 - item.PreparationMinutes)); item.PreparationMinutes = Math.Min(360.0, item.PreparationMinutes + (double)num); if (item.PreparationMinutes >= 360.0) { item.Stage = SiegeStage.Ready; if (party.Id == State.PlayerPartyId) { C.Raise(CampaignEventKind.Info, "Siege camp ready at " + settlement.Name + ".", true, settlement.Id); } } } if (item.Stage == SiegeStage.Ready) { C.AdvanceSiegeWorks(item, elapsed); } State.Touch(); } } RefreshSiegeAccess(); } internal void RefreshSiegeAccess() { bool flag = false; foreach (Party item in State.ActiveParties.Where((Party p) => p.Kind == PartyKind.Villager)) { Settlement settlement = State.Settlements.Get(item.HomeSettlementId); if (settlement != null && settlement.Type == SettlementType.Village && !(settlement.OwnerClanId == item.ClanId) && State.Clans.Contains(settlement.OwnerClanId) && !C.MilitaryPartyReserved(item.Id) && string.IsNullOrEmpty(item.EncounterId)) { item.ClanId = settlement.OwnerClanId; item.NextThinkMinute = State.Clock.Minute; flag = true; } } foreach (WorkshopState workshop in State.Workshops) { Settlement settlement2 = State.Settlements.Get(workshop.SettlementId); if (settlement2 == null) { continue; } if (IsSettlementBesieged(settlement2)) { if (workshop.Status != "Suspended") { workshop.Status = "Suspended"; flag = true; } } else if (workshop.Status == "Suspended" && settlement2.OwnerClanId == workshop.SettlementOwnerClanId && State.Clans.Contains(workshop.OwnerClanId) && State.Clans.Contains(settlement2.OwnerClanId) && WorkshopTypes.Get(workshop.TypeId) != null && !State.AreHostile(State.Clans.Get(workshop.OwnerClanId), State.Clans.Get(settlement2.OwnerClanId))) { workshop.Status = (workshop.Enabled ? "Ready" : "Paused"); flag = true; } } if (flag) { State.Touch(); } } public void DailySieges() { foreach (SiegeState item in State.Sieges.Where((SiegeState s) => s.Stage == SiegeStage.Preparing || s.Stage == SiegeStage.Ready).ToList()) { if (item.LastSupplyDay >= State.Clock.Day || !string.IsNullOrEmpty(item.SortieEncounterId) || SiegeCampReason(item, ready: false).Length > 0) { continue; } item.LastSupplyDay = State.Clock.Day; Settlement settlement = State.Settlements.Get(item.SettlementId); if (settlement == null) { continue; } C.TakeSettlementFood(settlement, C.SettlementFoodNeed(settlement)); if (C.SettlementFood(settlement) <= 1E-06) { item.StarvationDays++; foreach (TroopStack item2 in settlement.Garrison.Stacks.ToList()) { if (item2.Healthy > 0) { settlement.Garrison.Wound(item2.UnitId, Math.Max(1, item2.Healthy / 10)); } } settlement.Militia = Math.Max(0, settlement.Militia - Math.Max(1, settlement.Militia / 10)); settlement.Security = Math.Max(0.0, settlement.Security - 2.0); } State.Touch(); } C.SiegeSortiesSystem.DailyAiSallies(); } } internal sealed class SiegeWorksSystem { private readonly Campaign C; private CampaignState State => C.State; internal SiegeWorksSystem(Campaign host) { C = host; } public int SiegeEngineering(SiegeState siege) { Party party = State.Parties.Get(siege?.BesiegerPartyId); if (party == null) { return 0; } return C.RoleSkill(party, PartyRole.Engineer); } public double SiegeBuildRate(SiegeState siege) { return SiegeWorksRules.AttackerConstructionRate(SiegeEngineering(siege)) * (1.0 + Math.Max(0.0, C.PartyPerk(State.Parties.Get(siege?.BesiegerPartyId ?? ""), PerkEffect.SiegeBuild))); } internal double SiegeDefenderBuildRate(SiegeState siege) { Settlement settlement = State.Settlements.Get(siege.SettlementId); if (settlement == null) { return SiegeWorksRules.DefenderConstructionRate(0); } int num = (from p in C.SiegeResidentDefenders(settlement) select C.RoleSkill(p, PartyRole.Engineer)).DefaultIfEmpty(0).Max(); Hero hero = C.SettlementGovernor(settlement); if (hero != null && hero.CanFight && C.IsStationedGovernor(settlement, hero)) { num = Math.Max(num, Math.Max(0, Math.Min(300, hero.Skill("engineering")))); } double val = C.SettlementPerk(settlement, PerkEffect.DefenderSiegeBuild) + (from p in C.SiegeResidentDefenders(settlement) select C.PartyPerk(p, PerkEffect.SiegeBuild)).DefaultIfEmpty(0.0).Max(); return SiegeWorksRules.DefenderConstructionRate(num) * (1.0 + Math.Max(0.0, val)); } internal string SiegeWorksCommandReason(int slot) { string text = C.CargoCommandReason(); if (text.Length > 0) { return text; } text = C.SiegeCampReason(C.PlayerSiege, ready: false); if (text.Length > 0) { return text; } if (C.PlayerSiege.Stage != SiegeStage.Preparing && C.PlayerSiege.Stage != SiegeStage.Ready) { return "Make camp first."; } if (slot < 0 || slot >= 7) { return "Unknown siege emplacement."; } if (C.PlayerSiege.Works == null) { return "No siege works in this old-style assault."; } return ""; } public string SiegeBuildReason(int slot, SiegeEngineKind kind) { string text = SiegeWorksCommandReason(slot); if (text.Length > 0) { return text; } if (!SiegeWorksRules.FitsSlot(slot, kind)) { return "Pick an engine that fits this emplacement."; } SiegeEngineState siegeEngineState = C.PlayerSiege.Works.Attackers[slot]; if (siegeEngineState.Kind == kind && (!siegeEngineState.IsBuilt || siegeEngineState.IsOperational)) { if (!siegeEngineState.IsBuilt) { return "Already queued."; } return "Already built. Take it down first to rebuild."; } return ""; } public CommandResult BuildSiegeEngine(int slot, SiegeEngineKind kind) { string text = SiegeBuildReason(slot, kind); if (text.Length > 0) { return CommandResult.Fail(text); } SetSiegeEngine(C.PlayerSiege, slot, kind); State.Touch(); return CommandResult.Success(SiegeWorksRules.Name(kind) + " queued. Building goes in emplacement order once camp's up."); } public CommandResult ClearSiegeEngine(int slot) { string text = SiegeWorksCommandReason(slot); if (text.Length > 0) { return CommandResult.Fail(text); } if (C.PlayerSiege.Works.Attackers[slot].Kind == SiegeEngineKind.None) { return CommandResult.Fail("Already empty."); } SetSiegeEngine(C.PlayerSiege, slot, SiegeEngineKind.None); State.Touch(); return CommandResult.Success("Emplacement cleared; what was built is gone."); } internal static void SetSiegeEngine(SiegeState siege, int slot, SiegeEngineKind kind) { siege.Works.Attackers[slot] = new SiegeEngineState { Slot = slot, Kind = kind }; } internal void AdvanceSiegeWorks(SiegeState siege, double elapsed) { if (siege.Works != null && !(elapsed <= 0.0)) { SiegeWorksState works = siege.Works; double num = works.Attackers.Where((SiegeEngineState e) => e.Kind != SiegeEngineKind.None).Sum((SiegeEngineState e) => e.BuildProgress); double num2 = works.Defenders.Sum((SiegeEngineState e) => e.BuildProgress); int num3 = works.Attackers.Count((SiegeEngineState e) => e.Kind != SiegeEngineKind.None && e.IsBuilt); int num4 = works.Defenders.Count((SiegeEngineState e) => e.IsBuilt); bool flag = works.Attackers.Any((SiegeEngineState e) => e.Kind != SiegeEngineKind.None && !e.IsBuilt); bool flag2 = works.Defenders.Any((SiegeEngineState e) => !e.IsBuilt || e.Health <= 0.0); SiegeWorksRules.Advance(works, elapsed, SiegeBuildRate(siege), SiegeDefenderBuildRate(siege)); C.TrainSiegeEngineers(siege, elapsed / 60.0, flag && works.Attackers.Where((SiegeEngineState e) => e.Kind != SiegeEngineKind.None).Sum((SiegeEngineState e) => e.BuildProgress) > num + 1E-09, Math.Max(0, works.Attackers.Count((SiegeEngineState e) => e.Kind != SiegeEngineKind.None && e.IsBuilt) - num3), flag2 && works.Defenders.Sum((SiegeEngineState e) => e.BuildProgress) > num2 + 1E-09, Math.Max(0, works.Defenders.Count((SiegeEngineState e) => e.IsBuilt) - num4)); } } internal void PlanAiSiegeWorks(SiegeState siege) { if (siege.Works == null || siege.Stage == SiegeStage.Marching || siege.Stage == SiegeStage.Assault || siege.Stage == SiegeStage.Ended) { return; } int[] array = ((!siege.Works.Attackers[6].IsBuilt) ? new int[1] { 6 } : new int[3] { 6, 0, 1 }); foreach (int num in array) { SiegeEngineState siegeEngineState = siege.Works.Attackers[num]; if (siegeEngineState.Kind == SiegeEngineKind.None || (siegeEngineState.IsBuilt && !siegeEngineState.IsOperational)) { SetSiegeEngine(siege, num, (num == 6) ? SiegeEngineKind.BatteringRam : SiegeEngineKind.Trebuchet); State.Touch(); } } } internal bool AiSiegeWorksReady(SiegeState siege) { if (siege.Works != null && !(siege.Works.LeftWallHealth <= 0.0) && !(siege.Works.RightWallHealth <= 0.0) && !siege.Works.Attackers[6].IsOperational) { return State.Clock.Minute - siege.StartedMinute >= 3240; } return true; } } internal sealed class SkillTrainingSystem { private readonly Campaign C; private CampaignState State => C.State; internal SkillTrainingSystem(Campaign host) { C = host; } internal Hero PartyEngineer(Party party) { if (party == null) { return null; } return (from id in party.Troops.Heroes select State.Heroes.Get(id) into h where h != null && h.CanFight && h.ClanId == party.ClanId && Campaign.IsPresentPartyHero(party, h) orderby h.Skill("engineering") descending select h).ThenBy((Hero h) => h.Id, StringComparer.Ordinal).FirstOrDefault(); } internal void TrainSiegeEngineers(SiegeState siege, double hours, bool attackersBuilt, int attackersFinished, bool defendersBuilt, int defendersFinished) { if (hours <= 0.0) { return; } if (attackersBuilt || attackersFinished > 0) { Party party = State.Parties.Get(siege.BesiegerPartyId); if (party != null && party.ClanId == State.PlayerClanId) { C.GrantSkillExperience(C.RoleHolder(party, PartyRole.Engineer), "engineering", (attackersBuilt ? (hours * 5.0) : 0.0) + (double)attackersFinished * 40.0); } } if (!defendersBuilt && defendersFinished <= 0) { return; } Settlement settlement = State.Settlements.Get(siege.SettlementId); if (settlement != null) { Hero hero = (from p in C.SiegeResidentDefenders(settlement) where p.ClanId == State.PlayerClanId select C.RoleHolder(p, PartyRole.Engineer) into h where h != null orderby h.Skill("engineering") descending select h).ThenBy((Hero h) => h.Id, StringComparer.Ordinal).FirstOrDefault(); Hero hero2 = C.SettlementGovernor(settlement); if (hero2 != null && hero2.ClanId == State.PlayerClanId && hero2.CanFight && C.IsStationedGovernor(settlement, hero2) && (hero == null || hero2.Skill("engineering") > hero.Skill("engineering"))) { hero = hero2; } if (hero != null) { C.GrantSkillExperience(hero, "engineering", (defendersBuilt ? (hours * 5.0) : 0.0) + (double)defendersFinished * 40.0); } } } internal void TrainDiplomacy(double xp) { C.GrantSkillExperience(State.PlayerHero, "diplomacy", xp); } internal void TrainDiplomacyForRansom(long troops) { TrainDiplomacy(Math.Min(40.0, (double)Math.Max(0L, troops) * 2.0)); } } internal sealed class SmithingDeveloperSystem { private readonly Campaign C; private CampaignState State => C.State; internal SmithingDeveloperSystem(Campaign host) { C = host; } public string DeveloperSmithingReason(string heroId = null) { if (!State.DeveloperTools) { return "Developer tools were not enabled when this campaign was created."; } string text = C.SmithyReason(); if (text.Length > 0) { return text; } if (heroId != null) { return C.SmithReason(heroId); } return ""; } public CommandResult DeveloperAddSmithingMaterials() { string text = DeveloperSmithingReason(); if (text.Length > 0) { return CommandResult.Fail(text); } Party playerParty = State.PlayerParty; int num = 0; SmithingMaterial[] allMaterials = Smithing.AllMaterials; foreach (SmithingMaterial m in allMaterials) { int num2 = (Smithing.IsCargoMaterial(m) ? 10 : Math.Max(0, Math.Min(10, 999 - C.MaterialCount(playerParty, m)))); if (num2 > 0) { C.AddMaterial(playerParty, m, num2); num += num2; } } if (num == 0) { return CommandResult.Fail("Your party already carries as many smithing materials as it can."); } return DeveloperDone("Developer: added " + 10 + " of each smithing material."); } public CommandResult DeveloperClearSmithingMaterials() { string text = DeveloperSmithingReason(); if (text.Length > 0) { return CommandResult.Fail(text); } Party playerParty = State.PlayerParty; int num = 0; SmithingMaterial[] allMaterials = Smithing.AllMaterials; foreach (SmithingMaterial m in allMaterials) { int num2 = C.MaterialCount(playerParty, m); if (num2 > 0) { C.AddMaterial(playerParty, m, -num2); num += num2; } } if (num == 0) { return CommandResult.Fail("Your party carries no smithing materials."); } return DeveloperDone("Developer: removed all " + num + " smithing materials."); } public CommandResult DeveloperSetSmithingSkill(string heroId, int level) { string text = DeveloperSmithingReason(heroId); if (text.Length > 0) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Require(heroId); level = Math.Max(0, Math.Min(300, level)); if (hero.Skill("smithing") == level) { return CommandResult.Fail(hero.Name + " already has " + level + " Smithing."); } hero.Skills["smithing"] = level; hero.SkillXp?.Remove("smithing"); hero.SkillXpRemainders?.Remove("smithing"); return DeveloperDone("Developer: " + hero.Name + "'s Smithing is now " + level + ".", hero.Id); } public CommandResult DeveloperRestoreSmithingStamina(string heroId) { string text = DeveloperSmithingReason(heroId); if (text.Length > 0) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Require(heroId); if (State.Smithing.Stamina == null || !State.Smithing.Stamina.Remove(hero.Id)) { return CommandResult.Fail(hero.Name + " already has full stamina."); } return DeveloperDone("Developer: " + hero.Name + "'s stamina is full.", hero.Id); } public CommandResult DeveloperLearnAllSmithingParts() { string text = DeveloperSmithingReason(); if (text.Length > 0) { return CommandResult.Fail(text); } int num = Smithing.Parts.Count((SmithingPartDef part) => State.Smithing.UnlockedParts.Add(part.Id)); if (num == 0) { return CommandResult.Fail("Every part is already learned."); } return DeveloperDone("Developer: learned " + num + " smithing parts."); } public CommandResult DeveloperNewSmithingOrders() { string text = DeveloperSmithingReason(); if (text.Length > 0) { return CommandResult.Fail(text); } Settlement town = C.CurrentSettlement(); RandomStream rng = State.Random.Get("smithing.orders"); State.Smithing.Orders.RemoveAll((CraftingOrderState order) => order.SettlementId == town.Id); for (int num = 0; num < 6; num++) { CraftingOrderState craftingOrderState = C.CreateOrder(town, num, rng); if (craftingOrderState != null) { State.Smithing.Orders.Add(craftingOrderState); } } return DeveloperDone("Developer: " + town.Name + " has " + State.Smithing.Orders.Count((CraftingOrderState order) => order.SettlementId == town.Id) + " new crafting orders.", town.Id); } internal CommandResult DeveloperDone(string message, string link = null) { if (link == null) { State.AddLog(LogCategory.Info, message); } else { State.AddLog(LogCategory.Info, message, link); } State.Touch(); return CommandResult.Success(message); } } internal sealed class SmithingSystem { private readonly Campaign C; private CampaignState State => C.State; internal SmithingSystem(Campaign host) { C = host; } public void EnsureSmithingFields() { bool flag = false; if (State.Smithing == null) { State.Smithing = new SmithingState(); flag = true; } SmithingState s = State.Smithing; if (s.Stamina == null) { s.Stamina = new SortedDictionary(StringComparer.Ordinal); flag = true; } if (s.UnlockedParts == null) { s.UnlockedParts = new SortedSet(StringComparer.Ordinal); flag = true; } if (s.Research == null) { s.Research = new SortedDictionary(StringComparer.Ordinal); flag = true; } if (s.Weapons == null) { s.Weapons = new SortedDictionary(StringComparer.Ordinal); flag = true; } if (s.Orders == null) { s.Orders = new List(); flag = true; } if (!s.PartsInitialized) { foreach (SmithingPartDef item in Smithing.Parts.Where((SmithingPartDef p) => p.GivenByDefault)) { s.UnlockedParts.Add(item.Id); } s.PartsInitialized = true; flag = true; } foreach (WeaponClassDef def in Smithing.Classes) { if (Smithing.Parts.Any((SmithingPartDef p) => p.Class == def.Class && s.UnlockedParts.Contains(p.Id))) { continue; } foreach (SmithingPartDef item2 in Smithing.Parts.Where((SmithingPartDef p) => p.Class == def.Class && p.GivenByDefault)) { s.UnlockedParts.Add(item2.Id); } flag = true; } if (!s.OrdersInitialized) { RandomStream rng = State.Random.Get("smithing.orders"); foreach (Settlement item3 in SmithyTowns()) { for (int num = 0; num < 6; num++) { CraftingOrderState craftingOrderState = CreateOrder(item3, num, rng); if (craftingOrderState != null) { s.Orders.Add(craftingOrderState); } } } s.OrdersInitialized = true; s.LastOrderDay = State.Clock.Day; flag = true; } if (flag) { State.Touch(); } } internal IEnumerable SmithyTowns() { return State.Settlements.Where((Settlement x) => x.Type == SettlementType.Town).OrderBy((Settlement x) => x.Id, StringComparer.Ordinal); } public IEnumerable PartySmiths() { Party party = State.PlayerParty; if (party == null) { yield break; } foreach (string hero2 in party.Troops.Heroes) { Hero hero = State.Heroes.Get(hero2); if (hero != null && hero.State == HeroState.Active && Campaign.IsPresentPartyHero(party, hero) && (hero.Id == State.PlayerHeroId || C.IsOwnedCompanion(hero))) { yield return hero; } } } public bool HasHeroPerk(Hero hero, string perkId) { if (hero?.Perks == null || !hero.Perks.Contains(perkId)) { return false; } HeroPerkDef perk = HeroPerks.All.FirstOrDefault((HeroPerkDef p) => p.Id == perkId); if (perk != null && hero.Skill(perk.Skill) >= perk.RequiredSkill) { return HeroPerks.All.Count((HeroPerkDef p) => p.Group == perk.Group && hero.Perks.Contains(p.Id)) == 1; } return false; } public double SmithingMaxStamina(Hero hero) { return Math.Round(Smithing.MaximumStamina(hero?.Skill("smithing") ?? 0) * (1.0 + Math.Max(0.0, C.PersonalPerk(hero, PerkEffect.SmithStamina)))); } public double SmithingStamina(Hero hero) { if (hero == null) { return 0.0; } double num = SmithingMaxStamina(hero); if (State.Smithing?.Stamina == null || !State.Smithing.Stamina.TryGetValue(hero.Id, out var value)) { return num; } return Math.Max(0.0, Math.Min(num, value)); } internal void SpendStamina(Hero hero, double amount) { double value = Math.Max(0.0, SmithingStamina(hero) - amount); State.Smithing.Stamina[hero.Id] = Math.Round(value, 3); } internal bool InSettlement(Hero hero) { if (hero == null || hero.State != HeroState.Active) { return false; } if (!string.IsNullOrEmpty(hero.PartyId)) { Party party = State.Parties.Get(hero.PartyId); if (party != null && party.State == PartyState.InSettlement) { return !string.IsNullOrEmpty(party.CurrentSettlementId); } return false; } return !string.IsNullOrEmpty(hero.SettlementId); } internal void HourlySmithing() { if (State.Smithing?.Stamina == null || State.Smithing.Stamina.Count == 0) { return; } foreach (string item in State.Smithing.Stamina.Keys.ToList()) { Hero hero = State.Heroes.Get(item); if (hero == null || hero.State == HeroState.Dead) { State.Smithing.Stamina.Remove(item); } else if (InSettlement(hero)) { double num = SmithingMaxStamina(hero); double num2 = Math.Min(num, SmithingStamina(hero) + Smithing.StaminaPerHour(hero.Skill("smithing")) * (1.0 + Math.Max(0.0, C.PersonalPerk(hero, PerkEffect.SmithRecovery)))); if (num2 >= num - 1E-09) { State.Smithing.Stamina.Remove(item); } else { State.Smithing.Stamina[item] = Math.Round(num2, 3); } } } } public string SmithyReason() { string text = C.DisguiseBlockReason(); if (text.Length > 0) { return text; } string text2 = C.EquipmentCommandReason(); if (text2.Length > 0) { return text2; } Settlement settlement = C.CurrentSettlement(); Party playerParty = State.PlayerParty; if (settlement == null || settlement.Type != SettlementType.Town || !C.CanEnter(playerParty, settlement) || !(Vec2.Distance(playerParty.Position, settlement.Position) <= 0.01)) { return "Find a friendly town's smithy."; } return ""; } public string SmithReason(string heroId) { string text = SmithyReason(); if (text.Length > 0) { return text; } Hero hero = State.Heroes.Get(heroId ?? ""); if (hero == null || !PartySmiths().Contains(hero)) { return "Pick yourself or a companion with you."; } return ""; } public int MaterialCount(Party party, SmithingMaterial m) { if (!Smithing.IsCargoMaterial(m)) { return C.EquipmentCount(party, Smithing.MaterialItemId(m)); } return C.CargoCount(party, Smithing.MaterialItemId(m)); } internal static double MaterialUnitWeight(SmithingMaterial m) { if (!Smithing.IsCargoMaterial(m)) { return 0.5; } return TradeGoods.All.First((TradeGoodDef g) => g.Id == Smithing.MaterialItemId(m)).Weight; } internal void AddMaterial(Party party, SmithingMaterial m, int delta) { string text = Smithing.MaterialItemId(m); SortedDictionary sortedDictionary = (Smithing.IsCargoMaterial(m) ? party.Cargo : party.Equipment); int num = (Smithing.IsCargoMaterial(m) ? C.CargoCount(party, text) : C.EquipmentCount(party, text)) + delta; if (num <= 0) { sortedDictionary.Remove(text); } else { sortedDictionary[text] = num; } } internal string MaterialsReason(Party party, SortedDictionary cost) { foreach (KeyValuePair item in cost) { if (item.Value > 0 && MaterialCount(party, item.Key) < item.Value) { return "You need " + item.Value + " " + Smithing.MaterialName(item.Key).ToLowerInvariant() + " (you have " + MaterialCount(party, item.Key) + ")."; } } return ""; } internal string GainReason(Party party, SortedDictionary gain, double extraWeight) { double num = extraWeight; foreach (KeyValuePair item in gain) { num += (double)item.Value * MaterialUnitWeight(item.Key); if (!Smithing.IsCargoMaterial(item.Key) && item.Value > 0 && MaterialCount(party, item.Key) + item.Value > 999) { return "You can't carry any more " + Smithing.MaterialName(item.Key).ToLowerInvariant() + "."; } } if (num > 0.0 && C.CargoWeight(party) + num > C.CargoCapacity(party) + 1E-09) { return "No room for it."; } return ""; } public IEnumerable KnownRecipes(Hero smith) { return from r in Smithing.Recipes where r.RequiredPerk.Length == 0 || HasHeroPerk(smith, r.RequiredPerk) select Smithing.EffectiveRecipe(r, (string perk) => HasHeroPerk(smith, perk)); } public string RefineReason(string heroId, string recipeId) { string text = SmithReason(heroId); if (text.Length > 0) { return text; } Hero hero = State.Heroes.Require(heroId); RefiningRecipe basis = Smithing.Recipes.FirstOrDefault((RefiningRecipe r) => r.Id == recipeId); if (basis == null) { return "Unknown recipe."; } if (basis.RequiredPerk.Length > 0 && !HasHeroPerk(hero, basis.RequiredPerk)) { return "Requires the " + HeroPerks.All.First((HeroPerkDef p) => p.Id == basis.RequiredPerk).Name + " perk."; } RefiningRecipe refiningRecipe = Smithing.EffectiveRecipe(basis, (string perk) => HasHeroPerk(hero, perk)); double num = Smithing.RefineStamina(HasHeroPerk(hero, "perk.smith.practical_refiner")); if (SmithingStamina(hero) + 1E-09 < num) { return hero.Name + " is too tired (" + Math.Floor(SmithingStamina(hero)) + " / " + num + " stamina). Rest in a settlement."; } Party playerParty = State.PlayerParty; text = MaterialsReason(playerParty, refiningRecipe.Inputs); if (text.Length > 0) { return text; } double num2 = refiningRecipe.Inputs.Sum((KeyValuePair i) => (double)i.Value * MaterialUnitWeight(i.Key)); return GainReason(playerParty, refiningRecipe.Outputs, 0.0 - num2); } public CommandResult Refine(string heroId, string recipeId) { string text = RefineReason(heroId, recipeId); if (text.Length > 0) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Require(heroId); RefiningRecipe refiningRecipe = Smithing.EffectiveRecipe(Smithing.Recipes.First((RefiningRecipe r) => r.Id == recipeId), (string perk) => HasHeroPerk(hero, perk)); Party playerParty = State.PlayerParty; foreach (KeyValuePair input in refiningRecipe.Inputs) { AddMaterial(playerParty, input.Key, -input.Value); } foreach (KeyValuePair output in refiningRecipe.Outputs) { AddMaterial(playerParty, output.Key, output.Value); } SpendStamina(hero, Smithing.RefineStamina(HasHeroPerk(hero, "perk.smith.practical_refiner"))); C.GrantSkillExperience(hero, "smithing", Smithing.RefiningXp(refiningRecipe)); string msg = hero.Name + " made " + string.Join(" and ", from o in refiningRecipe.Outputs orderby o.Key descending select o.Value + " " + Smithing.MaterialName(o.Key).ToLowerInvariant()) + "."; State.Touch(); return CommandResult.Success(msg); } internal bool SmeltingYield(string itemId, out WeaponClass taught, out SortedDictionary yield, out long value) { taught = WeaponClass.OneHandedSword; yield = null; value = 0L; OwnedItemInfo ownedItemInfo = OwnedItems.Resolve(State, itemId); if (ownedItemInfo != null && ownedItemInfo.Kind == OwnedItemKind.CraftedWeapon) { taught = ownedItemInfo.Crafted.Class; yield = Smithing.SmeltingYield(ownedItemInfo.Crafted.Parts); value = ownedItemInfo.Crafted.Value; return true; } if (((ownedItemInfo != null && ownedItemInfo.Kind == OwnedItemKind.WeaponKit) || (ownedItemInfo != null && ownedItemInfo.Kind == OwnedItemKind.Shield)) && Smithing.KitSmelting(itemId, out taught, out yield)) { value = ownedItemInfo.Price; return true; } return false; } public SortedDictionary SmeltingPreview(string itemId) { if (!SmeltingYield(itemId, out var _, out var yield, out var _)) { return new SortedDictionary(); } return yield; } public bool CanSmelt(string itemId) { WeaponClass taught; SortedDictionary yield; long value; return SmeltingYield(itemId, out taught, out yield, out value); } public string SmeltReason(string heroId, string itemId) { string text = SmithReason(heroId); if (text.Length > 0) { return text; } Hero hero = State.Heroes.Require(heroId); Party playerParty = State.PlayerParty; if (!SmeltingYield(itemId, out var _, out var yield, out var _)) { return "Only forged items and the outfitter's swords, clubs, axes, javelins, bows and shields can be smelted."; } if (C.EquipmentCount(playerParty, itemId) < 1) { return "You can only smelt weapons in the bag."; } double num = Smithing.SmeltStamina(HasHeroPerk(hero, "perk.smith.practical_smelter")); if (SmithingStamina(hero) + 1E-09 < num) { return hero.Name + " is too tired (" + Math.Floor(SmithingStamina(hero)) + " / " + num + " stamina). Rest in a settlement."; } text = MaterialsReason(playerParty, new SortedDictionary { [SmithingMaterial.Charcoal] = 1 }); if (text.Length > 0) { return "Smelting needs one charcoal."; } OwnedItemInfo ownedItemInfo = OwnedItems.Resolve(State, itemId); return GainReason(playerParty, yield, 0.0 - ownedItemInfo.Weight - 0.5); } public CommandResult Smelt(string heroId, string itemId) { string text = SmeltReason(heroId, itemId); if (text.Length > 0) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Require(heroId); Party playerParty = State.PlayerParty; OwnedItemInfo ownedItemInfo = OwnedItems.Resolve(State, itemId); SmeltingYield(itemId, out var taught, out var yield, out var value); Campaign.SetEquipmentCount(playerParty.Equipment, itemId, C.EquipmentCount(playerParty, itemId) - 1); if (ownedItemInfo.Kind == OwnedItemKind.CraftedWeapon) { State.Smithing.Weapons.Remove(itemId); } AddMaterial(playerParty, SmithingMaterial.Charcoal, -1); foreach (KeyValuePair item in yield) { AddMaterial(playerParty, item.Key, item.Value); } SpendStamina(hero, Smithing.SmeltStamina(HasHeroPerk(hero, "perk.smith.practical_smelter"))); C.GrantSkillExperience(hero, "smithing", Smithing.SmeltingXp(value)); List list = AddResearch(taught, Smithing.SmeltingResearch(value, HasHeroPerk(hero, "perk.smith.curious_smelter"))); string text2 = hero.Name + " smelted " + ownedItemInfo.Name + " into " + ((yield.Count == 0) ? "nothing usable" : string.Join(", ", from m in yield orderby m.Key descending select m.Value + " " + Smithing.MaterialName(m.Key).ToLowerInvariant())) + "." + ((list.Count > 0) ? (" New part" + ((list.Count == 1) ? "" : "s") + ": " + string.Join(", ", list) + ".") : ""); State.AddLog(LogCategory.Economy, text2, hero.Id); State.Touch(); return CommandResult.Success(text2); } public bool PartUnlocked(string partId) { SmithingState smithing = State.Smithing; if (smithing == null) { return false; } return smithing.UnlockedParts?.Contains(partId) == true; } public int ResearchPoints(WeaponClass c) { if (State.Smithing?.Research == null || !State.Smithing.Research.TryGetValue(Smithing.ClassKey(c), out var value)) { return 0; } return value; } public int ResearchNeeded(WeaponClass c) { List list = Smithing.Parts.Where((SmithingPartDef p) => p.Class == c).ToList(); int num = list.Count((SmithingPartDef p) => PartUnlocked(p.Id)); if (num < list.Count) { return Smithing.ResearchForNextPart(list.Count, num); } return 0; } internal List AddResearch(WeaponClass c, int points) { List list = new List(); if (points <= 0) { return list; } SmithingState s = State.Smithing; string key = Smithing.ClassKey(c); long num = (long)ResearchPoints(c) + (long)points; RandomStream randomStream = State.Random.Get("smithing"); List list2 = Smithing.Parts.Where((SmithingPartDef p) => p.Class == c).ToList(); while (true) { List list3 = list2.Where((SmithingPartDef p) => !s.UnlockedParts.Contains(p.Id)).ToList(); if (list3.Count == 0) { num = 0L; break; } int num2 = Smithing.ResearchForNextPart(list2.Count, list2.Count - list3.Count); if (num < num2) { break; } num -= num2; int tier = list3.Min((SmithingPartDef p) => p.Tier); List list4 = list3.Where((SmithingPartDef p) => p.Tier == tier).OrderBy((SmithingPartDef p) => p.Id, StringComparer.Ordinal).ToList(); SmithingPartDef smithingPartDef = list4[randomStream.Range(0, list4.Count)]; s.UnlockedParts.Add(smithingPartDef.Id); list.Add(smithingPartDef.Name); } if (num <= 0) { s.Research.Remove(key); } else { s.Research[key] = (int)Math.Min(2147483647L, num); } return list; } internal static List NormaliseParts(IList parts) { return (from i in Enumerable.Range(0, 4) select (parts == null || i >= parts.Count) ? "" : (parts[i] ?? "")).ToList(); } public WeaponDesignPreview PreviewWeapon(string heroId, WeaponClass c, IList partIds, bool forOrder = false) { WeaponDesignPreview weaponDesignPreview = new WeaponDesignPreview(); List partIds2 = NormaliseParts(partIds); weaponDesignPreview.Reason = Smithing.DesignReason(c, partIds2); if (!weaponDesignPreview.Ok) { return weaponDesignPreview; } Hero hero = State.Heroes.Get(heroId ?? ""); weaponDesignPreview.Stats = Smithing.Stats(c, partIds2); weaponDesignPreview.Difficulty = Smithing.Difficulty(partIds2); weaponDesignPreview.TierScore = Smithing.TierScore(c, weaponDesignPreview.Stats, partIds2); weaponDesignPreview.Tier = Smithing.WeaponTier(weaponDesignPreview.TierScore); weaponDesignPreview.Value = Smithing.Value(c, weaponDesignPreview.TierScore, WeaponQuality.Common); weaponDesignPreview.Cost = Smithing.CraftingCost(partIds2); weaponDesignPreview.Stamina = Smithing.ForgingStamina(weaponDesignPreview.Tier, HasHeroPerk(hero, "perk.smith.practical_smith")); weaponDesignPreview.Forging = Smithing.Setup(hero?.Skill("smithing") ?? 0, weaponDesignPreview.Difficulty, Smithing.AveragePartTier(partIds2), (string perk) => HasHeroPerk(hero, perk)); weaponDesignPreview.DefaultName = Smithing.DefaultName(c, partIds2); SmithingPartDef smithingPartDef = Smithing.DesignParts(partIds2).FirstOrDefault((SmithingPartDef p) => !PartUnlocked(p.Id)); if (smithingPartDef != null) { weaponDesignPreview.Reason = "You have not learned " + smithingPartDef.Name + " yet."; return weaponDesignPreview; } weaponDesignPreview.Reason = SmithReason(heroId); if (!weaponDesignPreview.Ok) { return weaponDesignPreview; } if (SmithingStamina(hero) + 1E-09 < weaponDesignPreview.Stamina) { weaponDesignPreview.Reason = hero.Name + " is too tired (" + Math.Floor(SmithingStamina(hero)) + " / " + weaponDesignPreview.Stamina + " stamina). Rest in a settlement."; return weaponDesignPreview; } Party playerParty = State.PlayerParty; weaponDesignPreview.Reason = MaterialsReason(playerParty, weaponDesignPreview.Cost); if (!weaponDesignPreview.Ok) { return weaponDesignPreview; } if (!forOrder) { double num = weaponDesignPreview.Cost.Sum((KeyValuePair m) => (double)m.Value * MaterialUnitWeight(m.Key)); if (weaponDesignPreview.Stats.Weight - num > 0.0 && C.CargoWeight(playerParty) + weaponDesignPreview.Stats.Weight - num > C.CargoCapacity(playerParty) + 1E-09) { weaponDesignPreview.Reason = "No room for it."; } } return weaponDesignPreview; } internal static string CleanName(string name, string fallback) { string text = new string((name ?? "").Where((char ch) => !char.IsControl(ch)).ToArray()).Trim(); if (text.Length == 0) { return fallback; } if (text.Length <= 40) { return text; } return text.Substring(0, 40).Trim(); } internal CraftedWeaponState MakeWeapon(Hero hero, WeaponClass c, List parts, string name, WeaponDesignPreview preview, bool freeBuild, ForgingWork work, out List learned) { Party playerParty = State.PlayerParty; foreach (KeyValuePair item in preview.Cost) { AddMaterial(playerParty, item.Key, -item.Value); } SpendStamina(hero, preview.Stamina); WeaponQuality quality = Smithing.QualityFor(Smithing.WorkScore(work, preview.Forging), (work == null) ? preview.Forging.AutoQuality : preview.Forging.Ceiling); CraftedWeaponState craftedWeaponState = new CraftedWeaponState { Id = "crafted." + State.Smithing.NextWeaponNumber++.ToString(CultureInfo.InvariantCulture), Name = CleanName(name, preview.DefaultName), Class = c, Parts = parts, Quality = quality, Stats = Smithing.Finished(preview.Stats, quality, HasHeroPerk(hero, "perk.smith.edge"), HasHeroPerk(hero, "perk.smith.tip")), Value = Smithing.Value(c, preview.TierScore, quality), Tier = preview.Tier, TierScore = Math.Round(preview.TierScore, 4), Difficulty = preview.Difficulty, CrafterHeroId = hero.Id, CraftedMinute = State.Clock.Minute }; learned = AddResearch(c, Smithing.ForgingResearch(craftedWeaponState.Value, HasHeroPerk(hero, "perk.smith.curious_smith"), freeBuild)); return craftedWeaponState; } public string ForgeReason(string heroId, WeaponClass c, IList partIds) { return PreviewWeapon(heroId, c, partIds).Reason; } public CommandResult Forge(string heroId, WeaponClass c, IList partIds, string name, ForgingWork work = null) { WeaponDesignPreview weaponDesignPreview = PreviewWeapon(heroId, c, partIds); if (!weaponDesignPreview.Ok) { return CommandResult.Fail(weaponDesignPreview.Reason); } string text = Smithing.WorkReason(work, weaponDesignPreview.Forging); if (text.Length > 0) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Require(heroId); List learned; CraftedWeaponState craftedWeaponState = MakeWeapon(hero, c, NormaliseParts(partIds), name, weaponDesignPreview, freeBuild: true, work, out learned); State.Smithing.Weapons[craftedWeaponState.Id] = craftedWeaponState; State.PlayerParty.Equipment[craftedWeaponState.Id] = 1; C.GrantSkillExperience(hero, "smithing", Smithing.ForgingXp(craftedWeaponState.Value)); string text2 = hero.Name + " forged " + OwnedItems.CraftedName(craftedWeaponState) + " (worth " + craftedWeaponState.Value.ToString("N0") + ")." + ((learned.Count > 0) ? (" New part" + ((learned.Count == 1) ? "" : "s") + ": " + string.Join(", ", learned) + ".") : ""); State.AddLog(LogCategory.Economy, text2, hero.Id); State.Touch(); return CommandResult.Success(text2); } public string RenameReason(string itemId, string name) { OwnedItemInfo ownedItemInfo = OwnedItems.Resolve(State, itemId); if (ownedItemInfo == null || ownedItemInfo.Kind != OwnedItemKind.CraftedWeapon) { return "Only forged weapons can be renamed."; } if (CleanName(name, "").Length == 0) { return "Enter a name."; } if (CleanName(name, "") == ownedItemInfo.Crafted.Name) { return "The weapon already has this name."; } return C.EquipmentCommandReason(); } public CommandResult RenameCraftedWeapon(string itemId, string name) { string text = RenameReason(itemId, name); if (text.Length > 0) { return CommandResult.Fail(text); } CraftedWeaponState craftedWeaponState = State.Smithing.Weapons[itemId]; craftedWeaponState.Name = CleanName(name, craftedWeaponState.Name); State.Touch(); return CommandResult.Success("Renamed to " + OwnedItems.CraftedName(craftedWeaponState) + "."); } public IEnumerable OrdersAt(string settlementId) { return from o in State.Smithing?.Orders ?? new List() where o.SettlementId == settlementId orderby o.Slot select o; } public CraftingOrderState Order(string orderId) { return State.Smithing?.Orders?.FirstOrDefault((CraftingOrderState o) => o.Id == orderId); } internal int BestSmithSkill() { return (from h in PartySmiths() select h.Skill("smithing")).DefaultIfEmpty(State.PlayerHero?.Skill("smithing") ?? 0).Max(); } internal CraftingOrderState CreateOrder(Settlement town, int slot, RandomStream rng) { List<(string, string, string)> list = new List<(string, string, string)>(); NotableState notableState = C.SettlementNotable(town.Id); if (notableState != null) { list.Add(("notable", notableState.Id, notableState.Name)); } foreach (Party item in State.Parties.Where((Party p) => p.State == PartyState.InSettlement && p.CurrentSettlementId == town.Id && p.Kind == PartyKind.Lord).OrderBy((Party p) => p.Id, StringComparer.Ordinal)) { Hero hero = State.Heroes.Get(item.LeaderHeroId); Clan clan = State.Clans.Get(hero?.ClanId ?? ""); if (hero != null && hero.State == HeroState.Active && clan != null && !clan.IsBandit && clan.Id != State.PlayerClanId) { list.Add(("lord", hero.Id, hero.Name)); } } if (list.Count == 0) { return null; } (string, string, string) tuple = list[rng.Range(0, list.Count)]; int num = ((slot < Smithing.OrderBandLow.Length) ? (Smithing.OrderBandLow[slot] + rng.Range(0, 40)) : Math.Max(10, BestSmithSkill())); num = Math.Min(300, num + (int)Math.Round(Math.Max(0.0, town.Prosperity) / 500.0)); int num2 = Math.Max(1, Math.Min(5, (int)Math.Round((double)num / 50.0))); WeaponClass weaponClass = (WeaponClass)rng.Range(0, Smithing.Classes.Count); WeaponClassDef weaponClassDef = Smithing.ClassDef(weaponClass); List list2 = new List { "", "", "", "" }; PartSlot[] slots = weaponClassDef.Slots; foreach (PartSlot partSlot in slots) { int tier = ((partSlot == PartSlot.Blade) ? num2 : Math.Max(1, Math.Min(5, num2 + rng.Range(-1, 2)))); List list3 = (from p in Smithing.PartsFor(weaponClass, partSlot) where p.Tier == tier select p).OrderBy((SmithingPartDef p) => p.Id, StringComparer.Ordinal).ToList(); list2[(int)partSlot] = list3[rng.Range(0, list3.Count)].Id; } CraftingOrderState craftingOrderState = new CraftingOrderState { Id = "order." + State.Smithing.NextOrderNumber++.ToString(CultureInfo.InvariantCulture), SettlementId = town.Id, Slot = slot, IssuerKind = tuple.Item1, IssuerId = tuple.Item2, IssuerName = tuple.Item3, Class = weaponClass, DesignParts = list2, PostedDay = State.Clock.Day }; craftingOrderState.BaseReward = Math.Max(1L, (long)Math.Round((double)craftingOrderState.OrderValue * (0.9 + 0.2 * rng.NextDouble()))); return craftingOrderState; } internal bool IssuerAvailable(CraftingOrderState order) { if (order.IssuerKind == "notable") { return State.Notables?.Any((NotableState n) => n.Id == order.IssuerId && n.IsAlive) ?? false; } Hero hero = State.Heroes.Get(order.IssuerId); if (hero != null) { return hero.State != HeroState.Dead; } return false; } internal void DailySmithingOrders() { SmithingState smithing = State.Smithing; if (smithing?.Orders == null || !smithing.OrdersInitialized || smithing.LastOrderDay == State.Clock.Day) { return; } smithing.LastOrderDay = State.Clock.Day; RandomStream randomStream = State.Random.Get("smithing.orders"); foreach (Settlement town in SmithyTowns()) { int slot; for (slot = 0; slot < 6; slot++) { CraftingOrderState craftingOrderState = smithing.Orders.FirstOrDefault((CraftingOrderState o) => o.SettlementId == town.Id && o.Slot == slot); if (craftingOrderState != null && (!IssuerAvailable(craftingOrderState) || randomStream.NextDouble() < 0.05)) { smithing.Orders.Remove(craftingOrderState); craftingOrderState = null; CraftingOrderState craftingOrderState2 = CreateOrder(town, slot, randomStream); if (craftingOrderState2 != null) { smithing.Orders.Add(craftingOrderState2); } } else if (craftingOrderState == null && randomStream.NextDouble() < 0.25) { CraftingOrderState craftingOrderState3 = CreateOrder(town, slot, randomStream); if (craftingOrderState3 != null) { smithing.Orders.Add(craftingOrderState3); } } } } } public static OrderEvaluation EvaluateOrder(CraftingOrderState order, WeaponStats delivered, long deliveredValue) { WeaponClassDef def = Smithing.ClassDef(order.Class); WeaponStats required = order.Required; double[] array = Smithing.OrderStatValues(def, required); double[] array2 = Smithing.OrderStatValues(def, delivered); OrderEvaluation orderEvaluation = new OrderEvaluation(); for (int i = 0; i < array.Length; i++) { if (!(array[i] <= 0.0)) { orderEvaluation.RequiredSum += array[i]; orderEvaluation.DeliveredSum += array2[i]; } } bool flag = (required.SwingKind == DamageKind.None || required.SwingKind == delivered.SwingKind) && (required.ThrustKind == DamageKind.None || required.ThrustKind == delivered.ThrustKind) && (required.MissileKind == DamageKind.None || required.MissileKind == delivered.MissileKind); orderEvaluation.Success = flag && orderEvaluation.DeliveredSum + 1E-09 >= orderEvaluation.RequiredSum; double a = (orderEvaluation.Success ? ((double)order.BaseReward * (1.0 + 0.1 * (orderEvaluation.DeliveredSum - orderEvaluation.RequiredSum) / Math.Max(1.0, orderEvaluation.RequiredSum))) : ((double)order.BaseReward * 0.5 * Math.Min(1.0, (double)deliveredValue / (double)Math.Max(1L, order.OrderValue)))); orderEvaluation.Reward = Math.Max(0L, (long)Math.Round(a)); return orderEvaluation; } public string OrderReason(string heroId, string orderId, IList partIds) { CraftingOrderState craftingOrderState = Order(orderId); Settlement settlement = C.CurrentSettlement(); if (craftingOrderState == null || settlement == null || craftingOrderState.SettlementId != settlement.Id) { return "That order isn't here."; } Hero hero = State.Heroes.Get(heroId ?? ""); if (!craftingOrderState.Valid) { return "That order's gone."; } if (hero != null && hero.Skill("smithing") + 50 < craftingOrderState.Difficulty) { return "Requires " + (craftingOrderState.Difficulty - 50) + " smithing to accept (difficulty " + craftingOrderState.Difficulty + ")."; } WeaponDesignPreview weaponDesignPreview = PreviewWeapon(heroId, craftingOrderState.Class, partIds, forOrder: true); if (!weaponDesignPreview.Ok) { return weaponDesignPreview.Reason; } if (State.PlayerClan.Gold <= long.MaxValue - craftingOrderState.BaseReward * 2) { return ""; } return "Your treasury's full."; } public CommandResult CompleteOrder(string heroId, string orderId, IList partIds, string name, ForgingWork work = null) { string text = OrderReason(heroId, orderId, partIds); if (text.Length > 0) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Require(heroId); CraftingOrderState craftingOrderState = Order(orderId); WeaponDesignPreview weaponDesignPreview = PreviewWeapon(heroId, craftingOrderState.Class, partIds, forOrder: true); string text2 = Smithing.WorkReason(work, weaponDesignPreview.Forging); if (text2.Length > 0) { return CommandResult.Fail(text2); } List learned; CraftedWeaponState craftedWeaponState = MakeWeapon(hero, craftingOrderState.Class, NormaliseParts(partIds), name, weaponDesignPreview, freeBuild: false, work, out learned); OrderEvaluation orderEvaluation = EvaluateOrder(craftingOrderState, craftedWeaponState.Stats, craftedWeaponState.Value); State.Smithing.Orders.Remove(craftingOrderState); if (orderEvaluation.Reward > 0) { State.Transact(State.PlayerClan, orderEvaluation.Reward, LedgerAccount.Smithing, "Crafting order for " + craftingOrderState.IssuerName); } C.GrantSkillExperience(hero, "smithing", Smithing.OrderXp(craftedWeaponState.Value, craftingOrderState.OrderValue, orderEvaluation.Success)); if (orderEvaluation.Success && craftingOrderState.IssuerKind == "notable" && HasHeroPerk(hero, "perk.smith.experienced")) { C.AdjustNotableRelation(craftingOrderState.IssuerId, 2, "crafting order"); } if (orderEvaluation.Success && craftingOrderState.IssuerKind == "lord" && HasHeroPerk(hero, "perk.smith.steel3")) { Hero hero2 = State.Heroes.Get(craftingOrderState.IssuerId); if (hero2 != null && !string.IsNullOrEmpty(hero2.ClanId)) { C.AdjustClanRelation(hero2.ClanId, State.PlayerClanId, 4); } } string text3 = craftingOrderState.IssuerName + (orderEvaluation.Success ? " was pleased with " : " accepted, disappointed, ") + OwnedItems.CraftedName(craftedWeaponState) + " and paid " + orderEvaluation.Reward.ToString("N0") + " denars." + ((learned.Count > 0) ? (" New part" + ((learned.Count == 1) ? "" : "s") + ": " + string.Join(", ", learned) + ".") : ""); State.AddLog(LogCategory.Economy, text3, hero.Id, craftingOrderState.SettlementId); State.Touch(); return CommandResult.Success(text3); } } internal sealed class StoryEventsSystem { private readonly Campaign C; private CampaignState State => C.State; private static List StoryEvents => Campaign.StoryEvents; public bool RandomEventsEnabled => C.Settings.RandomEvents; public bool EventPending => State.StoryEvents?.Pending != null; public static IEnumerable StoryEventIds => StoryEvents.Select((Campaign.StoryEventDefinition d) => d.Id); internal StoryEventsSystem(Campaign host) { C = host; } public void EnsureStoryEventFields() { bool flag = false; if (State.StoryEvents == null) { State.StoryEvents = new StoryEventsState(); flag = true; } StoryEventsState storyEvents = State.StoryEvents; if (storyEvents.CooldownUntilDay == null) { storyEvents.CooldownUntilDay = new SortedDictionary(StringComparer.Ordinal); flag = true; } if (storyEvents.History == null) { storyEvents.History = new List(); flag = true; } if (storyEvents.Pending != null && StoryEventDef(storyEvents.Pending.EventId) == null) { storyEvents.Pending = null; flag = true; } if (!storyEvents.Started) { storyEvents.Started = true; storyEvents.NextDay = State.Clock.Day + new RandomStream("events.first", State.Random.Seed).Range(10, 19); flag = true; } if (flag) { State.Touch(); } } public CommandResult SetRandomEventsEnabled(bool on) { C.Settings.RandomEvents = on; State.AddLog(LogCategory.Info, "Random events: " + (on ? "on." : "off.")); State.Touch(); return CommandResult.Success(on ? "Random events are on: about once a fortnight, something will happen." : "Random events are off (one already waiting for your answer stays)."); } internal string EventContext() { Party playerParty = State.PlayerParty; PlayerActivity activity = State.Player.Activity; if (playerParty == null || State.PlayerHero == null || State.PlayerHero.State != HeroState.Active || C.AwaitingHeir || C.LineEnded) { return ""; } if (activity == PlayerActivity.Captive || activity == PlayerActivity.InBattle || activity == PlayerActivity.InEncounter || activity == PlayerActivity.Raiding || activity == PlayerActivity.Besieging) { return ""; } if (!State.Player.LastReportSeen && State.Player.LastReport != null) { return ""; } if (!string.IsNullOrEmpty(playerParty.EncounterId) || C.TournamentBusyReason().Length > 0 || C.InDisguise) { return ""; } StoryEventsState storyEvents = State.StoryEvents; if (storyEvents.LastVictoryMinute >= 0 && State.Clock.Minute - storyEvents.LastVictoryMinute <= 360) { return "Battle"; } if (playerParty.State == PartyState.InSettlement) { Settlement settlement = State.Settlements.Get(playerParty.CurrentSettlementId); if (settlement == null || settlement.Type != SettlementType.Hideout) { return "Settlement"; } return ""; } int hourOfDay = State.Clock.HourOfDay; bool flag = hourOfDay >= 20 || hourOfDay < 5; if (activity == PlayerActivity.Waiting || (activity == PlayerActivity.Travelling && flag)) { return "Camp"; } if (activity == PlayerActivity.Travelling) { return "Road"; } return ""; } internal void HourlyStoryEvents() { StoryEventsState e = State.StoryEvents; if (e == null || !e.Started || e.Pending != null || !C.Settings.RandomEvents || State.Clock.Day < e.NextDay) { return; } string context = EventContext(); if (context.Length == 0) { return; } RandomStream rng = State.Random.Get("events.story"); if (rng.Chance(0.2)) { long today = State.Clock.Day; long value; var list = (from d in StoryEvents where d.Context == context && (!e.CooldownUntilDay.TryGetValue(d.Id, out value) || value <= today) select new { d = d, pending = new PendingEventState { EventId = d.Id, Context = context, Minute = State.Clock.Minute } } into x where x.d.Prepare(C, x.pending, rng) select x).ToList(); if (list.Count != 0) { var anon = list[rng.Range(0, list.Count)]; e.Count++; anon.pending.InstanceId = "event." + e.Count.ToString(CultureInfo.InvariantCulture); e.Pending = anon.pending; e.NextDay = today + rng.Range(10, 19); e.CooldownUntilDay[anon.d.Id] = today + 120; State.Player.WaitUntilMinute = 0L; C.ClearOrder(State.PlayerParty); C.UpdatePlayerTimeStates(); C.ForcePause(anon.d.Title); C.Raise(CampaignEventKind.Info, anon.d.Title, true); State.Touch(); } } } public CommandResult DeveloperStartEvent(string eventId = "") { if (!State.DeveloperTools) { return CommandResult.Fail("Developer tools were not enabled when this campaign was created."); } if (State.StoryEvents == null || !State.StoryEvents.Started) { EnsureStoryEventFields(); } StoryEventsState storyEvents = State.StoryEvents; if (storyEvents.Pending != null) { return CommandResult.Fail("Something's already waiting for your answer."); } string context = EventContext(); if (context.Length == 0) { return CommandResult.Fail("Nothing can happen right now (travel, wait or stay somewhere first)."); } RandomStream rng = State.Random.Get("events.story"); List list = StoryEvents.Where((Campaign.StoryEventDefinition d) => (eventId.Length != 0) ? (d.Id == eventId) : (d.Context == context)).ToList(); if (list.Count == 0) { return CommandResult.Fail((eventId.Length == 0) ? "No event fits here." : "Unknown event."); } foreach (Campaign.StoryEventDefinition item in list.OrderBy((Campaign.StoryEventDefinition x) => rng.NextDouble()).ToList()) { PendingEventState pendingEventState = new PendingEventState { EventId = item.Id, Context = item.Context, Minute = State.Clock.Minute }; if (item.Prepare(C, pendingEventState, rng)) { storyEvents.Count++; pendingEventState.InstanceId = "event." + storyEvents.Count.ToString(CultureInfo.InvariantCulture); storyEvents.Pending = pendingEventState; C.ForcePause(item.Title); State.Touch(); return CommandResult.Success("Developer: " + item.Title + "."); } } return CommandResult.Fail("That event does not fit here and now."); } public static string StoryEventContext(string id) { return StoryEventDef(id)?.Context ?? ""; } public static List> DeveloperEventList() { return StoryEvents.Select((Campaign.StoryEventDefinition d) => new KeyValuePair(d.Id, d.Title + " (" + d.Context.ToLowerInvariant() + ")")).ToList(); } public StoryPrompt PendingEventPrompt() { PendingEventState pendingEventState = State.StoryEvents?.Pending; Campaign.StoryEventDefinition storyEventDefinition = ((pendingEventState == null) ? null : StoryEventDef(pendingEventState.EventId)); if (storyEventDefinition == null) { return null; } StoryPrompt storyPrompt = new StoryPrompt(); storyPrompt.Kind = "event"; storyPrompt.SubjectId = pendingEventState.InstanceId; storyPrompt.Title = storyEventDefinition.Title; storyPrompt.SpeakerRole = ((pendingEventState.Context == "Battle") ? "After the battle" : ((!(pendingEventState.Context == "Settlement")) ? ((pendingEventState.Context == "Camp") ? "In camp" : "On the road") : (State.Settlements.Get(State.PlayerParty?.CurrentSettlementId ?? "")?.Name ?? "In town"))); storyPrompt.Lines.AddRange(storyEventDefinition.Lines(C, pendingEventState)); storyPrompt.Options.AddRange(storyEventDefinition.Options(C, pendingEventState)); return storyPrompt; } public CommandResult ChooseEventOption(string optionId) { StoryEventsState storyEvents = State.StoryEvents; PendingEventState pendingEventState = storyEvents?.Pending; Campaign.StoryEventDefinition storyEventDefinition = ((pendingEventState == null) ? null : StoryEventDef(pendingEventState.EventId)); if (storyEventDefinition == null) { return CommandResult.Fail("Nothing's waiting on you."); } StoryOption storyOption = storyEventDefinition.Options(C, pendingEventState).FirstOrDefault((StoryOption o) => o.Id == optionId); if (storyOption == null) { return CommandResult.Fail("That choice is not open."); } if (!storyOption.Enabled) { return CommandResult.Fail(storyOption.Reason); } string text = storyEventDefinition.Resolve(C, pendingEventState, optionId, State.Random.Get("events.story")) ?? ""; storyEvents.Pending = null; storyEvents.History.Add(new EventRecord { InstanceId = pendingEventState.InstanceId, EventId = storyEventDefinition.Id, Title = storyEventDefinition.Title, Context = pendingEventState.Context, Minute = pendingEventState.Minute, Choice = storyOption.Text, Result = text }); if (storyEvents.History.Count > 40) { storyEvents.History.RemoveAt(0); } State.AddLog(LogCategory.Info, storyEventDefinition.Title + ": " + text); State.Touch(); return CommandResult.Success(text); } internal static Campaign.StoryEventDefinition StoryEventDef(string id) { return StoryEvents.FirstOrDefault((Campaign.StoryEventDefinition d) => d.Id == id); } internal static StoryOption Opt(string id, string text, string reason = "", string hint = "") { return new StoryOption { Id = id, Text = text, Reason = (reason ?? ""), Hint = (hint ?? "") }; } internal static List L(params string[] lines) { return lines.ToList(); } internal void AddMorale(double delta) { Party playerParty = State.PlayerParty; if (playerParty != null) { playerParty.Morale = Math.Max(0.0, Math.Min(100.0, playerParty.Morale + delta)); } } internal string WoundOne(RandomStream rng) { Party playerParty = State.PlayerParty; List list = playerParty?.Troops.Stacks.Where((TroopStack s) => s.Healthy > 0).OrderBy((TroopStack s) => s.UnitId, StringComparer.Ordinal).ToList(); if (list == null || list.Count == 0) { return ""; } TroopStack troopStack = list[rng.Range(0, list.Count)]; playerParty.Troops.Wound(troopStack.UnitId, 1); return C.UnitDef(troopStack.UnitId)?.Name ?? "soldier"; } internal Settlement NearestPlace(SettlementType? type, double within) { Party p = State.PlayerParty; if (p == null) { return null; } return (from s in State.Settlements where s.Type != SettlementType.Hideout && (!type.HasValue || s.Type == type) && Vec2.Distance(s.Position, p.Position) <= within orderby Vec2.Distance(s.Position, p.Position) select s).ThenBy((Settlement s) => s.Id, StringComparer.Ordinal).FirstOrDefault(); } internal Settlement EventPlace(PendingEventState p) { return State.Settlements.Get(p.SettlementId ?? ""); } internal string Gold(long n) { return n.ToString("N0", CultureInfo.InvariantCulture) + " denars"; } internal string CantAfford(long n) { if (State.PlayerClan.Gold >= n) { return ""; } return "You cannot spare " + Gold(n) + "."; } internal bool PayPlace(Settlement s, long amount, string reason) { if (amount <= 0 || State.PlayerClan.Gold < amount) { return false; } State.Transact(State.PlayerClan, -amount, LedgerAccount.Events, reason); if (s?.Market != null) { s.Market.Gold += amount; } return true; } internal double Chance(double baseChance, string skill, double per) { return Math.Max(0.1, Math.Min(0.9, baseChance + (double)C.Skill(skill) / per)); } internal static string Pct(double chance) { return (int)Math.Round(chance * 100.0) + "%"; } internal Clan FriendlyLordClan() { return (from cl in State.Clans.Where(delegate(Clan cl) { if (!cl.IsBandit && !cl.IsEliminated && cl.Id != State.PlayerClanId && !State.AreHostile(State.PlayerClan, cl)) { Hero hero = State.Heroes.Get(cl.LeaderHeroId); if (hero == null) { return false; } return hero.State == HeroState.Active; } return false; }) orderby C.ClanRelation(State.PlayerClanId, cl.Id) descending select cl).ThenBy((Clan cl) => cl.Id, StringComparer.Ordinal).FirstOrDefault(); } } internal sealed class SuccessionSystem { private readonly Campaign C; private CampaignRules Rules => C.Rules; private CampaignState State => C.State; public bool AwaitingHeir => State.Families?.AwaitingHeir ?? false; public bool LineEnded => State.Families?.LineEnded ?? false; public Hero DeceasedPlayer => State.Heroes.Get(State.Families?.DeceasedPlayerId ?? ""); internal SuccessionSystem(Campaign host) { C = host; } internal void BeginSuccession(Hero deceased) { FamiliesState families = State.Families; families.DeceasedPlayerId = deceased.Id; if (State.Player.Activity == PlayerActivity.Captive || State.Player.Activity == PlayerActivity.Waiting || State.Player.Activity == PlayerActivity.Travelling) { State.Player.CaptorPartyId = ""; State.Player.CaptorSettlementId = ""; Party playerParty = State.PlayerParty; State.Player.Activity = ((playerParty != null && playerParty.State == PartyState.InSettlement) ? PlayerActivity.InSettlement : PlayerActivity.Idle); if (playerParty != null && playerParty.State == PartyState.Active) { C.ClearOrder(playerParty); } } State.Player.WaitUntilMinute = 0L; bool flag = HeirCandidates().Count > 0; if (flag) { families.AwaitingHeir = true; } else { families.LineEnded = true; } string text = deceased.Name + " has died" + ((string.IsNullOrEmpty(deceased.DeathCause) || deceased.DeathCause == "old age") ? " of old age" : (" " + deceased.DeathCause)) + $" at {C.HeroYears(deceased)}. " + (flag ? "Choose who leads your clan now." : "There is nobody left to carry on your line."); State.AddLog(LogCategory.Warning, text, deceased.Id); C.Raise(CampaignEventKind.Family, text, true, deceased.Id); C.ForcePause(flag ? "Choose your heir" : "Your line has ended"); } public List HeirCandidates() { Clan clan = State.PlayerClan; Hero last = DeceasedPlayer ?? State.PlayerHero; if (clan == null) { return new List(); } return (from h in State.Heroes where h.ClanId == clan.Id && !h.IsPlayer && h.IsFamily && C.IsGrown(h) && (h.State == HeroState.Active || h.State == HeroState.Captive) orderby (h.State != HeroState.Active) ? 1 : 0, (last == null || (!(h.FatherId == last.Id) && !(h.MotherId == last.Id))) ? ((last != null && last.SpouseId == h.Id) ? 1 : 2) : 0, C.HeroAge(h) descending select h).ThenBy((Hero h) => h.Id, StringComparer.Ordinal).ToList(); } public string HeirReason(string heroId) { if (!AwaitingHeir) { return "Nobody needs to succeed you."; } List source = HeirCandidates(); Hero hero = source.FirstOrDefault((Hero h) => h.Id == heroId); if (hero == null) { return "Only grown family in your clan can succeed you."; } if (hero.State == HeroState.Captive && source.Any((Hero h) => h.State == HeroState.Active)) { return hero.Name + " is a prisoner; pick someone free while there's anyone left."; } return ""; } public CommandResult ChooseHeir(string heroId) { string text = HeirReason(heroId); if (text.Length > 0) { return CommandResult.Fail(text); } FamiliesState families = State.Families; Hero hero = State.Heroes.Require(heroId); Hero old = DeceasedPlayer ?? State.PlayerHero; Clan playerClan = State.PlayerClan; Party playerParty = State.PlayerParty; if (old != null) { old.IsPlayer = false; } C.ClearHeroRoleAssignments(hero.Id); C.ClearHeroGovernorAssignments(hero.Id); hero.Occupation = HeroOccupation.Player; hero.IsPlayer = true; hero.IsFamily = true; hero.DailyWage = 0; hero.HireCost = 0L; State.PlayerHeroId = hero.Id; playerClan.LeaderHeroId = hero.Id; if (string.IsNullOrEmpty(State.Families.ClanSurnames.TryGetValue(playerClan.Id, out var value) ? value : "")) { C.ClanSurname(playerClan); } families.AwaitingHeir = false; families.DeceasedPlayerId = ""; families.Courtships.RemoveAll((CourtshipState c) => c.SuitorId == old?.Id); playerParty.LeaderHeroId = hero.Id; playerParty.Name = hero.Name + "'s Warband"; string text2; if (hero.State == HeroState.Captive) { Party party = State.Parties.Get(hero.CaptorPartyId); State.Player.Activity = PlayerActivity.Captive; State.Player.CaptorPartyId = hero.CaptorPartyId; State.Player.CaptorSettlementId = hero.CaptorSettlementId; State.Player.CaptiveSinceMinute = hero.CaptiveSinceMinute; bool flag = State.Clans.Get(party?.ClanId ?? "")?.IsBandit ?? false; State.Player.CaptivityMaxDays = (flag ? Rules.BanditMaxCaptivityDays : Rules.LordMaxCaptivityDays); if (playerParty.State != PartyState.Disbanded && playerParty.State != PartyState.Destroyed) { RecoverSeparatedCompanionsBeforeScatter(playerParty); playerParty.Troops.Stacks.Clear(); playerParty.Prisoners.Stacks.Clear(); playerParty.Cargo?.Clear(); playerParty.Equipment?.Clear(); playerParty.Food = 0.0; playerParty.State = PartyState.Disbanded; C.ClearOrder(playerParty); } text2 = "You are now " + hero.Name + ", a prisoner of " + (party?.Name ?? State.Settlements.Get(hero.CaptorSettlementId)?.Name ?? "your captors") + "."; } else { Party party2 = State.Parties.Get(hero.PartyId); Vec2 position = party2?.Position ?? State.Settlements.Get(hero.SettlementId)?.Position ?? playerParty.Position; Settlement settlement = ((party2 == null) ? State.Settlements.Get(hero.SettlementId) : ((party2.State == PartyState.InSettlement) ? State.Settlements.Get(party2.CurrentSettlementId) : null)); if (party2 != null && party2.Id != playerParty.Id) { party2.Troops.Heroes.Remove(hero.Id); } hero.SettlementId = ""; if (playerParty.State == PartyState.Disbanded || playerParty.State == PartyState.Destroyed) { playerParty.State = PartyState.Active; playerParty.Position = position; playerParty.CurrentSettlementId = ""; playerParty.EncounterId = ""; playerParty.Morale = 40.0; playerParty.DisengagedUntilMinute = State.Clock.Minute + (long)(Rules.DisengageHours * 60.0); C.ClearOrder(playerParty); State.Player.Activity = PlayerActivity.Idle; if (settlement != null && settlement.Type != SettlementType.Hideout && C.CanEnter(playerParty, settlement)) { playerParty.Position = settlement.Position; playerParty.State = PartyState.InSettlement; playerParty.CurrentSettlementId = settlement.Id; State.Player.MenuSettlementId = settlement.Id; State.Player.Activity = PlayerActivity.InSettlement; } } if (!playerParty.Troops.Heroes.Contains(hero.Id)) { playerParty.Troops.Heroes.Insert(0, hero.Id); } else { playerParty.Troops.Heroes.Remove(hero.Id); playerParty.Troops.Heroes.Insert(0, hero.Id); } hero.PartyId = playerParty.Id; text2 = "You are now " + hero.Name + ", head of " + playerClan.Name + "."; } C.ReconcileCaravans(); C.ReconcileMilitaryParties(); State.AddLog(LogCategory.Warning, text2, hero.Id, playerClan.Id); C.Raise(CampaignEventKind.Family, text2, false, hero.Id); State.Touch(); return CommandResult.Success(text2); } internal void RecoverSeparatedCompanionsBeforeScatter(Party party) { foreach (Hero item in State.Heroes.Where((Hero h) => h.Occupation == HeroOccupation.Companion && h.State == HeroState.Active && (h.PartyId == party.Id || party.Troops.Heroes.Contains(h.Id))).ToList()) { C.ShelterCompanion(item, party.Position, "separated when your warband scattered"); } foreach (string item2 in party.Prisoners.Heroes.ToList()) { OutcomeCommitter.ReleaseHero(C, State.Heroes.Get(item2), "freed when their captors scattered"); } party.Prisoners.Heroes.Clear(); party.RoleAssignments?.Clear(); } } internal sealed class TournamentsSystem { private readonly Campaign C; private ContentDatabase Content => C.Content; private CampaignRules Rules => C.Rules; private CampaignState State => C.State; public IEnumerable HeardTournaments => ActiveTournaments.Where((TournamentState t) => State.Tournaments.Heard?.Contains(t.Id) ?? false); public IEnumerable ActiveTournaments => (State.Tournaments?.Active ?? new List()).OrderBy((TournamentState t) => t.EndMinute).ThenBy((TournamentState t) => t.Id, StringComparer.Ordinal); public TournamentState PlayerTournament => State.Tournaments?.Active?.FirstOrDefault((TournamentState t) => t.Run != null); internal TournamentsSystem(Campaign host) { C = host; } public void EnsureTournamentFields() { bool flag = false; if (State.Tournaments == null) { State.Tournaments = new TournamentsState(); flag = true; } if (State.Tournaments.Active == null) { State.Tournaments.Active = new List(); flag = true; } if (State.Tournaments.Heard == null) { State.Tournaments.Heard = new List(); flag = true; } if (State.Tournaments.Wins == null) { State.Tournaments.Wins = new SortedDictionary(StringComparer.Ordinal); flag = true; } if (!State.Tournaments.WinsSeeded && State.Tournaments.Started) { SeedTournamentWins(); flag = true; } foreach (TournamentState item in State.Tournaments.Active) { if (item.Prize == null) { item.Prize = new TournamentPrizeState(); flag = true; } if (item.Run != null) { if (item.Run.Fighters == null) { item.Run.Fighters = new List(); flag = true; } if (item.Run.Matches == null) { item.Run.Matches = new List(); flag = true; } if (item.Run.AttemptId == null) { item.Run.AttemptId = ""; flag = true; } } } if (State.Tournaments.LastResult != null && State.Tournaments.LastResult.Lines == null) { State.Tournaments.LastResult.Lines = new List(); flag = true; } if (flag) { State.Touch(); } } private void SeedTournamentWins() { SortedDictionary wins = State.Tournaments.Wins; List list = State.Heroes.Where((Hero h) => (h.Occupation == HeroOccupation.Lord || h.Occupation == HeroOccupation.Companion) && h.State != HeroState.Dead && h.ClanId != State.PlayerClanId && C.IsGrown(h)).ToList(); List list2 = (from h in list select C.UnitPower(h.UnitId) into x orderby x select x).ToList(); double num = ((list2.Count == 0) ? 1.0 : Math.Max(1E-06, list2[list2.Count / 2])); foreach (Hero item in list) { double num2 = Math.Max(0.0, Math.Min(30.0, C.HeroAge(item) - 18.0)); double num3 = Math.Max(0.5, Math.Min(1.6, C.UnitPower(item.UnitId) / num)); double num4 = (double)(StableHash.Combine(StableHash.Fnv1a64(State.CampaignId ?? ""), StableHash.Fnv1a64(item.Id)) >> 11) * 1.1102230246251565E-16; int num5 = (int)Math.Floor(num2 / 8.0 * num3 * 2.0 * num4 * num4 * ((item.Occupation == HeroOccupation.Lord) ? 1.0 : 0.6)); if (num5 > 0) { wins[item.Id] = num5; } } State.Tournaments.WinsSeeded = true; } internal void RecordTournamentWin(TournamentFighterState champion) { if (!string.IsNullOrEmpty(champion?.HeroId) && State.Heroes.Get(champion.HeroId) != null) { SortedDictionary wins = State.Tournaments.Wins; wins[champion.HeroId] = (wins.TryGetValue(champion.HeroId, out var value) ? value : 0) + 1; } } public List> TournamentLeaderboard() { return (from e in State.Tournaments?.Wins ?? new SortedDictionary(StringComparer.Ordinal) where e.Value > 0 select new KeyValuePair(State.Heroes.Get(e.Key), e.Value) into e where e.Key != null && e.Key.State != HeroState.Dead orderby e.Value descending select e).ThenBy, string>((KeyValuePair e) => e.Key.Name, StringComparer.Ordinal).ThenBy, string>((KeyValuePair e) => e.Key.Id, StringComparer.Ordinal).ToList(); } public int TournamentWins(string heroId) { if (State.Tournaments?.Wins == null || !State.Tournaments.Wins.TryGetValue(heroId ?? "", out var value)) { return 0; } return value; } public void HearOfTournament(string id) { List heard = State.Tournaments.Heard; List active = State.Tournaments.Active; heard.RemoveAll((string x) => !active.Any((TournamentState t) => t.Id == x)); if (active.Any((TournamentState t) => t.Id == id) && !heard.Contains(id)) { heard.Add(id); } State.Touch(); } public TournamentState TournamentAt(string townId) { return State.Tournaments?.Active?.FirstOrDefault((TournamentState t) => t.TownId == townId); } public string TournamentBusyReason() { if (PlayerTournament != null) { return "Finish the tournament, or pull out, first."; } return ""; } public void EnsureTournaments() { EnsureTournamentFields(); if (State.Tournaments.Started) { return; } if (!State.Tournaments.WinsSeeded) { SeedTournamentWins(); } RandomStream randomStream = State.Random.Get("tournaments"); foreach (Settlement item in C.Towns()) { if (TournamentHostReason(item).Length == 0 && randomStream.Chance(0.25)) { AnnounceTournament(item, randomStream, randomStream.Range(3, 15), log: false); } } State.Tournaments.Started = true; State.Touch(); } public string TournamentHostReason(Settlement town) { if (town == null || town.Type != SettlementType.Town) { return "Only towns hold tournaments."; } Clan clan = State.Clans.Get(town.OwnerClanId); if (clan == null || clan.IsBandit || clan.IsEliminated) { return "The town has no rightful holder."; } if (C.IsSettlementBesieged(town)) { return "The town is under siege."; } if (TournamentAt(town.Id) != null) { return "There's already a tournament on here."; } return ""; } public TournamentState AnnounceTournamentAt(string townId) { EnsureTournamentFields(); Settlement town = State.Settlements.Get(townId ?? ""); if (TournamentHostReason(town).Length > 0) { return null; } TournamentState result = AnnounceTournament(town, State.Random.Get("tournaments"), 14, log: true); State.Touch(); return result; } internal TournamentState AnnounceTournament(Settlement town, RandomStream rng, int days, bool log) { TournamentState tournamentState = new TournamentState { Id = "tournament." + State.Tournaments.NextNumber++.ToString(CultureInfo.InvariantCulture), TownId = town.Id, AnnouncedMinute = State.Clock.Minute, EndMinute = State.Clock.Minute + (long)days * 1440L, Prize = CreateTournamentPrize(town, rng) }; State.Tournaments.Active.Add(tournamentState); if (log) { State.AddLog(LogCategory.Info, town.Name + " announced a tournament. The prize is " + tournamentState.Prize.Name + ".", town.Id); } return tournamentState; } internal void DailyTournaments() { EnsureTournamentFields(); if (!State.Tournaments.Started) { EnsureTournaments(); return; } RandomStream randomStream = State.Random.Get("tournaments"); foreach (TournamentState item in State.Tournaments.Active.ToList()) { if (item.Run != null) { continue; } Settlement settlement = State.Settlements.Get(item.TownId); if (settlement == null || settlement.Type != SettlementType.Town || C.IsSettlementBesieged(settlement)) { State.Tournaments.Active.Remove(item); if (settlement != null) { State.AddLog(LogCategory.Info, "The tournament at " + settlement.Name + " was called off.", settlement.Id); } } else if (State.Clock.Minute >= item.EndMinute) { HoldTournament(item, settlement, randomStream); } } foreach (Settlement item2 in C.Towns()) { if (TournamentHostReason(item2).Length == 0 && randomStream.Chance(0.025)) { AnnounceTournament(item2, randomStream, 14, log: true); } } } internal void HoldTournament(TournamentState t, Settlement town, RandomStream rng) { TournamentRunState tournamentRunState = new TournamentRunState { Fighters = GatherFighters(town, withPlayer: false, rng) }; while (tournamentRunState.Round < Tournaments.Rounds) { DrawRound(tournamentRunState, rng); foreach (TournamentMatchState item in (from m in RoundMatches(tournamentRunState) where m.Winner < 0 select m).ToList()) { SimulateMatch(tournamentRunState, item, rng); } tournamentRunState.Round++; } TournamentFighterState tournamentFighterState = tournamentRunState.Fighters.FirstOrDefault((TournamentFighterState f) => !f.Eliminated); State.Tournaments.Active.Remove(t); if (tournamentFighterState == null) { return; } RecordTournamentWin(tournamentFighterState); if (tournamentFighterState.Kind == TournamentFighterKind.Lord) { Clan clan = State.Clans.Get(tournamentFighterState.ClanId); if (clan != null) { clan.Renown += 3.0; } State.AddLog(LogCategory.Info, tournamentFighterState.Name + ((clan == null) ? "" : (" of " + clan.Name)) + " won the tournament at " + town.Name + " and took the prize: " + t.Prize.Name + ".", town.Id, tournamentFighterState.HeroId); } else { State.AddLog(LogCategory.Info, tournamentFighterState.Name + ", a local " + (C.UnitDef(tournamentFighterState.UnitId)?.Name ?? "fighter").ToLowerInvariant() + ", won the tournament at " + town.Name + " and took the prize: " + t.Prize.Name + ".", town.Id); } } internal TournamentPrizeState CreateTournamentPrize(Settlement town, RandomStream rng) { List list = new List { TournamentPrizeKind.Weapon, TournamentPrizeKind.Horse }; List list2 = PrizeAbilities(); if (list2.Count > 0) { list.Add(TournamentPrizeKind.Ability); } TournamentPrizeKind tournamentPrizeKind = list[rng.Range(0, list.Count)]; switch (tournamentPrizeKind) { case TournamentPrizeKind.Ability: { string text = list2[rng.Range(0, list2.Count)]; return new TournamentPrizeState { Kind = tournamentPrizeKind, AbilityId = text, Name = "the special ability " + C.AbilityName(text) }; } default: return WeaponPrize(rng); case TournamentPrizeKind.Horse: return HorsePrize(town, rng); } } internal List PrizeAbilities() { Hero hero = State.PlayerHero; HashSet offered = new HashSet(from t in (State.Tournaments?.Active ?? new List()).Where(delegate(TournamentState t) { TournamentPrizeState prize = t.Prize; return prize != null && prize.Kind == TournamentPrizeKind.Ability; }) select t.Prize.AbilityId, StringComparer.Ordinal); return (from a in C.KnownAbilities select a.Id into id where !C.HeroKnowsAbility(hero, id) && !offered.Contains(id) select id).ToList(); } internal TournamentPrizeState WeaponPrize(RandomStream rng) { UnitDef unitDef = C.UnitDef(State.PlayerHero?.UnitId ?? ""); bool thrown = unitDef != null && unitDef.Role == TroopRole.Ranged; List list = (from c in Smithing.Classes where c.Thrown == thrown select c.Class).ToList(); if (list.Count == 0) { list = Smithing.Classes.Select((WeaponClassDef c) => c.Class).ToList(); } WeaponClass weaponClass = list[rng.Range(0, list.Count)]; WeaponClassDef weaponClassDef = Smithing.ClassDef(weaponClass); List list2 = new List { "", "", "", "" }; PartSlot[] slots = weaponClassDef.Slots; foreach (PartSlot partSlot in slots) { int tier = ((partSlot == PartSlot.Blade) ? rng.Range(4, 6) : rng.Range(3, 6)); List list3 = (from p in Smithing.PartsFor(weaponClass, partSlot) where p.Tier == tier select p).OrderBy((SmithingPartDef p) => p.Id, StringComparer.Ordinal).ToList(); list2[(int)partSlot] = list3[rng.Range(0, list3.Count)].Id; } double num2 = rng.NextDouble(); WeaponQuality quality = ((num2 < 0.6) ? WeaponQuality.Fine : ((num2 < 0.95) ? WeaponQuality.Masterwork : WeaponQuality.Legendary)); WeaponStats weaponStats = Smithing.Stats(weaponClass, list2); double num3 = Smithing.TierScore(weaponClass, weaponStats, list2); CraftedWeaponState craftedWeaponState = new CraftedWeaponState { Id = "", Name = Smithing.DefaultName(weaponClass, list2), Class = weaponClass, Parts = list2, Quality = quality, Stats = Smithing.Finished(weaponStats, quality, sharpenedEdge: false, sharpenedTip: false), Value = Smithing.Value(weaponClass, num3, quality), Tier = Smithing.WeaponTier(num3), TierScore = Math.Round(num3, 4), Difficulty = Smithing.Difficulty(list2), CraftedMinute = State.Clock.Minute }; return new TournamentPrizeState { Kind = TournamentPrizeKind.Weapon, Weapon = craftedWeaponState, Name = OwnedItems.CraftedName(craftedWeaponState), Value = craftedWeaponState.Value }; } internal TournamentPrizeState HorsePrize(Settlement town, RandomStream rng) { List list = Horses.Breeds.Where((HorseBreedDef b) => b.Kind == HorseKind.War).ToList(); List list2 = list.Where((HorseBreedDef b) => b.Cultures.Contains(town.CultureId)).ToList(); List list3 = ((list2.Count > 0 && rng.NextDouble() < 0.7) ? list2 : list); HorseBreedDef breed = list3[rng.Range(0, list3.Count)]; HorseState horseState = C.CreateHorse(breed, rng, rng.Range(4.0, 7.0), rng.Range(0.06, 0.1), "Won at the " + town.Name + " tournament", assignId: false); horseState.Experience = Math.Round(rng.Range(320.0, 760.0), 1); horseState.Condition = 1.0; TournamentPrizeState tournamentPrizeState = new TournamentPrizeState(); tournamentPrizeState.Kind = TournamentPrizeKind.Horse; tournamentPrizeState.Horse = horseState; tournamentPrizeState.Value = C.HorseValue(horseState); tournamentPrizeState.Name = horseState.Name + ", " + Article(Campaign.HorseQuality(horseState)) + " " + Campaign.HorseQuality(horseState).ToLowerInvariant() + " " + C.BreedName(horseState); return tournamentPrizeState; } internal static string Article(string word) { if (word.Length <= 0 || "AEIOUaeiou".IndexOf(word[0]) < 0) { return "a"; } return "an"; } internal void AwardTournamentPrize(TournamentState t, Hero winner, Settlement town) { TournamentPrizeState prize = t.Prize; switch (prize.Kind) { case TournamentPrizeKind.Weapon: { C.EnsureSmithingFields(); CraftedWeaponState weapon = prize.Weapon; weapon.Id = "crafted." + State.Smithing.NextWeaponNumber++.ToString(CultureInfo.InvariantCulture); State.Smithing.Weapons[weapon.Id] = weapon; SortedDictionary equipment = State.PlayerParty.Equipment; equipment[weapon.Id] = (equipment.TryGetValue(weapon.Id, out var value) ? value : 0) + 1; break; } case TournamentPrizeKind.Horse: { HorseState horse = prize.Horse; horse.Id = C.NewHorseId(); horse.Place = HorsePlace.Party; horse.PlaceId = State.PlayerPartyId; horse.AcquiredDay = State.Clock.Day; State.Horses.Horses[horse.Id] = horse; break; } case TournamentPrizeKind.Ability: C.LearnAbility(winner, prize.AbilityId); break; } } internal TournamentFighterState HeroFighter(Hero hero, TournamentFighterKind kind) { return new TournamentFighterState { Name = hero.Name, Kind = kind, HeroId = hero.Id, UnitId = hero.UnitId, ClanId = hero.ClanId, Strength = Math.Max(0.1, C.HeroPower(hero)) }; } internal List GatherFighters(Settlement town, bool withPlayer, RandomStream rng) { List list = new List(); if (withPlayer) { list.Add(HeroFighter(State.PlayerHero, TournamentFighterKind.Player)); foreach (string hero2 in State.PlayerParty.Troops.Heroes) { Hero hero = State.Heroes.Get(hero2); if (hero != null && !hero.IsPlayer && C.IsOwnedCompanion(hero) && hero.CanFight && Tournaments.CanFight(C.UnitDef(hero.UnitId))) { if (list.Count >= 16) { break; } list.Add(HeroFighter(hero, TournamentFighterKind.Companion)); } } } foreach (Party item in State.Parties.Where((Party p) => p.Kind == PartyKind.Lord && p.State == PartyState.InSettlement && p.CurrentSettlementId == town.Id).OrderBy((Party p) => p.Id, StringComparer.Ordinal)) { Hero lord = State.Heroes.Get(item.LeaderHeroId ?? ""); Clan clan = State.Clans.Get(lord?.ClanId ?? ""); if (lord != null && lord.State == HeroState.Active && lord.CanFight && clan != null && !clan.IsBandit && !(clan.Id == State.PlayerClanId) && Tournaments.CanFight(C.UnitDef(lord.UnitId)) && !list.Any((TournamentFighterState f) => f.HeroId == lord.Id)) { if (list.Count >= 16) { break; } list.Add(HeroFighter(lord, TournamentFighterKind.Lord)); } } List list2 = Content.Units.Where((UnitDef u) => u.Culture == town.CultureId && Tournaments.CanFight(u) && Tournaments.LocalTierWeight(u.Tier) > 0.0).OrderBy((UnitDef u) => u.Id, StringComparer.Ordinal).ToList(); if (list2.Count == 0) { list2 = Content.Units.Where((UnitDef u) => Tournaments.CanFight(u) && Tournaments.LocalTierWeight(u.Tier) > 0.0).OrderBy((UnitDef u) => u.Id, StringComparer.Ordinal).ToList(); } List weights = list2.Select((UnitDef u) => Tournaments.LocalTierWeight(u.Tier)).ToList(); HashSet hashSet = new HashSet(list.Select((TournamentFighterState f) => f.Name), StringComparer.Ordinal); while (list.Count < 16 && list2.Count > 0) { UnitDef unitDef = list2[Math.Max(0, rng.PickWeighted(weights))]; int num = 0; string text; do { text = Tournaments.LocalName(rng); } while (!hashSet.Add(text) && ++num < 30); list.Add(new TournamentFighterState { Name = text, Kind = TournamentFighterKind.Local, UnitId = unitDef.Id, Strength = Math.Max(0.1, C.UnitPower(unitDef.Id)) }); } for (int num2 = 0; num2 < list.Count; num2++) { list[num2].Id = num2 + 1; } return list; } public TournamentFighterState TournamentFighter(TournamentRunState run, int id) { return run?.Fighters?.FirstOrDefault((TournamentFighterState f) => f.Id == id); } public IEnumerable RoundMatches(TournamentRunState run) { return run?.Matches?.Where((TournamentMatchState m) => m.Round == run.Round) ?? Enumerable.Empty(); } public TournamentMatchState PlayerMatch(TournamentRunState run) { return RoundMatches(run).FirstOrDefault((TournamentMatchState m) => m.TeamA.Contains(1) || m.TeamB.Contains(1)); } internal static void Shuffle(IList items, RandomStream rng) { for (int num = items.Count - 1; num > 0; num--) { int index = rng.Range(0, num + 1); T value = items[num]; items[num] = items[index]; items[index] = value; } } internal void DrawRound(TournamentRunState run, RandomStream rng) { List list = (from f in run.Fighters where !f.Eliminated select f.Id).ToList(); Shuffle(list, rng); int num = Tournaments.TeamSize[Math.Min(run.Round, Tournaments.Rounds - 1)]; for (int num2 = 0; num2 + 2 * num <= list.Count; num2 += 2 * num) { run.Matches.Add(new TournamentMatchState { Round = run.Round, TeamA = list.GetRange(num2, num), TeamB = list.GetRange(num2 + num, num) }); } } internal bool FighterAvailable(TournamentFighterState fighter) { if (fighter == null || fighter.Eliminated) { return false; } if (string.IsNullOrEmpty(fighter.HeroId)) { return true; } Hero hero = State.Heroes.Get(fighter.HeroId); if (hero != null && hero.State == HeroState.Active) { return hero.CanFight; } return false; } internal double TeamStrength(TournamentRunState run, IEnumerable team) { return team.Select((int id) => TournamentFighter(run, id)).Where(FighterAvailable).Sum((TournamentFighterState f) => f.Strength); } internal void SimulateMatch(TournamentRunState run, TournamentMatchState match, RandomStream rng) { double num = TeamStrength(run, match.TeamA); double num2 = TeamStrength(run, match.TeamB); int winner = (((num <= 0.0 && num2 > 0.0) || ((!(num2 <= 0.0) || !(num > 0.0)) && !(rng.NextDouble() < Tournaments.WinChance(num, num2)))) ? 1 : 0); ResolveMatch(run, match, winner); } internal static void ResolveMatch(TournamentRunState run, TournamentMatchState match, int winner) { match.Winner = winner; foreach (int id in (winner == 0) ? match.TeamB : match.TeamA) { TournamentFighterState tournamentFighterState = run.Fighters.FirstOrDefault((TournamentFighterState f) => f.Id == id); if (tournamentFighterState != null && !tournamentFighterState.Eliminated) { tournamentFighterState.Eliminated = true; tournamentFighterState.EliminatedInRound = match.Round; } } } public double PlayerTournamentChance(TournamentState t) { TournamentRunState tournamentRunState = t?.Run; if (tournamentRunState != null) { TournamentFighterState tournamentFighterState = TournamentFighter(tournamentRunState, 1); if (tournamentFighterState != null && !tournamentFighterState.Eliminated) { Dictionary strength = tournamentRunState.Fighters.ToDictionary((TournamentFighterState f) => f.Id, (TournamentFighterState f) => (!FighterAvailable(f)) ? 0.0 : f.Strength); RandomStream randomStream = new RandomStream(t.Id + ".odds." + tournamentRunState.Round.ToString(CultureInfo.InvariantCulture), State.Random.Seed); int num = 0; for (int num2 = 0; num2 < 300; num2++) { HashSet hashSet = new HashSet(from f in tournamentRunState.Fighters where !f.Eliminated select f.Id); foreach (TournamentMatchState item in from m in RoundMatches(tournamentRunState) where m.Winner < 0 select m) { double strengthA = item.TeamA.Sum((int id) => strength[id]); double strengthB = item.TeamB.Sum((int id) => strength[id]); foreach (int item2 in (randomStream.NextDouble() < Tournaments.WinChance(strengthA, strengthB)) ? item.TeamB : item.TeamA) { hashSet.Remove(item2); } } for (int num3 = tournamentRunState.Round + 1; num3 < Tournaments.Rounds; num3++) { if (!hashSet.Contains(1)) { break; } List list = hashSet.OrderBy((int id) => id).ToList(); Shuffle(list, randomStream); int num4 = Tournaments.TeamSize[num3]; for (int num5 = 0; num5 + 2 * num4 <= list.Count; num5 += 2 * num4) { List range = list.GetRange(num5, num4); List range2 = list.GetRange(num5 + num4, num4); double strengthA2 = range.Sum((int id) => strength[id]); double strengthB2 = range2.Sum((int id) => strength[id]); foreach (int item3 in (randomStream.NextDouble() < Tournaments.WinChance(strengthA2, strengthB2)) ? range2 : range) { hashSet.Remove(item3); } } } if (hashSet.Count == 1 && hashSet.Contains(1)) { num++; } } return (double)num / 300.0; } } return 0.0; } public (int companions, int lords) TournamentEntrantPreview(string townId) { Settlement town = State.Settlements.Get(townId ?? ""); if (town == null || State.PlayerParty == null) { return (companions: 0, lords: 0); } int val = State.PlayerParty.Troops.Heroes.Select((string id) => State.Heroes.Get(id)).Count((Hero h) => h != null && !h.IsPlayer && C.IsOwnedCompanion(h) && h.CanFight && Tournaments.CanFight(C.UnitDef(h.UnitId))); int val2 = (from p in State.Parties where p.Kind == PartyKind.Lord && p.State == PartyState.InSettlement && p.CurrentSettlementId == town.Id select State.Heroes.Get(p.LeaderHeroId ?? "")).Count(delegate(Hero h) { if (h != null && h.State == HeroState.Active && h.CanFight) { Clan clan = State.Clans.Get(h.ClanId); if (clan != null && !clan.IsBandit && clan.Id != State.PlayerClanId) { return Tournaments.CanFight(C.UnitDef(h.UnitId)); } } return false; }); val = Math.Min(val, 15); return (companions: val, lords: Math.Min(val2, 15 - val)); } public string TournamentJoinReason(string townId) { string text = C.DisguiseBlockReason(); if (text.Length > 0) { return text; } Settlement settlement = State.Settlements.Get(townId ?? ""); TournamentState tournamentState = TournamentAt(townId); if (settlement == null || tournamentState == null) { return "No tournament here right now."; } if (PlayerTournament != null) { return "You're already in a tournament."; } Party playerParty = State.PlayerParty; if (playerParty == null || playerParty.State != PartyState.InSettlement || playerParty.CurrentSettlementId != settlement.Id) { return "You must be in " + settlement.Name + " to enter."; } if (!string.IsNullOrEmpty(State.Player.PendingEncounterId) || State.Player.Activity == PlayerActivity.InEncounter || State.Player.Activity == PlayerActivity.InBattle) { return "Deal with the encounter first."; } if (C.IsSettlementBesieged(settlement)) { return "Postponed: the town is under siege."; } Hero playerHero = State.PlayerHero; if (playerHero == null || playerHero.State != HeroState.Active) { return "Your character cannot enter."; } if (!playerHero.CanFight) { return "You're too badly hurt to fight. Rest up first."; } if (!Tournaments.CanFight(C.UnitDef(playerHero.UnitId))) { return "Your archetype can't fight in the arena."; } return ""; } public CommandResult JoinTournament(string townId) { string text = TournamentJoinReason(townId); if (text.Length > 0) { return CommandResult.Fail(text); } TournamentState tournamentState = TournamentAt(townId); Settlement settlement = State.Settlements.Require(townId); RandomStream rng = State.Random.Get("tournaments"); TournamentRunState tournamentRunState = (tournamentState.Run = new TournamentRunState { Fighters = GatherFighters(settlement, withPlayer: true, rng) }); DrawRound(tournamentRunState, rng); tournamentRunState.Odds = Tournaments.Odds(PlayerTournamentChance(tournamentState)); int num = tournamentRunState.Fighters.Count((TournamentFighterState f) => f.Kind == TournamentFighterKind.Companion); int num2 = tournamentRunState.Fighters.Count((TournamentFighterState f) => f.Kind == TournamentFighterKind.Lord); string text2 = "You entered the tournament at " + settlement.Name + " with " + 15 + " other fighters" + ((num + num2 == 0) ? "." : (" (" + string.Join(", ", new string[2] { (num > 0) ? (num + " of your companion" + ((num == 1) ? "" : "s")) : "", (num2 > 0) ? (num2 + " lord" + ((num2 == 1) ? "" : "s")) : "" }.Where((string x) => x.Length > 0)) + ").")); State.AddLog(LogCategory.Info, text2, settlement.Id); State.Touch(); return CommandResult.Success(text2); } public string TournamentBetReason(long amount) { TournamentState playerTournament = PlayerTournament; if (playerTournament == null) { return "You're not in a tournament."; } TournamentRunState run = playerTournament.Run; TournamentFighterState tournamentFighterState = TournamentFighter(run, 1); if (tournamentFighterState == null || tournamentFighterState.Eliminated) { return "You're out of the tournament."; } if (run.AttemptId.Length > 0) { return "Your match is under way."; } TournamentMatchState tournamentMatchState = PlayerMatch(run); if (tournamentMatchState == null || tournamentMatchState.Winner >= 0) { return "Bets close once your match is decided."; } if (amount <= 0) { return "Choose an amount to bet."; } long num = 150 - run.BetThisRound; if (num <= 0) { return "That's the most you can bet this round."; } if (amount > num) { return "You can bet at most " + num + " more denars this round."; } if (State.PlayerClan.Gold < amount) { return "Not enough denars."; } if (State.Settlements.Get(playerTournament.TownId)?.Market == null) { return "Nobody is taking bets here."; } return ""; } public CommandResult PlaceTournamentBet(long amount) { string text = TournamentBetReason(amount); if (text.Length > 0) { return CommandResult.Fail(text); } TournamentState playerTournament = PlayerTournament; TournamentRunState run = playerTournament.Run; Settlement settlement = State.Settlements.Require(playerTournament.TownId); State.Transact(State.PlayerClan, -amount, LedgerAccount.Tournament, "Bet on yourself at the " + settlement.Name + " tournament"); settlement.Market.Gold += amount; run.BetThisRound += amount; run.BetTotal += amount; long num = (long)Math.Round((double)amount * run.Odds); run.BetPayout += num; State.Touch(); return CommandResult.Success("You bet " + amount + " denars at " + run.Odds.ToString("0.0", CultureInfo.InvariantCulture) + " to 1. Winning the tournament would pay " + run.BetPayout.ToString("N0", CultureInfo.InvariantCulture) + " denars."); } public TournamentMatchState NextSpectatorMatch(TournamentRunState run) { if (run == null || !run.Spectating) { return null; } return RoundMatches(run).FirstOrDefault((TournamentMatchState m) => m.Winner < 0); } public string TournamentWatchReason() { TournamentState playerTournament = PlayerTournament; if (playerTournament == null) { return "You're not at a tournament."; } TournamentRunState run = playerTournament.Run; if (!run.Spectating) { return "You're still in this tournament."; } if (run.AttemptId.Length > 0) { return "A match is under way."; } TournamentMatchState tournamentMatchState = NextSpectatorMatch(run); if (tournamentMatchState == null) { return "No match waiting."; } if (!tournamentMatchState.TeamA.Any((int id) => FighterAvailable(TournamentFighter(run, id))) || !tournamentMatchState.TeamB.Any((int id) => FighterAvailable(TournamentFighter(run, id)))) { return "One side has nobody left to fight: decide it without watching."; } BattleMapDef battleMapDef = Content.BattleMaps.Get("map.bannerlord_siege_v1"); if (battleMapDef == null || !battleMapDef.TabsMapMatch.Contains("00_simulation_day")) { return "The arena's battle map is unavailable."; } return ""; } public CommandResult SkipSpectatorMatch() { TournamentState playerTournament = PlayerTournament; TournamentMatchState tournamentMatchState = NextSpectatorMatch(playerTournament?.Run); if (tournamentMatchState == null || playerTournament.Run.AttemptId.Length > 0) { return CommandResult.Fail("No match waiting to be decided."); } SimulateMatch(playerTournament.Run, tournamentMatchState, State.Random.Get("tournaments")); List lines = new List { MatchLine(playerTournament.Run, tournamentMatchState) }; string msg = ContinueTournament(playerTournament, lines); State.Touch(); return CommandResult.Success(msg); } public CommandResult CompleteSpectatorMatch(string attemptId, bool teamAWon) { TournamentState playerTournament = PlayerTournament; if (playerTournament == null || string.IsNullOrEmpty(attemptId) || playerTournament.Run.AttemptId != attemptId) { return CommandResult.Fail("This match result is out of date."); } TournamentRunState run = playerTournament.Run; TournamentMatchState tournamentMatchState = NextSpectatorMatch(run); run.AttemptId = ""; State.Player.Activity = PlayerActivity.Idle; C.UpdatePlayerTimeStates(); if (tournamentMatchState == null) { State.Touch(); return CommandResult.Fail("Already decided."); } tournamentMatchState.Fought = true; ResolveMatch(run, tournamentMatchState, (!teamAWon) ? 1 : 0); List lines = new List { MatchLine(run, tournamentMatchState) }; string msg = ContinueTournament(playerTournament, lines); State.Touch(); return CommandResult.Success(msg); } internal string MatchLine(TournamentRunState run, TournamentMatchState match) { List list = ((match.Winner == 0) ? match.TeamA : match.TeamB); return string.Join(" & ", list.Select((int id) => TournamentFighter(run, id)?.Name ?? "?")) + ((list.Count == 1) ? " wins" : " win") + " the match."; } public string TournamentFightReason() { TournamentState playerTournament = PlayerTournament; if (playerTournament == null) { return "You're not in a tournament."; } TournamentRunState run = playerTournament.Run; TournamentFighterState tournamentFighterState = TournamentFighter(run, 1); if (tournamentFighterState == null || tournamentFighterState.Eliminated) { return "You're out of the tournament."; } if (run.AttemptId.Length > 0) { return "Your match is under way."; } TournamentMatchState tournamentMatchState = PlayerMatch(run); if (tournamentMatchState == null || tournamentMatchState.Winner >= 0) { return "Your match has been decided."; } Hero playerHero = State.PlayerHero; if (playerHero == null || playerHero.State != HeroState.Active || !playerHero.CanFight) { return "You're in no state to fight. Pull out."; } if (!Tournaments.CanFight(C.UnitDef(playerHero.UnitId))) { return "Your archetype can't fight in the arena."; } BattleMapDef battleMapDef = Content.BattleMaps.Get("map.bannerlord_siege_v1"); if (battleMapDef == null || !battleMapDef.TabsMapMatch.Contains("00_simulation_day")) { return "The arena's battle map is unavailable."; } return ""; } public BattlePlan PrepareTournamentMatch() { TournamentState playerTournament = PlayerTournament; int num; string text; if (playerTournament == null) { num = 0; } else { num = ((playerTournament.Run?.Spectating == true) ? 1 : 0); if (num != 0) { text = TournamentWatchReason(); goto IL_0046; } } text = TournamentFightReason(); goto IL_0046; IL_009b: List list; List item = (List)list; int num2; TournamentMatchState tournamentMatchState; List item2 = ((num2 != 0) ? tournamentMatchState.TeamB : tournamentMatchState.TeamA); BattleMapDef battleMapDef = Content.BattleMaps.Get("map.bannerlord_siege_v1"); TournamentRunState run; run.Attempts++; TournamentState playerTournament2; Encounter encounter = new Encounter { Id = playerTournament2.Id + ".round" + (run.Round + 1).ToString(CultureInfo.InvariantCulture), CreatedAtMinute = State.Clock.Minute, Kind = EncounterKind.Tournament, Biome = "arena", PlayerInvolved = true, PlayerSide = BattleSide.Attacker, AttemptCounter = run.Attempts, ExpectedRevision = State.Revision, BattleMapId = battleMapDef.Id, Phase = EncounterPhase.Preparing }; encounter.CurrentAttemptId = encounter.Id + "#" + run.Attempts.ToString(CultureInfo.InvariantCulture); BattleManifest battleManifest = new BattleManifest { EncounterId = encounter.Id, AttemptId = encounter.CurrentAttemptId }; int num3 = 1; (List, BattleSide)[] array = new(List, BattleSide)[2] { (item, BattleSide.Attacker), (item2, BattleSide.Defender) }; for (int i = 0; i < array.Length; i++) { (List, BattleSide) tuple = array[i]; foreach (int item3 in tuple.Item1) { TournamentFighterState tournamentFighterState = TournamentFighter(run, item3); if (FighterAvailable(tournamentFighterState)) { UnitDef unitDef = C.UnitDef(tournamentFighterState.UnitId); Hero hero = State.Heroes.Get(tournamentFighterState.HeroId ?? ""); bool flag = tournamentFighterState.Kind == TournamentFighterKind.Player || tournamentFighterState.Kind == TournamentFighterKind.Companion; battleManifest.Combatants.Add(new Combatant { Id = num3++, Side = tuple.Item2, PartyId = (flag ? State.PlayerPartyId : ""), UnitId = tournamentFighterState.UnitId, HeroId = (hero?.Id ?? ""), Loadout = (flag ? Campaign.CopyHeroLoadout(hero?.Loadout) : null), EquipmentStats = ((flag && hero?.Loadout != null) ? C.HeroEquipmentStats(hero) : null), Role = (unitDef?.Role ?? TroopRole.Infantry), Tier = (unitDef?.Tier ?? 1), Slots = 1, Workload = (unitDef?.Workload ?? 1.0), Group = ManifestBuilder.GroupFor(unitDef?.Role ?? TroopRole.Infantry) }); } } } int num4 = battleManifest.Combatants.Count((Combatant c) => c.Side == BattleSide.Attacker); int num5 = battleManifest.Combatants.Count - num4; if (num4 == 0 || num5 == 0) { throw new InvalidOperationException("This match has nobody to fight."); } battleManifest.AttackerAllowance = num4; battleManifest.DefenderAllowance = num5; battleManifest.Budget = battleManifest.Combatants.Count; encounter.Manifest = battleManifest; State.Touch(); return new BattlePlan { Encounter = encounter, Manifest = battleManifest, Budget = battleManifest.Budget, PlayerSide = BattleSide.Attacker, PlayerSideAllowance = num4, EnemySideAllowance = num5, Map = battleMapDef, MapIsStandIn = false, Config = ReinforcementConfig.FromRules(Rules, battleManifest.Budget), SuggestedInitial = (from c in battleManifest.Combatants where c.Side == BattleSide.Attacker select c.Id).ToList(), EnemyInitial = (from c in battleManifest.Combatants where c.Side == BattleSide.Defender select c.Id).ToList() }; IL_0046: string text2 = text; if (text2.Length > 0) { throw new InvalidOperationException(text2); } playerTournament2 = PlayerTournament; run = playerTournament2.Run; tournamentMatchState = ((num != 0) ? NextSpectatorMatch(run) : PlayerMatch(run)); if (num == 0) { num2 = (tournamentMatchState.TeamA.Contains(1) ? 1 : 0); if (num2 == 0) { list = tournamentMatchState.TeamB; goto IL_009b; } } else { num2 = 1; } list = tournamentMatchState.TeamA; goto IL_009b; } public string BeginTournamentMatch(BattlePlan plan) { TournamentState playerTournament = PlayerTournament; if (playerTournament == null || plan?.Encounter == null || plan.Encounter.Kind != EncounterKind.Tournament || (playerTournament.Run.Spectating ? TournamentWatchReason() : TournamentFightReason()).Length > 0) { throw new InvalidOperationException("Prepare the tournament match first."); } playerTournament.Run.AttemptId = plan.Encounter.CurrentAttemptId; plan.Encounter.Phase = EncounterPhase.InBattle; State.Player.Activity = PlayerActivity.InBattle; State.Touch(); return playerTournament.Run.AttemptId; } public void AbortTournamentMatch(string reason) { TournamentState playerTournament = PlayerTournament; if (playerTournament != null && playerTournament.Run.AttemptId.Length > 0) { playerTournament.Run.AttemptId = ""; State.AddLog(LogCategory.Info, "Your tournament match was interrupted (" + reason + "). It will be fought again.", playerTournament.TownId); } if (State.Player.Activity == PlayerActivity.InBattle && string.IsNullOrEmpty(State.Player.PendingEncounterId)) { State.Player.Activity = PlayerActivity.Idle; C.UpdatePlayerTimeStates(); } State.Touch(); } public CommandResult CompleteTournamentMatch(string attemptId, bool playerTeamWon, bool playerKnockedOut) { TournamentState playerTournament = PlayerTournament; if (playerTournament == null || string.IsNullOrEmpty(attemptId) || playerTournament.Run.AttemptId != attemptId) { return CommandResult.Fail("This match result is out of date."); } TournamentRunState run = playerTournament.Run; TournamentMatchState tournamentMatchState = PlayerMatch(run); run.AttemptId = ""; State.Player.Activity = PlayerActivity.Idle; C.UpdatePlayerTimeStates(); if (tournamentMatchState == null || tournamentMatchState.Winner >= 0) { State.Touch(); return CommandResult.Fail("Already decided."); } bool flag = tournamentMatchState.TeamA.Contains(1); tournamentMatchState.Fought = true; ResolveMatch(run, tournamentMatchState, (playerTeamWon != flag) ? 1 : 0); bool flag2 = Tournaments.TeamSize[run.Round] == 1; List list = new List(); if (playerTeamWon) { list.Add(flag2 ? "You won the final!" : (playerKnockedOut ? "You were knocked down, but your team won the match." : "Your team won the match.")); } else { list.Add(flag2 ? "You lost the final." : "Your team lost. You're out: watch the rest from the stands, or leave."); } if (!playerTeamWon && !flag2) { run.Spectating = true; } string msg = ContinueTournament(playerTournament, list); State.Touch(); return CommandResult.Success(msg); } public string TournamentWithdrawReason() { TournamentState playerTournament = PlayerTournament; if (playerTournament == null) { return "You're not in a tournament."; } if (playerTournament.Run.AttemptId.Length > 0) { if (!playerTournament.Run.Spectating) { return "Your match is under way."; } return "A match is under way."; } return ""; } public CommandResult WithdrawFromTournament() { string text = TournamentWithdrawReason(); if (text.Length > 0) { return CommandResult.Fail(text); } TournamentState playerTournament = PlayerTournament; TournamentFighterState tournamentFighterState = TournamentFighter(playerTournament.Run, 1); List list = new List(); if (playerTournament.Run.Spectating) { playerTournament.Run.Spectating = false; list.Add("You left the stands."); } if (tournamentFighterState != null && !tournamentFighterState.Eliminated) { tournamentFighterState.Eliminated = true; tournamentFighterState.EliminatedInRound = playerTournament.Run.Round; list.Add("You pulled out of the tournament."); } string msg = ContinueTournament(playerTournament, list); State.Touch(); return CommandResult.Success(msg); } internal string ContinueTournament(TournamentState t, List lines) { TournamentRunState run = t.Run; RandomStream rng = State.Random.Get("tournaments"); Settlement town = State.Settlements.Get(t.TownId); do { if (!run.Spectating) { foreach (TournamentMatchState item in (from m in RoundMatches(run) where m.Winner < 0 select m).ToList()) { SimulateMatch(run, item, rng); } } if (RoundMatches(run).Any((TournamentMatchState m) => m.Winner < 0)) { return string.Join(" ", lines); } TournamentFighterState tournamentFighterState = TournamentFighter(run, 1); bool flag = tournamentFighterState != null && !tournamentFighterState.Eliminated; if (run.Round + 1 >= Tournaments.Rounds || run.Fighters.Count((TournamentFighterState f) => !f.Eliminated) <= 1) { ConcludeTournament(t, town, lines); return string.Join(" ", lines); } run.Round++; run.BetThisRound = 0L; DrawRound(run, rng); if (flag) { run.Odds = Tournaments.Odds(PlayerTournamentChance(t)); lines.Add(Tournaments.RoundNames[run.Round] + " next."); return string.Join(" ", lines); } } while (!run.Spectating); lines.Add(Tournaments.RoundNames[run.Round] + " is drawn."); return string.Join(" ", lines); } internal void ConcludeTournament(TournamentState t, Settlement town, List lines) { TournamentRunState run = t.Run; TournamentFighterState tournamentFighterState = run.Fighters.FirstOrDefault((TournamentFighterState f) => !f.Eliminated); string text = town?.Name ?? "the town"; TournamentResultState tournamentResultState = new TournamentResultState { TownId = t.TownId, TownName = text, PrizeName = t.Prize.Name, WinnerName = (tournamentFighterState?.Name ?? "Nobody"), BetTotal = run.BetTotal }; bool num = tournamentFighterState != null && (tournamentFighterState.Kind == TournamentFighterKind.Player || tournamentFighterState.Kind == TournamentFighterKind.Companion); RecordTournamentWin(tournamentFighterState); if (num) { Hero winner = State.Heroes.Get(tournamentFighterState.HeroId); AwardTournamentPrize(t, winner, town); State.PlayerClan.Renown += 3.0; tournamentResultState.ClanWon = true; tournamentResultState.Renown = 3.0; tournamentResultState.PlayerWon = tournamentFighterState.Kind == TournamentFighterKind.Player; if (tournamentResultState.PlayerWon) { lines.Add("You are the champion of " + text + " and won " + t.Prize.Name + "."); if (run.BetPayout > 0 && town?.Market != null) { long num2 = Math.Min(run.BetPayout, Math.Max(0L, town.Market.Gold)); town.Market.Gold -= num2; State.Transact(State.PlayerClan, num2, LedgerAccount.Tournament, "Bet winnings at the " + text + " tournament"); tournamentResultState.BetPaid = num2; lines.Add("Your bets paid " + num2.ToString("N0", CultureInfo.InvariantCulture) + " denars" + ((num2 < run.BetPayout) ? " (all the bookmakers had)" : "") + "."); } } else { lines.Add(tournamentFighterState.Name + " won the tournament and " + t.Prize.Name + " for your clan."); } lines.Add("Your clan gained " + 3.0.ToString("0", CultureInfo.InvariantCulture) + " renown."); } else if (tournamentFighterState != null) { if (tournamentFighterState.Kind == TournamentFighterKind.Lord) { Clan clan = State.Clans.Get(tournamentFighterState.ClanId); if (clan != null) { clan.Renown += 3.0; } } lines.Add(tournamentFighterState.Name + " won the tournament and took " + t.Prize.Name + "."); if (run.BetTotal > 0) { lines.Add("You lost your bets of " + run.BetTotal.ToString("N0", CultureInfo.InvariantCulture) + " denars."); } } C.NoteCompanionTournament(from f in run.Fighters where f.Kind == TournamentFighterKind.Companion select f.HeroId); tournamentResultState.Lines = new List(lines); State.Tournaments.LastResult = tournamentResultState; State.Tournaments.Active.Remove(t); State.AddLog(LogCategory.Info, (tournamentFighterState?.Name ?? "Nobody") + " won the tournament at " + text + ". The prize: " + t.Prize.Name + ".", t.TownId); } public void MarkTournamentResultSeen() { if (State.Tournaments?.LastResult != null && !State.Tournaments.LastResult.Seen) { State.Tournaments.LastResult.Seen = true; State.Touch(); } } } internal sealed class TownVisitSystem { private readonly Campaign C; private ContentDatabase Content => C.Content; private static HashSet OddGuards => Campaign.OddGuards; private CampaignRules Rules => C.Rules; private CampaignState State => C.State; private static (string id, int weight)[] TownCivilians => Campaign.TownCivilians; internal TownVisitSystem(Campaign host) { C = host; } public string TownVisitReason() { Party playerParty = State.PlayerParty; if (playerParty == null || playerParty.State != PartyState.InSettlement) { return "You're not staying in a town or castle."; } Settlement settlement = State.Settlements.Get(playerParty.CurrentSettlementId); if (settlement == null || (settlement.Type != SettlementType.Town && settlement.Type != SettlementType.Castle)) { return "Only towns and castles can be walked round."; } if (!string.IsNullOrEmpty(State.Player.PendingEncounterId) || State.Player.Activity == PlayerActivity.InBattle || State.Player.Activity == PlayerActivity.InEncounter) { return "Resolve your current encounter first."; } if (C.IsSettlementBesieged(settlement)) { return settlement.Name + " is under siege."; } TournamentState playerTournament = C.PlayerTournament; if (playerTournament != null && playerTournament.Run?.AttemptId.Length > 0) { return "Your tournament match is under way."; } Hero playerHero = State.PlayerHero; if (playerHero == null || playerHero.State != HeroState.Active) { return "Your character is not here."; } UnitDef unitDef = C.UnitDef(playerHero.UnitId); if (unitDef == null || string.IsNullOrEmpty(unitDef.TabsUnitId)) { return "Your character has no TABS body."; } if (unitDef.Slots != 1 || unitDef.Workload > 2.0) { return "You're too big to walk the streets."; } BattleMapDef battleMapDef = Content.BattleMaps.Get("map.bannerlord_siege_v1"); if (battleMapDef == null || !battleMapDef.TabsMapMatch.Contains("00_simulation_day")) { return "The battle map the town is built on is unavailable."; } return ""; } public BattlePlan PrepareTownVisit() { string text = TownVisitReason(); if (text.Length > 0) { throw new InvalidOperationException(text); } Settlement settlement = State.Settlements.Get(State.PlayerParty.CurrentSettlementId); Hero playerHero = State.PlayerHero; UnitDef unitDef = C.UnitDef(playerHero.UnitId); BattleMapDef battleMapDef = Content.BattleMaps.Get("map.bannerlord_siege_v1"); Encounter encounter = new Encounter { Id = "visit." + settlement.Id + "." + State.Clock.Minute.ToString(CultureInfo.InvariantCulture), CreatedAtMinute = State.Clock.Minute, Kind = EncounterKind.TownVisit, Biome = "town", PlayerInvolved = true, PlayerSide = BattleSide.Attacker, AttemptCounter = 1, ExpectedRevision = State.Revision, BattleMapId = battleMapDef.Id, Phase = EncounterPhase.Preparing }; encounter.CurrentAttemptId = encounter.Id + "#1"; BattleManifest battleManifest = new BattleManifest { EncounterId = encounter.Id, AttemptId = encounter.CurrentAttemptId }; battleManifest.Combatants.Add(new Combatant { Id = 1, Side = BattleSide.Attacker, PartyId = State.PlayerPartyId, UnitId = playerHero.UnitId, HeroId = playerHero.Id, Loadout = Campaign.CopyHeroLoadout(playerHero.Loadout), EquipmentStats = ((playerHero.Loadout != null) ? C.HeroEquipmentStats(playerHero) : null), Role = unitDef.Role, Tier = unitDef.Tier, Slots = 1, Workload = unitDef.Workload, Group = "visit.hero" }); List<(string, UnitDef)> list = TownVisitPeople(settlement, unitDef); UnitDef unitDef2 = TownVisitLocal(settlement, unitDef); List list2 = C.NoblesHere(); Hero holder = KeepHolderHere(settlement, list2); IEnumerable source; if (holder != null) { source = new Hero[1] { holder }.Concat(list2.Where((Hero h) => h != holder)); } else { IEnumerable enumerable = list2; source = enumerable; } foreach (Hero item in source.Take(6).ToList()) { list.Add((TownVisitRoles.Named((item == holder) ? "visit.lord" : "visit.noble", item.Id), InPerson(C.UnitDef(item.UnitId)) ? C.UnitDef(item.UnitId) : unitDef2)); } foreach (Hero item2 in C.AvailableCompanions().Take(3)) { list.Add((TownVisitRoles.Named("visit.companion", item2.Id), InPerson(C.UnitDef(item2.UnitId)) ? C.UnitDef(item2.UnitId) : unitDef2)); } foreach (var item3 in list) { List combatants = battleManifest.Combatants; Combatant obj = new Combatant { Id = battleManifest.Combatants.Count + 1, Side = BattleSide.Attacker, PartyId = "", UnitId = item3.Item2.Id, HeroId = "", Role = item3.Item2.Role, Tier = item3.Item2.Tier, Slots = 1, Workload = Math.Min(item3.Item2.Workload, 2.0) }; (obj.Group, _) = item3; combatants.Add(obj); } int count = battleManifest.Combatants.Count; UnitDef unitDef3 = TownVisitLocal(settlement, unitDef); battleManifest.Combatants.Add(new Combatant { Id = count + 1, Side = BattleSide.Defender, PartyId = "", UnitId = unitDef3.Id, HeroId = "", Role = unitDef3.Role, Tier = unitDef3.Tier, Slots = 1, Workload = unitDef3.Workload, Group = "visit.hidden" }); battleManifest.AttackerAllowance = count; battleManifest.DefenderAllowance = 1; battleManifest.Budget = count + 1; encounter.Manifest = battleManifest; return new BattlePlan { Encounter = encounter, Manifest = battleManifest, Budget = count + 1, PlayerSide = BattleSide.Attacker, PlayerSideAllowance = count, EnemySideAllowance = 1, Map = battleMapDef, MapIsStandIn = false, Config = ReinforcementConfig.FromRules(Rules, count + 1), SuggestedInitial = (from c in battleManifest.Combatants where c.Side == BattleSide.Attacker select c.Id).ToList(), EnemyInitial = new List { count + 1 } }; } public Hero KeepHolderHere(Settlement s, IList staying) { if (s == null || staying == null) { return null; } Clan owner = State.Clans.Get(s.OwnerClanId); if (owner == null) { return null; } return staying.FirstOrDefault((Hero h) => h.Id == owner.LeaderHeroId) ?? staying.FirstOrDefault((Hero h) => h.ClanId == owner.Id); } internal static bool WalksTheStreets(UnitDef u) { if (u != null && !string.IsNullOrEmpty(u.TabsUnitId) && u.Slots == 1 && u.Workload <= 2.0) { return !u.Mounted; } return false; } internal static bool InPerson(UnitDef u) { if (!WalksTheStreets(u)) { if (u != null && u.Mounted && !string.IsNullOrEmpty(u.TabsUnitId) && u.Slots == 1) { return u.Workload <= 3.0; } return false; } return true; } internal List<(string role, UnitDef unit)> TownVisitPeople(Settlement s, UnitDef heroUnit) { Random random = new Random(TownVisitSeed(s.Id)); List<(string id, int weight)> civilians = TownCivilians.Where(((string id, int weight) c) => WalksTheStreets(C.UnitDef(c.id))).ToList(); List source = (from u in Content.Units where u.Culture == s.CultureId && WalksTheStreets(u) && (u.Role == TroopRole.Infantry || u.Role == TroopRole.Ranged || u.Role == TroopRole.Support) orderby u.Tier select u).ThenBy((UnitDef u) => u.Id, StringComparer.Ordinal).ToList(); List source2 = source.Where((UnitDef u) => u.Role == TroopRole.Infantry && !OddGuards.Contains(u.Id)).ToList(); UnitDef guard = source2.Where((UnitDef u) => u.Tier >= 2 && u.Tier <= 4).LastOrDefault() ?? source2.LastOrDefault((UnitDef u) => u.Tier <= 4) ?? First(new string[2] { "medieval.knight", "medieval.squire" }) ?? heroUnit; UnitDef recruit = TownVisitLocal(s, null) ?? source2.FirstOrDefault() ?? guard; List soldiers = source.Where((UnitDef u) => u.Tier <= 3).ToList(); if (soldiers.Count == 0) { soldiers.Add(recruit); } List<(string, UnitDef)> people = new List<(string, UnitDef)>(); bool castle = s.Type == SettlementType.Castle; Add("visit.guard", 6, () => guard); UnitDef keepGuard = source2.Where((UnitDef u) => u.Tier >= 3).LastOrDefault() ?? guard; Add("visit.keepguard", 4, () => keepGuard); Add("visit.steward", 1, () => First(new string[4] { "renaissance.painter", "medieval.healer", "dynasty.monk", "medieval.peasant" })); if (castle) { Add("visit.drill", 4, () => recruit); } else { Add("visit.merchant", 8, () => Or(First(new string[1] { (new string[4] { "farmer.potionseller", "farmer.farmer", "medieval.peasant", "renaissance.painter" })[random.Next(4)] }), Civilian())); } Add("visit.worker", 1, () => First(new string[3] { "wildwest.miner", "farmer.farmer", "medieval.peasant" })); Add("visit.priest", 1, () => First(new string[3] { "medieval.healer", "dynasty.monk", "medieval.peasant" })); if (!castle) { Add("visit.bard", 1, () => First(new string[2] { "medieval.bard", "medieval.peasant" })); } Add("visit.folk", castle ? 12 : 26, () => (!(random.NextDouble() < (castle ? 0.5 : 0.25))) ? Or(Civilian(), Soldier()) : Soldier()); if (!castle) { Add("visit.child", 5, () => First(new string[1] { "farmer.halfling" }) ?? Civilian()); } return people; void Add(string role, int count, Func pick) { for (int i = 0; i < count; i++) { people.Add((role, pick() ?? recruit)); } } UnitDef Civilian() { if (civilians.Count == 0) { return null; } int num = random.Next(civilians.Sum(((string id, int weight) c) => c.weight)); foreach (var item in civilians) { if (num < item.weight) { return C.UnitDef(item.id); } num -= item.weight; } return C.UnitDef(civilians[0].id); } UnitDef First(params string[] ids) { return ids.Select(C.UnitDef).FirstOrDefault(WalksTheStreets); } static UnitDef Or(UnitDef unit, UnitDef fallback) { return unit ?? fallback; } UnitDef Soldier() { return soldiers[random.Next(soldiers.Count)]; } } internal static int TownVisitSeed(string id) { int num = 23; string text = id ?? ""; foreach (char c in text) { num = num * 37 + c; } return num & 0x7FFFFFFF; } internal UnitDef TownVisitLocal(Settlement s, UnitDef fallback) { CultureDef cultureDef = (Content.Cultures.Contains(s.CultureId ?? "") ? Content.Culture(s.CultureId) : null); UnitDef unitDef = ((cultureDef == null) ? null : C.UnitDef(cultureDef.BasicTroop)); if (!WalksTheStreets(unitDef)) { return fallback; } return unitDef; } } public sealed class TutorialStepDef { public string Id = ""; public string Title = ""; public string Text = ""; public string Hint = ""; public Func Check; public Action Mark; public Func Target; public string Practice = ""; public bool Manual => Check == null; } public sealed class TutorialChapterDef { public string Id = ""; public string Name = ""; public string Summary = ""; public string Icon = ""; public List Steps = new List(); } public sealed class TutorialView { public bool Active; public string ChapterId = ""; public string ChapterName = ""; public int ChapterNumber; public int ChapterCount; public int StepNumber; public int StepCount; public string Title = ""; public string Text = ""; public string Hint = ""; public bool Manual; public bool Done; public string TargetId = ""; public string Practice = ""; public bool Minimised; public bool Finished; } internal sealed class TutorialSystem { private readonly Campaign C; public const string Basics = "basics"; public const string Battle = "battle"; public const string Siege = "siege"; public const string Kingdom = "kingdom"; public const string Arena = "arena"; public const string Horses = "horses"; public const string Smithing = "smithing"; public const string Trade = "trade"; public const string Clan = "clan"; public const string Quests = "quests"; public const string Family = "family"; public static readonly IReadOnlyList Chapters = BuildChapters(); private CampaignState State => C.State; private TutorialState T { get { if (State.Tutorial == null) { State.Tutorial = new TutorialState(); } TutorialState tutorial = State.Tutorial; if (tutorial.Chapters == null) { tutorial.Chapters = new List(); } if (tutorial.Done == null) { tutorial.Done = new List(); } if (tutorial.Marks == null) { tutorial.Marks = new SortedDictionary(StringComparer.Ordinal); } if (tutorial.Signals == null) { tutorial.Signals = new SortedSet(StringComparer.Ordinal); } return tutorial; } } public TutorialStepDef CurrentStep { get { if (!T.Active) { return null; } return Chapter(T.Chapter)?.Steps.ElementAtOrDefault(T.Step); } } internal TutorialSystem(Campaign host) { C = host; } public static TutorialChapterDef Chapter(string id) { return Chapters.FirstOrDefault((TutorialChapterDef c) => c.Id == id); } private static TutorialStepDef S(string id, string title, string text, string hint = "", Func check = null, Action mark = null, Func target = null, string practice = "") { return new TutorialStepDef { Id = id, Title = title, Text = text, Hint = hint, Check = check, Mark = mark, Target = target, Practice = practice }; } private static bool Signal(TutorialState t, params string[] names) { return names.Any((string n) => t.Signals.Contains(n)); } private static double M(TutorialState t, string key) { if (!t.Marks.TryGetValue(key, out var value)) { return 0.0; } return value; } private static Party Me(Campaign c) { return c.State.PlayerParty; } private static Settlement Here(Campaign c) { Party party = Me(c); if (party == null || party.State != PartyState.InSettlement) { return null; } return c.State.Settlements.Get(Me(c).CurrentSettlementId); } private static string NearestTown(Campaign c, Func where = null) { Party p = Me(c); if (p == null) { return ""; } Clan me = c.State.PlayerClan; return (from s in (from s in c.State.Settlements where s.Type == SettlementType.Town && !c.State.AreHostile(me, c.State.Clans.Get(s.OwnerClanId)) && (@where == null || @where(s)) orderby Vec2.Distance(p.Position, s.Position) select s).ThenBy((Settlement s) => s.Id, StringComparer.Ordinal) select s.Id).FirstOrDefault() ?? ""; } private static int Cargo(Campaign c) { return (Me(c)?.Cargo?.Values.Sum()).GetValueOrDefault(); } private static List BuildChapters() { List list = new List(); list.Add(new TutorialChapterDef { Id = "basics", Name = "The basics", Icon = "Map", Summary = "Travelling, time, towns, recruiting, food, your party and saving.", Steps = { S("welcome", "Welcome", "You lead a small warband and a clan of your own. Everything happens on this map: travel, trade, recruit, and fight when parties meet. This card shows what to try next. Do each thing and it moves on by itself, or press Skip. Minimise it with −, and change the parts you chose with Parts."), S("travel", "Travel", "Right-click somewhere on the map to travel there; right-click a settlement to go in, or a party to go after it. Double right-click goes at fast speed. Wheel zooms, middle-drag or WASD pans, Q and E rotate, C centres on you.", "Right-click the map.", (Campaign c, TutorialState t) => Me(c) != null && (Vec2.Distance(Me(c).Position, new Vec2(M(t, "x"), M(t, "y"))) > 0.5 || c.State.Player.Activity == PlayerActivity.Travelling), delegate(Campaign c, TutorialState t) { t.Marks["x"] = Me(c).Position.X; t.Marks["y"] = Me(c).Position.Y; }), S("time", "Time", "Time only moves while you let it: 1 is normal speed, 2 fast and Space pauses or resumes. Standing still, your party waits where it is. Menus pause it. Days pass, food is eaten and wages are paid at dawn.", "Press 1 or 2 and let a few hours pass.", (Campaign c, TutorialState t) => c.State.Clock.Minute - t.StepStartMinute >= 180), S("town", "Visit a town", "Towns have markets, taverns, an arena and a smithy. Right-click one to go in; its menu opens when you arrive. Show on map points you to the nearest friendly town.", "Go into a town.", delegate(Campaign c, TutorialState t) { Settlement settlement = Here(c); return settlement != null && settlement.Type == SettlementType.Town; }, null, (Campaign c) => NearestTown(c)), S("recruit", "Recruit soldiers", "The Recruit tab lists volunteers from the town and its villages. Hire a few: they cost a fee and a daily wage, and better volunteers come with better relations with the notables.", "Recruit at least one soldier.", (Campaign c, TutorialState t) => (double)(Me(c)?.Troops.TotalTroops ?? 0) > M(t, "troops"), delegate(Campaign c, TutorialState t) { t.Marks["troops"] = Me(c)?.Troops.TotalTroops ?? 0; }), S("food", "Buy food", "Your party eats every day. Buy grain or other food at the market (Trade, I) before you run low; hungry soldiers lose morale and desert.", "Buy some food.", (Campaign c, TutorialState t) => c.FoodSupply(Me(c)) > M(t, "food") + 0.5, delegate(Campaign c, TutorialState t) { t.Marks["food"] = c.FoodSupply(Me(c)); }), S("party", "Your party", "P opens your party: troops, their upgrades, prisoners and the roles your companions take (scout, surgeon, quartermaster, engineer).", "Press P.", (Campaign c, TutorialState t) => Signal(t, "party")), S("characters", "Characters and gear", "H opens your characters: skills, levels, equipment and companions. Pick a slot, then a weapon to compare it; the (i) button beside any weapon shows its full stats.", "Press H.", (Campaign c, TutorialState t) => Signal(t, "characters")), S("journal", "Journal and encyclopedia", "L opens the journal (quests, places you've found, events); N the encyclopedia, with every settlement, lord, clan, kingdom and troop, and a page for each of the game's ideas.", "Press L or N.", (Campaign c, TutorialState t) => Signal(t, "journal", "encyclopedia")), S("save", "Saving", "The game saves itself each day and before battles. Esc opens Save and Load for your own saves, and the game settings.", "Press Esc.", (Campaign c, TutorialState t) => Signal(t, "save")) } }); list.Add(new TutorialChapterDef { Id = "battle", Name = "Battles", Icon = "Sword", Summary = "Deploying, giving orders and fighting, with a practice battle.", Steps = { S("encounter", "When parties meet", "Go after a party (right-click it) or be caught by one, and you meet. You can fight, talk, or try to leave. Fighting opens the battle in TABS: first you deploy, then it plays out with TABS's physics."), S("deploy", "Deploying", "Choose who fights first, then Position troops. Click a troop or press 1–6 for its group (infantry, ranged, cavalry, support, monsters, siege), 0 for all. Pick a formation (line, shield wall, wedge…), set frontage and spacing, right-click to move them and Q/E to turn them. F1–F8 queue starting orders. Begin battle (Enter) starts it."), S("orders", "Orders in battle", "The orders panel (bottom left) commands the selected groups: Hold F1, Attack F2, Move F3, Retreat F4, Charge F5, Advance F6, Fall back F7, Follow F8, Face F11. Formation and fire orders are there too. Backspace retreats everyone; T is slow motion. You can take over any of your soldiers the usual TABS way."), S("practice", "A practice battle", "Try it: twenty of the Wardens against twenty Viking raiders, on a field of their own. Nothing in your campaign changes, and you come back here when it's over.", "Press Practice fight (or Skip).", (Campaign c, TutorialState t) => Signal(t, "practice-battle"), null, null, "battle"), S("after", "After a battle", "Win and you take prisoners and loot; the wounded recover with time (a good surgeon helps). Lose and you may be taken prisoner yourself. Your heroes are only knocked out, unless you turned on deaths in battle.") } }); list.Add(new TutorialChapterDef { Id = "siege", Name = "Sieges", Icon = "Siege", Summary = "Besieging castles and towns, siege engines, assaults and defence.", Steps = { S("start", "Laying siege", "You can only besiege a castle or town of someone you are at war with. Take a party (or an army) to it and choose to besiege it: you make camp outside. The defenders live on their food; you on yours."), S("camp", "The siege camp", "In camp your engineer builds rams, siege towers, ladders and artillery, which take days. Artillery wears the walls down. When you are ready, assault; or wait and let hunger do the work."), S("assault", "The assault", "In the assault you deploy at the camp. Siege orders on the orders panel choose which way each group goes in: the ram, either tower, the ladders, breaches or the gate. Charge means storm now. Hold the gate or the walls' top and the place is yours."), S("practice", "A practice siege", "Try storming a fortress: the Wardens attack walls held by Viking raiders. Nothing in your campaign changes, and you come back here when it's over.", "Press Practice siege (or Skip).", (Campaign c, TutorialState t) => Signal(t, "practice-siege"), null, null, "siege"), S("defend", "Defending", "When your own town or castle is besieged, garrison and militia defend it, and you can break in to help or attack the camp from outside. Walls (built in the Manage tab) make each section stronger.") } }); list.Add(new TutorialChapterDef { Id = "kingdom", Name = "Joining a kingdom", Icon = "Crown", Summary = "Kingdoms, mercenary service, vassalage and your own realm.", Steps = { S("realm", "Clans and kingdoms", "You start as an independent clan. K opens your clan and the kingdoms: their wars, their lords and how they feel about you.", "Press K.", (Campaign c, TutorialState t) => Signal(t, "realm")), S("mercenary", "Serving for pay", "A kingdom will hire a landless clan as mercenaries. Talk to a lord of that kingdom (meet their party, or find them in a town or castle) and offer your service, or sign at their town. You are paid each day and share their wars.", "Become a mercenary or vassal of a kingdom (or Skip).", delegate(Campaign c, TutorialState t) { ClanServiceState clanService = c.State.ClanService; if (clanService == null || clanService.Kind != ClanServiceKind.Mercenary) { ClanServiceState clanService2 = c.State.ClanService; if (clanService2 == null || clanService2.Kind != ClanServiceKind.Vassal) { return !string.IsNullOrEmpty(c.State.PlayerClan?.KingdomId); } } return true; }), S("vassal", "Vassal and fiefs", "With " + 100 + " renown you can swear fealty as a vassal. Vassals vote in the council and can be given towns and castles, which pay taxes and have to be governed: the Manage tab sets policies, building and budgets."), S("own", "A kingdom of your own", "An independent clan with " + 200 + " renown and " + 1000L + " denars can found a kingdom of its own (K). Other clans may join you; you make war and peace, and the council votes on policies.") } }); list.Add(new TutorialChapterDef { Id = "arena", Name = "The arena", Icon = "Flag", Summary = "Tournaments, betting and prizes.", Steps = { S("find", "Finding a tournament", "Towns hold tournaments from time to time; people in taverns tell you where. Show on map points you to the nearest one.", "Go to a town holding a tournament.", (Campaign c, TutorialState t) => Here(c) != null && c.TournamentAt(Here(c).Id) != null, null, (Campaign c) => NearestTown(c, (Settlement s) => c.TournamentAt(s.Id) != null)), S("enter", "Entering", "In the town, Arena opens the tournament: the prize, who is fighting and the rounds. Enter it to fight in the first round; your companions can enter too.", "Open the arena.", (Campaign c, TutorialState t) => Signal(t, "arena")), S("fight", "Fighting", "Each round is a small TABS battle in the arena. Win and you go on; lose and you are out, unhurt. You can bet on yourself before each round.", "Fight a round (or Skip).", delegate(Campaign c, TutorialState t) { TournamentsState tournaments = c.State.Tournaments; if (tournaments == null || tournaments.Active?.Any(delegate(TournamentState x) { TournamentRunState run = x.Run; return run != null && run.Fighters?.Any((TournamentFighterState f) => f.Kind == TournamentFighterKind.Player) == true; }) != true) { TournamentsState tournaments2 = c.State.Tournaments; int value = default(int); if (tournaments2 != null && tournaments2.Wins?.TryGetValue(c.State.PlayerHero?.Id ?? "", out value) == true) { return (double)value > M(t, "wins"); } return false; } return true; }, delegate(Campaign c, TutorialState t) { t.Marks["wins"] = ((c.State.Tournaments?.Wins != null && c.State.Tournaments.Wins.TryGetValue(c.State.PlayerHero?.Id ?? "", out var value)) ? value : 0); }), S("prizes", "Prizes", "The winner takes the prize: a fine weapon, a horse, or a special ability for a hero (switch abilities on in their Abilities tab). Wins raise your renown.") } }); list.Add(new TutorialChapterDef { Id = "horses", Name = "Horses", Icon = "Horse", Summary = "Buying horses, riding them, and breeding.", Steps = { S("stable", "The stable", "J opens the stable: your clan's horses, who rides which, and horses for sale where you are.", "Press J.", (Campaign c, TutorialState t) => Signal(t, "stable")), S("buy", "Buying a horse", "Every town sells horses, and so do ranch villages (cheapest). Look at speed, manoeuvre, charge and temperament: a difficult horse needs a better rider.", "Buy a horse (or Skip).", (Campaign c, TutorialState t) => (double)c.ClanHorses().Count() > M(t, "horses"), delegate(Campaign c, TutorialState t) { t.Marks["horses"] = c.ClanHorses().Count(); }, (Campaign c) => NearestTown(c)), S("ride", "Riding", "Give a horse to a hero in the stable. They ride it on the map (your party moves faster with mounts for everyone) and into field battles. Horses tire, can be hurt or killed, and grow fond of their riders.", "Put your hero on a horse (or Skip).", (Campaign c, TutorialState t) => c.HeroRides(c.State.PlayerHero)), S("stud", "Studs and breeding", "Buy a stud farm at a horse-ranch village. Horses can be kept there instead of in your herd, and a mare and a stallion there can be bred: the foal takes after both.") } }); list.Add(new TutorialChapterDef { Id = "smithing", Name = "Smithing", Icon = "Anvil", Summary = "Refining, forging your own weapons, orders and smelting.", Steps = { S("smithy", "The smithy", "Every town has a smithy (Smithy in the town menu). Your heroes work there; each job costs stamina, which comes back with rest.", "Open a smithy.", (Campaign c, TutorialState t) => Signal(t, "smithy"), null, (Campaign c) => NearestTown(c)), S("refine", "Materials", "Refine hardwood into charcoal and iron ore into iron, or smelt weapons you don't want for their metal. Better metal makes better parts."), S("forge", "Forging", "Choose a weapon type, then a part for each slot: blade, guard, grip and pommel (or head, shaft…). The stats show as you choose. Forging is a short game at the anvil: keep the heat up, strike on the mark, quench at the right moment.", "Forge a weapon (or Skip).", (Campaign c, TutorialState t) => (double)(c.State.Smithing?.Weapons?.Count).GetValueOrDefault() > M(t, "weapons"), delegate(Campaign c, TutorialState t) { t.Marks["weapons"] = (c.State.Smithing?.Weapons?.Count).GetValueOrDefault(); }), S("equip", "Using it", "Forged weapons go into your party's bag. Equip one in the characters screen (H), and its (i) button shows its stats. Smiths' orders in each town pay for weapons made to measure.") } }); list.Add(new TutorialChapterDef { Id = "trade", Name = "Trade and caravans", Icon = "Trade", Summary = "Buying cheap, selling dear, workshops and caravans.", Steps = { S("market", "Markets", "I opens trade and your treasury. Each town's prices follow what it makes and what it lacks: goods are cheap where they are made.", "Press I.", (Campaign c, TutorialState t) => Signal(t, "economy")), S("buy", "Buying goods", "Buy goods your party can carry (weight shows in the trade screen) where they are cheap.", "Buy some goods (or Skip).", (Campaign c, TutorialState t) => (double)Cargo(c) > M(t, "cargo"), delegate(Campaign c, TutorialState t) { t.Marks["cargo"] = Cargo(c); }), S("sell", "Selling", "Sell them where they are scarce. The trade screen shows what you paid and what you would make."), S("caravans", "Workshops and caravans", "With money to spare, buy a workshop in a town, or fit out a caravan led by a companion to trade for you. Both earn while you are elsewhere, and both can be lost.") } }); list.Add(new TutorialChapterDef { Id = "clan", Name = "Your clan", Icon = "Party", Summary = "Companions, their roles and parties, fiefs and governors.", Steps = { S("companion", "Companions", "Wanderers in taverns will join you for a fee and a wage. They fight beside you, take party roles, and can lead parties and caravans of their own.", "Hire a companion (or Skip).", (Campaign c, TutorialState t) => (double)c.State.Heroes.Count((Hero h) => h.ClanId == c.State.PlayerClanId && h.Occupation == HeroOccupation.Companion && !h.IsFamily) > M(t, "companions"), delegate(Campaign c, TutorialState t) { t.Marks["companions"] = c.State.Heroes.Count((Hero h) => h.ClanId == c.State.PlayerClanId && h.Occupation == HeroOccupation.Companion && !h.IsFamily); }, (Campaign c) => NearestTown(c)), S("roles", "Roles and parties", "In the party screen give companions roles: a scout sees further, a surgeon heals, a quartermaster stretches food, an engineer builds siege engines. Companions can also lead their own warbands (K → clan)."), S("fiefs", "Fiefs", "Your towns and castles have a Manage tab: tax policy, projects and a build queue, garrison and governor budgets, and the town's hardship. Appoint a companion as governor to run it while you're away."), S("garrisons", "Garrisons", "The Garrison tab of a town or castle gives its garrison standing orders: daily drill, promotions (with a path for each troop and a tier cap), a size to recruit up to, and taking in the dungeon's prisoners once they come round. From there you can send soldiers to another of your garrisons, or send out guards to patrol, guard a village, escort a caravan or follow you into battle.") } }); list.Add(new TutorialChapterDef { Id = "quests", Name = "Quests", Icon = "Quest", Summary = "Finding work, doing it or sending a companion.", Steps = { S("ask", "Asking for work", "In a settlement the Locals tab lists its notables; ask about their troubles. Lords answer \"Have you any work for me?\", and strangers in taverns have work of their own.", "Open a settlement's Locals tab (or Skip).", (Campaign c, TutorialState t) => Signal(t, "locals")), S("take", "Taking a quest", "Each trouble has two or three ways to deal with it, and some can be handed to a companion with a few soldiers.", "Take a quest (or Skip).", (Campaign c, TutorialState t) => (double)c.ActiveQuests.Count() > M(t, "quests"), delegate(Campaign c, TutorialState t) { t.Marks["quests"] = c.ActiveQuests.Count(); }), S("journal", "Following it", "The journal (L) lists your quests, with what to do next and where. Track one to see it on the map.", "Press L.", (Campaign c, TutorialState t) => Signal(t, "journal")) } }); list.Add(new TutorialChapterDef { Id = "family", Name = "Family", Icon = "Family", Summary = "Marriage, children and heirs.", Steps = { S("screen", "Your family", "F opens your family: your spouse, children, heir and courtships, and the family rules.", "Press F.", (Campaign c, TutorialState t) => Signal(t, "family")), S("courtship", "Courtship", "In towns and castles the Nobles (or Keep) tab lists lords and ladies staying there. Talk with an unmarried one; " + 3 + " good conversations win their favour. Then propose: their clan's leader has to agree, and a marriage gift is due."), S("heirs", "Children and heirs", "Children grow up at home and come of age at " + 18 + ". If you die, you carry on as an heir from your clan; the family rules (F) say who comes first.") } }); return list; } public void EnsureTutorialFields() { TutorialState t = T; if (t.Active && (Chapter(t.Chapter) == null || t.Step < 0 || t.Step >= Chapter(t.Chapter).Steps.Count)) { t.Active = false; State.Touch(); } } public CommandResult StartTutorial(IEnumerable chapters) { List list = (from id in (chapters ?? Enumerable.Empty()).Distinct() where Chapter(id) != null orderby Chapters.ToList().FindIndex((TutorialChapterDef c) => c.Id == id) select id).ToList(); if (list.Count == 0) { return CommandResult.Fail("Choose at least one part."); } TutorialState t = T; t.Chapters = list; t.Done.RemoveAll(list.Contains); t.Active = true; t.Minimised = false; Begin(list[0], 0); State.Touch(); return CommandResult.Success("Tutorial: " + string.Join(", ", list.Select((string id) => Chapter(id).Name).ToArray()) + "."); } public void StopTutorial() { T.Active = false; State.Touch(); } private void Begin(string chapter, int step) { TutorialState t = T; t.Chapter = chapter; t.Step = step; t.StepStartMinute = State.Clock.Minute; t.StepDoneMinute = -1L; t.Marks.Clear(); t.Signals.Clear(); TutorialStepDef tutorialStepDef = Chapter(chapter)?.Steps.ElementAtOrDefault(step); try { tutorialStepDef?.Mark?.Invoke(C, t); } catch (Exception) { } } public void TutorialNext() { TutorialState t = T; if (t.Active) { TutorialChapterDef tutorialChapterDef = Chapter(t.Chapter); if (tutorialChapterDef != null && t.Step + 1 < tutorialChapterDef.Steps.Count) { Begin(t.Chapter, t.Step + 1); State.Touch(); } else { NextChapter(); } } } public void TutorialBack() { TutorialState t = T; if (!t.Active) { return; } if (t.Step > 0) { Begin(t.Chapter, t.Step - 1); State.Touch(); return; } int num = t.Chapters.IndexOf(t.Chapter); if (num > 0) { TutorialChapterDef tutorialChapterDef = Chapter(t.Chapters[num - 1]); Begin(tutorialChapterDef.Id, tutorialChapterDef.Steps.Count - 1); State.Touch(); } } public void SkipTutorialChapter() { NextChapter(); } private void NextChapter() { TutorialState t = T; if (!t.Done.Contains(t.Chapter)) { t.Done.Add(t.Chapter); } int num = t.Chapters.IndexOf(t.Chapter); string text = t.Chapters.Skip(num + 1).FirstOrDefault((string id) => !t.Done.Contains(id)); if (text == null) { t.Active = false; t.Chapter = ""; t.Step = 0; } else { Begin(text, 0); } State.Touch(); } public void SetTutorialMinimised(bool minimised) { T.Minimised = minimised; State.Touch(); } public void TutorialSignal(string name) { TutorialState t = T; if (t.Active && !string.IsNullOrEmpty(name) && !t.Signals.Contains(name)) { t.Signals.Add(name); State.Touch(); } } public bool StepComplete() { TutorialStepDef currentStep = CurrentStep; if (currentStep == null || currentStep.Check == null) { return false; } try { return currentStep.Check(C, T); } catch (Exception) { return false; } } public bool UpdateTutorial() { TutorialState t = T; if (!t.Active) { return false; } if (t.StepDoneMinute < 0) { if (!StepComplete()) { return false; } t.StepDoneMinute = State.Clock.Minute; State.Touch(); return true; } TutorialNext(); return true; } public TutorialView View() { TutorialState t = T; TutorialView tutorialView = new TutorialView { Active = t.Active, Minimised = t.Minimised, Finished = (!t.Active && t.Done.Count > 0) }; TutorialChapterDef tutorialChapterDef = (t.Active ? Chapter(t.Chapter) : null); TutorialStepDef currentStep = CurrentStep; if (tutorialChapterDef == null || currentStep == null) { return tutorialView; } tutorialView.ChapterId = tutorialChapterDef.Id; tutorialView.ChapterName = tutorialChapterDef.Name; tutorialView.ChapterNumber = t.Chapters.IndexOf(tutorialChapterDef.Id) + 1; tutorialView.ChapterCount = t.Chapters.Count; tutorialView.StepNumber = t.Step + 1; tutorialView.StepCount = tutorialChapterDef.Steps.Count; tutorialView.Title = currentStep.Title; tutorialView.Text = currentStep.Text; tutorialView.Hint = currentStep.Hint; tutorialView.Manual = currentStep.Manual; tutorialView.Done = t.StepDoneMinute >= 0; tutorialView.Practice = currentStep.Practice; try { tutorialView.TargetId = currentStep.Target?.Invoke(C) ?? ""; } catch (Exception) { tutorialView.TargetId = ""; } return tutorialView; } } internal sealed class UnderworldSystem { private readonly Campaign C; private static string[] AlleyNames => Campaign.AlleyNames; private ContentDatabase Content => C.Content; private static string[] GangLeaderNames => Campaign.GangLeaderNames; private static string[] GangLeaderUnits => Campaign.GangLeaderUnits; private static string[] GangNames => Campaign.GangNames; private static HashSet OddGuards => Campaign.OddGuards; private CampaignRules Rules => C.Rules; private CampaignState State => C.State; private static string[] ThugUnits => Campaign.ThugUnits; private static (string id, int weight)[] TownCivilians => Campaign.TownCivilians; internal UnderworldSystem(Campaign host) { C = host; } internal void EnsureAlleys() { CrimeState crime = State.Crime; foreach (Settlement town in State.Settlements.Where((Settlement s) => s.Type == SettlementType.Town).OrderBy((Settlement s) => s.Id, StringComparer.Ordinal)) { if (!crime.Alleys.Any((AlleyState a) => a.SettlementId == town.Id)) { Random r = new Random(Campaign.StableSeed("alleys:" + town.Id)); List list = AlleyNames.OrderBy((string _) => r.Next()).Take(3).ToList(); for (int num = 0; num < 3; num++) { AlleyState alleyState = new AlleyState { Id = town.Id + "#alley" + num, SettlementId = town.Id, Index = num, Name = list[num] }; NewGang(alleyState, r); crime.Alleys.Add(alleyState); } } } crime.AlleysStarted = true; } internal static void NewGang(AlleyState alley, Random r) { alley.OwnerClanId = ""; alley.OverseerHeroId = ""; alley.GangName = GangNames[r.Next(GangNames.Length)]; alley.GangLeaderName = GangLeaderNames[r.Next(GangLeaderNames.Length)]; alley.GangSize = 3 + r.Next(3); } public List AlleysOf(Settlement s) { if (s != null && State.Crime?.Alleys != null) { return (from a in State.Crime.Alleys where a.SettlementId == s.Id orderby a.Index select a).ToList(); } return new List(); } public AlleyState Alley(string id) { return State.Crime?.Alleys?.FirstOrDefault((AlleyState a) => a.Id == id); } public bool OwnsAlley(AlleyState a) { if (a != null && a.OwnerClanId.Length > 0) { return a.OwnerClanId == State.PlayerClanId; } return false; } public long AlleyIncome(AlleyState a) { Settlement settlement = State.Settlements.Get(a?.SettlementId ?? ""); Hero hero = State.Heroes.Get(a?.OverseerHeroId ?? ""); if (settlement == null || hero == null) { return 0L; } return (long)Math.Round((12.0 + Math.Max(0.0, settlement.Prosperity) / 250.0) * (1.0 + (double)hero.Level / 30.0)); } internal double OverseerStrength(Hero h) { if (h != null) { return (double)(8 + h.Level * 2) + (double)h.Skill("leadership") / 20.0 + (double)h.Skill("tactics") / 20.0 + (double)(h.CanFight ? 4 : 0); } return 0.0; } internal bool ValidOverseer(AlleyState a, Hero h) { if (h != null && h.State == HeroState.Active && h.ClanId == State.PlayerClanId && h.Occupation == HeroOccupation.Companion && string.IsNullOrEmpty(h.PartyId)) { return h.SettlementId == a.SettlementId; } return false; } internal void DailyAlleys() { RandomStream randomStream = State.Random.Get("crime"); long day = State.Clock.Day; foreach (AlleyState alley in State.Crime.Alleys) { Settlement settlement = State.Settlements.Get(alley.SettlementId); if (settlement == null) { continue; } if (!OwnsAlley(alley)) { if (alley.GangSize < 6 && randomStream.Chance(0.15)) { alley.GangSize++; } continue; } Hero hero = State.Heroes.Get(alley.OverseerHeroId); if (alley.OverseerHeroId.Length > 0 && !ValidOverseer(alley, hero)) { alley.OverseerHeroId = ""; hero = null; } long num = AlleyIncome(alley); if (num > 0) { State.Transact(State.PlayerClan, num, LedgerAccount.Other, "Takings from " + alley.Name + " in " + settlement.Name); alley.IncomeTotal += num; } if (day < alley.ChallengeDay || !randomStream.Chance((hero != null) ? 0.035 : 0.12)) { continue; } Random random = new Random(Campaign.StableSeed("gang:" + alley.Id + ":" + day.ToString(CultureInfo.InvariantCulture))); string text = GangNames[random.Next(GangNames.Length)]; double num2 = 10.0 + randomStream.NextDouble() * 16.0; if (hero != null && OverseerStrength(hero) >= num2) { alley.ChallengeDay = day + 6; C.GrantSkillExperience(hero, "leadership", 30.0); State.AddLog(LogCategory.Info, hero.Name + " saw " + text + " off from " + alley.Name + " in " + settlement.Name + ".", hero.Id, settlement.Id); continue; } NewGang(alley, random); alley.GangName = text; alley.ChallengeDay = 0L; if (hero != null) { hero.Health = Math.Min(hero.Health, 0.4); } string text2 = text.Substring(0, 1).ToUpperInvariant() + text.Substring(1) + " took " + alley.Name + " in " + settlement.Name + " from you" + ((hero != null) ? ("; " + hero.Name + " was beaten and is recovering there.") : ": nobody was running it."); State.AddLog(LogCategory.Warning, text2, settlement.Id); C.Raise(CampaignEventKind.Warning, text2, false, settlement.Id); } } public string AssignOverseerReason(string alleyId, string heroId) { CommandResult commandResult = C.RequireFree(); if (!commandResult.Ok) { return commandResult.Message; } AlleyState alleyState = Alley(alleyId); if (!OwnsAlley(alleyState)) { return "That alley is not yours."; } Settlement settlement = C.CurrentSettlement(); if (settlement == null || settlement.Id != alleyState.SettlementId) { return "Go to " + (State.Settlements.Get(alleyState.SettlementId)?.Name ?? "the town") + " to put someone in charge."; } Hero h = State.Heroes.Get(heroId); if (h == null || h.ClanId != State.PlayerClanId || h.Occupation != HeroOccupation.Companion) { return "Only one of your companions can run an alley."; } if (h.State != HeroState.Active || !Campaign.IsPresentPartyHero(State.PlayerParty, h)) { return h.Name + " must be with your party."; } if (State.Parties.Any((Party p) => p.LeaderHeroId == h.Id && p.State != PartyState.Destroyed && p.State != PartyState.Disbanded)) { return h.Name + " leads a party."; } if (alleyState.OverseerHeroId.Length > 0) { return "Someone already runs " + alleyState.Name + "."; } return ""; } public CommandResult AssignOverseer(string alleyId, string heroId) { string text = AssignOverseerReason(alleyId, heroId); if (text.Length > 0) { return CommandResult.Fail(text); } AlleyState alleyState = Alley(alleyId); Hero hero = State.Heroes.Get(heroId); C.ClearHeroRoleAssignments(hero.Id); State.PlayerParty.Troops.Heroes.Remove(hero.Id); hero.PartyId = ""; hero.SettlementId = alleyState.SettlementId; alleyState.OverseerHeroId = hero.Id; if (alleyState.ChallengeDay < State.Clock.Day + 3) { alleyState.ChallengeDay = State.Clock.Day + 3; } State.AddLog(LogCategory.Info, hero.Name + " now runs " + alleyState.Name + " in " + State.Settlements.Get(alleyState.SettlementId)?.Name + ".", hero.Id, alleyState.SettlementId); State.Touch(); return CommandResult.Success(hero.Name + " stays behind to run " + alleyState.Name + ": about " + AlleyIncome(alleyState) + " denars a day."); } public string RecallOverseerReason(string alleyId) { CommandResult commandResult = C.RequireFree(); if (!commandResult.Ok) { return commandResult.Message; } AlleyState alleyState = Alley(alleyId); if (alleyState == null || alleyState.OverseerHeroId.Length == 0) { return "Nobody runs that alley."; } Settlement settlement = C.CurrentSettlement(); if (settlement == null || settlement.Id != alleyState.SettlementId) { return "Go to the town to take them back."; } return ""; } public CommandResult RecallOverseer(string alleyId) { string text = RecallOverseerReason(alleyId); if (text.Length > 0) { return CommandResult.Fail(text); } AlleyState alleyState = Alley(alleyId); Hero hero = State.Heroes.Get(alleyState.OverseerHeroId); alleyState.OverseerHeroId = ""; if (hero != null && hero.State == HeroState.Active && hero.ClanId == State.PlayerClanId && string.IsNullOrEmpty(hero.PartyId)) { C.JoinCompanionToPlayerParty(hero); } State.Touch(); return CommandResult.Success((hero?.Name ?? "Your overseer") + " rejoins your party. " + alleyState.Name + " is left to itself."); } public List DungeonPrisonersHere() { Settlement s = C.CurrentSettlement(); if (s == null || s.Type == SettlementType.Village || s.Type == SettlementType.Hideout) { return new List(); } return (from h in State.Heroes where h.State == HeroState.Captive && h.CaptorSettlementId == s.Id && !h.IsPlayer orderby (!(h.ClanId == State.PlayerClanId)) ? 1 : 0 select h).ThenBy((Hero h) => h.Name, StringComparer.Ordinal).ToList(); } public string PrisonBreakReason(string heroId) { string text = C.TownVisitReason(); if (text.Length > 0) { return text; } Settlement settlement = C.CurrentSettlement(); if (settlement.OwnerClanId == State.PlayerClanId) { return "These are your own cells: you hold the keys."; } Hero hero = State.Heroes.Get(heroId); if (hero == null || hero.State != HeroState.Captive || hero.CaptorSettlementId != settlement.Id) { return "That prisoner isn't held here."; } if (!State.PlayerHero.CanFight) { return "You're too badly hurt for this."; } return ""; } public string AlleyFightReason(string alleyId) { string text = C.TownVisitReason(); if (text.Length > 0) { return text; } AlleyState alleyState = Alley(alleyId); Settlement settlement = C.CurrentSettlement(); if (alleyState == null || settlement == null || alleyState.SettlementId != settlement.Id) { return "That alley isn't in this town."; } if (OwnsAlley(alleyState)) { return alleyState.Name + " is already yours."; } if (!State.PlayerHero.CanFight) { return "You're too badly hurt to fight."; } return ""; } public BattlePlan PreparePrisonBreak(string heroId) { string text = PrisonBreakReason(heroId); if (text.Length > 0) { throw new InvalidOperationException(text); } Settlement settlement = C.CurrentSettlement(); Hero hero = State.Heroes.Get(heroId); List<(string, UnitDef, Hero)> list = new List<(string, UnitDef, Hero)>(); UnitDef unitDef = C.TownVisitLocal(settlement, C.UnitDef(State.PlayerHero.UnitId)); list.Add((TownVisitRoles.Named("visit.prisoner", hero.Id), Campaign.WalksTheStreets(C.UnitDef(hero.UnitId)) ? C.UnitDef(hero.UnitId) : unitDef, hero)); UnitDef item = CrimeGuardUnit(settlement); bool flag = C.CrimeTierWith(settlement) >= CrimeTier.Hunted; List<(string, UnitDef)> list2 = new List<(string, UnitDef)>(); int num = ((settlement.Type == SettlementType.Castle) ? 5 : 4) + (flag ? 2 : 0); for (int i = 0; i < num; i++) { list2.Add(("visit.gaolguard", item)); } for (int j = 0; j < (flag ? 6 : 4); j++) { list2.Add(("visit.watch", item)); } return CrimePlan(settlement, "prison:" + hero.Id, list, list2); } public BattlePlan PrepareAlleyFight(string alleyId) { string text = AlleyFightReason(alleyId); if (text.Length > 0) { throw new InvalidOperationException(text); } Settlement s = C.CurrentSettlement(); AlleyState alleyState = Alley(alleyId); Party party = State.PlayerParty; List<(string, UnitDef, Hero)> list = new List<(string, UnitDef, Hero)>(); foreach (Hero item2 in (from id in party.Troops.Heroes select State.Heroes.Get(id) into h where h != null && !h.IsPlayer && h.CanFight && Campaign.IsPresentPartyHero(party, h) && Campaign.WalksTheStreets(C.UnitDef(h.UnitId)) orderby h.Level descending select h).ThenBy((Hero h) => h.Id, StringComparer.Ordinal).Take(2)) { list.Add((TownVisitRoles.Named("visit.follower", item2.Id), C.UnitDef(item2.UnitId), item2)); } UnitDef unitDef = ThugUnits.Select(C.UnitDef).FirstOrDefault(Campaign.WalksTheStreets) ?? C.TownVisitLocal(s, C.UnitDef(State.PlayerHero.UnitId)); Random random = new Random(Campaign.StableSeed("gangfolk:" + alleyState.Id)); List list2 = ThugUnits.Select(C.UnitDef).Where(Campaign.WalksTheStreets).ToList(); if (list2.Count == 0) { list2.Add(unitDef); } UnitDef item = GangLeaderUnits.Select(C.UnitDef).FirstOrDefault(Campaign.WalksTheStreets) ?? unitDef; List<(string, UnitDef)> list3 = new List<(string, UnitDef)> { ("visit.gangleader", item) }; for (int num = 0; num < Math.Max(2, alleyState.GangSize); num++) { list3.Add(("visit.gang", list2[random.Next(list2.Count)])); } return CrimePlan(s, "alley:" + alleyState.Id, list, list3); } internal UnitDef CrimeGuardUnit(Settlement s) { List source = (from u in Content.Units where u.Culture == s.CultureId && Campaign.WalksTheStreets(u) && u.Role == TroopRole.Infantry && !OddGuards.Contains(u.Id) orderby u.Tier select u).ThenBy((UnitDef u) => u.Id, StringComparer.Ordinal).ToList(); return source.Where((UnitDef u) => u.Tier >= 2 && u.Tier <= 4).LastOrDefault() ?? source.LastOrDefault() ?? C.TownVisitLocal(s, C.UnitDef(State.PlayerHero.UnitId)); } internal BattlePlan CrimePlan(Settlement s, string mission, List<(string role, UnitDef unit, Hero hero)> mine, List<(string role, UnitDef unit)> theirs, bool withHero = true) { Hero playerHero = State.PlayerHero; UnitDef unitDef = C.UnitDef(playerHero.UnitId); BattleMapDef battleMapDef = Content.BattleMaps.Get("map.bannerlord_siege_v1"); Encounter encounter = new Encounter { Id = "crime." + s.Id + "." + State.Clock.Minute.ToString(CultureInfo.InvariantCulture), CreatedAtMinute = State.Clock.Minute, Kind = EncounterKind.TownVisit, Biome = "town", PlayerInvolved = true, PlayerSide = BattleSide.Attacker, Mission = mission, AttemptCounter = 1, ExpectedRevision = State.Revision, BattleMapId = battleMapDef.Id, Phase = EncounterPhase.Preparing }; encounter.CurrentAttemptId = encounter.Id + "#1"; BattleManifest battleManifest = new BattleManifest { EncounterId = encounter.Id, AttemptId = encounter.CurrentAttemptId }; if (withHero) { battleManifest.Combatants.Add(new Combatant { Id = 1, Side = BattleSide.Attacker, PartyId = State.PlayerPartyId, UnitId = playerHero.UnitId, HeroId = playerHero.Id, Loadout = Campaign.CopyHeroLoadout(playerHero.Loadout), EquipmentStats = ((playerHero.Loadout != null) ? C.HeroEquipmentStats(playerHero) : null), Role = unitDef.Role, Tier = unitDef.Tier, Slots = 1, Workload = unitDef.Workload, Group = "visit.hero" }); } foreach (var item in mine) { List combatants = battleManifest.Combatants; Combatant obj = new Combatant { Id = battleManifest.Combatants.Count + 1, Side = BattleSide.Attacker, PartyId = "", UnitId = item.unit.Id, HeroId = "", Loadout = ((item.hero != null && item.unit.Id == item.hero.UnitId) ? Campaign.CopyHeroLoadout(item.hero.Loadout) : null), Role = item.unit.Role, Tier = item.unit.Tier, Slots = 1, Workload = item.unit.Workload }; (obj.Group, _, _) = item; combatants.Add(obj); } int count = battleManifest.Combatants.Count; foreach (var their in theirs) { List combatants2 = battleManifest.Combatants; Combatant obj2 = new Combatant { Id = battleManifest.Combatants.Count + 1, Side = BattleSide.Defender, PartyId = "", UnitId = their.unit.Id, HeroId = "", Role = their.unit.Role, Tier = their.unit.Tier, Slots = 1, Workload = their.unit.Workload }; (obj2.Group, _) = their; combatants2.Add(obj2); } UnitDef unitDef2 = C.TownVisitLocal(s, unitDef); battleManifest.Combatants.Add(new Combatant { Id = battleManifest.Combatants.Count + 1, Side = BattleSide.Defender, PartyId = "", UnitId = unitDef2.Id, HeroId = "", Role = unitDef2.Role, Tier = unitDef2.Tier, Slots = 1, Workload = unitDef2.Workload, Group = "visit.hidden" }); int num = battleManifest.Combatants.Count - count; battleManifest.AttackerAllowance = count; battleManifest.DefenderAllowance = num; battleManifest.Budget = count + num; encounter.Manifest = battleManifest; return new BattlePlan { Encounter = encounter, Manifest = battleManifest, Budget = count + num, PlayerSide = BattleSide.Attacker, PlayerSideAllowance = count, EnemySideAllowance = num, Map = battleMapDef, MapIsStandIn = false, Config = ReinforcementConfig.FromRules(Rules, count + num), SuggestedInitial = (from c in battleManifest.Combatants where c.Side == BattleSide.Attacker select c.Id).ToList(), EnemyInitial = (from c in battleManifest.Combatants where c.Side == BattleSide.Defender select c.Id).ToList() }; } public BattlePlan PrepareExecutionScene(string heroId, bool inDungeon) { string text = C.ExecuteReason(heroId, inDungeon); if (text.Length > 0) { throw new InvalidOperationException(text); } Hero hero = State.Heroes.Get(heroId); Party party = State.PlayerParty; Settlement settlement = C.CurrentSettlement(); if (settlement == null || (settlement.Type != SettlementType.Town && settlement.Type != SettlementType.Castle)) { settlement = (from s in State.Settlements where s.Type == SettlementType.Town || s.Type == SettlementType.Castle orderby Vec2.Distance(s.Position, party.Position) select s).ThenBy((Settlement s) => s.Id, StringComparer.Ordinal).FirstOrDefault(); } if (settlement == null) { throw new InvalidOperationException("There is no town or castle to hold it in."); } Hero playerHero = State.PlayerHero; UnitDef unitDef = C.TownVisitLocal(settlement, C.UnitDef(playerHero.UnitId)); List<(string, UnitDef, Hero)> list = new List<(string, UnitDef, Hero)>(); if (!playerHero.CanFight || !Campaign.WalksTheStreets(C.UnitDef(playerHero.UnitId))) { list.Add(("visit.executioner", CrimeGuardUnit(settlement), null)); } Random random = new Random(Campaign.StableSeed("crowd:" + settlement.Id)); List list2 = TownCivilians.Select(((string id, int weight) c) => C.UnitDef(c.id)).Where(Campaign.WalksTheStreets).ToList(); if (list2.Count == 0) { list2.Add(unitDef); } for (int num = 0; num < 16; num++) { list.Add(("visit.crowd", (num % 5 == 4) ? CrimeGuardUnit(settlement) : list2[random.Next(list2.Count)], null)); } List<(string, UnitDef)> theirs = new List<(string, UnitDef)> { (TownVisitRoles.Named("visit.condemned", hero.Id), Campaign.WalksTheStreets(C.UnitDef(hero.UnitId)) ? C.UnitDef(hero.UnitId) : unitDef) }; BattlePlan battlePlan = CrimePlan(settlement, "execution:" + hero.Id + ":" + (inDungeon ? "dungeon" : "party") + ":" + settlement.Id, list, theirs, playerHero.CanFight && Campaign.WalksTheStreets(C.UnitDef(playerHero.UnitId))); Combatant combatant = battlePlan.Manifest.Combatants.FirstOrDefault((Combatant c) => c.Side == BattleSide.Defender && c.Group.StartsWith("visit.condemned", StringComparison.Ordinal)); if (combatant != null) { combatant.Loadout = Campaign.CopyHeroLoadout(hero.Loadout); } return battlePlan; } public CommandResult CompleteCrimeMission(string mission, CrimeMissionResult r) { if (string.IsNullOrEmpty(mission) || r == null) { return CommandResult.Fail("Nothing happened."); } if (mission.StartsWith("execution:", StringComparison.Ordinal)) { string[] array = mission.Split(new char[1] { ':' }); if (array.Length < 3) { return CommandResult.Fail("Nothing happened."); } return C.ExecutePrisoner(array[1], array[2] == "dungeon"); } Settlement settlement = C.CurrentSettlement(); if (settlement == null) { return CommandResult.Fail("You've left the town."); } string faction = C.CrimeFactionOf(settlement); if (mission.StartsWith("prison:", StringComparison.Ordinal)) { Hero hero = State.Heroes.Get(mission.Substring(7)); if (r.GuardsDowned > 0) { C.AddCrime(faction, 3.0 * (double)r.GuardsDowned, r.GuardsDowned + " of the guards struck down in " + settlement.Name, settlement.Id); } if (r.HeroDown) { C.AddCrime(faction, 12.0, "trying to break " + (hero?.Name ?? "a prisoner") + " out of " + settlement.Name, settlement.Id); CapturePlayerInDungeon(settlement); return CommandResult.Fail("The guards overpower you. You wake in a cell in " + settlement.Name + "'s dungeon; your party has scattered."); } if (r.Success && hero != null && hero.State == HeroState.Captive && hero.CaptorSettlementId == settlement.Id) { C.AddCrime(faction, 25.0, "breaking " + hero.Name + " out of " + settlement.Name, hero.Id, settlement.Id); C.TrainRoguery(60.0); OutcomeCommitter.ReleaseHero(C, hero, "broken out of " + settlement.Name + " by you"); string text; if (hero.ClanId == State.PlayerClanId && hero.State == HeroState.Active) { foreach (Party party in State.Parties) { party.Troops.Heroes.Remove(hero.Id); } C.JoinCompanionToPlayerParty(hero); text = hero.Name + " is back with your party."; } else { if (!string.IsNullOrEmpty(hero.ClanId)) { C.AdjustClanRelation(State.PlayerClanId, hero.ClanId, 15); } text = hero.Name + " thanks you and makes for home. " + (State.Clans.Get(hero.ClanId)?.Name ?? "Their clan") + " will not forget it."; } State.Crime.DisguisedSettlementId = ""; C.LeaveSettlementInternal(State.PlayerParty); C.UpdatePlayerTimeStates(); State.AddLog(LogCategory.Captivity, "You broke " + hero.Name + " out of " + settlement.Name + ".", hero.Id, settlement.Id); State.Touch(); return CommandResult.Success("You slip out of " + settlement.Name + " with " + hero.Name + " before the alarm spreads. " + text); } if (r.Alarm) { C.AddCrime(faction, 12.0, "trying to break " + (hero?.Name ?? "a prisoner") + " out of " + settlement.Name, settlement.Id); if (C.InDisguise) { State.Crime.DisguisedSettlementId = ""; C.LeaveSettlementInternal(State.PlayerParty); C.UpdatePlayerTimeStates(); return CommandResult.Fail("The alarm is up and your disguise with it: you flee " + settlement.Name + "."); } return CommandResult.Fail("The alarm was raised. " + (hero?.Name ?? "The prisoner") + " is still in the cells."); } return CommandResult.Success("You leave the gaol be, for now."); } if (mission.StartsWith("alley:", StringComparison.Ordinal)) { AlleyState alleyState = Alley(mission.Substring(6)); if (alleyState == null) { return CommandResult.Fail("That alley is gone."); } if (r.HeroDown) { long num = State.PlayerClan?.Gold ?? 0; long num2 = Math.Min(500L, Math.Max(0L, num / 10)); if (num2 > 0) { State.Transact(State.PlayerClan, -num2, LedgerAccount.Other, "Robbed by " + alleyState.GangName + " in " + settlement.Name); } State.PlayerHero.Health = Math.Min(State.PlayerHero.Health, 0.3); State.Touch(); return CommandResult.Fail(alleyState.GangName.Substring(0, 1).ToUpperInvariant() + alleyState.GangName.Substring(1) + " beat you senseless and empty your purse" + ((num2 > 0) ? (" (" + num2.ToString("N0") + " denars)") : "") + "."); } if (r.Success) { string gangName = alleyState.GangName; alleyState.OwnerClanId = State.PlayerClanId; alleyState.OverseerHeroId = ""; alleyState.TakenDay = State.Clock.Day; alleyState.ChallengeDay = State.Clock.Day + 5; C.TrainRoguery(40.0); State.AddLog(LogCategory.Info, "You took " + alleyState.Name + " in " + settlement.Name + " from " + gangName + ".", settlement.Id); State.Touch(); return CommandResult.Success(alleyState.GangLeaderName + " yields. " + alleyState.Name + " is yours: put a companion in charge of it to collect its takings."); } return CommandResult.Success("You leave " + alleyState.Name + " to " + alleyState.GangName + ", for now."); } return CommandResult.Fail("Nothing happened."); } internal void CapturePlayerInDungeon(Settlement s) { Hero playerHero = State.PlayerHero; Party playerParty = State.PlayerParty; State.Crime.DisguisedSettlementId = ""; State.Crime.GateSettlementId = ""; if (playerParty != null && playerParty.State == PartyState.InSettlement) { C.LeaveSettlementInternal(playerParty); } C.ClearHeroRoleAssignments(playerHero.Id); C.ClearHeroGovernorAssignments(playerHero.Id); playerParty?.Troops.Heroes.Remove(playerHero.Id); playerHero.PartyId = ""; playerHero.SettlementId = ""; playerHero.State = HeroState.Captive; playerHero.CaptorPartyId = ""; playerHero.CaptorSettlementId = s.Id; playerHero.CaptiveSinceMinute = State.Clock.Minute; if (!s.Prisoners.Heroes.Contains(playerHero.Id)) { s.Prisoners.Heroes.Add(playerHero.Id); } State.Player.Activity = PlayerActivity.Captive; State.Player.CaptorPartyId = ""; State.Player.CaptorSettlementId = s.Id; State.Player.CaptiveSinceMinute = State.Clock.Minute; State.Player.CaptivityMaxDays = Rules.LordMaxCaptivityDays; if (playerParty != null && playerParty.State != PartyState.Destroyed) { playerParty.Troops.Stacks.Clear(); playerParty.Prisoners.Stacks.Clear(); playerParty.Cargo.Clear(); playerParty.Food = 0.0; playerParty.State = PartyState.Disbanded; C.ClearOrder(playerParty); } State.AddLog(LogCategory.Captivity, "You were thrown into the dungeon of " + s.Name + ".", s.Id); C.Raise(CampaignEventKind.Captured, "You have been thrown into the dungeon of " + s.Name + ".", true, s.Id); C.RecoverSeparatedCompanions(); State.Touch(); } } internal sealed class VillageRecoverySystem { private readonly Campaign C; private ContentDatabase Content => C.Content; private CampaignState State => C.State; internal VillageRecoverySystem(Campaign host) { C = host; } public void EnsureVillageRecoveryFields() { bool flag = false; foreach (Settlement settlement in State.Settlements) { if (settlement.VillageRecovery == null) { settlement.VillageRecovery = new VillageRecoveryState(); flag = true; } VillageRecoveryState villageRecovery = settlement.VillageRecovery; if (villageRecovery.ProductionRemainders == null) { villageRecovery.ProductionRemainders = new SortedDictionary(StringComparer.Ordinal); flag = true; } if (!villageRecovery.Initialized) { villageRecovery.Initialized = true; villageRecovery.LastRecoveryDay = State.Clock.Day; flag = true; } } if (flag) { State.Touch(); } } public double VillageOutputFactor(Settlement settlement) { if (settlement == null || settlement.Type != SettlementType.Village) { return 1.0; } if (C.IsVillageBeingRaided(settlement)) { return 0.0; } return 1.0 - (double)Math.Max(0, Math.Min(100, settlement.VillageRecovery?.Damage ?? 0)) / 100.0; } public double VillageTaxFactor(Settlement settlement) { return VillageOutputFactor(settlement); } public int VillageRecoveryDays(Settlement settlement) { if (settlement == null || settlement.Type != SettlementType.Village) { return 0; } return (Math.Max(0, settlement.VillageRecovery?.Damage ?? 0) + 20 - 1) / 20; } public string VillageRecruitmentReason(Settlement settlement) { if (settlement == null || settlement.Type != SettlementType.Village) { return ""; } if (C.IsVillageBeingRaided(settlement)) { return "The village is under attack."; } if ((settlement.VillageRecovery?.Damage ?? 0) < 50) { return ""; } return "Volunteers only come back once damage is under 50."; } public int VillageProductionAmount(Settlement settlement, string goodId, int baseUnits) { if (baseUnits <= 0) { return 0; } if (settlement == null || settlement.Type != SettlementType.Village) { return baseUnits; } if (string.IsNullOrEmpty(goodId) || !TradeGoods.All.Any((TradeGoodDef x) => x.Id == goodId)) { return 0; } VillageRecoveryState villageRecovery = settlement.VillageRecovery; if (villageRecovery == null || !villageRecovery.Initialized || villageRecovery.ProductionRemainders == null) { return 0; } villageRecovery.ProductionRemainders.TryGetValue(goodId, out var value); double num = (double)baseUnits * VillageOutputFactor(settlement) + value; int num2 = (int)Math.Floor(num + 1E-09); double num3 = Math.Max(0.0, num - (double)num2); if (num3 < 1E-09) { if (villageRecovery.ProductionRemainders.Remove(goodId)) { State.Touch(); } } else if (Math.Abs(num3 - value) > 1E-09 || !villageRecovery.ProductionRemainders.ContainsKey(goodId)) { villageRecovery.ProductionRemainders[goodId] = num3; State.Touch(); } return num2; } public void RecordPlayerVillageRaid(Settlement settlement) { if (settlement != null && settlement.Type == SettlementType.Village && State.Settlements.Get(settlement.Id) == settlement && settlement.VillageRecovery != null && settlement.VillageRecovery.LastPlayerRaidDay != State.Clock.Day) { settlement.VillageRecovery.LastPlayerRaidDay = State.Clock.Day; State.Touch(); } } public void ApplyVillageRaidDamage(Settlement settlement, bool playerRaid) { if (settlement == null || settlement.Type != SettlementType.Village || State.Settlements.Get(settlement.Id) != settlement || settlement.VillageRecovery == null || !settlement.VillageRecovery.Initialized) { return; } VillageRecoveryState villageRecovery = settlement.VillageRecovery; if (villageRecovery.LastRaidMinute != State.Clock.Minute) { villageRecovery.Damage = 100; villageRecovery.LastRaidMinute = State.Clock.Minute; villageRecovery.LastRecoveryDay = State.Clock.Day; if (playerRaid) { villageRecovery.LastPlayerRaidDay = State.Clock.Day; } C.RaidStudFarm(settlement); settlement.Security = Math.Max(0.0, settlement.Security - 20.0); settlement.Loyalty = Math.Max(0.0, settlement.Loyalty - 10.0); settlement.Prosperity = Math.Min(settlement.Prosperity, Math.Max(100.0, settlement.Prosperity - 50.0)); State.AddLog(LogCategory.Economy, settlement.Name + " was raided and its food stores burned; production and taxes recover over five days.", settlement.Id); State.Touch(); } } public void DailyVillageRecovery() { bool flag = false; foreach (Settlement settlement in State.Settlements) { VillageRecoveryState villageRecovery = settlement.VillageRecovery; if (settlement.Type != SettlementType.Village || villageRecovery == null || !villageRecovery.Initialized || villageRecovery.LastRecoveryDay >= State.Clock.Day) { continue; } villageRecovery.LastRecoveryDay = State.Clock.Day; flag = true; if (villageRecovery.Damage > 0 && !C.IsVillageBeingRaided(settlement)) { villageRecovery.Damage = Math.Max(0, villageRecovery.Damage - 20); if (villageRecovery.Damage == 0) { State.AddLog(LogCategory.Economy, settlement.Name + " has recovered from the raid.", settlement.Id); } } } if (ReplaceLostVillagers()) { flag = true; } if (flag) { State.Touch(); } } internal bool ReplaceLostVillagers() { int num = Math.Max(1, Content.Scenarios.Get(State.ScenarioId)?.VillagerPartiesPerVillage ?? 1); Dictionary dictionary = (from p in State.Parties where p.Kind == PartyKind.Villager && p.State != PartyState.Destroyed && p.State != PartyState.Disbanded group p by p.HomeSettlementId ?? "").ToDictionary, string, int>((IGrouping g) => g.Key, (IGrouping g) => g.Count(), StringComparer.Ordinal); RandomStream randomStream = State.Random.Get("world"); bool result = false; foreach (Settlement item in State.Settlements.Where((Settlement s) => s.Type == SettlementType.Village).OrderBy((Settlement s) => s.Id, StringComparer.Ordinal).ToList()) { dictionary.TryGetValue(item.Id, out var value); if (value >= num || C.IsVillageBeingRaided(item) || (item.VillageRecovery?.Damage ?? 0) >= 50) { continue; } Clan clan = State.Clans.Get(item.OwnerClanId); if (clan != null && !clan.IsBandit && !clan.IsEliminated) { CultureDef cultureDef = Content.Cultures.Get(item.CultureId ?? ""); if (cultureDef != null && C.UnitDef(cultureDef.BasicTroop) != null && randomStream.Chance(1.0 / 7.0)) { Party party = new Party { Id = State.Ids.Allocate("party"), Name = "Villagers of " + item.Name, Kind = PartyKind.Villager, ClanId = clan.Id, HomeSettlementId = item.Id, Position = item.Position, State = PartyState.InSettlement, CurrentSettlementId = item.Id, Morale = 50.0, WaitUntilMinute = State.Clock.Minute + 60 * randomStream.Range(1, 12) }; party.Troops.Add(cultureDef.BasicTroop, 4 + randomStream.Range(0, 5)); State.Parties.Add(party); result = true; } } } return result; } public string VillageRecoveryAidReason() { string text = C.CargoCommandReason(); if (text.Length > 0) { return text; } Settlement settlement = C.CurrentSettlement(); Party playerParty = State.PlayerParty; if (settlement == null || settlement.Type != SettlementType.Village || playerParty.State != PartyState.InSettlement || Vec2.Distance(playerParty.Position, settlement.Position) > 0.01) { return "You can only aid a friendly village. Go there."; } Clan clan = State.Clans.Get(settlement.OwnerClanId); if (clan == null || clan.IsBandit || clan.IsEliminated || !C.CanEnter(playerParty, settlement)) { return "You can't aid a hostile village."; } if (!string.IsNullOrEmpty(playerParty.EncounterId) || C.IsVillageBeingRaided(settlement)) { return "Stop the fighting first."; } VillageRecoveryState villageRecovery = settlement.VillageRecovery; if (villageRecovery == null || !villageRecovery.Initialized) { return "Village recovery is unavailable."; } if (villageRecovery.Damage <= 0) { return "Already recovered."; } if (villageRecovery.LastAidDay >= State.Clock.Day) { return "You've already helped here today."; } if (C.CargoCount(playerParty, "good.timber") < 3 || C.CargoCount(playerParty, "good.tools") < 1) { return "Bring " + 3 + " hardwood and " + 1 + " tools in your cargo."; } return ""; } public CommandResult AidVillageRecovery() { string text = VillageRecoveryAidReason(); if (text.Length > 0) { return CommandResult.Fail(text); } Settlement settlement = C.CurrentSettlement(); VillageRecoveryState villageRecovery = settlement.VillageRecovery; C.ConsumeProjectCargo("good.timber", 3); C.ConsumeProjectCargo("good.tools", 1); int num = Math.Min(25, villageRecovery.Damage); villageRecovery.Damage -= num; villageRecovery.LastAidDay = State.Clock.Day; NotableState notableState = ((villageRecovery.LastPlayerRaidDay < 0 || State.Clock.Day - villageRecovery.LastPlayerRaidDay >= 7) ? C.SettlementNotable(settlement.Id) : null); if (notableState != null) { C.AdjustNotableRelation(notableState.Id, 3, "village recovery aid"); } State.AddLog(LogCategory.Economy, "Delivered recovery aid to " + settlement.Name + "; damage reduced by " + num + ".", settlement.Id); State.Touch(); return CommandResult.Success("Recovery aid delivered."); } } internal sealed class WanderersSystem { private readonly Campaign C; private ContentDatabase Content => C.Content; private CampaignRules Rules => C.Rules; private CampaignState State => C.State; public IEnumerable WanderingHeroes => State.Heroes.Where(IsWanderer); public int WandererTarget => Wanderers.TargetFor(TavernTowns().Count); internal WanderersSystem(Campaign host) { C = host; } public bool IsWanderer(Hero h) { if (h != null && h.Occupation == HeroOccupation.Companion && string.IsNullOrEmpty(h.ClanId) && h.State == HeroState.Active && string.IsNullOrEmpty(h.PartyId) && string.IsNullOrEmpty(h.CaptorPartyId)) { return string.IsNullOrEmpty(h.CaptorSettlementId); } return false; } public WandererPlan WandererPlan(string heroId) { if (heroId == null || State.Wanderers?.Plans == null || !State.Wanderers.Plans.TryGetValue(heroId, out var value)) { return null; } return value; } public bool IsTravellingWanderer(Hero h) { if (IsWanderer(h)) { return WandererPlan(h.Id)?.Travelling ?? false; } return false; } internal List TavernTowns() { return State.Settlements.Where((Settlement s) => s.Type == SettlementType.Town).OrderBy((Settlement s) => s.Id, StringComparer.Ordinal).ToList(); } public void EnsureWandererFields() { bool flag = false; if (State.Wanderers == null) { State.Wanderers = new WanderersState(); flag = true; } WanderersState wanderers = State.Wanderers; if (wanderers.Plans == null) { wanderers.Plans = new SortedDictionary(StringComparer.Ordinal); flag = true; } RandomStream randomStream = State.Random.Get("wanderers"); if (ReconcileWandererPlans(randomStream)) { flag = true; } if (!wanderers.Started) { int wandererTarget = WandererTarget; for (int i = WanderingHeroes.Count(); i < wandererTarget; i++) { if (SpawnWanderer(randomStream) == null) { break; } } wanderers.Started = true; wanderers.NextArrivalDay = State.Clock.Day + randomStream.Range(3, 8); flag = true; } if (flag) { State.Touch(); } } internal bool ReconcileWandererPlans(RandomStream rng) { SortedDictionary plans = State.Wanderers.Plans; bool result = false; foreach (Hero hero in State.Heroes) { bool num = IsWanderer(hero); plans.TryGetValue(hero.Id, out var value); if (!num) { if (value != null) { plans.Remove(hero.Id); result = true; } } else if (value == null) { plans[hero.Id] = new WandererPlan { LeaveDay = State.Clock.Day + StayDays(rng) }; result = true; } } return result; } internal void NoteNewWanderer(Hero hero) { if (State.Wanderers?.Plans != null && IsWanderer(hero)) { State.Wanderers.Plans[hero.Id] = new WandererPlan { LeaveDay = State.Clock.Day + StayDays(State.Random.Get("wanderers")) }; } } internal static int StayDays(RandomStream rng) { return rng.Range(5, 13); } internal void DailyWanderers() { if (State.Wanderers == null) { return; } WanderersState wanderers = State.Wanderers; RandomStream randomStream = State.Random.Get("wanderers"); ReconcileWandererPlans(randomStream); long day = State.Clock.Day; foreach (KeyValuePair item in wanderers.Plans.ToList()) { WandererPlan value = item.Value; if (!value.Travelling && value.LeaveDay <= day) { Hero hero = State.Heroes.Get(item.Key); Settlement settlement = State.Settlements.Get(hero?.SettlementId ?? ""); Settlement settlement2 = WandererDestination(settlement, randomStream); if (hero == null || settlement == null || settlement2 == null) { value.LeaveDay = day + StayDays(randomStream); continue; } double num = Math.Max(0.1, Rules.BaseSpeed * 0.8); long num2 = Math.Max(60L, (long)Math.Round(Vec2.Distance(settlement.Position, settlement2.Position) / num * 60.0)); value.FromId = settlement.Id; value.DestinationId = settlement2.Id; value.ArriveMinute = State.Clock.Minute + num2; hero.SettlementId = ""; } } int num3 = WanderingHeroes.Count(); int wandererTarget = WandererTarget; if (num3 < wandererTarget) { if (day >= wanderers.NextArrivalDay && SpawnWanderer(randomStream) != null) { wanderers.NextArrivalDay = day + randomStream.Range(3, 8); } } else if (wanderers.NextArrivalDay < day + 3) { wanderers.NextArrivalDay = day + 3; } } internal void HourlyWanderers() { if (State.Wanderers?.Plans == null) { return; } RandomStream randomStream = null; foreach (KeyValuePair plan in State.Wanderers.Plans) { WandererPlan value = plan.Value; if (value.Travelling && value.ArriveMinute <= State.Clock.Minute) { Hero hero = State.Heroes.Get(plan.Key); if (hero != null) { hero.SettlementId = value.DestinationId; value.DestinationId = ""; value.FromId = ""; value.ArriveMinute = 0L; value.LeaveDay = State.Clock.Day + StayDays(randomStream ?? (randomStream = State.Random.Get("wanderers"))); } } } } internal Settlement WandererDestination(Settlement from, RandomStream rng) { List list = (from s in TavernTowns() where s.Id != @from?.Id && !C.IsSettlementBesieged(s) select s).ToList(); if (list.Count == 0) { return null; } if (from != null) { list = list.OrderBy((Settlement s) => Vec2.Distance(from.Position, s.Position)).ThenBy((Settlement s) => s.Id, StringComparer.Ordinal).Take(5) .ToList(); } return rng.Pick(list); } internal Hero SpawnWanderer(RandomStream rng) { List list = (from s in TavernTowns() where !C.IsSettlementBesieged(s) select s).ToList(); if (list.Count == 0) { return null; } Dictionary present = (from h in WanderingHeroes where !string.IsNullOrEmpty(h.SettlementId) group h by h.SettlementId).ToDictionary, string, int>((IGrouping g) => g.Key, (IGrouping g) => g.Count(), StringComparer.Ordinal); int value; int fewest = list.Min((Settlement s) => present.TryGetValue(s.Id, out value) ? value : 0); Settlement settlement = rng.Pick(list.Where((Settlement s) => (present.TryGetValue(s.Id, out value) ? value : 0) == fewest).ToList()); List list2 = (from id in (from s in State.Settlements where s.Type != SettlementType.Hideout select s.CultureId).Distinct() where !string.IsNullOrEmpty(id) && Wanderers.Bodies(Content.Units, id).Count > 0 select id).OrderBy((string id) => id, StringComparer.Ordinal).ToList(); if (list2.Count == 0) { return null; } string text = ((list2.Contains(settlement.CultureId) && rng.Chance(0.6)) ? settlement.CultureId : rng.Pick(list2)); WandererArchetype wandererArchetype = rng.Pick(Wanderers.Archetypes); List bodies = Wanderers.Bodies(Content.Units, text); List items = wandererArchetype.Roles.Select((TroopRole role) => bodies.Where((UnitDef u) => u.Role == role).ToList()).FirstOrDefault((List list3) => list3.Count > 0) ?? bodies; UnitDef unitDef = rng.Pick(items); SortedDictionary skills = Wanderers.Skills(wandererArchetype, rng); Wanderers.Price(skills, out var hireCost, out var dailyWage); CultureDef culture = Content.Cultures.Get(text); HashSet taken = new HashSet(State.Heroes.Select((Hero h) => h.Name), StringComparer.Ordinal); Hero hero = new Hero { Id = State.Ids.Allocate("hero.wanderer"), Name = Wanderers.Name(text, rng, taken), Description = Wanderers.Describe(rng.Pick(wandererArchetype.Descriptions), culture), CultureId = text, UnitId = unitDef.Id, Occupation = HeroOccupation.Companion, SettlementId = settlement.Id, HireCost = hireCost, DailyWage = dailyWage, Skills = skills }; State.Heroes.Add(hero); C.HeroDevelopmentSystem.InitialiseHero(hero); FamiliesState families = State.Families; if (families != null && families.Started) { C.GiveIdentity(hero); } State.Wanderers.Plans[hero.Id] = new WandererPlan { LeaveDay = State.Clock.Day + StayDays(rng) }; return hero; } } internal sealed class WardrobeSystem { private readonly Campaign C; private CampaignState State => C.State; public IEnumerable ClothingPieces { get { IEnumerable enumerable = State.Wardrobe?.Pieces?.Values; return enumerable ?? Enumerable.Empty(); } } internal WardrobeSystem(Campaign host) { C = host; } public void EnsureWardrobeFields() { bool flag = false; if (State.Wardrobe == null) { State.Wardrobe = new WardrobeState(); flag = true; } if (State.Wardrobe.Pieces == null) { State.Wardrobe.Pieces = new SortedDictionary(StringComparer.Ordinal); flag = true; } if (State.Wardrobe.UnitPieces == null) { State.Wardrobe.UnitPieces = new SortedDictionary>(StringComparer.Ordinal); flag = true; } foreach (Hero hero in State.Heroes) { if (hero.Loadout != null && hero.Loadout.Clothing == null) { hero.Loadout.Clothing = new SortedDictionary(StringComparer.Ordinal); flag = true; } } if (flag) { State.Touch(); } } public ClothingPieceDef ClothingPiece(string id) { if (id == null || State.Wardrobe?.Pieces == null || !State.Wardrobe.Pieces.TryGetValue(id, out var value)) { return null; } return value; } public int ImportWardrobe(WardrobeCatalogue catalogue) { if (catalogue?.Pieces == null) { return 0; } EnsureWardrobeFields(); WardrobeState wardrobe = State.Wardrobe; SortedDictionary> sortedDictionary = new SortedDictionary>(StringComparer.Ordinal); HashSet known = new HashSet(from p in catalogue.Pieces where p != null && Wardrobe.IsPieceId(p.Id) select p.Id, StringComparer.Ordinal); foreach (KeyValuePair> item in catalogue.UnitPieces ?? new SortedDictionary>(StringComparer.Ordinal)) { UnitDef unitDef = C.UnitDef(item.Key); if (unitDef != null && item.Value != null) { List list = item.Value.Where((string id) => known.Contains(id) || wardrobe.Pieces.ContainsKey(id)).Distinct(StringComparer.Ordinal).OrderBy((string id) => id, StringComparer.Ordinal) .ToList(); if (list.Count != 0) { sortedDictionary[unitDef.Id] = list; } } } List list2 = new List(); foreach (WardrobeCatalogue.Piece item2 in catalogue.Pieces.OrderBy((WardrobeCatalogue.Piece p) => p?.Id ?? "", StringComparer.Ordinal)) { if (item2 != null && Wardrobe.IsPieceId(item2.Id) && Enum.IsDefined(typeof(ClothingSlot), item2.Slot) && !wardrobe.Pieces.ContainsKey(item2.Id)) { int tier = Wardrobe.TierForCost(item2.WearerCost); wardrobe.Pieces[item2.Id] = new ClothingPieceDef { Id = item2.Id, Name = (string.IsNullOrWhiteSpace(item2.Name) ? Wardrobe.FallbackName(item2.Slot, Wardrobe.NativeId(item2.Id)) : item2.Name.Trim()), Slot = item2.Slot, Tier = tier, ColorChannels = Math.Max(0, Math.Min(12, item2.ColorChannels)) }; list2.Add(item2.Id); } } bool flag = list2.Count > 0; foreach (KeyValuePair> item3 in sortedDictionary) { if (!wardrobe.UnitPieces.TryGetValue(item3.Key, out var value) || !value.SequenceEqual(item3.Value)) { wardrobe.UnitPieces[item3.Key] = item3.Value; flag = true; } } if (flag | StockClothing(list2)) { if (list2.Count > 0) { State.AddLog(LogCategory.Economy, list2.Count + " TABS clothing pieces are now sold by town outfitters."); } State.Touch(); } return list2.Count; } internal bool StockClothing(List addedPieces) { List list = State.Settlements.Where((Settlement s) => s.Type == SettlementType.Town && s.Market != null && s.Market.EquipmentInitialized && s.Market.EquipmentStock != null).OrderBy((Settlement s) => s.Id, StringComparer.Ordinal).ToList(); if (list.Count == 0 || State.Wardrobe.Pieces.Count == 0) { return false; } RandomStream randomStream = State.Random.Get("wardrobe"); List list2 = list.Where((Settlement t) => !t.Market.ClothingInitialized).ToList(); List list3 = ((list2.Count == list.Count) ? State.Wardrobe.Pieces.Keys.ToList() : addedPieces.ToList()); bool flag = false; Dictionary> cultures = ClothingCultures(); Shuffle(list3, randomStream); for (int num = 0; num < list3.Count; num++) { flag |= AddClothingStock(list[num % list.Count], list3[num], 1); } foreach (Settlement town in list2) { ClothingSlot[] slots = Wardrobe.Slots; foreach (ClothingSlot slot in slots) { SortedSet value; List list4 = (from p in State.Wardrobe.Pieces.Values where p.Slot == slot && cultures.TryGetValue(p.Id, out value) && value.Contains(town.CultureId) select p.Id).OrderBy((string id) => id, StringComparer.Ordinal).ToList(); Shuffle(list4, randomStream); foreach (string item in list4.Take(3)) { flag |= AddClothingStock(town, item, 1 + randomStream.Range(0, 2)); } } town.Market.ClothingInitialized = true; flag = true; } return flag; } public Dictionary> ClothingCultures() { Dictionary> dictionary = new Dictionary>(StringComparer.Ordinal); foreach (KeyValuePair> item in State.Wardrobe?.UnitPieces ?? new SortedDictionary>(StringComparer.Ordinal)) { string text = C.UnitDef(item.Key)?.Culture; if (string.IsNullOrEmpty(text) || item.Value == null) { continue; } foreach (string item2 in item.Value) { if (!dictionary.TryGetValue(item2, out var value)) { value = (dictionary[item2] = new SortedSet(StringComparer.Ordinal)); } value.Add(text); } } return dictionary; } internal static void Shuffle(List items, RandomStream rng) { for (int num = items.Count - 1; num > 0; num--) { int index = rng.Range(0, num + 1); string value = items[num]; items[num] = items[index]; items[index] = value; } } internal bool AddClothingStock(Settlement town, string id, int count) { int num = C.EquipmentStock(town, id); int num2 = Math.Min(100, num + count); if (num2 == num) { return false; } town.Market.EquipmentStock[id] = num2; return true; } public WornClothingState WornClothing(Hero hero, ClothingSlot slot, int layer = 1) { if (hero?.Loadout?.Clothing == null || !hero.Loadout.Clothing.TryGetValue(Wardrobe.LayerKey(slot, layer), out var value)) { return null; } return value; } public List ExtraLayers(Hero hero, ClothingSlot slot) { return (from layer in Enumerable.Range(2, 2) where WornClothing(hero, slot, layer) != null select layer).ToList(); } private bool WearsPiece(Hero hero, ClothingSlot slot, string pieceId) { return Enumerable.Range(1, 3).Any((int layer) => WornClothing(hero, slot, layer)?.PieceId == pieceId); } public static bool SupportsWardrobe(UnitDef unit) { if (unit != null && !unit.Mounted && unit.Slots == 1 && !string.IsNullOrEmpty(unit.TabsUnitId)) { if (unit.Role != TroopRole.Infantry && unit.Role != TroopRole.Ranged) { return unit.Role == TroopRole.Support; } return true; } return false; } public string WardrobeHeroReason(string heroId) { string text = C.EquipmentCommandReason(); if (text.Length > 0) { return text; } Hero hero = State.Heroes.Get(heroId ?? ""); if (hero == null || hero.ClanId != State.PlayerClanId || (hero.Id != State.PlayerHeroId && !C.IsOwnedCompanion(hero))) { return "Pick yourself or a companion."; } if (hero.State != HeroState.Active || !Campaign.IsPresentPartyHero(State.PlayerParty, hero)) { return "They have to be in your party to change clothes."; } if (!SupportsWardrobe(C.UnitDef(hero.UnitId))) { return "This archetype can't change clothes."; } List list = new List(); EquipmentValidation.CheckLoadout(State, hero.Loadout, "This hero", list); return list.FirstOrDefault() ?? ""; } public string ClothingEquipReason(string heroId, string pieceId, bool onTop = false) { string text = WardrobeHeroReason(heroId); if (text.Length > 0) { return text; } ClothingPieceDef clothingPieceDef = ClothingPiece(pieceId); if (clothingPieceDef == null) { return "Unknown clothing piece."; } Party playerParty = State.PlayerParty; if (C.EquipmentCount(playerParty, clothingPieceDef.Id) < 1) { return "You don't own that piece."; } Hero hero = State.Heroes.Require(heroId); if (WearsPiece(hero, clothingPieceDef.Slot, clothingPieceDef.Id)) { return "This piece is already worn."; } if (onTop) { if (ExtraLayers(hero, clothingPieceDef.Slot).Count < 2) { return ""; } return "Two pieces are already worn on top here: take one off first."; } ClothingPieceDef clothingPieceDef2 = ClothingPiece(WornClothing(hero, clothingPieceDef.Slot)?.PieceId); if (clothingPieceDef2 != null && C.EquipmentCount(playerParty, clothingPieceDef2.Id) >= 100) { return "Your bag cannot hold another " + clothingPieceDef2.Name + "."; } double num = (clothingPieceDef2?.Weight ?? 0.0) - clothingPieceDef.Weight; if (num > 0.0 && C.CargoWeight(playerParty) + num > C.CargoCapacity(playerParty) + 1E-09) { return "No room for what you're taking off."; } return ""; } public CommandResult EquipClothing(string heroId, string pieceId, bool onTop = false) { string text = ClothingEquipReason(heroId, pieceId, onTop); if (text.Length > 0) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Require(heroId); ClothingPieceDef piece = ClothingPiece(pieceId); SortedDictionary equipment = State.PlayerParty.Equipment; if (onTop) { int layer = Enumerable.Range(2, 2).First((int l) => WornClothing(hero, piece.Slot, l) == null); Campaign.SetEquipmentCount(equipment, piece.Id, C.EquipmentCount(State.PlayerParty, piece.Id) - 1); Wear(hero)[Wardrobe.LayerKey(piece.Slot, layer)] = new WornClothingState { PieceId = piece.Id }; string text2 = hero.Name + " put on " + piece.Name + " as well."; State.AddLog(LogCategory.Info, text2, hero.Id); State.Touch(); return CommandResult.Success(text2); } ClothingPieceDef clothingPieceDef = ClothingPiece(WornClothing(hero, piece.Slot)?.PieceId); Campaign.SetEquipmentCount(equipment, piece.Id, C.EquipmentCount(State.PlayerParty, piece.Id) - 1); if (clothingPieceDef != null) { Campaign.SetEquipmentCount(equipment, clothingPieceDef.Id, C.EquipmentCount(State.PlayerParty, clothingPieceDef.Id) + 1); } Wear(hero)[Wardrobe.SlotKey(piece.Slot)] = new WornClothingState { PieceId = piece.Id }; string text3 = hero.Name + " put on " + piece.Name + "."; State.AddLog(LogCategory.Info, text3, hero.Id); State.Touch(); return CommandResult.Success(text3); } internal SortedDictionary Wear(Hero hero) { if (hero.Loadout == null) { hero.Loadout = new HeroEquipmentState(); } if (hero.Loadout.Clothing == null) { hero.Loadout.Clothing = new SortedDictionary(StringComparer.Ordinal); } return hero.Loadout.Clothing; } internal string ReturnPieceReason(Hero hero, ClothingSlot slot, int layer = 1) { ClothingPieceDef clothingPieceDef = ClothingPiece(WornClothing(hero, slot, layer)?.PieceId); if (clothingPieceDef == null) { return ""; } Party playerParty = State.PlayerParty; if (C.EquipmentCount(playerParty, clothingPieceDef.Id) >= 100) { return "Your bag cannot hold another " + clothingPieceDef.Name + "."; } if (C.CargoWeight(playerParty) + clothingPieceDef.Weight > C.CargoCapacity(playerParty) + 1E-09) { return "Your party needs room for " + clothingPieceDef.Name + "."; } return ""; } internal void ReturnPiece(Hero hero, ClothingSlot slot, int layer = 1) { ClothingPieceDef clothingPieceDef = ClothingPiece(WornClothing(hero, slot, layer)?.PieceId); if (clothingPieceDef != null) { Campaign.SetEquipmentCount(State.PlayerParty.Equipment, clothingPieceDef.Id, C.EquipmentCount(State.PlayerParty, clothingPieceDef.Id) + 1); } } public string ClothingResetReason(string heroId, ClothingSlot slot) { string text = WardrobeHeroReason(heroId); if (text.Length > 0) { return text; } if (!Enum.IsDefined(typeof(ClothingSlot), slot)) { return "Unknown clothing slot."; } Hero hero = State.Heroes.Require(heroId); if (WornClothing(hero, slot) == null) { return "This slot already shows the archetype's own clothes."; } return ReturnPieceReason(hero, slot); } public CommandResult ResetClothing(string heroId, ClothingSlot slot) { string text = ClothingResetReason(heroId, slot); if (text.Length > 0) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Require(heroId); ClothingPieceDef clothingPieceDef = ClothingPiece(WornClothing(hero, slot).PieceId); ReturnPiece(hero, slot); hero.Loadout.Clothing.Remove(Wardrobe.SlotKey(slot)); string text2 = ((clothingPieceDef != null) ? (hero.Name + " returned " + clothingPieceDef.Name + " to the party's bag.") : (hero.Name + "'s " + Wardrobe.SlotName(slot).ToLowerInvariant() + " shows the archetype's own clothing again.")); State.AddLog(LogCategory.Info, text2, hero.Id); State.Touch(); return CommandResult.Success(text2); } public string ClothingLayerRemoveReason(string heroId, ClothingSlot slot, int layer) { string text = WardrobeHeroReason(heroId); if (text.Length > 0) { return text; } if (!Enum.IsDefined(typeof(ClothingSlot), slot) || layer < 2 || layer > 3) { return "Unknown clothing layer."; } Hero hero = State.Heroes.Require(heroId); if (WornClothing(hero, slot, layer) == null) { return "Nothing is worn there."; } return ReturnPieceReason(hero, slot, layer); } public CommandResult RemoveClothingLayer(string heroId, ClothingSlot slot, int layer) { string text = ClothingLayerRemoveReason(heroId, slot, layer); if (text.Length > 0) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Require(heroId); ClothingPieceDef clothingPieceDef = ClothingPiece(WornClothing(hero, slot, layer).PieceId); ReturnPiece(hero, slot, layer); hero.Loadout.Clothing.Remove(Wardrobe.LayerKey(slot, layer)); string text2 = hero.Name + " took off " + (clothingPieceDef?.Name ?? "the piece") + ". It's back in the party's bag."; State.AddLog(LogCategory.Info, text2, hero.Id); State.Touch(); return CommandResult.Success(text2); } public string ClothingBareReason(string heroId, ClothingSlot slot) { string text = WardrobeHeroReason(heroId); if (text.Length > 0) { return text; } if (!Enum.IsDefined(typeof(ClothingSlot), slot)) { return "Unknown clothing slot."; } Hero hero = State.Heroes.Require(heroId); WornClothingState wornClothingState = WornClothing(hero, slot); if (wornClothingState != null && wornClothingState.Bare) { return "This slot is already bare."; } return ReturnPieceReason(hero, slot); } public CommandResult SetClothingBare(string heroId, ClothingSlot slot) { string text = ClothingBareReason(heroId, slot); if (text.Length > 0) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Require(heroId); ReturnPiece(hero, slot); Wear(hero)[Wardrobe.SlotKey(slot)] = new WornClothingState { Bare = true }; string text2 = hero.Name + " now wears nothing on the " + Wardrobe.SlotName(slot).ToLowerInvariant() + "."; State.AddLog(LogCategory.Info, text2, hero.Id); State.Touch(); return CommandResult.Success(text2); } public string ClothingColorReason(string heroId, ClothingSlot slot, IList colors, int layer = 1) { string text = WardrobeHeroReason(heroId); if (text.Length > 0) { return text; } WornClothingState wornClothingState = WornClothing(State.Heroes.Require(heroId), slot, layer); ClothingPieceDef clothingPieceDef = ClothingPiece(wornClothingState?.PieceId); if (clothingPieceDef == null) { return "You can only recolour your own pieces."; } if (colors == null) { return "Choose the piece's colours."; } if (colors.Count > Math.Max(clothingPieceDef.ColorChannels, 0) || colors.Count > 12) { return clothingPieceDef.Name + " has only " + clothingPieceDef.ColorChannels + " colour" + ((clothingPieceDef.ColorChannels == 1) ? "" : "s") + "."; } if (colors.Any((int c) => c < -1 || c > 255)) { return "Pick a colour."; } if (Wardrobe.NormalizeColors(wornClothingState.Colors).SequenceEqual(Wardrobe.NormalizeColors(colors))) { return "Those colours are already on."; } return ""; } public CommandResult SetClothingColors(string heroId, ClothingSlot slot, IList colors, int layer = 1) { string text = ClothingColorReason(heroId, slot, colors, layer); if (text.Length > 0) { return CommandResult.Fail(text); } WornClothingState wornClothingState = WornClothing(State.Heroes.Require(heroId), slot, layer); wornClothingState.Colors = Wardrobe.NormalizeColors(colors); State.Touch(); return CommandResult.Success(ClothingPiece(wornClothingState.PieceId).Name + ((wornClothingState.Colors.Count == 0) ? " has its own colours again." : " recoloured.")); } public double HeroSize(Hero hero) { if (hero?.Loadout == null || !Wardrobe.ValidSize(hero.Loadout.Size)) { return 1.0; } return hero.Loadout.Size; } public string HeroSizeReason(string heroId, double size) { string text = WardrobeHeroReason(heroId); if (text.Length > 0) { return text; } if (!Wardrobe.ValidSize(size)) { return "Choose a size between " + Math.Round(80.0) + "% and " + Math.Round(125.0) + "%."; } if (Math.Abs(Wardrobe.RoundSize(size) - HeroSize(State.Heroes.Require(heroId))) < 1E-09) { return "Already that size."; } return ""; } public CommandResult SetHeroSize(string heroId, double size) { string text = HeroSizeReason(heroId, size); if (text.Length > 0) { return CommandResult.Fail(text); } Hero hero = State.Heroes.Require(heroId); if (hero.Loadout == null) { hero.Loadout = new HeroEquipmentState(); } hero.Loadout.Size = Wardrobe.RoundSize(size); string msg = hero.Name + "'s size is now " + Math.Round(hero.Loadout.Size * 100.0) + "%."; State.Touch(); return CommandResult.Success(msg); } internal string LootClothing(Party player, IEnumerable downedUnitIds) { if (player == null || player.Id != State.PlayerPartyId || State.Wardrobe?.UnitPieces == null || State.Wardrobe.UnitPieces.Count == 0) { return ""; } if (player.Equipment == null) { player.Equipment = new SortedDictionary(StringComparer.Ordinal); } RandomStream randomStream = State.Random.Get("loot"); List list = new List(); int num = 0; foreach (string downedUnitId in downedUnitIds) { if (list.Count + num >= 8) { break; } if (!State.Wardrobe.UnitPieces.TryGetValue(downedUnitId ?? "", out var value) || value == null || value.Count == 0 || randomStream.NextDouble() >= 0.06) { continue; } ClothingPieceDef clothingPieceDef = ClothingPiece(value[randomStream.Range(0, value.Count)]); if (clothingPieceDef != null) { if (C.EquipmentCount(player, clothingPieceDef.Id) >= 100 || C.CargoWeight(player) + clothingPieceDef.Weight > C.CargoCapacity(player) + 1E-09) { num++; continue; } player.Equipment[clothingPieceDef.Id] = C.EquipmentCount(player, clothingPieceDef.Id) + 1; list.Add(clothingPieceDef.Name); } } if (list.Count + num == 0) { return ""; } string text = ((list.Count > 0) ? ("Clothing looted: " + string.Join(", ", list) + ".") : ""); if (num > 0) { text = text + ((text.Length > 0) ? " " : "") + num + " more piece" + ((num == 1) ? " was" : "s were") + " left behind: the bag is full."; } State.AddLog(LogCategory.Economy, text, player.Id); return text; } } } namespace TabsBannerlord.Core.Battle { public static class AutoResolver { private sealed class Fighter { public Combatant C; public double Hp; public double MaxHp; public double Atk; public double Def; public double Ranged; public bool Down; public double Pending; } public static double Matchup(TroopRole attacker, TroopRole target) { if (attacker == TroopRole.Cavalry && target == TroopRole.Ranged) { return 1.35; } if (attacker == TroopRole.Infantry && target == TroopRole.Cavalry) { return 1.15; } if (attacker == TroopRole.Ranged && target == TroopRole.Monster) { return 1.2; } if (attacker == TroopRole.Monster && target == TroopRole.Infantry) { return 1.2; } if (attacker == TroopRole.Siege && target == TroopRole.Infantry) { return 1.25; } return 1.0; } public static BattleResult Resolve(TabsBannerlord.Core.Campaign.Campaign campaign, Encounter enc, BattleManifest manifest) { CampaignRules rules = campaign.Rules; RandomStream randomStream = campaign.State.Random.Get("autoresolve"); Dictionary> dictionary = new Dictionary> { [BattleSide.Attacker] = new List(), [BattleSide.Defender] = new List() }; foreach (Combatant item in manifest.Combatants.OrderBy((Combatant c) => c.Id)) { UnitDef unitDef = campaign.UnitDef(item.UnitId); EquipmentCombatStats equipmentCombatStats = (item.IsHero ? item.EquipmentStats : null); double num = (equipmentCombatStats?.Health ?? unitDef?.Health ?? 1.0) * 10.0; if (item.IsHero) { num *= 1.5 * (campaign.State.Heroes.Get(item.HeroId)?.Health ?? 1.0) * (1.0 + campaign.HeroBattleHealthBonus(item.HeroId)); } num *= campaign.BattleHealthMultiplier(item) / campaign.CombatantDamageTakenMultiplier(item); double num2 = 1.0; if (item.Mount != null) { num *= 1.0 + Math.Max(0.0, item.Mount.HitPoints) / 800.0 + item.Mount.RiderHealthBonus; num2 = 1.0 + Math.Max(0.0, item.Mount.Charge) / 150.0 + Math.Max(0.0, item.Mount.Speed - 40.0) / 200.0; } dictionary[item.Side].Add(new Fighter { C = item, Hp = num, MaxHp = num, Atk = (equipmentCombatStats?.Attack ?? unitDef?.Attack ?? 1.0) * num2 * campaign.CombatantDamageMultiplier(item), Def = (equipmentCombatStats?.Defense ?? unitDef?.Defense ?? 1.0), Ranged = (equipmentCombatStats?.Ranged ?? unitDef?.Ranged ?? 0.0) }); item.State = DeploymentState.Active; item.EverDeployed = true; } Dictionary dictionary2 = new Dictionary { [BattleSide.Attacker] = TacticsMultiplier(campaign, enc, BattleSide.Attacker), [BattleSide.Defender] = TacticsMultiplier(campaign, enc, BattleSide.Defender) }; Dictionary dictionary3 = new Dictionary { [BattleSide.Attacker] = Strength(dictionary[BattleSide.Attacker]), [BattleSide.Defender] = Strength(dictionary[BattleSide.Defender]) }; BattleResult battleResult = new BattleResult { CampaignId = campaign.State.CampaignId, EncounterId = enc.Id, AttemptId = enc.CurrentAttemptId, ExpectedRevision = enc.ExpectedRevision, Simulated = true }; BattleSide? battleSide = null; int num3 = 0; for (num3 = 1; num3 <= rules.AutoResolveMaxRounds; num3++) { List list = dictionary[BattleSide.Attacker].Where((Fighter f) => !f.Down).ToList(); List list2 = dictionary[BattleSide.Defender].Where((Fighter f) => !f.Down).ToList(); if (list.Count == 0 || list2.Count == 0) { break; } BattleSide[] array = new BattleSide[2] { BattleSide.Attacker, BattleSide.Defender }; foreach (BattleSide battleSide2 in array) { List obj = ((battleSide2 == BattleSide.Attacker) ? list : list2); List list3 = ((battleSide2 == BattleSide.Attacker) ? list2 : list); foreach (Fighter item2 in obj) { Fighter fighter = list3[randomStream.Range(0, list3.Count)]; double num5 = Matchup(item2.C.Role, fighter.C.Role) * dictionary2[battleSide2]; if (num3 <= 3 && item2.Ranged > 0.0) { num5 *= 1.0 + item2.Ranged * 0.5; } double num6 = item2.Atk * randomStream.Range(0.6, 1.4) * num5 / (1.0 + fighter.Def * 0.35); fighter.Pending += num6; } } foreach (Fighter item3 in list.Concat(list2)) { item3.Hp -= item3.Pending; item3.Pending = 0.0; if (item3.Hp <= 0.0) { item3.Down = true; } } array = new BattleSide[2] { BattleSide.Attacker, BattleSide.Defender }; foreach (BattleSide battleSide3 in array) { BattleSide key = ((battleSide3 == BattleSide.Attacker) ? BattleSide.Defender : BattleSide.Attacker); double num7 = Strength(dictionary[battleSide3]); double num8 = Strength(dictionary[key]); if (num7 > 0.0 && num8 > 0.0 && num7 < 0.2 * dictionary3[battleSide3] && num7 < 0.4 * num8) { battleSide = battleSide3; break; } } if (battleSide.HasValue) { break; } } if (!battleSide.HasValue && dictionary.Values.All((List l) => l.Any((Fighter f) => !f.Down))) { double num9 = Strength(dictionary[BattleSide.Attacker]) / Math.Max(1E-09, dictionary3[BattleSide.Attacker]); double num10 = Strength(dictionary[BattleSide.Defender]) / Math.Max(1E-09, dictionary3[BattleSide.Defender]); battleSide = ((!(num9 < num10)) ? BattleSide.Defender : BattleSide.Attacker); } bool flag = dictionary[BattleSide.Attacker].Any((Fighter f) => !f.Down); bool flag2 = dictionary[BattleSide.Defender].Any((Fighter f) => !f.Down); if (battleSide.HasValue) { battleResult.EndKind = BattleEndKind.Retreat; battleResult.LosingSide = battleSide.Value; battleResult.Winner = ((battleSide.Value != BattleSide.Attacker) ? WinnerSide.Attacker : WinnerSide.Defender); } else if (!flag && !flag2) { battleResult.EndKind = BattleEndKind.MutualDestruction; battleResult.Winner = WinnerSide.None; } else { battleResult.EndKind = BattleEndKind.Victory; battleResult.Winner = (flag ? WinnerSide.Attacker : WinnerSide.Defender); battleResult.LosingSide = (flag ? BattleSide.Defender : BattleSide.Attacker); } foreach (Fighter item4 in from f in dictionary.Values.SelectMany((List x) => x) orderby f.C.Id select f) { CombatOutcome outcome = ((!item4.Down) ? ((!battleSide.HasValue || item4.C.Side != battleSide.Value) ? CombatOutcome.Unhurt : CombatOutcome.Fled) : CombatOutcome.Downed); item4.C.State = DeploymentState.Exited; item4.C.Outcome = outcome; battleResult.Outcomes.Add(new CombatantResult { Id = item4.C.Id, Outcome = outcome }); } battleResult.DurationSeconds = num3 * 2; return battleResult; } private static double Strength(List fighters) { double num = 0.0; foreach (Fighter fighter in fighters) { if (!fighter.Down) { num += (fighter.Atk * 0.6 + fighter.Def * 0.4) * Math.Max(0.0, fighter.Hp); } } return num; } private static double TacticsMultiplier(TabsBannerlord.Core.Campaign.Campaign campaign, Encounter enc, BattleSide side) { List list = enc.PartiesOn(side); if (list.Count == 0) { return 1.0; } Party party = campaign.State.Parties.Get(list[0]); return (1.0 + (double)(campaign.State.Heroes.Get(party?.LeaderHeroId)?.Skill("tactics") ?? 0) / 500.0) * (1.0 + Math.Max(0.0, campaign.PartyPerk(party, PerkEffect.AutoResolve))); } public static double EstimateWinChance(TabsBannerlord.Core.Campaign.Campaign campaign, Encounter enc, BattleSide side, int samples = 7) { double num = 0.0; double num2 = 0.0; foreach (string attackerParty in enc.AttackerParties) { num += campaign.PartyStrength(campaign.State.Parties.Get(attackerParty)); } foreach (string defenderParty in enc.DefenderParties) { num2 += campaign.PartyStrength(campaign.State.Parties.Get(defenderParty)); } double num3 = ((side == BattleSide.Attacker) ? num : num2); double num4 = ((side == BattleSide.Attacker) ? num2 : num); if (num3 + num4 <= 0.0) { return 0.5; } double num5 = num3 * num3; double num6 = num4 * num4; return num5 / (num5 + num6); } } public sealed class BattleActorRegistry { private readonly Dictionary> _groups = new Dictionary>(); private readonly Dictionary _owners = new Dictionary(); public int GroupCount => _groups.Count; public int ActorCount => _owners.Count; public void RegisterGroup(int groupId, IEnumerable actorIds) { if (groupId == 0) { throw new ArgumentOutOfRangeException("groupId"); } if (_groups.ContainsKey(groupId)) { throw new InvalidOperationException("Battle actor group already exists: " + groupId); } HashSet hashSet = ReadActors(actorIds); ValidateOwnership(groupId, hashSet); _groups.Add(groupId, hashSet); foreach (int item in hashSet) { _owners.Add(item, groupId); } } public void AddActors(int groupId, IEnumerable actorIds) { HashSet hashSet = RequireGroup(groupId); HashSet hashSet2 = ReadActors(actorIds); ValidateOwnership(groupId, hashSet2); foreach (int item in hashSet2) { if (hashSet.Add(item)) { _owners.Add(item, groupId); } } } public void ReplaceActor(int oldActorId, IEnumerable replacementActorIds) { if (!_owners.TryGetValue(oldActorId, out var value)) { throw new InvalidOperationException("Cannot replace an unregistered battle actor: " + oldActorId); } HashSet hashSet = ReadActors(replacementActorIds); ValidateOwnership(value, hashSet); HashSet hashSet2 = _groups[value]; hashSet2.Remove(oldActorId); _owners.Remove(oldActorId); foreach (int item in hashSet) { if (hashSet2.Add(item)) { _owners.Add(item, value); } } } public bool TryGetGroup(int actorId, out int groupId) { return _owners.TryGetValue(actorId, out groupId); } public bool RemoveActor(int actorId, out int groupId, out bool groupEmpty) { groupEmpty = false; if (!_owners.TryGetValue(actorId, out groupId)) { return false; } _owners.Remove(actorId); HashSet hashSet = _groups[groupId]; hashSet.Remove(actorId); groupEmpty = hashSet.Count == 0; if (groupEmpty) { _groups.Remove(groupId); } return true; } public int[] GetActors(int groupId) { if (!_groups.TryGetValue(groupId, out var value)) { return new int[0]; } int[] array = new int[value.Count]; value.CopyTo(array); Array.Sort(array); return array; } public void Clear() { _groups.Clear(); _owners.Clear(); } private HashSet RequireGroup(int groupId) { if (!_groups.TryGetValue(groupId, out var value)) { throw new InvalidOperationException("Battle actor group does not exist: " + groupId); } return value; } private static HashSet ReadActors(IEnumerable actorIds) { if (actorIds == null) { throw new ArgumentNullException("actorIds"); } HashSet hashSet = new HashSet(); foreach (int actorId in actorIds) { if (actorId == 0) { throw new ArgumentOutOfRangeException("actorIds", "Native actor ID cannot be zero."); } hashSet.Add(actorId); } if (hashSet.Count == 0) { throw new ArgumentException("A battle actor group must contain at least one body.", "actorIds"); } return hashSet; } private void ValidateOwnership(int groupId, HashSet actors) { foreach (int actor in actors) { if (_owners.TryGetValue(actor, out var value) && value != groupId) { throw new InvalidOperationException("Battle actor " + actor + " already belongs to group " + value); } } } } public enum BattleSide { Attacker, Defender } public enum WinnerSide { None, Attacker, Defender } public enum EncounterPhase { AwaitingDecision, Preparing, InBattle, Committed, Cancelled } public sealed class Encounter : IEntity { public long CreatedAtMinute; public EncounterKind Kind; public Vec2 Position; public string Biome = "grassland"; public string InitiatorPartyId = ""; public string SiegeId = ""; public List AttackerParties = new List(); public List DefenderParties = new List(); public EncounterPhase Phase; public bool PlayerInvolved; public BattleSide PlayerSide; public int AttemptCounter; public string CurrentAttemptId = ""; public long ExpectedRevision; public string BattleMapId = ""; public BattleManifest Manifest; public string ResultSummary = ""; public string Mission = ""; public bool MustFight; public string HideoutId = ""; public string HideoutStage = ""; public string SiegeStage = ""; public string SortieSiegeId = ""; public string Sortie = ""; public SortedDictionary SquadTroops = new SortedDictionary(StringComparer.Ordinal); public List SquadHeroes = new List(); public string Id { get; set; } = ""; public bool IsKeepBattle => SiegeStage == "keep"; public IEnumerable AllParties => AttackerParties.Concat(DefenderParties); public List PartiesOn(BattleSide side) { if (side != BattleSide.Attacker) { return DefenderParties; } return AttackerParties; } public BattleSide SideOf(string partyId) { if (!AttackerParties.Contains(partyId)) { return BattleSide.Defender; } return BattleSide.Attacker; } } public enum DeploymentState { Reserve, Scheduled, Active, Exited, Withdrawn } public enum CombatOutcome { Pending, Unhurt, Downed, Fled } public sealed class Combatant { public int Id; public BattleSide Side; public string PartyId = ""; public string UnitId = ""; public string HeroId = ""; public HeroEquipmentState Loadout; public EquipmentCombatStats EquipmentStats; public MountSpec Mount; public TroopRole Role; public int Tier = 1; public int Slots = 1; public double Workload = 1.0; public DeploymentState State; public CombatOutcome Outcome; public bool EverDeployed; public string Group = ""; public int Priority; public double WaitingSince; public bool IsHero => !string.IsNullOrEmpty(HeroId); } public sealed class MountSpec { public string HorseId = ""; public string Name = ""; public string BreedId = ""; public int Coat; public double Speed; public double Manoeuvre; public double Charge; public double HitPoints; public double Size = 1.0; public bool Heavy; public double RiderHealthBonus; } public sealed class BattleManifest { public string EncounterId = ""; public string AttemptId = ""; public List Combatants = new List(); public int AttackerAllowance; public int DefenderAllowance; public int Budget; public Combatant Get(int id) { if (id >= 1 && id <= Combatants.Count && Combatants[id - 1].Id == id) { return Combatants[id - 1]; } return Combatants.FirstOrDefault((Combatant c) => c.Id == id); } public IEnumerable OnSide(BattleSide side) { return Combatants.Where((Combatant c) => c.Side == side); } } public enum BattleEndKind { Victory, MutualDestruction, Retreat, Surrender, Interrupted } public sealed class HeroBattleCredit { public string HeroId = ""; public int Kills; public int KilledTiers; public double Damage; public string WeaponSkill = ""; public bool Possessed; } public sealed class CombatantResult { public int Id; public CombatOutcome Outcome; public CombatOutcome MountOutcome; } public sealed class BattleResult { public string CampaignId = ""; public string EncounterId = ""; public string AttemptId = ""; public long ExpectedRevision; public BattleEndKind EndKind; public WinnerSide Winner; public BattleSide LosingSide = BattleSide.Defender; public List Outcomes = new List(); public List Credits = new List(); public double DurationSeconds; public bool Simulated; } public sealed class PartyBattleReport { public string PartyId = ""; public string PartyName = ""; public BattleSide Side; public int Fought; public int Reserve; public int Killed; public int Wounded; public int Captured; public int Escaped; public int PrisonersTaken; public long Loot; public int Xp; public long HeroXp; public bool Destroyed; } public sealed class BattleReport { public string EncounterId = ""; public BattleEndKind EndKind; public WinnerSide Winner; public bool PlayerWon; public bool PlayerCaptured; public bool Simulated; public List Parties = new List(); public List Lines = new List(); public TroopRoster RescuedTroops = new TroopRoster(); public int RescuedRecruited; public int RescuedReleased; public long RescueMinute; public Vec2 RescuePosition; } public enum DeploymentFormation { Line, ShieldWall, Loose, Circle, Square, Wedge, Column, Scatter } public static class DeploymentLayout { public static int DefaultColumns(DeploymentFormation formation, int count) { if (!Enum.IsDefined(typeof(DeploymentFormation), formation)) { throw new ArgumentOutOfRangeException("formation"); } if (count <= 0) { return 0; } return formation switch { DeploymentFormation.Column => Math.Min(3, count), DeploymentFormation.Circle => Math.Min(count, Math.Max(1, (int)Math.Ceiling((double)count / Math.PI))), DeploymentFormation.Square => Math.Min(count, (int)Math.Ceiling((double)count / 4.0) + 1), DeploymentFormation.Wedge => Math.Min(count, (int)Math.Ceiling((Math.Sqrt(8.0 * (double)count + 1.0) - 1.0) / 2.0)), DeploymentFormation.ShieldWall => Math.Min(count, (int)Math.Ceiling(Math.Sqrt(2.0 * (double)count))), DeploymentFormation.Scatter => Math.Min(count, (int)Math.Ceiling(Math.Sqrt(count))), _ => Math.Min(count, (int)Math.Ceiling(Math.Sqrt(3.0 * (double)count))), }; } public static bool TryForm(IReadOnlyList layout, IEnumerable selectedIds, Vec2 targetCenter, double yawDegrees, DeploymentFormation formation, int columns, double spacingScale, DeploymentArea area, out List proposed, out string reason) { proposed = null; if (!IsFinite(targetCenter) || !IsFinite(yawDegrees)) { reason = "Pick a spot and a facing."; return false; } if (!Enum.IsDefined(typeof(DeploymentFormation), formation)) { reason = "Choose an available formation."; return false; } if (!IsFinite(spacingScale) || spacingScale < 0.75 || spacingScale > 2.0) { reason = "Formation spacing must be between 75% and 200%."; return false; } if (!ReadSelection(layout, selectedIds, out var selected, out reason)) { return false; } if (columns < 0 || columns > selected.Count) { reason = "Too wide for the soldiers you've picked."; return false; } List list = new List(selected.Count); double num = 0.0; foreach (DeploymentPlacement item in layout) { if (selected.Contains(item.CombatantId)) { list.Add(item); num = Math.Max(num, item.Radius); } } list.Sort(delegate(DeploymentPlacement a, DeploymentPlacement b) { int combatantId = a.CombatantId; return combatantId.CompareTo(b.CombatantId); }); int width = ((columns == 0) ? DefaultColumns(formation, list.Count) : columns); List list2 = FormationSlots(formation, list, width); Vec2 zero = Vec2.Zero; for (int num2 = 0; num2 < list2.Count; num2++) { zero += list2[num2]; } zero /= (double)list2.Count; double num3 = Math.Max(num * 2.0, (num * 2.0 + formation switch { DeploymentFormation.Scatter => 1.1, DeploymentFormation.Loose => 1.65, DeploymentFormation.ShieldWall => 0.08, _ => 0.45, }) * spacingScale); double num4 = double.MaxValue; for (int num5 = 0; num5 < list2.Count; num5++) { for (int num6 = num5 + 1; num6 < list2.Count; num6++) { num4 = Math.Min(num4, Vec2.Distance(list2[num5], list2[num6])); } } double num7 = ((list2.Count == 1) ? 1.0 : (num3 / num4)); if (!IsFinite(num7) || num7 <= 0.0) { reason = "These soldiers won't fit that formation."; return false; } double num8 = NormalizeDegrees(yawDegrees); Dictionary dictionary = new Dictionary(); for (int num9 = 0; num9 < list.Count; num9++) { Vec2 offset = (list2[num9] - zero) * num7; double num10 = num8; if (list.Count > 1 && (formation == DeploymentFormation.Circle || formation == DeploymentFormation.Square)) { num10 = NormalizeDegrees(num8 + Math.Atan2(offset.X, offset.Y) * 180.0 / Math.PI); } Vec2 vec = targetCenter + Rotate(offset, num8); if (!IsFinite(vec) || !IsFinite(num10)) { reason = "Pick a spot and a facing."; return false; } dictionary.Add(list[num9].CombatantId, new DeploymentPlacement(list[num9].CombatantId, vec, num10, list[num9].Radius)); } List list3 = new List(layout.Count); foreach (DeploymentPlacement item2 in layout) { list3.Add(selected.Contains(item2.CombatantId) ? dictionary[item2.CombatantId] : item2); } proposed = list3; return ValidateSelection(list3, selected, area, out reason); } private static List FormationSlots(DeploymentFormation formation, List moving, int width) { int count = moving.Count; List list = new List(count); if (count == 1) { list.Add(Vec2.Zero); return list; } switch (formation) { case DeploymentFormation.Circle: case DeploymentFormation.Square: { for (int k = 0; k < count; k++) { if (formation == DeploymentFormation.Circle) { double num7 = Math.PI * 2.0 * (double)k / (double)count; list.Add(new Vec2(Math.Sin(num7), Math.Cos(num7))); continue; } double num8 = 4.0 * (double)k / (double)count; int num9 = (int)num8; double num10 = num8 - (double)num9; list.Add(num9 switch { 2 => new Vec2(1.0 - 2.0 * num10, -1.0), 1 => new Vec2(1.0, 1.0 - 2.0 * num10), 0 => new Vec2(-1.0 + 2.0 * num10, 1.0), _ => new Vec2(-1.0, -1.0 + 2.0 * num10), }); } return list; } case DeploymentFormation.Wedge: { int num5 = 0; while (list.Count < count) { int num6 = Math.Min(num5 + 1, count - list.Count); for (int j = 0; j < num6; j++) { list.Add(new Vec2((double)j - (double)(num6 - 1) / 2.0, (double)(-num5) * Math.Sqrt(3.0) / 2.0)); } num5++; } return list; } default: { for (int i = 0; i < count; i++) { int num = i / width; int num2 = i % width; int num3 = Math.Min(width, count - num * width); Vec2 item = new Vec2((double)num2 - (double)(num3 - 1) / 2.0, -num); if (formation == DeploymentFormation.Scatter) { uint num4 = FormationHash((uint)moving[i].CombatantId); item += new Vec2(((double)(num4 & 0xFFFF) / 65535.0 - 0.5) * 0.65, ((double)(num4 >> 16) / 65535.0 - 0.5) * 0.65); } list.Add(item); } return list; } } } private static uint FormationHash(uint value) { value ^= 0x9E3779B9u; value ^= value >> 16; value *= 2146121005; value ^= value >> 15; value *= 2221713035u; return value ^ (value >> 16); } public static bool IsFinite(double value) { if (!double.IsNaN(value)) { return !double.IsInfinity(value); } return false; } public static bool IsFinite(Vec2 value) { if (IsFinite(value.X)) { return IsFinite(value.Y); } return false; } public static double NormalizeDegrees(double degrees) { if (!IsFinite(degrees)) { throw new ArgumentException("Deployment angle must be finite."); } double num = degrees % 360.0; if (!(num < 0.0)) { return num; } return num + 360.0; } public static Vec2 Rotate(Vec2 offset, double yawDegrees) { double num = NormalizeDegrees(yawDegrees) * Math.PI / 180.0; double num2 = Math.Sin(num); double num3 = Math.Cos(num); return new Vec2(offset.X * num3 + offset.Y * num2, (0.0 - offset.X) * num2 + offset.Y * num3); } public static Vec2 Centroid(IReadOnlyList placements) { if (placements == null || placements.Count == 0) { throw new ArgumentException("Pick at least one soldier."); } Vec2 vec = Vec2.Zero; for (int i = 0; i < placements.Count; i++) { if (!IsFinite(placements[i].Position)) { throw new ArgumentException("Deployment positions must be finite."); } vec = vec * ((double)i / (double)(i + 1)) + placements[i].Position / (i + 1); } return vec; } public static bool TryTransform(IReadOnlyList layout, IEnumerable selectedIds, Vec2 targetCenter, double yawDeltaDegrees, DeploymentArea area, out List proposed, out string reason) { proposed = null; if (!IsFinite(targetCenter) || !IsFinite(yawDeltaDegrees)) { reason = "Pick a spot and a facing."; return false; } if (!ReadSelection(layout, selectedIds, out var selected, out reason)) { return false; } List list = new List(); foreach (DeploymentPlacement item in layout) { if (selected.Contains(item.CombatantId)) { list.Add(item); } } Vec2 vec = Centroid(list); double num = NormalizeDegrees(yawDeltaDegrees); List list2 = new List(layout.Count); foreach (DeploymentPlacement item2 in layout) { list2.Add(selected.Contains(item2.CombatantId) ? new DeploymentPlacement(item2.CombatantId, targetCenter + Rotate(item2.Position - vec, num), NormalizeDegrees(NormalizeDegrees(item2.YawDegrees) + num), item2.Radius) : item2); } foreach (DeploymentPlacement item3 in list2) { if (!IsFinite(item3.Position)) { reason = "Pick a spot and a facing."; return false; } } proposed = list2; return ValidateSelection(list2, selected, area, out reason); } public static bool TryValidate(IReadOnlyList layout, IEnumerable selectedIds, DeploymentArea area, out string reason) { if (ReadSelection(layout, selectedIds, out var selected, out reason)) { return ValidateSelection(layout, selected, area, out reason); } return false; } private static bool ReadSelection(IReadOnlyList layout, IEnumerable selectedIds, out HashSet selected, out string reason) { selected = new HashSet(); reason = "Pick at least one soldier."; if (layout == null || selectedIds == null) { return false; } foreach (int selectedId in selectedIds) { if (selectedId <= 0 || !selected.Add(selectedId)) { reason = "The deployment selection is invalid."; return false; } } if (selected.Count == 0) { return false; } HashSet hashSet = new HashSet(); foreach (DeploymentPlacement item in layout) { if (item.CombatantId <= 0 || !hashSet.Add(item.CombatantId) || !IsFinite(item.Position) || !IsFinite(item.YawDegrees) || !IsFinite(item.Radius) || item.Radius <= 0.0) { reason = "A soldier has an invalid deployment footprint."; return false; } } if (!selected.IsSubsetOf(hashSet)) { reason = "One of the selected soldiers is gone."; return false; } reason = ""; return true; } private static bool ValidateSelection(IReadOnlyList layout, HashSet selected, DeploymentArea area, out string reason) { reason = ""; if (area == null) { reason = "The deployment area is unavailable."; return false; } for (int i = 0; i < layout.Count; i++) { DeploymentPlacement deploymentPlacement = layout[i]; if (selected.Contains(deploymentPlacement.CombatantId) && !area.Contains(deploymentPlacement.Position, deploymentPlacement.Radius)) { reason = "Keep the whole formation inside your deployment area."; return false; } for (int j = i + 1; j < layout.Count; j++) { DeploymentPlacement deploymentPlacement2 = layout[j]; if (selected.Contains(deploymentPlacement.CombatantId) || selected.Contains(deploymentPlacement2.CombatantId)) { double num = deploymentPlacement.Radius + deploymentPlacement2.Radius; if (Vec2.Distance(deploymentPlacement.Position, deploymentPlacement2.Position) + 1E-07 < num) { reason = "Leave more room between soldiers."; return false; } } } } return true; } } public readonly struct DeploymentPlacement { public readonly int CombatantId; public readonly Vec2 Position; public readonly double YawDegrees; public readonly double Radius; public DeploymentPlacement(int combatantId, Vec2 position, double yawDegrees, double radius) { CombatantId = combatantId; Position = position; YawDegrees = yawDegrees; Radius = radius; } } public sealed class DeploymentArea { public Vec2 Center { get; } public Vec2 Forward { get; } public Vec2 Right => new Vec2(Forward.Y, 0.0 - Forward.X); public double HalfWidth { get; } public double BackDepth { get; } public double FrontGap { get; } public DeploymentArea(Vec2 center, Vec2 forward, double halfWidth, double backDepth, double frontGap) { if (!DeploymentLayout.IsFinite(center) || !DeploymentLayout.IsFinite(forward)) { throw new ArgumentException("Deployment directions and positions must be finite."); } if (!DeploymentLayout.IsFinite(halfWidth) || halfWidth <= 0.0 || !DeploymentLayout.IsFinite(backDepth) || !DeploymentLayout.IsFinite(frontGap) || frontGap < 0.0 || backDepth <= frontGap) { throw new ArgumentException("Deployment dimensions must describe a non-empty rectangle."); } double num = Math.Max(Math.Abs(forward.X), Math.Abs(forward.Y)); if (num <= 0.0) { throw new ArgumentException("Deployment forward direction cannot be zero."); } Vec2 vec = forward / num; Forward = vec / vec.Length; Center = center; HalfWidth = halfWidth; BackDepth = backDepth; FrontGap = frontGap; } public bool Contains(Vec2 position, double radius) { if (!DeploymentLayout.IsFinite(position) || !DeploymentLayout.IsFinite(radius) || radius <= 0.0) { return false; } Vec2 a = position - Center; double value = Vec2.Dot(a, Right); double num = Vec2.Dot(a, Forward); if (DeploymentLayout.IsFinite(value) && DeploymentLayout.IsFinite(num) && Math.Abs(value) + radius <= HalfWidth + 1E-07 && num - radius >= 0.0 - BackDepth - 1E-07) { return num + radius <= 0.0 - FrontGap + 1E-07; } return false; } } public sealed class FieldSite { public int Seed; public string Biome = "grassland"; public string Flavor = ""; public string Ground = "grass"; public double Relief; public double Trees; public double Rocks; public bool River; public bool Bridge; public bool Ford; public bool Road; public bool Coast; public bool Village; public bool Camp; public bool Ruins; public bool Hill; public int HillSide; public int CoastSide; public string Culture = ""; public bool StoneBuildings; public string Name = "Open field"; public FieldSite Copy() { return (FieldSite)MemberwiseClone(); } public FieldSite Normalized() { FieldSite fieldSite = Copy(); fieldSite.Relief = Math.Max(0.0, Math.Min(1.0, fieldSite.Relief)); fieldSite.Trees = Math.Max(0.0, Math.Min(1.0, fieldSite.Trees)); fieldSite.Rocks = Math.Max(0.0, Math.Min(1.0, fieldSite.Rocks)); if (fieldSite.River && !fieldSite.Bridge && !fieldSite.Ford) { fieldSite.Ford = true; } if (!fieldSite.River) { fieldSite.Bridge = false; fieldSite.Ford = false; } if (fieldSite.River) { fieldSite.Hill = false; fieldSite.Coast = false; } fieldSite.HillSide = Math.Max(-1, Math.Min(1, fieldSite.HillSide)); fieldSite.CoastSide = ((fieldSite.CoastSide >= 0) ? 1 : (-1)); if (fieldSite.Coast && fieldSite.Hill && fieldSite.HillSide == fieldSite.CoastSide) { fieldSite.HillSide = -fieldSite.CoastSide; } if (fieldSite.Village && fieldSite.Camp) { fieldSite.Camp = false; } if (fieldSite.Village || fieldSite.Camp) { fieldSite.Ruins = false; } if (fieldSite.Seed < 0) { fieldSite.Seed = -fieldSite.Seed; } fieldSite.Name = FieldBattlefield.Describe(fieldSite); return fieldSite; } } public static class FieldBattlefield { public const string MapId = "map.bannerlord_field_v1"; public const int MapContentVersion = 1; public static bool Supports(EncounterKind kind) { if (kind != EncounterKind.FieldBattle && kind != EncounterKind.BanditAmbush && kind != EncounterKind.SettlementDefense) { return kind == EncounterKind.HideoutRaid; } return true; } public static FieldSite Plan(TabsBannerlord.Core.Campaign.Campaign c, Encounter enc) { if (c?.FieldSiteOverride != null) { return c.FieldSiteOverride.Normalized(); } FieldSite fieldSite = new FieldSite { Seed = (int)(StableHash.Fnv1a64("field|" + enc?.Id) & 0x7FFFFFFF), Biome = (enc?.Biome ?? "grassland") }; Dictionary counts = new Dictionary(); int total = 0; if (c?.Nav != null && enc != null) { (int x, int y) tuple = c.Nav.ToCell(enc.Position); int item = tuple.x; int item2 = tuple.y; for (int i = -2; i <= 2; i++) { for (int j = -2; j <= 2; j++) { if (j * j + i * i <= 5 && c.Nav.InBounds(item + j, item2 + i)) { TerrainType type = c.Nav.Cell(item + j, item2 + i).Type; counts[type] = (counts.TryGetValue(type, out var value) ? value : 0) + 1; total++; } } } } WorldRegionDef worldRegionDef = c?.World?.Regions?.OrderBy((WorldRegionDef r) => Sq(r.X - (enc?.Position.X ?? 0.0)) + Sq(r.Y - (enc?.Position.Y ?? 0.0))).FirstOrDefault(); if (worldRegionDef != null && (worldRegionDef.Biome == "golden" || worldRegionDef.Biome == "sakura" || worldRegionDef.Biome == "autumn" || worldRegionDef.Biome == "volcanic")) { fieldSite.Flavor = worldRegionDef.Biome; } fieldSite.Culture = ((from s in c?.State?.Settlements?.Where((Settlement s) => s.Type != SettlementType.Hideout) orderby Vec2.Distance(s.Position, enc?.Position ?? Vec2.Zero) select s).FirstOrDefault())?.CultureId ?? worldRegionDef?.Culture ?? ""; fieldSite.StoneBuildings = !(fieldSite.Culture == "viking") && !(fieldSite.Culture == "tribal") && !(fieldSite.Culture == "farmer") && !(fieldSite.Culture == "pirate"); string text = fieldSite.Biome ?? "grassland"; bool flag = text == "snow" || (Count(new TerrainType[1] { TerrainType.Snow }) * 2 > total && total > 0); bool flag2 = text == "desert" || (Count(new TerrainType[1] { TerrainType.Desert }) * 2 > total && total > 0); bool flag3 = text == "swamp" || (Count(new TerrainType[1] { TerrainType.Swamp }) * 2 > total && total > 0); fieldSite.Ground = (flag ? "snow" : (flag2 ? "sand" : (flag3 ? "swamp" : ((fieldSite.Flavor == "volcanic") ? "ash" : "grass")))); int n = Count(new TerrainType[1] { TerrainType.Forest }); int num = Count(new TerrainType[1] { TerrainType.Hills }); int num2 = Count(new TerrainType[1] { TerrainType.Mountains }); int num3 = Count(new TerrainType[3] { TerrainType.River, TerrainType.Bridge, TerrainType.Ford }); int num4 = Count(new TerrainType[2] { TerrainType.Road, TerrainType.Bridge }); int num5 = Count(new TerrainType[2] { TerrainType.Water, TerrainType.Beach }); double num6 = 0.18 + 0.55 * share(num + num2) + 0.35 * share(num2); double num7; switch (text) { default: num7 = 0.0; break; case "mountains": case "mountain": num7 = 0.45; break; case "hills": num7 = 0.3; break; } fieldSite.Relief = Clamp(num6 + num7 + (flag2 ? 0.2 : 0.0) - (flag3 ? 0.12 : 0.0) + (R(1) - 0.5) * 0.2); fieldSite.Trees = Clamp((flag2 ? 0.03 : (flag3 ? 0.35 : (flag ? 0.3 : 0.22))) + 0.75 * share(n) + ((text == "forest") ? 0.4 : 0.0) + (R(2) - 0.5) * 0.2); fieldSite.Rocks = Clamp(0.12 + 0.6 * share(num2) + 0.25 * share(num) + (flag2 ? 0.15 : 0.0) + ((fieldSite.Flavor == "volcanic") ? 0.25 : 0.0) + (R(3) - 0.5) * 0.15); Encounter encounter = enc; fieldSite.Village = encounter != null && encounter.Kind == EncounterKind.SettlementDefense; Encounter encounter2 = enc; fieldSite.Camp = encounter2 != null && encounter2.Kind == EncounterKind.HideoutRaid; fieldSite.River = (num3 > 0 || text == "river") && !flag2; if (fieldSite.River) { fieldSite.Bridge = Count(new TerrainType[1] { TerrainType.Bridge }) > 0 || R(4) < 0.55; fieldSite.Ford = !fieldSite.Bridge || R(5) < 0.6; } fieldSite.Road = num4 > 0 || fieldSite.Bridge || R(6) < 0.2; fieldSite.Coast = !fieldSite.River && (num5 > 0 || text == "coast"); fieldSite.CoastSide = ((!(R(7) < 0.5)) ? 1 : (-1)); fieldSite.Hill = !fieldSite.River && (text == "hills" || num + num2 > 0 || R(8) < 0.3); fieldSite.HillSide = ((!(R(9) < 0.4)) ? ((!(R(10) < 0.5)) ? 1 : (-1)) : 0); if (fieldSite.Coast && fieldSite.HillSide == fieldSite.CoastSide) { fieldSite.HillSide = -fieldSite.CoastSide; } fieldSite.Ruins = !fieldSite.Village && !fieldSite.Camp && R(11) < 0.2; fieldSite.Name = Describe(fieldSite); return fieldSite; int Count(params TerrainType[] types) { int value2; return types.Sum((TerrainType t) => counts.TryGetValue(t, out value2) ? value2 : 0); } double R(int salt) { return (double)(StableHash.Fnv1a64("field|" + enc?.Id + "|" + salt) % 10000) / 10000.0; } double share(int num8) { if (total != 0) { return (double)num8 / (double)total; } return 0.0; } } public static string Describe(FieldSite s) { string text = ((s.Ground == "snow") ? "Snowfield" : ((s.Ground == "sand") ? "Dunes" : ((s.Ground == "swamp") ? "Marsh" : ((s.Ground == "ash") ? "Ashlands" : ((s.Trees > 0.6) ? "Woodland" : ((s.Relief > 0.55) ? "Hills" : ((s.Flavor == "golden") ? "Golden fields" : ((s.Flavor == "sakura") ? "Blossom vale" : ((s.Flavor == "autumn") ? "Autumn meadows" : "Open field"))))))))); if (s.Village) { return text + " village"; } if (s.Camp) { return text + " outlaw camp"; } if (s.River) { return text + (s.Bridge ? " bridge" : " ford"); } if (s.Coast) { return text + " shore"; } if (s.Ruins) { return text + " ruins"; } return text; } private static double Sq(double v) { return v * v; } private static double Clamp(double v) { return Math.Max(0.0, Math.Min(1.0, v)); } } public enum ReservePriority { Balanced, StrongestFirst, TrainingFirst, RosterOrder } public static class ManifestBuilder { public static string GroupFor(TroopRole role) { return role switch { TroopRole.Ranged => "ranged", TroopRole.Cavalry => "cavalry", TroopRole.Support => "support", TroopRole.Monster => "monsters", TroopRole.Siege => "siege", _ => "infantry", }; } public static BattleManifest Build(TabsBannerlord.Core.Campaign.Campaign campaign, Encounter enc, int budget) { CampaignState state = campaign.State; BattleManifest battleManifest = new BattleManifest { EncounterId = enc.Id, Budget = budget }; int num = 1; BattleSide[] array = new BattleSide[2] { BattleSide.Attacker, BattleSide.Defender }; foreach (BattleSide side in array) { foreach (string item3 in enc.PartiesOn(side)) { Party party = state.Parties.Require(item3); bool flag = enc.Kind == EncounterKind.HideoutRaid && item3 == state.PlayerPartyId; foreach (string hero2 in party.Troops.Heroes) { Hero hero = state.Heroes.Get(hero2); if (hero != null && hero.CanFight && (!flag || enc.SquadHeroes.Contains(hero2))) { UnitDef unitDef = campaign.UnitDef(hero.UnitId); battleManifest.Combatants.Add(new Combatant { Id = num++, Side = side, PartyId = item3, UnitId = hero.UnitId, HeroId = hero2, Loadout = TabsBannerlord.Core.Campaign.Campaign.CopyHeroLoadout(hero.Loadout), EquipmentStats = ((hero.Loadout == null) ? null : campaign.HeroEquipmentStats(hero)), Mount = ((enc.Kind == EncounterKind.Siege) ? null : campaign.MountForBattle(hero)), Role = (unitDef?.Role ?? TroopRole.Infantry), Tier = Math.Max(unitDef?.Tier ?? 3, 3), Slots = (unitDef?.Slots ?? 1), Workload = (unitDef?.Workload ?? 1.0), Group = GroupFor(unitDef?.Role ?? TroopRole.Infantry) }); } } foreach (TroopStack stack in party.Troops.Stacks) { UnitDef unitDef2 = campaign.UnitDef(stack.UnitId); int num2 = stack.Healthy; if (flag) { num2 = Math.Min(num2, enc.SquadTroops.TryGetValue(stack.UnitId, out var value) ? value : 0); } for (int j = 0; j < num2; j++) { battleManifest.Combatants.Add(new Combatant { Id = num++, Side = side, PartyId = item3, UnitId = stack.UnitId, Role = (unitDef2?.Role ?? TroopRole.Infantry), Tier = (unitDef2?.Tier ?? 1), Slots = (unitDef2?.Slots ?? 1), Workload = (unitDef2?.Workload ?? 1.0), Group = GroupFor(unitDef2?.Role ?? TroopRole.Infantry) }); } } } } ApplyPriority(battleManifest, BattleSide.Attacker, ReservePriority.Balanced); ApplyPriority(battleManifest, BattleSide.Defender, ReservePriority.Balanced); if (budget > 0) { (int attacker, int defender) tuple = SlotAllocator.Allocate(budget, SlotsOf(battleManifest, BattleSide.Attacker), SlotsOf(battleManifest, BattleSide.Defender), campaign.Rules.MinSideShare); int item = tuple.attacker; int item2 = tuple.defender; battleManifest.AttackerAllowance = item; battleManifest.DefenderAllowance = item2; } return battleManifest; } public static int SlotsOf(BattleManifest m, BattleSide side) { return (from c in m.OnSide(side) where c.State == DeploymentState.Reserve || c.State == DeploymentState.Scheduled || c.State == DeploymentState.Active select c).Sum((Combatant c) => c.Slots); } public static void ApplyPriority(BattleManifest m, BattleSide side, ReservePriority mode) { List source = m.OnSide(side).ToList(); IEnumerable enumerable; switch (mode) { case ReservePriority.StrongestFirst: enumerable = from c in source orderby c.IsHero descending, c.Tier descending, c.Id select c; break; case ReservePriority.TrainingFirst: enumerable = from c in source orderby c.IsHero descending, c.Tier, c.Id select c; break; case ReservePriority.RosterOrder: enumerable = source.OrderBy((Combatant c) => c.Id); break; default: { List collection = (from c in source where c.IsHero orderby c.Id select c).ToList(); List> list = (from g in (from c in source where !c.IsHero group c by c.Group).OrderBy, string>((IGrouping g) => g.Key, StringComparer.Ordinal) select new Queue(from c in g orderby c.Tier descending, c.Id select c)).ToList(); List list2 = new List(collection); bool flag = true; while (flag) { flag = false; foreach (Queue item in list) { if (item.Count > 0) { list2.Add(item.Dequeue()); flag = true; } } } enumerable = list2; break; } } int num = 0; foreach (Combatant item2 in enumerable) { item2.Priority = num++; } } } public static class SlotAllocator { public static (int attacker, int defender) Allocate(int budget, int attackerSlots, int defenderSlots, double minShare) { if (budget <= 0) { return (attacker: attackerSlots, defender: defenderSlots); } attackerSlots = Math.Max(0, attackerSlots); defenderSlots = Math.Max(0, defenderSlots); int num = attackerSlots + defenderSlots; if (num <= budget) { return (attacker: attackerSlots, defender: defenderSlots); } if (attackerSlots == 0) { return (attacker: 0, defender: Math.Min(budget, defenderSlots)); } if (defenderSlots == 0) { return (attacker: Math.Min(budget, attackerSlots), defender: 0); } double val = (double)attackerSlots / (double)num; minShare = Math.Max(0.0, Math.Min(0.5, minShare)); val = Math.Max(minShare, Math.Min(1.0 - minShare, val)); int num2 = (int)Math.Round((double)budget * val, MidpointRounding.AwayFromZero); int num3 = budget - num2; if (num2 > attackerSlots) { num3 = Math.Min(defenderSlots, num3 + (num2 - attackerSlots)); num2 = attackerSlots; } if (num3 > defenderSlots) { num2 = Math.Min(attackerSlots, num2 + (num3 - defenderSlots)); num3 = defenderSlots; } return (attacker: num2, defender: num3); } public static Dictionary SplitAmongParties(BattleManifest m, BattleSide side, int allowance, string playerPartyId, double playerMinShare = 0.25) { var list = (from c in m.OnSide(side) group c by c.PartyId into g select new { Party = g.Key, Slots = g.Sum((Combatant c) => c.Slots) }).OrderBy(x => x.Party, StringComparer.Ordinal).ToList(); Dictionary dictionary = new Dictionary(StringComparer.Ordinal); int num = list.Sum(p => p.Slots); if (num == 0) { return dictionary; } if (num <= allowance) { foreach (var item3 in list) { dictionary[item3.Party] = item3.Slots; } return dictionary; } int num2 = allowance; var anon = list.FirstOrDefault(p => p.Party == playerPartyId); if (anon != null) { int num3 = Math.Min(anon.Slots, (int)Math.Ceiling((double)allowance * playerMinShare)); dictionary[anon.Party] = num3; num2 -= num3; } var source = list.Where(p => p.Party != playerPartyId).ToList(); int num4 = source.Sum(p => p.Slots) + ((anon != null) ? (anon.Slots - dictionary[anon.Party]) : 0); List<(string, int)> list2 = source.Select(p => (Party: p.Party, Slots: p.Slots)).ToList(); if (anon != null && anon.Slots > dictionary[anon.Party]) { list2.Add((anon.Party, anon.Slots - dictionary[anon.Party])); } int num5 = 0; List<(string, double)> list3 = new List<(string, double)>(); foreach (var item4 in list2) { string item = item4.Item1; int item2 = item4.Item2; double num6 = ((num4 == 0) ? 0.0 : ((double)num2 * (double)item2 / (double)num4)); int num7 = Math.Min(item2, (int)Math.Floor(num6)); dictionary[item] = (dictionary.TryGetValue(item, out var value) ? value : 0) + num7; num5 += num7; list3.Add((item, num6 - (double)num7)); } foreach (var item5 in list3.OrderByDescending<(string, double), double>(((string party, double frac) x) => x.frac).ThenBy<(string, double), string>(((string party, double frac) x) => x.party, StringComparer.Ordinal)) { if (num5 >= num2) { break; } dictionary[item5.Item1]++; num5++; } return dictionary; } public static List AutoSelectInitial(BattleManifest m, BattleSide side, int allowance, Dictionary partyShares) { List list = new List(); Dictionary dictionary = new Dictionary(StringComparer.Ordinal); int num = 0; foreach (Combatant item in from c in m.OnSide(side) orderby c.Priority select c) { if (num + item.Slots <= allowance) { dictionary.TryGetValue(item.PartyId, out var value); if (partyShares == null || !partyShares.TryGetValue(item.PartyId, out var value2) || value + item.Slots <= value2) { list.Add(item.Id); dictionary[item.PartyId] = value + item.Slots; num += item.Slots; } } } return list; } } public sealed class CommitResult { public bool Success; public bool Duplicate; public string Error = ""; public BattleReport Report; } public static class OutcomeCommitter { public static CommitResult Validate(TabsBannerlord.Core.Campaign.Campaign campaign, BattleResult result) { CampaignState state = campaign.State; CommitResult commitResult = new CommitResult(); if (result == null) { commitResult.Error = "No result."; return commitResult; } if (result.CampaignId != state.CampaignId) { commitResult.Error = "Result belongs to a different campaign."; return commitResult; } if (state.CommittedEncounters.Contains(result.EncounterId)) { commitResult.Duplicate = true; commitResult.Error = "Encounter already committed."; return commitResult; } Encounter encounter = state.Encounters.Get(result.EncounterId); if (encounter == null) { commitResult.Error = "Unknown encounter " + result.EncounterId; return commitResult; } if (encounter.Phase != EncounterPhase.InBattle) { commitResult.Error = $"Encounter is not in battle (phase {encounter.Phase})."; return commitResult; } if (encounter.CurrentAttemptId != result.AttemptId) { commitResult.Error = "Obsolete battle attempt " + result.AttemptId + " (current " + encounter.CurrentAttemptId + ")."; return commitResult; } if (encounter.ExpectedRevision != result.ExpectedRevision) { commitResult.Error = "Campaign changed since the battle was prepared."; return commitResult; } if (result.EndKind == BattleEndKind.Interrupted) { commitResult.Error = "Interrupted battles return to the encounter decision instead of committing."; return commitResult; } string text = campaign.SiegeBattleValidation(encounter); if (text.Length > 0) { commitResult.Error = text; return commitResult; } BattleManifest manifest = encounter.Manifest; if (manifest == null) { commitResult.Error = "Encounter has no manifest."; return commitResult; } HashSet hashSet = new HashSet(); foreach (CombatantResult outcome in result.Outcomes) { if (manifest.Get(outcome.Id) == null) { commitResult.Error = "Outcome for unknown combatant " + outcome.Id; return commitResult; } if (!hashSet.Add(outcome.Id)) { commitResult.Error = "Duplicate outcome for combatant " + outcome.Id; return commitResult; } if (outcome.Outcome == CombatOutcome.Pending) { commitResult.Error = "Unresolved outcome for combatant " + outcome.Id; return commitResult; } } if (hashSet.Count != manifest.Combatants.Count) { commitResult.Error = $"Outcomes cover {hashSet.Count} of {manifest.Combatants.Count} combatants."; return commitResult; } foreach (string allParty in encounter.AllParties) { if (state.Parties.Get(allParty) == null) { commitResult.Error = "Participant party missing: " + allParty; return commitResult; } } if (encounter.PlayerInvolved && result.Winner != WinnerSide.None && (result.EndKind == BattleEndKind.Victory || result.EndKind == BattleEndKind.Surrender)) { BattleSide battleSide = ((result.Winner != WinnerSide.Attacker) ? BattleSide.Defender : BattleSide.Attacker); if (encounter.PlayerSide == battleSide && encounter.PartiesOn(battleSide).Contains(state.PlayerPartyId)) { BattleSide side = ((battleSide == BattleSide.Attacker) ? BattleSide.Defender : BattleSide.Attacker); Dictionary dictionary = new Dictionary(StringComparer.Ordinal); long num = 0L; foreach (string item in encounter.PartiesOn(side)) { TroopRoster prisoners = state.Parties.Get(item).Prisoners; HashSet hashSet2 = new HashSet(StringComparer.Ordinal); if (prisoners?.Stacks == null) { commitResult.Error = "The defeated party has invalid prisoner records."; return commitResult; } foreach (TroopStack stack in prisoners.Stacks) { if (stack == null || string.IsNullOrEmpty(stack.UnitId) || campaign.UnitDef(stack.UnitId) == null || !hashSet2.Add(stack.UnitId) || stack.Healthy < 0 || stack.Wounded < 0 || stack.Xp < 0 || (long)stack.Healthy + (long)stack.Wounded <= 0 || double.IsNaN(stack.PrisonerRecruitment) || double.IsInfinity(stack.PrisonerRecruitment) || stack.PrisonerRecruitment < 0.0 || stack.PrisonerRecruitment > (double)((long)stack.Healthy + (long)stack.Wounded)) { commitResult.Error = "The defeated party has invalid prisoner records."; return commitResult; } if (!dictionary.TryGetValue(stack.UnitId, out var value)) { value = (dictionary[stack.UnitId] = new long[3]); } value[0] += stack.Healthy; value[1] += stack.Wounded; value[2] += stack.Xp; num += (long)stack.Healthy + (long)stack.Wounded; if (num > int.MaxValue || value[2] > int.MaxValue) { commitResult.Error = "The rescued troop records exceed their supported capacity."; return commitResult; } } } } } commitResult.Success = true; return commitResult; } public static CommitResult Commit(TabsBannerlord.Core.Campaign.Campaign campaign, BattleResult result) { CommitResult commitResult = Validate(campaign, result); if (!commitResult.Success) { return commitResult; } CampaignState state = campaign.State; CampaignRules rules = campaign.Rules; Encounter enc = state.Encounters.Get(result.EncounterId); BattleManifest manifest = enc.Manifest; RandomStream randomStream = state.Random.Get("battle"); Dictionary outcomes = result.Outcomes.ToDictionary((CombatantResult o) => o.Id, (CombatantResult o) => o.Outcome); bool flag = result.EndKind != BattleEndKind.MutualDestruction && result.Winner != WinnerSide.None; BattleSide loserSide = ((!flag || result.Winner == WinnerSide.Attacker) ? BattleSide.Defender : BattleSide.Attacker); BattleSide battleSide = ((loserSide == BattleSide.Attacker) ? BattleSide.Defender : BattleSide.Attacker); bool flag2 = result.EndKind == BattleEndKind.Surrender; bool flag3 = flag; BattleReport battleReport = new BattleReport { EncounterId = enc.Id, EndKind = result.EndKind, Winner = result.Winner, Simulated = result.Simulated }; List<(string, BattleSide, string)> leaders = enc.AllParties.Select((string pid) => (pid: pid, enc.SideOf(pid), state.Parties.Get(pid)?.LeaderHeroId ?? "")).ToList(); Dictionary partyReports = new Dictionary(StringComparer.Ordinal); foreach (string allParty in enc.AllParties) { Party party = state.Parties.Get(allParty); partyReports[allParty] = new PartyBattleReport { PartyId = allParty, PartyName = party.Name, Side = enc.SideOf(allParty) }; } Party party2 = null; if (flag3) { party2 = (from id in enc.PartiesOn(battleSide) select state.Parties.Get(id) into p where p != null orderby p.Troops.TotalTroops descending select p).ThenBy((Party p) => p.Id, StringComparer.Ordinal).FirstOrDefault(); } List<(string, int, int)> list = new List<(string, int, int)>(); List capturedHeroes = new List(); TroopRoster troopRoster = new TroopRoster(); bool flag4 = flag && enc.PlayerInvolved && enc.PlayerSide == battleSide && enc.PartiesOn(battleSide).Contains(state.PlayerPartyId) && (result.EndKind == BattleEndKind.Victory || flag2); double num = 0.0; double num2 = 0.0; Dictionary dictionary = enc.AllParties.ToDictionary((string id) => id, (string id) => campaign.RoleSkill(state.Parties.Get(id), PartyRole.Surgeon), StringComparer.Ordinal); Dictionary dictionary2 = enc.AllParties.ToDictionary((string id) => id, (string id) => campaign.HasRolePerk(state.Parties.Get(id), PartyRole.Surgeon, "perk.surgeon.survivor"), StringComparer.Ordinal); Dictionary dictionary3 = enc.AllParties.ToDictionary((string id) => id, (string id) => campaign.PartyPerk(state.Parties.Get(id), PerkEffect.WoundSurvival), StringComparer.Ordinal); foreach (Combatant item4 in manifest.Combatants.OrderBy((Combatant c) => c.Id)) { CombatOutcome combatOutcome = outcomes[item4.Id]; Party party3 = state.Parties.Get(item4.PartyId); PartyBattleReport partyBattleReport = partyReports[item4.PartyId]; bool flag5 = flag && item4.Side == loserSide; if (item4.EverDeployed || combatOutcome == CombatOutcome.Downed) { partyBattleReport.Fought++; } else { partyBattleReport.Reserve++; } if (combatOutcome == CombatOutcome.Downed) { if (item4.Side == loserSide) { num += (double)item4.Tier; } else { num2 += (double)item4.Tier; } } if (item4.IsHero) { Hero hero = state.Heroes.Get(item4.HeroId); if (hero == null) { continue; } if (combatOutcome == CombatOutcome.Downed) { if ((rules.HeroesCanDie || state.Settings.HeroesCanDie) && !hero.IsPlayer && randomStream.Chance(0.1)) { KillHero(campaign, hero, party3); partyBattleReport.Killed++; continue; } hero.Health = Math.Min(hero.Health, 0.2); if (flag5 && flag3) { capturedHeroes.Add(hero); partyBattleReport.Captured++; } else { partyBattleReport.Wounded++; } } else if (flag2 && flag5) { capturedHeroes.Add(hero); partyBattleReport.Captured++; } else if (combatOutcome == CombatOutcome.Fled) { partyBattleReport.Escaped++; } } else if (combatOutcome == CombatOutcome.Downed) { double probability = Math.Min(0.95, rules.BaseWoundSurvival + (double)dictionary[party3.Id] / 300.0 + (dictionary2[party3.Id] ? 0.05 : 0.0) + dictionary3[party3.Id]); if (randomStream.Chance(probability)) { if (flag5 && flag3) { party3.Troops.RemoveHealthy(item4.UnitId, 1); list.Add((item4.UnitId, 0, 1)); partyBattleReport.Captured++; } else { party3.Troops.Wound(item4.UnitId, 1); partyBattleReport.Wounded++; } } else { party3.Troops.RemoveHealthy(item4.UnitId, 1); partyBattleReport.Killed++; } } else if (flag2 && flag5) { party3.Troops.RemoveHealthy(item4.UnitId, 1); list.Add((item4.UnitId, 1, 0)); partyBattleReport.Captured++; } else if (combatOutcome == CombatOutcome.Fled) { partyBattleReport.Escaped++; } } if (flag) { foreach (string item5 in enc.PartiesOn(loserSide)) { Party party4 = state.Parties.Get(item5); PartyBattleReport partyBattleReport2 = partyReports[item5]; if (!(result.EndKind == BattleEndKind.Victory || flag2)) { continue; } foreach (TroopStack item6 in party4.Troops.Stacks.ToList()) { int wounded = item6.Wounded; int num3 = (flag2 ? item6.Healthy : 0); if (wounded + num3 != 0) { party4.Troops.Remove(item6.UnitId, wounded + num3, woundedFirst: true); list.Add((item6.UnitId, num3, wounded)); partyBattleReport2.Captured += wounded + num3; } } foreach (string hid in party4.Troops.Heroes.ToList()) { Hero hero2 = state.Heroes.Get(hid); if (hero2 != null && hero2.State == HeroState.Active && !capturedHeroes.Contains(hero2) && !manifest.Combatants.Any((Combatant c) => c.HeroId == hid && outcomes[c.Id] == CombatOutcome.Fled) && (!hero2.CanFight || flag2)) { capturedHeroes.Add(hero2); partyBattleReport2.Captured++; } } int totalTroops = party4.Prisoners.TotalTroops; if (totalTroops > 0) { if (flag4) { foreach (TroopStack stack in party4.Prisoners.Stacks) { troopRoster.Add(stack.UnitId, stack.Healthy, stack.Wounded, stack.Xp); } } party4.Prisoners.Stacks.Clear(); state.AddLog(LogCategory.Battle, $"{totalTroops} prisoners held by {party4.Name} were freed.", party4.Id); } foreach (string item7 in party4.Prisoners.Heroes.ToList()) { ReleaseHero(campaign, state.Heroes.Get(item7), "freed after the battle"); } party4.Prisoners.Heroes.Clear(); } } Dictionary dictionary4 = result.Outcomes.ToDictionary((CombatantResult o) => o.Id, (CombatantResult o) => o.MountOutcome); RandomStream rng = state.Random.Get("horses"); foreach (Combatant item8 in from c in manifest.Combatants where c.IsHero && c.Mount != null orderby c.Id select c) { Hero hero3 = state.Heroes.Get(item8.HeroId); if (hero3 != null) { campaign.ApplyHorseBattleOutcome(item8, outcomes[item8.Id], dictionary4.TryGetValue(item8.Id, out var value) ? value : CombatOutcome.Pending, capturedHeroes.Contains(hero3), hero3.State == HeroState.Dead, flag && item8.Side == battleSide, result.Simulated, rng, battleReport.Lines, party2); } } if (flag && (result.EndKind == BattleEndKind.Victory || flag2)) { foreach (string item9 in enc.PartiesOn(loserSide)) { Party party5 = state.Parties.Get(item9); string text = campaign.SeizeCargo(party5, party2); if (text.Length > 0) { battleReport.Lines.Add(text); } string text2 = campaign.SeizeHerd(party5, party5.Troops.Heroes.Where((string id) => !capturedHeroes.Any((Hero h) => h.Id == id)).ToList()); if (text2.Length > 0) { battleReport.Lines.Add(text2); } } } if (party2 != null) { int num4 = campaign.PrisonerLimit(party2); int num5 = 0; int num6 = 0; foreach (var item10 in list) { string item = item10.Item1; int item2 = item10.Item2; int item3 = item10.Item3; int num7 = Math.Max(0, num4 - party2.Prisoners.TotalTroops); int num8 = Math.Min(item3, num7); num7 -= num8; int num9 = Math.Min(item2, num7); if (num8 + num9 > 0) { party2.Prisoners.Add(item, num9, num8); } num5 += num8 + num9; num6 += item2 + item3 - num8 - num9; } partyReports[party2.Id].PrisonersTaken += num5; if (num6 > 0) { battleReport.Lines.Add($"{num6} captives were released: {party2.Name} cannot hold more prisoners."); } foreach (Hero item11 in capturedHeroes) { CaptureHero(campaign, item11, party2, deferCompanionRecovery: true); } } campaign.RecoverSeparatedCompanions(); List list2 = (flag ? (from id in enc.PartiesOn(battleSide) select state.Parties.Get(id)).ToList() : new List()); if (flag) { long num10 = (long)Math.Round(num * rules.LootPerEnemyTier); foreach (string item12 in enc.PartiesOn(loserSide)) { Party party6 = state.Parties.Get(item12); if (party6.Gold > 0 && (result.EndKind == BattleEndKind.Victory || flag2)) { long num11 = party6.Gold / 2; party6.Gold -= num11; num10 += num11; } } int num12 = list2.Sum((Party p) => Math.Max(1, partyReports[p.Id].Fought)); foreach (Party item13 in list2.OrderBy((Party p) => p.Id, StringComparer.Ordinal)) { long num13 = ((num12 == 0) ? 0 : (num10 * Math.Max(1, partyReports[item13.Id].Fought) / num12)); partyReports[item13.Id].Loot = num13; Clan clan = state.Clans.Get(item13.ClanId); if (num13 > 0) { if (clan != null && !clan.IsBandit && (item13.Kind == PartyKind.Player || item13.Kind == PartyKind.Lord || item13.Kind == PartyKind.SiegeDefender)) { state.Transact(clan, num13, LedgerAccount.Loot, "Battle loot " + enc.Id); } else { item13.Gold += num13; } } item13.Morale = Math.Min(100.0, item13.Morale + 6.0); if (clan != null && !clan.IsBandit && list2.Count > 0) { clan.Renown += rules.RenownPerEnemyTier * num / (double)list2.Count * (1.0 + Math.Max(0.0, campaign.PartyPerk(item13, PerkEffect.BattleRenown))); } } foreach (string item14 in enc.PartiesOn(loserSide)) { Party party7 = state.Parties.Get(item14); party7.Morale = Math.Max(0.0, party7.Morale - 10.0); } Party party8 = list2.FirstOrDefault((Party p) => p.Id == state.PlayerPartyId); if (party8 != null && party8.State != PartyState.Disbanded && (result.EndKind == BattleEndKind.Victory || flag2)) { IEnumerable downedUnitIds = from c in manifest.Combatants where c.Side == loserSide && !c.IsHero && outcomes[c.Id] == CombatOutcome.Downed orderby c.Id select c.UnitId; string text3 = campaign.LootClothing(party8, downedUnitIds); if (text3.Length > 0) { battleReport.Lines.Add(text3); } } } AwardXp(campaign, enc, manifest, outcomes, BattleSide.Attacker, (enc.AttackerParties.Count == 0) ? 0.0 : ((loserSide == BattleSide.Attacker) ? num2 : num), partyReports, result.Credits); AwardXp(campaign, enc, manifest, outcomes, BattleSide.Defender, (enc.DefenderParties.Count == 0) ? 0.0 : ((BattleSide.Defender == loserSide) ? num2 : num), partyReports, result.Credits); long disengagedUntilMinute = state.Clock.Minute + (long)(rules.DisengageHours * 60.0); foreach (string allParty2 in enc.AllParties) { Party party9 = state.Parties.Get(allParty2); party9.EncounterId = ""; if (party9.State == PartyState.Engaged) { party9.State = PartyState.Active; } if (party9.Order.Kind == OrderKind.Engage && enc.AllParties.Contains(party9.Order.TargetId)) { campaign.ClearOrder(party9); } if ((flag && enc.SideOf(allParty2) == loserSide) || !flag) { party9.DisengagedUntilMinute = disengagedUntilMinute; } HandleLeaderLoss(campaign, party9, partyReports[allParty2]); if (party9.Kind == PartyKind.SiegeDefender || party9.State == PartyState.Disbanded || !party9.Troops.IsEmpty) { continue; } if (party9.Id == state.PlayerPartyId) { string text4 = campaign.SeizeHerd(party9); if (text4.Length > 0) { battleReport.Lines.Add(text4); } party9.State = PartyState.Disbanded; party9.Cargo.Clear(); party9.Equipment?.Clear(); party9.Food = 0.0; } else { DestroyParty(campaign, party9, "defeated"); } partyReports[allParty2].Destroyed = true; } enc.Phase = EncounterPhase.Committed; campaign.ReconcileMilitaryParties(); foreach (PartyBattleReport value2 in partyReports.Values) { Party party10 = state.Parties.Get(value2.PartyId); if (party10 != null && (party10.State == PartyState.Destroyed || party10.State == PartyState.Disbanded)) { value2.Destroyed = true; } } state.CommittedEncounters.Add(enc.Id); battleReport.Parties = partyReports.Values.ToList(); enc.ResultSummary = Summarize(campaign, enc, result, battleReport); battleReport.Lines.Insert(0, enc.ResultSummary); state.AddLog(LogCategory.Battle, enc.ResultSummary, enc.AllParties.ToArray()); if (enc.PlayerInvolved) { Hero playerHero = state.PlayerHero; battleReport.PlayerWon = flag && enc.PlayerSide == battleSide; battleReport.PlayerCaptured = playerHero != null && playerHero.State == HeroState.Captive; Party playerParty = state.PlayerParty; if (flag4 && !battleReport.PlayerCaptured && state.Player.Activity != PlayerActivity.Captive && playerParty != null && playerParty.State == PartyState.Active && playerHero != null && playerHero.State == HeroState.Active && playerHero.PartyId == playerParty.Id && playerParty.Troops.Heroes.Count((string id) => id == playerHero.Id) == 1) { battleReport.RescuedTroops = troopRoster; battleReport.RescueMinute = state.Clock.Minute; battleReport.RescuePosition = playerParty.Position; if (troopRoster.TotalTroops > 0) { battleReport.Lines.Add($"{troopRoster.TotalTroops} rescued troops are waiting on you."); } } campaign.AcknowledgeReport(); state.Player.LastReport = battleReport; state.Player.LastReportSeen = false; state.Player.PendingEncounterId = ""; if (!battleReport.PlayerCaptured && state.Player.Activity != PlayerActivity.Captive) { state.Player.Activity = PlayerActivity.Idle; } campaign.Raise(CampaignEventKind.BattleCommitted, enc.ResultSummary, true, enc.Id); campaign.RememberBattle(enc, leaders, battleReport.PlayerWon, flag); if (flag) { campaign.CompanionsReactToBattle(battleReport.PlayerWon); } } campaign.RecordPoliticalBattleInfluence(enc, result, battleReport); campaign.CompleteSiegeBattle(enc, result, battleReport); campaign.CompleteSiegeSortie(enc, result, battleReport); campaign.RecordContractBattle(enc, result, battleReport); campaign.CompleteHideoutRaid(enc, result, battleReport); campaign.RecordQuestBattle(enc, result, battleReport); campaign.ReconcileCaravans(); campaign.PruneEncounters(); campaign.StartPendingKeepBattles(); state.Touch(); return new CommitResult { Success = true, Report = battleReport }; } private static void AwardXp(TabsBannerlord.Core.Campaign.Campaign campaign, Encounter enc, BattleManifest m, Dictionary outcomes, BattleSide side, double enemyTierDowned, Dictionary reports, List credits = null) { CampaignRules rules = campaign.Rules; CampaignState state = campaign.State; List list = m.OnSide(side).ToList(); if (list.Count == 0 || enemyTierDowned <= 0.0) { return; } double num = enemyTierDowned * rules.XpPerEnemyTier; double num2 = list.Sum((Combatant c) => (!c.EverDeployed) ? rules.ReserveXpFactor : 1.0); Dictionary<(string, string), double> dictionary = new Dictionary<(string, string), double>(); foreach (Combatant item in list) { if (!item.IsHero && outcomes[item.Id] != CombatOutcome.Downed && !(num2 <= 0.0) && !(num <= 0.0)) { double num3 = (item.EverDeployed ? 1.0 : rules.ReserveXpFactor); (string, string) key = (item.PartyId, item.UnitId); dictionary.TryGetValue(key, out var value); dictionary[key] = value + num * num3 / num2; } } foreach (KeyValuePair<(string, string), double> item2 in dictionary.OrderBy, string>((KeyValuePair<(string party, string unit), double> k) => k.Key.party, StringComparer.Ordinal).ThenBy, string>((KeyValuePair<(string party, string unit), double> k) => k.Key.unit, StringComparer.Ordinal)) { Party party = state.Parties.Get(item2.Key.Item1); int num4 = (int)Math.Round(item2.Value * (1.0 + Math.Max(0.0, campaign.PartyPerk(party, PerkEffect.TroopBattleXp)))); party?.Troops.AddXp(item2.Key.Item2, num4); if (party != null) { reports[party.Id].Xp += num4; } } Party party2 = state.Parties.Get(enc.PartiesOn(side).FirstOrDefault() ?? ""); Hero hero = state.Heroes.Get(party2?.LeaderHeroId ?? ""); if (hero != null) { campaign.GrantSkillExperience(hero, "tactics", enemyTierDowned * 2.0, grantHeroXp: false); campaign.GrantSkillExperience(hero, "leadership", enemyTierDowned, grantHeroXp: false); } int xp = (int)Math.Min(2147483647.0, Math.Round(enemyTierDowned * 5.0)); HashSet trained = new HashSet(StringComparer.Ordinal); foreach (Combatant item3 in from c in list where c.IsHero && c.EverDeployed group c by c.HeroId into g select g.First()) { Hero hero2 = state.Heroes.Get(item3.HeroId); if (hero2 != null) { trained.Add(hero2.Id); long xp2 = hero2.Xp; campaign.GrantHeroExperience(hero2, xp); campaign.TrainBattleSkills(item3, hero2, enemyTierDowned, credits?.FirstOrDefault((HeroBattleCredit x) => x.HeroId == hero2.Id)); reports[item3.PartyId].HeroXp += Math.Max(0L, hero2.Xp - xp2); } } if (credits == null || !enc.PlayerInvolved || enc.PlayerSide != side) { return; } foreach (HeroBattleCredit item4 in credits.Where((HeroBattleCredit x) => x.Possessed && x.HeroId == state.PlayerHeroId && !trained.Contains(x.HeroId))) { Hero playerHero = state.PlayerHero; long num5 = playerHero?.Xp ?? 0; campaign.TrainBattleSkills(null, playerHero, enemyTierDowned, item4, participated: false); Party playerParty = state.PlayerParty; if (playerHero != null && playerParty != null && reports.TryGetValue(playerParty.Id, out var value2)) { value2.HeroXp += Math.Max(0L, playerHero.Xp - num5); } } } private static void HandleLeaderLoss(TabsBannerlord.Core.Campaign.Campaign campaign, Party p, PartyBattleReport pr) { if (campaign.MilitaryPartyFor(p) != null) { return; } CampaignState state = campaign.State; if ((p.Kind != PartyKind.Lord && p.Kind != PartyKind.Caravan) || string.IsNullOrEmpty(p.LeaderHeroId)) { return; } Hero hero = state.Heroes.Get(p.LeaderHeroId); if (hero != null && hero.State == HeroState.Active && p.Troops.Heroes.Contains(hero.Id)) { return; } if (p.Kind == PartyKind.Caravan) { int totalTroops = p.Troops.TotalTroops; p.Troops.Stacks.Clear(); DestroyParty(campaign, p, "caravan leader lost"); if (totalTroops > 0) { state.AddLog(LogCategory.Battle, $"{totalTroops} guards of {p.Name} scattered after losing their leader.", p.Id); } pr.Destroyed = true; return; } Settlement settlement = state.Settlements.Get(p.HomeSettlementId); int num = 0; if (settlement != null && settlement.OwnerClanId == p.ClanId) { foreach (TroopStack stack in p.Troops.Stacks) { settlement.Garrison.Add(stack.UnitId, stack.Healthy, stack.Wounded); num += stack.Total; } foreach (TroopStack stack2 in p.Prisoners.Stacks) { settlement.Prisoners.Add(stack2.UnitId, stack2.Healthy, stack2.Wounded); } } int num2 = p.Troops.TotalTroops - num; p.Troops.Stacks.Clear(); p.Prisoners.Stacks.Clear(); foreach (string item in p.Troops.Heroes.ToList()) { Hero hero2 = state.Heroes.Get(item); if (hero2 != null && hero2.PartyId == p.Id) { if (hero2.Occupation == HeroOccupation.Companion) { campaign.ShelterCompanion(hero2, p.Position, "their party lost its leader"); continue; } hero2.PartyId = ""; hero2.SettlementId = p.HomeSettlementId; } } p.Troops.Heroes.Clear(); DestroyParty(campaign, p, (num > 0) ? $"leader lost; {num} troops returned to {settlement?.Name}" : "leader lost"); if (num2 > 0) { state.AddLog(LogCategory.Battle, $"{num2} troops of {p.Name} scattered after losing their leader.", p.Id); } pr.Destroyed = true; } public static void DestroyParty(TabsBannerlord.Core.Campaign.Campaign campaign, Party p, string reason) { CampaignState state = campaign.State; if (p.State == PartyState.Destroyed) { return; } p.State = PartyState.Destroyed; p.EncounterId = ""; p.RoleAssignments?.Clear(); p.Cargo?.Clear(); p.Equipment?.Clear(); p.Food = 0.0; if (p.Kind == PartyKind.Caravan) { p.Gold = 0L; } campaign.ClearOrder(p); foreach (string item in p.Troops.Heroes.ToList()) { Hero hero = state.Heroes.Get(item); if (hero != null && hero.PartyId == p.Id) { if (hero.Occupation == HeroOccupation.Companion) { campaign.ShelterCompanion(hero, p.Position, "their party was destroyed"); continue; } hero.PartyId = ""; hero.SettlementId = p.HomeSettlementId; } } p.Troops.Heroes.Clear(); foreach (string item2 in p.Prisoners.Heroes.ToList()) { ReleaseHero(campaign, state.Heroes.Get(item2), "freed when their captors were destroyed"); } p.Prisoners.Heroes.Clear(); p.Prisoners.Stacks.Clear(); state.PlayerSightings.Remove(p.Id); state.AddLog(LogCategory.Battle, p.Name + " was destroyed (" + reason + ").", p.Id); } public static void CaptureHero(TabsBannerlord.Core.Campaign.Campaign campaign, Hero hero, Party captor, bool deferCompanionRecovery = false) { if (hero == null || captor == null || hero.State == HeroState.Dead || (hero.State == HeroState.Captive && hero.CaptorPartyId == captor.Id)) { return; } CampaignState state = campaign.State; campaign.ClearHeroRoleAssignments(hero.Id); campaign.ClearHeroGovernorAssignments(hero.Id); state.Parties.Get(hero.CaptorPartyId)?.Prisoners.Heroes.Remove(hero.Id); state.Settlements.Get(hero.CaptorSettlementId)?.Prisoners.Heroes.Remove(hero.Id); Party party = state.Parties.Get(hero.PartyId); party?.Troops.Heroes.Remove(hero.Id); hero.PartyId = ""; hero.SettlementId = ""; hero.State = HeroState.Captive; hero.CaptorPartyId = captor.Id; hero.CaptorSettlementId = ""; hero.CaptiveSinceMinute = state.Clock.Minute; if (!captor.Prisoners.Heroes.Contains(hero.Id)) { captor.Prisoners.Heroes.Add(hero.Id); } state.AddLog(LogCategory.Captivity, hero.Name + " was taken prisoner by " + captor.Name + ".", hero.Id, captor.Id); if (captor.Id == state.PlayerPartyId) { campaign.RememberHero(hero, "captured"); } if (hero.IsPlayer) { state.Player.Activity = PlayerActivity.Captive; state.Player.CaptorPartyId = captor.Id; state.Player.CaptorSettlementId = ""; state.Player.CaptiveSinceMinute = state.Clock.Minute; bool flag = state.Clans.Get(captor.ClanId)?.IsBandit ?? false; state.Player.CaptivityMaxDays = (flag ? campaign.Rules.BanditMaxCaptivityDays : campaign.Rules.LordMaxCaptivityDays); Party playerParty = state.PlayerParty; if (playerParty != null && playerParty.State != PartyState.Destroyed) { playerParty.Troops.Stacks.Clear(); playerParty.Prisoners.Stacks.Clear(); campaign.SeizeCargo(playerParty, captor); playerParty.Food = 0.0; playerParty.State = PartyState.Disbanded; campaign.ClearOrder(playerParty); } campaign.Raise(CampaignEventKind.Captured, captor.Name + " has taken you prisoner.", true, captor.Id); if (!deferCompanionRecovery) { campaign.RecoverSeparatedCompanions(); } } if (!deferCompanionRecovery && party != null && party.Kind == PartyKind.Caravan) { campaign.ReconcileCaravans(); } if (!deferCompanionRecovery) { campaign.ReconcileMilitaryParties(); } } public static void ReleaseHero(TabsBannerlord.Core.Campaign.Campaign campaign, Hero hero, string reason) { if (hero == null || hero.State != HeroState.Captive) { return; } CampaignState state = campaign.State; Party party = state.Parties.Get(hero.CaptorPartyId); party?.Prisoners.Heroes.Remove(hero.Id); Settlement settlement = state.Settlements.Get(hero.CaptorSettlementId); settlement?.Prisoners.Heroes.Remove(hero.Id); Vec2 vec = party?.Position ?? settlement?.Position ?? state.PlayerParty?.Position ?? Vec2.Zero; campaign.ClearHeroRoleAssignments(hero.Id); campaign.ClearHeroGovernorAssignments(hero.Id); hero.State = HeroState.Active; hero.PartyId = ""; hero.CaptorPartyId = ""; hero.CaptorSettlementId = ""; if (hero.IsPlayer) { campaign.OnPlayerReleased(reason); return; } if (hero.Occupation == HeroOccupation.Companion) { campaign.ShelterCompanion(hero, vec, reason); return; } state.Clans.Get(hero.ClanId); Settlement settlement2 = state.Settlements.FirstOrDefault((Settlement s) => s.OwnerClanId == hero.ClanId); hero.SettlementId = settlement2?.Id ?? ""; state.AddLog(LogCategory.Captivity, hero.Name + " was released (" + reason + ").", hero.Id); } private static void KillHero(TabsBannerlord.Core.Campaign.Campaign campaign, Hero hero, Party party) { CampaignState state = campaign.State; hero.State = HeroState.Dead; if (hero.Loadout != null) { if (!hero.Loadout.SlotItems().Any()) { SortedDictionary clothing = hero.Loadout.Clothing; if (clothing == null || !clothing.Values.Any((WornClothingState w) => !string.IsNullOrEmpty(w?.PieceId))) { goto IL_008c; } } state.AddLog(LogCategory.Economy, hero.Name + "'s equipped items were lost with them.", hero.Id); } goto IL_008c; IL_008c: foreach (string item in hero.Loadout?.SlotItems().ToList() ?? new List()) { if (Smithing.IsCraftedId(item)) { state.Smithing?.Weapons?.Remove(item); } } hero.Loadout = null; campaign.ClearHeroRoleAssignments(hero.Id); campaign.ClearHeroGovernorAssignments(hero.Id); party?.Troops.Heroes.Remove(hero.Id); hero.PartyId = ""; hero.SettlementId = ""; state.AddLog(LogCategory.Battle, hero.Name + " has fallen in battle.", hero.Id); campaign.OnHeroDied(hero); } private static string Summarize(TabsBannerlord.Core.Campaign.Campaign campaign, Encounter enc, BattleResult result, BattleReport report) { string text = Names(BattleSide.Attacker); string text2 = Names(BattleSide.Defender); string text3 = (result.Simulated ? " (simulated)" : ""); switch (result.EndKind) { case BattleEndKind.MutualDestruction: return text + " and " + text2 + " destroyed each other" + text3 + "."; case BattleEndKind.Retreat: return $"{Names(result.LosingSide)} retreated from {Names((result.LosingSide == BattleSide.Attacker) ? BattleSide.Defender : BattleSide.Attacker)}{text3}. Losses {Lost(BattleSide.Attacker)} / {Lost(BattleSide.Defender)}."; case BattleEndKind.Surrender: return Names(result.LosingSide) + " surrendered to " + Names((result.LosingSide == BattleSide.Attacker) ? BattleSide.Defender : BattleSide.Attacker) + "."; default: { string text4 = ((result.Winner == WinnerSide.Attacker) ? text : text2); string text5 = ((result.Winner == WinnerSide.Attacker) ? text2 : text); return $"{text4} defeated {text5}{text3}. Losses {Lost(BattleSide.Attacker)} / {Lost(BattleSide.Defender)}."; } } int Lost(BattleSide s) { return report.Parties.Where((PartyBattleReport p) => p.Side == s).Sum((PartyBattleReport p) => p.Killed + p.Wounded + p.Captured); } string Names(BattleSide s) { return string.Join(" & ", from id in enc.PartiesOn(s) select campaign.State.Parties.Get(id)?.Name ?? id); } } } public sealed class ReinforcementConfig { public int Budget = 120; public double MinSideShare = 0.3; public double IntervalSeconds = 8.0; public double CountdownSeconds = 3.0; public int MinBatch = 6; public int MaxSpawnPerFrame = 4; public double WorkloadBudget = 192.0; public double EntryBlockedTimeoutSeconds = 30.0; public double QueueAgingSeconds = 20.0; public static ReinforcementConfig FromRules(CampaignRules r, int budget) { return new ReinforcementConfig { Budget = budget, MinSideShare = r.MinSideShare, IntervalSeconds = r.ReinforcementIntervalSeconds, CountdownSeconds = r.ArrivalCountdownSeconds, MinBatch = r.MinReinforcementBatch, MaxSpawnPerFrame = r.MaxSpawnPerFrame, WorkloadBudget = (double)budget * r.WorkloadBudgetFactor, EntryBlockedTimeoutSeconds = r.EntryBlockedTimeoutSeconds, QueueAgingSeconds = r.QueueAgingSeconds }; } } public enum DelayReason { None, NoReserves, WaitingForCapacity, WaitingForInterval, WaitingForBatch, WorkloadLimit, NoEntryZone, Withdrawn } public sealed class EntryZoneState { public string Id = ""; public BattleSide Side; public bool Blocked; public string Direction = ""; } public sealed class ScheduledArrival { public int Id; public BattleSide Side; public List Combatants = new List(); public string ZoneId = ""; public double ScheduledAt; public double ArriveAt; public bool Dispatched; } public sealed class SpawnRequest { public int ArrivalId; public int CombatantId; public string ZoneId = ""; public BattleSide Side; public bool Initial; } public sealed class SideStatus { public BattleSide Side; public int Active; public int Temporary; public int Incoming; public int Reserve; public int Resolved; public int Withdrawn; public int Quota; public DelayReason Delay; public SortedDictionary NextCandidate = new SortedDictionary(StringComparer.Ordinal); public double? NextArrivalIn; public bool Retreating; } public sealed class BattleEvaluation { public bool Finished; public WinnerSide Winner; public BattleEndKind EndKind; public BattleSide LosingSide; public bool EntryProblem; public BattleSide EntryProblemSide; } public sealed class ReinforcementScheduler { private sealed class TemporaryReservation { public BattleSide Side; public int Slots; public double Workload; } public readonly BattleManifest Manifest; public readonly ReinforcementConfig Config; private readonly List _zones; private readonly Dictionary _lastArrival = new Dictionary(); private readonly Dictionary _blockedSince = new Dictionary(); private readonly Dictionary _delay = new Dictionary(); private readonly Dictionary _quota = new Dictionary(); private readonly HashSet _retreating = new HashSet(); private readonly List _arrivals = new List(); private readonly Queue _pending = new Queue(); private readonly List _announcements = new List(); private readonly Dictionary _temporary = new Dictionary(); private readonly Func _unitName; private int _nextArrivalId = 1; private bool _started; private static readonly BattleSide[] Sides = new BattleSide[2] { BattleSide.Attacker, BattleSide.Defender }; public double Now { get; private set; } public IReadOnlyList Arrivals => _arrivals; public int PendingSpawnCount => _pending.Count; public ReinforcementScheduler(BattleManifest manifest, ReinforcementConfig config, IEnumerable zones, Func unitName = null) { Manifest = manifest; Config = config; _zones = zones?.ToList() ?? new List(); _unitName = unitName ?? ((Func)((string s) => s)); BattleSide[] sides = Sides; for (int num = 0; num < sides.Length; num++) { BattleSide side = sides[num]; _lastArrival[side] = double.NegativeInfinity; _blockedSince[side] = double.NaN; _delay[side] = DelayReason.None; _quota[side] = 0; if (!_zones.Any((EntryZoneState z) => z.Side == side)) { _zones.Add(new EntryZoneState { Id = side.ToString() + "-default", Side = side, Direction = ((side == BattleSide.Attacker) ? "your edge" : "the enemy edge") }); } } } public bool TryReserveTemporary(int token, BattleSide side, int slots, double workload) { if (token <= 0 || (side != BattleSide.Attacker && side != BattleSide.Defender) || slots <= 0 || workload <= 0.0 || double.IsNaN(workload) || double.IsInfinity(workload)) { return false; } if (_temporary.TryGetValue(token, out var value)) { if (value.Side == side && value.Slots == slots) { return value.Workload == workload; } return false; } if (_retreating.Contains(side)) { return false; } if (slots > (long)Config.Budget - (long)UsedSlots() || workload > Config.WorkloadBudget - UsedWorkload() + 1E-09) { return false; } _temporary.Add(token, new TemporaryReservation { Side = side, Slots = slots, Workload = workload }); return true; } public bool ReleaseTemporary(int token) { return _temporary.Remove(token); } public int CountTemporary(BattleSide side) { return _temporary.Values.Count((TemporaryReservation t) => t.Side == side); } public void ClearTemporary(BattleSide? side = null) { if (!side.HasValue) { _temporary.Clear(); return; } foreach (int item in (from p in _temporary where p.Value.Side == side.Value select p.Key).ToList()) { _temporary.Remove(item); } } public void SelectInitial(BattleSide side, IEnumerable ids, int allowance) { if (_started) { throw new InvalidOperationException("Initial deployment is already committed."); } int num = 0; HashSet hashSet = new HashSet(); foreach (int id in ids) { Combatant combatant = Manifest.Get(id) ?? throw new ArgumentException("Unknown combatant " + id); if (combatant.Side != side) { throw new ArgumentException($"Combatant {id} is not on side {side}"); } if (!hashSet.Add(id)) { throw new ArgumentException($"Combatant {id} selected twice"); } if (combatant.State != DeploymentState.Reserve) { throw new ArgumentException($"Combatant {id} is not in reserve"); } num += combatant.Slots; } if (num > allowance) { throw new ArgumentException($"Selection uses {num} slots but the allowance is {allowance}"); } foreach (int item in hashSet) { Manifest.Get(item).State = DeploymentState.Scheduled; _pending.Enqueue(new SpawnRequest { CombatantId = item, Side = side, Initial = true, ZoneId = (ZoneFor(side)?.Id ?? "") }); } _quota[side] = allowance; } public List TakeInitialSpawns() { List list = new List(); while (_pending.Count > 0 && _pending.Peek().Initial) { list.Add(_pending.Dequeue()); } return list; } public void StartCombat() { _started = true; BattleSide[] sides = Sides; foreach (BattleSide battleSide in sides) { if (CountActive(battleSide) + CountScheduled(battleSide) > 0) { _lastArrival[battleSide] = 0.0; } } } public void OnSpawned(int id) { Combatant combatant = Manifest.Get(id); if (combatant != null && combatant.State == DeploymentState.Scheduled) { combatant.State = DeploymentState.Active; combatant.EverDeployed = true; } } public void OnSpawnFailed(int id, string reason) { Combatant combatant = Manifest.Get(id); if (combatant != null && combatant.State == DeploymentState.Scheduled) { combatant.State = (_retreating.Contains(combatant.Side) ? DeploymentState.Withdrawn : DeploymentState.Reserve); combatant.Priority = -1 - id; combatant.WaitingSince = Now; _announcements.Add("Spawn of " + _unitName(combatant.UnitId) + " failed (" + reason + "); returned to reserve."); } } public void OnExited(int id, CombatOutcome outcome) { Combatant combatant = Manifest.Get(id); if (combatant != null && combatant.State == DeploymentState.Active) { combatant.State = DeploymentState.Exited; combatant.Outcome = ((outcome == CombatOutcome.Fled) ? CombatOutcome.Fled : CombatOutcome.Downed); } } public bool OnRevived(int id) { Combatant combatant = Manifest.Get(id); if (combatant == null || combatant.State != DeploymentState.Exited || combatant.Outcome != CombatOutcome.Downed) { return false; } if (UsedSlots() + combatant.Slots > Config.Budget) { return false; } if (UsedWorkload() + combatant.Workload > Config.WorkloadBudget + 1E-09) { return false; } combatant.State = DeploymentState.Active; combatant.Outcome = CombatOutcome.Pending; return true; } public void SetZones(IEnumerable zones) { _zones.Clear(); _zones.AddRange(zones); BattleSide[] sides = Sides; for (int i = 0; i < sides.Length; i++) { BattleSide side = sides[i]; if (!_zones.Any((EntryZoneState z) => z.Side == side)) { _zones.Add(new EntryZoneState { Id = side.ToString() + "-default", Side = side, Direction = ((side == BattleSide.Attacker) ? "your edge" : "the enemy edge") }); } } foreach (SpawnRequest r in _pending) { if (!_zones.Any((EntryZoneState z) => z.Id == r.ZoneId)) { r.ZoneId = ZoneFor(r.Side)?.Id ?? ""; } } } public void SetZoneBlocked(string zoneId, bool blocked) { EntryZoneState entryZoneState = _zones.FirstOrDefault((EntryZoneState x) => x.Id == zoneId); if (entryZoneState != null) { entryZoneState.Blocked = blocked; } } public void RetreatGroup(BattleSide side, string group) { foreach (Combatant item in from c in Manifest.OnSide(side) where c.Group == @group select c) { if (item.State == DeploymentState.Reserve || item.State == DeploymentState.Scheduled) { item.State = DeploymentState.Withdrawn; } } CleanupArrivals(); _announcements.Add($"{side} {group} withdrawing; their reinforcements are cancelled."); } public void RetreatAll(BattleSide side) { _retreating.Add(side); foreach (Combatant item in Manifest.OnSide(side)) { if (item.State == DeploymentState.Reserve || item.State == DeploymentState.Scheduled) { item.State = DeploymentState.Withdrawn; } } CleanupArrivals(); _announcements.Add($"{side} is retreating from the field."); } public bool IsRetreating(BattleSide side) { return _retreating.Contains(side); } public void CompleteRetreat(BattleSide side) { if (!_retreating.Contains(side)) { return; } foreach (Combatant item in from c in Manifest.OnSide(side) where c.State == DeploymentState.Active select c) { item.State = DeploymentState.Exited; item.Outcome = CombatOutcome.Fled; } ClearTemporary(side); } private void CleanupArrivals() { foreach (ScheduledArrival arrival in _arrivals) { arrival.Combatants.RemoveAll((int id) => Manifest.Get(id).State != DeploymentState.Scheduled); } _arrivals.RemoveAll((ScheduledArrival a) => a.Combatants.Count == 0); List list = _pending.Where((SpawnRequest r) => Manifest.Get(r.CombatantId).State == DeploymentState.Scheduled).ToList(); _pending.Clear(); foreach (SpawnRequest item in list) { _pending.Enqueue(item); } } private int CountActive(BattleSide s) { return Manifest.OnSide(s).Count((Combatant c) => c.State == DeploymentState.Active); } private int CountScheduled(BattleSide s) { return Manifest.OnSide(s).Count((Combatant c) => c.State == DeploymentState.Scheduled); } private int SlotsInUse(BattleSide s) { return (from c in Manifest.OnSide(s) where c.State == DeploymentState.Active || c.State == DeploymentState.Scheduled select c).Sum((Combatant c) => c.Slots) + _temporary.Values.Where((TemporaryReservation t) => t.Side == s).Sum((TemporaryReservation t) => t.Slots); } private int ReserveSlots(BattleSide s) { return (from c in Manifest.OnSide(s) where c.State == DeploymentState.Reserve select c).Sum((Combatant c) => c.Slots); } public int UsedSlots() { return SlotsInUse(BattleSide.Attacker) + SlotsInUse(BattleSide.Defender); } public double UsedWorkload() { return Manifest.Combatants.Where((Combatant c) => c.State == DeploymentState.Active || c.State == DeploymentState.Scheduled).Sum((Combatant c) => c.Workload) + _temporary.Values.Sum((TemporaryReservation t) => t.Workload); } private EntryZoneState ZoneFor(BattleSide side) { return _zones.FirstOrDefault((EntryZoneState z) => z.Side == side && !z.Blocked); } public void Tick(double dt) { if (dt < 0.0) { dt = 0.0; } Now += dt; if (!_started) { return; } int attackerSlots = SlotsInUse(BattleSide.Attacker) + ReserveSlots(BattleSide.Attacker); int defenderSlots = SlotsInUse(BattleSide.Defender) + ReserveSlots(BattleSide.Defender); var (value, value2) = SlotAllocator.Allocate(Config.Budget, attackerSlots, defenderSlots, Config.MinSideShare); _quota[BattleSide.Attacker] = value; _quota[BattleSide.Defender] = value2; Dictionary dictionary = new Dictionary(); BattleSide[] sides = Sides; foreach (BattleSide battleSide in sides) { dictionary[battleSide] = DesiredWave(battleSide); } int num = Math.Max(0, Config.Budget - UsedSlots()); int num2 = dictionary[BattleSide.Attacker] + dictionary[BattleSide.Defender]; if (num2 > num) { int num3 = ((num2 != 0) ? ((int)Math.Floor((double)num * (double)dictionary[BattleSide.Attacker] / (double)num2)) : 0); int num4 = ((num2 != 0) ? ((int)Math.Floor((double)num * (double)dictionary[BattleSide.Defender] / (double)num2)) : 0); int num5 = num - num3 - num4; if (num5 > 0) { if (CountActive(BattleSide.Defender) + CountTemporary(BattleSide.Defender) < CountActive(BattleSide.Attacker) + CountTemporary(BattleSide.Attacker)) { num4 += num5; } else { num3 += num5; } } dictionary[BattleSide.Attacker] = Math.Min(dictionary[BattleSide.Attacker], num3); dictionary[BattleSide.Defender] = Math.Min(dictionary[BattleSide.Defender], num4); sides = Sides; foreach (BattleSide key in sides) { if (dictionary[key] == 0 && _delay[key] == DelayReason.None) { _delay[key] = DelayReason.WaitingForCapacity; } } } sides = Sides; foreach (BattleSide battleSide2 in sides) { if (dictionary[battleSide2] > 0) { ScheduleWave(battleSide2, dictionary[battleSide2]); } } foreach (ScheduledArrival item in (from x in _arrivals where !x.Dispatched && x.ArriveAt <= Now + 1E-09 orderby x.ArriveAt, x.Id select x).ToList()) { item.Dispatched = true; foreach (int combatant in item.Combatants) { if (Manifest.Get(combatant).State == DeploymentState.Scheduled) { _pending.Enqueue(new SpawnRequest { ArrivalId = item.Id, CombatantId = combatant, ZoneId = item.ZoneId, Side = item.Side }); } } } _arrivals.RemoveAll((ScheduledArrival a) => a.Dispatched); } private int DesiredWave(BattleSide side) { if (_retreating.Contains(side)) { _delay[side] = DelayReason.Withdrawn; return 0; } List list = (from c in Manifest.OnSide(side) where c.State == DeploymentState.Reserve select c).ToList(); if (list.Count == 0) { _delay[side] = DelayReason.NoReserves; return 0; } int num = Math.Max(0, _quota[side] - SlotsInUse(side)); if (num == 0) { _delay[side] = DelayReason.WaitingForCapacity; return 0; } bool flag = CountActive(side) + CountScheduled(side) + CountTemporary(side) == 0; if (!flag && Now - _lastArrival[side] < Config.IntervalSeconds) { _delay[side] = DelayReason.WaitingForInterval; return 0; } bool flag2 = list.Sum((Combatant c) => c.Slots) <= num; int num2 = Math.Min(Config.MinBatch, Math.Max(1, _quota[side] / 4)); if (!flag && !flag2 && num < num2) { _delay[side] = DelayReason.WaitingForBatch; return 0; } if (ZoneFor(side) == null) { _delay[side] = DelayReason.NoEntryZone; if (double.IsNaN(_blockedSince[side])) { _blockedSince[side] = Now; } return 0; } _blockedSince[side] = double.NaN; _delay[side] = DelayReason.None; return num; } private void ScheduleWave(BattleSide side, int slotBudget) { EntryZoneState entryZoneState = ZoneFor(side); if (entryZoneState == null) { return; } List list = (from c in Manifest.OnSide(side) where c.State == DeploymentState.Reserve orderby c.Priority, c.Id select c).ToList(); double num = Config.WorkloadBudget - UsedWorkload(); bool flag = CountActive(side) + CountScheduled(side) + CountTemporary(side) == 0; List list2 = new List(); int num2 = 0; foreach (Combatant item in list) { if (num2 + item.Slots > slotBudget) { continue; } bool flag2 = item.Workload <= num + 1E-09; if (!flag2 && flag && list2.Count == 0 && _temporary.Count == 0 && UsedWorkload() <= Config.WorkloadBudget) { flag2 = true; } if (!flag2) { if (double.IsNaN(item.WaitingSince) || item.WaitingSince <= 0.0) { item.WaitingSince = Now; } if (Now - item.WaitingSince >= Config.QueueAgingSeconds) { if (list2.Count == 0) { _delay[side] = DelayReason.WorkloadLimit; } break; } } else { list2.Add(item); num2 += item.Slots; num -= item.Workload; if (num2 >= slotBudget) { break; } } } if (list2.Count == 0) { if (_delay[side] == DelayReason.None) { _delay[side] = DelayReason.WorkloadLimit; } return; } ScheduledArrival scheduledArrival = new ScheduledArrival { Id = _nextArrivalId++, Side = side, ZoneId = entryZoneState.Id, ScheduledAt = Now, ArriveAt = Now + (flag ? 0.0 : Config.CountdownSeconds) }; foreach (Combatant item2 in list2) { item2.State = DeploymentState.Scheduled; item2.WaitingSince = 0.0; scheduledArrival.Combatants.Add(item2.Id); } _arrivals.Add(scheduledArrival); _lastArrival[side] = Now; string arg = string.Join(", ", from g in (from c in list2 group c by c.UnitId).OrderBy, string>((IGrouping g) => g.Key, StringComparer.Ordinal) select g.Count() + " " + _unitName(g.Key)); _announcements.Add($"{side} reinforcements ({arg}) arriving from {entryZoneState.Direction}" + ((scheduledArrival.ArriveAt > Now) ? $" in {scheduledArrival.ArriveAt - Now:0}s." : " now.")); } public List TakeSpawnRequests() { List list = new List(); while (_pending.Count > 0 && list.Count < Config.MaxSpawnPerFrame) { list.Add(_pending.Dequeue()); } return list; } public List DrainAnnouncements() { List result = new List(_announcements); _announcements.Clear(); return result; } public SideStatus Status(BattleSide side) { SideStatus sideStatus = new SideStatus { Side = side, Quota = _quota[side], Delay = _delay[side], Retreating = _retreating.Contains(side), Temporary = CountTemporary(side) }; using (IEnumerator enumerator = Manifest.OnSide(side).GetEnumerator()) { while (enumerator.MoveNext()) { switch (enumerator.Current.State) { case DeploymentState.Active: sideStatus.Active++; break; case DeploymentState.Scheduled: sideStatus.Incoming++; break; case DeploymentState.Reserve: sideStatus.Reserve++; break; case DeploymentState.Exited: sideStatus.Resolved++; break; case DeploymentState.Withdrawn: sideStatus.Withdrawn++; break; } } } ScheduledArrival scheduledArrival = (from a in _arrivals where a.Side == side && !a.Dispatched orderby a.ArriveAt select a).FirstOrDefault(); if (scheduledArrival != null) { sideStatus.NextArrivalIn = Math.Max(0.0, scheduledArrival.ArriveAt - Now); } int num = Math.Max(Config.MinBatch, _quota[side] - SlotsInUse(side)); int num2 = 0; foreach (Combatant item in from c in Manifest.OnSide(side) where c.State == DeploymentState.Reserve orderby c.Priority, c.Id select c) { if (num2 + item.Slots > num) { break; } sideStatus.NextCandidate.TryGetValue(item.UnitId, out var value); sideStatus.NextCandidate[item.UnitId] = value + 1; num2 += item.Slots; } return sideStatus; } public BattleEvaluation Evaluate() { BattleEvaluation battleEvaluation = new BattleEvaluation(); Dictionary dictionary = new Dictionary(); BattleSide[] sides = Sides; foreach (BattleSide battleSide in sides) { dictionary[battleSide] = Manifest.OnSide(battleSide).Count((Combatant c) => c.State == DeploymentState.Active || c.State == DeploymentState.Scheduled || c.State == DeploymentState.Reserve) + CountTemporary(battleSide); } sides = Sides; foreach (BattleSide battleSide2 in sides) { if (!double.IsNaN(_blockedSince[battleSide2]) && Now - _blockedSince[battleSide2] >= Config.EntryBlockedTimeoutSeconds) { battleEvaluation.EntryProblem = true; battleEvaluation.EntryProblemSide = battleSide2; } } sides = Sides; foreach (BattleSide battleSide3 in sides) { BattleSide battleSide4 = ((battleSide3 == BattleSide.Attacker) ? BattleSide.Defender : BattleSide.Attacker); if (_retreating.Contains(battleSide3) && CountActive(battleSide3) == 0 && CountScheduled(battleSide3) == 0 && CountTemporary(battleSide3) == 0) { battleEvaluation.Finished = true; battleEvaluation.EndKind = BattleEndKind.Retreat; battleEvaluation.LosingSide = battleSide3; battleEvaluation.Winner = ((battleSide4 == BattleSide.Attacker) ? WinnerSide.Attacker : WinnerSide.Defender); return battleEvaluation; } } if (dictionary[BattleSide.Attacker] == 0 && dictionary[BattleSide.Defender] == 0) { battleEvaluation.Finished = true; battleEvaluation.EndKind = BattleEndKind.MutualDestruction; battleEvaluation.Winner = WinnerSide.None; return battleEvaluation; } sides = Sides; foreach (BattleSide battleSide5 in sides) { if (dictionary[battleSide5] == 0) { battleEvaluation.Finished = true; battleEvaluation.EndKind = BattleEndKind.Victory; battleEvaluation.LosingSide = battleSide5; battleEvaluation.Winner = ((battleSide5 != BattleSide.Attacker) ? WinnerSide.Attacker : WinnerSide.Defender); return battleEvaluation; } } return battleEvaluation; } public BattleResult BuildResult(string campaignId, string encounterId, string attemptId, long expectedRevision, BattleEvaluation eval, double duration) { BattleResult battleResult = new BattleResult { CampaignId = campaignId, EncounterId = encounterId, AttemptId = attemptId, ExpectedRevision = expectedRevision, EndKind = eval.EndKind, Winner = eval.Winner, LosingSide = eval.LosingSide, DurationSeconds = duration }; foreach (Combatant combatant in Manifest.Combatants) { CombatOutcome outcome = ((combatant.State != DeploymentState.Exited) ? CombatOutcome.Unhurt : combatant.Outcome); if (eval.EndKind == BattleEndKind.Retreat && combatant.Side == eval.LosingSide && combatant.State == DeploymentState.Active) { outcome = CombatOutcome.Fled; } battleResult.Outcomes.Add(new CombatantResult { Id = combatant.Id, Outcome = outcome }); } return battleResult; } } public sealed class SiegeAssault { public const string MapId = "map.bannerlord_siege_v1"; public const int MapContentVersion = 2; public const double SoloBreachSeconds = 45.0; public const double FullCrewBreachSeconds = 20.0; public const int FullCrewSize = 3; public const double ManualBatteringMultiplier = 5.0; public bool GateOpen { get; private set; } public double GateIntegrity { get; private set; } = 1.0; public bool RamWorking { get; private set; } public bool GateWorking { get; private set; } public double RamIntegrity { get; private set; } public bool HasRam => RamIntegrity > 0.0; public SiegeAssault(double ramIntegrity = 1.0) { if (double.IsNaN(ramIntegrity) || double.IsInfinity(ramIntegrity) || ramIntegrity < 0.0 || ramIntegrity > 1.0) { throw new ArgumentOutOfRangeException("ramIntegrity"); } RamIntegrity = ramIntegrity; } public bool Tick(double seconds, int attackers, int defenders, bool fighting) { RamWorking = false; GateWorking = false; if (GateOpen || !fighting || attackers <= 0 || defenders > 0 || seconds <= 0.0 || double.IsNaN(seconds) || double.IsInfinity(seconds)) { return false; } GateWorking = true; RamWorking = HasRam; int num = Math.Min(attackers, 3); double num2 = 45.0 - 25.0 * (double)(num - 1) / 2.0; num2 *= (HasRam ? (1.0 / (0.35 + 0.65 * RamIntegrity)) : 5.0); GateIntegrity = Math.Max(0.0, GateIntegrity - Math.Min(seconds, 1.0) / num2); if (GateIntegrity > 1E-09) { return false; } GateIntegrity = 0.0; GateOpen = true; RamWorking = false; GateWorking = false; return true; } } } namespace TabsBannerlord.Core.Audio { public enum MusicCue { None, CampaignMap, Battle, Siege, Victory, Defeat, Town, Arena } public enum MusicScene { Outside, CampaignMap, BattleLoading, BattleField, BattleResults, BattleFailed, TownVisit, ArenaField } public static class MusicCues { public static readonly MusicCue[] All = new MusicCue[7] { MusicCue.CampaignMap, MusicCue.Battle, MusicCue.Siege, MusicCue.Victory, MusicCue.Defeat, MusicCue.Town, MusicCue.Arena }; public static readonly string[] CampaignTracks = new string[4] { "bannerlord_campaign_map_loop.wav", "bannerlord_campaign_market_day_loop.wav", "bannerlord_campaign_quiet_roads_loop.wav", "bannerlord_campaign_banners_loop.wav" }; public const double MinCampaignTrackSeconds = 60.0; public static IEnumerable AllFiles => All.SelectMany(Files).Distinct(); public static MusicCue Choose(MusicScene scene, bool siege, bool playerWon) { switch (scene) { case MusicScene.CampaignMap: case MusicScene.BattleLoading: return MusicCue.CampaignMap; case MusicScene.BattleField: if (!siege) { return MusicCue.Battle; } return MusicCue.Siege; case MusicScene.BattleResults: if (!playerWon) { return MusicCue.Defeat; } return MusicCue.Victory; case MusicScene.TownVisit: return MusicCue.Town; case MusicScene.ArenaField: return MusicCue.Arena; default: return MusicCue.None; } } public static bool Loops(MusicCue cue) { if (cue != MusicCue.CampaignMap && cue != MusicCue.Battle && cue != MusicCue.Siege && cue != MusicCue.Town) { return cue == MusicCue.Arena; } return true; } public static string FileName(MusicCue cue) { return cue switch { MusicCue.CampaignMap => CampaignTracks[0], MusicCue.Battle => "bannerlord_battle_loop.wav", MusicCue.Siege => "bannerlord_siege_loop.wav", MusicCue.Victory => "bannerlord_victory.wav", MusicCue.Defeat => "bannerlord_defeat.wav", MusicCue.Town => "bannerlord_town_loop.wav", MusicCue.Arena => "bannerlord_arena_loop.wav", _ => "", }; } public static IReadOnlyList Files(MusicCue cue) { return cue switch { MusicCue.None => new string[0], MusicCue.CampaignMap => CampaignTracks, _ => new string[1] { FileName(cue) }, }; } public static int NextCampaignTrack(int previous, IList usable, Random rng) { List list = new List(); for (int i = 0; i < usable.Count; i++) { if (usable[i] && i != previous) { list.Add(i); } } if (list.Count == 0) { if (previous < 0 || previous >= usable.Count || !usable[previous]) { return -1; } return previous; } return list[rng.Next(list.Count)]; } public static double HandOffTime(double loopSeconds, double played, double lead) { if (loopSeconds <= 0.0) { return double.PositiveInfinity; } double val = Math.Max(Math.Ceiling(60.0 / loopSeconds - 1E-09), Math.Ceiling((played + lead) / loopSeconds - 1E-09)); return Math.Max(1.0, val) * loopSeconds; } } public enum UiSound { Click, Confirm, Deny, Open, Close } public static class UiSounds { public static readonly UiSound[] All = new UiSound[5] { UiSound.Click, UiSound.Confirm, UiSound.Deny, UiSound.Open, UiSound.Close }; public static string FileName(UiSound sound) { return sound switch { UiSound.Confirm => "ui_confirm.wav", UiSound.Deny => "ui_deny.wav", UiSound.Open => "ui_open.wav", UiSound.Close => "ui_close.wav", _ => "ui_click.wav", }; } public static int Priority(UiSound sound) { switch (sound) { case UiSound.Open: case UiSound.Close: return 3; case UiSound.Confirm: return 2; case UiSound.Deny: return 1; default: return 0; } } public static UiSound Merge(UiSound? chosen, UiSound requested) { if (!chosen.HasValue || Priority(chosen.Value) < Priority(requested)) { return requested; } return chosen.Value; } public static UiSound? ForPanelChange(int before, int after) { if (before == after) { return null; } if ((after & ~before) != 0) { return UiSound.Open; } return UiSound.Close; } } public sealed class PcmAudio { public int Channels; public int SampleRate; public float[] Samples = new float[0]; public int Frames { get { if (Channels > 0) { return Samples.Length / Channels; } return 0; } } public double Seconds { get { if (SampleRate > 0) { return (double)Frames / (double)SampleRate; } return 0.0; } } } public static class WavFile { public const int ImaAdpcm = 17; private static readonly int[] StepTable = new int[89] { 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767 }; private static readonly int[] IndexTable = new int[16] { -1, -1, -1, -1, 2, 4, 6, 8, -1, -1, -1, -1, 2, 4, 6, 8 }; public static PcmAudio Load(string path) { return Read(File.ReadAllBytes(path)); } public static PcmAudio Read(byte[] bytes) { if (bytes == null || bytes.Length < 12 || Tag(bytes, 0) != "RIFF" || Tag(bytes, 8) != "WAVE") { throw new InvalidDataException("Not a RIFF/WAVE file."); } int num = 0; int num2 = 0; int num3 = 0; int num4 = 0; int num5 = -1; int factFrames = -1; int num6 = -1; int num7 = 0; int num8 = 12; while (num8 + 8 <= bytes.Length) { string text = Tag(bytes, num8); long num9 = BitConverter.ToUInt32(bytes, num8 + 4); int num10 = num8 + 8; if (text == "fmt ") { if (num9 < 16 || num10 + 16 > bytes.Length) { throw new InvalidDataException("The WAV format chunk is too short."); } num5 = BitConverter.ToUInt16(bytes, num10); num = BitConverter.ToUInt16(bytes, num10 + 2); num2 = BitConverter.ToInt32(bytes, num10 + 4); num4 = BitConverter.ToUInt16(bytes, num10 + 12); num3 = BitConverter.ToUInt16(bytes, num10 + 14); if (num5 == 65534 && num9 >= 26 && num10 + 26 <= bytes.Length) { num5 = BitConverter.ToUInt16(bytes, num10 + 24); } } else if (text == "fact" && num9 >= 4 && num10 + 4 <= bytes.Length) { factFrames = (int)Math.Min(2147483647u, BitConverter.ToUInt32(bytes, num10)); } else if (text == "data") { num6 = num10; num7 = (int)Math.Min(num9, (long)bytes.Length - (long)num10); break; } long num11 = num10 + num9 + (num9 & 1); if (num11 > int.MaxValue) { break; } num8 = (int)num11; } if (num5 < 0) { throw new InvalidDataException("The WAV file has no format chunk."); } switch (num5) { case 17: if (num < 1 || num > 2) { throw new InvalidDataException("Only mono or stereo WAV files are supported (" + num + " channels)."); } if (num2 <= 0 || num3 != 4 || num4 < 4 * num + 4 * num || (num4 - 4 * num) % (4 * num) != 0) { throw new InvalidDataException("The IMA ADPCM format is invalid."); } if (num6 < 0) { throw new InvalidDataException("The WAV file has no data chunk."); } return ReadImaAdpcm(bytes, num6, num7, num, num2, num4, factFrames); default: throw new InvalidDataException("Only uncompressed PCM WAV files are supported (format " + num5 + ")."); case 1: { if (num3 != 16) { throw new InvalidDataException("Only 16-bit WAV files are supported (" + num3 + "-bit)."); } if (num < 1 || num > 2) { throw new InvalidDataException("Only mono or stereo WAV files are supported (" + num + " channels)."); } if (num2 <= 0) { throw new InvalidDataException("The WAV sample rate is invalid."); } if (num4 != num * 2) { throw new InvalidDataException("The WAV block alignment is invalid."); } if (num6 < 0) { throw new InvalidDataException("The WAV file has no data chunk."); } float[] array = new float[num7 / num4 * num]; int num12 = 0; int num13 = num6; while (num12 < array.Length) { array[num12] = (float)(short)(bytes[num13] | (bytes[num13 + 1] << 8)) / 32768f; num12++; num13 += 2; } return new PcmAudio { Channels = num, SampleRate = num2, Samples = array }; } } } private static PcmAudio ReadImaAdpcm(byte[] bytes, int dataStart, int dataLength, int channels, int rate, int blockAlign, int factFrames) { int num = (blockAlign - 4 * channels) * 2 / channels + 1; int num2 = (dataLength + blockAlign - 1) / blockAlign; int num3 = ((factFrames >= 0) ? factFrames : (num2 * num)); float[] array = new float[((long)num3 * (long)channels <= int.MaxValue) ? (num3 * channels) : 0]; int[] array2 = new int[channels]; int[] array3 = new int[channels]; int num4 = 0; for (int i = 0; i < num2; i++) { if (num4 >= num3) { break; } int num5 = dataStart + i * blockAlign; int num6 = Math.Min(dataStart + dataLength, num5 + blockAlign); if (num5 + 4 * channels > num6) { break; } for (int j = 0; j < channels; j++) { array2[j] = (short)(bytes[num5 + 4 * j] | (bytes[num5 + 4 * j + 1] << 8)); array3[j] = Math.Max(0, Math.Min(88, (int)bytes[num5 + 4 * j + 2])); array[num4 * channels + j] = (float)array2[j] / 32768f; } int num7 = num4 + 1; int num8 = num5 + 4 * channels; int num9 = (num - 1) / 8; for (int k = 0; k < num9; k++) { for (int l = 0; l < channels; l++) { int num10 = 0; while (num10 < 4 && num8 < num6) { int num11 = bytes[num8]; for (int m = 0; m < 2; m++) { int num12 = ((m == 0) ? (num11 & 0xF) : (num11 >> 4)); int num13 = num7 + k * 8 + num10 * 2 + m; int num14 = StepTable[array3[l]]; int num15 = (2 * (num12 & 7) + 1) * num14 >> 3; array2[l] += (((num12 & 8) != 0) ? (-num15) : num15); if (array2[l] > 32767) { array2[l] = 32767; } else if (array2[l] < -32768) { array2[l] = -32768; } array3[l] = Math.Max(0, Math.Min(88, array3[l] + IndexTable[num12])); if (num13 < num3) { array[num13 * channels + l] = (float)array2[l] / 32768f; } } num10++; num8++; } } } num4 = Math.Min(num3, num4 + num); } return new PcmAudio { Channels = channels, SampleRate = rate, Samples = array }; } private static string Tag(byte[] bytes, int offset) { return Encoding.ASCII.GetString(bytes, offset, 4); } } }