-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSkirmishAiSystem.cs
More file actions
1567 lines (1454 loc) · 77.2 KB
/
Copy pathSkirmishAiSystem.cs
File metadata and controls
1567 lines (1454 loc) · 77.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using Nova.AI.Data;
using Nova.Core;
using Nova.Simulation;
using Nova.Simulation.CommandsV1;
using Nova.Simulation.Combat;
using Nova.Simulation.Construction;
using Nova.Simulation.Definitions;
using Nova.Simulation.Economy;
using Nova.Simulation.Pathfinding;
using Nova.Simulation.Production;
using Nova.Simulation.State;
using Nova.Simulation.Victory;
using Nova.Simulation.Vision;
namespace Nova.AI
{
/// <summary>
/// Deterministic MS-1 skirmish opponent (docs/tech/AIArchitecture.md).
/// Plays one slot of the canonical two-slot match — build order, economy,
/// army and attacks — over the SAME command path a human uses: every
/// action is a schema-v1 <see cref="CommandIntent"/> handed to the AI
/// peer's own slot-bound <see cref="CommandIngress"/> (session authority
/// assigns slot, sequence and target tick; <see cref="AiPeerCommandTransport"/>
/// forwards the sealed records into the host intake). No direct calls into
/// construction/production/economy mutation APIs — the executor's
/// state-dependent validation judges every AI order exactly like a UI
/// order (Commands.md section 4).
/// <para>
/// READ BOUNDARY (AIArchitecture.md sections 1 and 6): enemy entities are
/// observed ONLY through <see cref="FogOfWarSystem.GetVisibleEntities"/>
/// — the team's committed view, the single legal sight for targeting.
/// Own-slot data (credits, power, production queues, placements, own unit
/// orders) is read from the canonical systems; a human player has the same
/// own-slot information, so no hidden state leaks into a decision. Static
/// map geometry (registered Aetherium fields, and with them the enemy
/// start area — the demo map seats every base beside its field) is known
/// map knowledge, never fog-hidden entity data. The strict
/// AIArchitecture.md split (a TeamWorldView type and a versioned
/// AiSidecar) does not exist in this slice yet; reading the committed own
/// state directly is the documented G1 simplification, and the system is
/// STATELESS (every decision is a pure function of the tick and the
/// committed state — no timers, no memory), so there is no AI state to
/// serialize and plain <see cref="ISimSystem"/> satisfies the kernel
/// registration checklist. Save/restore therefore reproduces the same
/// later intents without any sidecar block.
/// </para>
/// <para>
/// DECISION LOOP (fixed cadence <see cref="DecisionTickInterval"/> = 20
/// ticks = 2.0 s, ascending-index scans only, no PRNG): (1) build order —
/// Refinery first (no prerequisite since D-077), then the Power plant
/// required by D-103, then Barracks, one site at a time; Power also
/// preempts whenever the committed margin would drop below the profile
/// reserve, the spot picked by a deterministic
/// search validated through <see cref="ConstructionSystem.ValidatePlacement"/>
/// — the identical rules the command executor applies; (2) the Builder is
/// moved next to an unfinished site when it is out of the documented
/// Chebyshev reach <= 1 (ConstructionSystem remarks), and a replacement
/// Builder is queued at the HQ when none is alive; (3) once the Refinery
/// stands, harvesters are queued up to
/// <see cref="AiFactionProfile.TargetHarvesterCount"/>, every idle own
/// harvester receives a Harvest intent on the own field, and harvesters
/// held out of reach are WALKED into the economy's reach rule with
/// explicit Move intents (gather leg toward a field-and-footprint
/// dual-reach cell, return leg toward the footprint — this slice does not
/// use the Refinery's rally point at all, it micro-manages like a human;
/// a rally point WOULD be accepted, see the note at the economy step);
/// (4) once the
/// Barracks stands, infantry is queued up to
/// <see cref="AiFactionProfile.TargetArmySize"/> as funds allow;
/// (5) the army resolves a POSTURE (does it act at all, which target,
/// which destination), then ONE ASSIGNMENT PER UNIT, then submission that
/// groups units sharing an order into a single intent: at
/// <see cref="AiFactionProfile.AttackSquadThreshold"/> living combat units
/// the army is sent toward the enemy start area, and the best scored
/// visible enemy receives an EXPLICIT AttackTarget intent from every unit.
/// There is no attack-move (GB-002), but D-087 DID add auto-acquisition to
/// <see cref="CombatSystem"/>: an idle armed unit picks the nearest
/// visible hostile in range by itself. Explicit orders are never
/// retargeted, so an AI order always wins over the automatic pick — and
/// therefore has to be at least as good as it. The enemy HQ is preferred
/// once visible (D-077: its loss defeats the slot).
/// </para>
/// <para>
/// Rejection tolerance: affordability, the power rule and placement
/// legality are pre-checked against the same rules the executor uses, and
/// redundant re-issues are suppressed by comparing the standing order
/// (move target, attack target, harvest field) before
/// submitting. Anything still rejected (e.g. backpressure) is simply
/// retried on the next cadence — the stateless loop never spams.
/// Determinism: intents submitted while the kernel executes tick T are
/// sealed into the batch of T+1 (the host advances the AI peer clock
/// before stepping); the one-tick input delay is the canonical one every
/// command pays (MatchSession.InputDelayTicks = 1, part of the match
/// fingerprint).
/// </para>
/// <para>
/// Zero engine dependencies (no UnityEngine types).
/// </para>
/// </summary>
public sealed class SkirmishAiSystem : ISimSystem
{
// THE NUMBERS LIVE IN Nova.AI.Data. What used to be four const fields
// here are profile values now — behaviour in C#, numbers in one place
// (AIArchitecture.md section 3). The shipped profile carries exactly
// the constants that stood here, so this move changes nothing; the
// proof is the unchanged end-state pin in SkirmishAiTests, not the
// four determinism baselines — those never run this system.
/// <summary>Decision cadence in ticks: 20 ticks = 2.0 s on the canonical 10 Hz clock.</summary>
public ushort DecisionTickInterval => _profile.Profile.DecisionTickInterval;
/// <summary>Largest Chebyshev ring around the placement anchor the spot search tries (documented AI choice, not a rule).</summary>
private int PlacementSearchRadius => _profile.Profile.PlacementSearchRadius;
/// <summary>Infantry queued per decision tick while below the army cap (smooths spending over the cadence).</summary>
private int InfantryQueueBatch => _profile.Profile.InfantryQueueBatch;
/// <summary>Harvesters queued per decision tick while below the harvester target.</summary>
private int HarvesterQueueBatch => _profile.Profile.HarvesterQueueBatch;
/// <summary>One own construction site seen in the ascending scan (the site entity sits at the footprint center cell).</summary>
private struct SiteInfo
{
public int CellX;
public int CellY;
public uint AssignedBuilderRaw;
}
private readonly byte _aiPlayerId;
private readonly AiFactionProfile _profile;
private readonly CommandIngress _ingress;
private readonly EntityManager _entityManager;
private readonly EconomySystem _economy;
private readonly ConstructionSystem _construction;
private readonly ProductionSystem _production;
private readonly FogOfWarSystem _fogOfWar;
private readonly VictorySystem _victory;
public string Name => $"SkirmishAi_{_profile.FactionName}_P{_aiPlayerId}";
public byte AiPlayerId => _aiPlayerId;
/// <summary>
/// <paramref name="ingress"/> is the AI peer's OWN slot-bound ingress
/// (its session's local slot is <paramref name="aiPlayerId"/>), never
/// the human host ingress — that is what keeps the AI on the canonical
/// intent path with an authority-assigned slot, sequence and target
/// tick.
/// </summary>
public SkirmishAiSystem(
byte aiPlayerId,
AiFactionProfile profile,
CommandIngress ingress,
EntityManager entityManager,
EconomySystem economy,
ConstructionSystem construction,
ProductionSystem production,
FogOfWarSystem fogOfWar,
VictorySystem victory)
{
_aiPlayerId = aiPlayerId;
_profile = profile;
_ingress = ingress ?? throw new ArgumentNullException(nameof(ingress));
_entityManager = entityManager ?? throw new ArgumentNullException(nameof(entityManager));
_economy = economy ?? throw new ArgumentNullException(nameof(economy));
_construction = construction ?? throw new ArgumentNullException(nameof(construction));
_production = production ?? throw new ArgumentNullException(nameof(production));
_fogOfWar = fogOfWar ?? throw new ArgumentNullException(nameof(fogOfWar));
_victory = victory ?? throw new ArgumentNullException(nameof(victory));
}
public void Initialize(SimulationKernel kernel)
{
kernel?.Logger.LogInfo(
$"[{Name}] Initialized MS-1 skirmish AI for slot {_aiPlayerId} " +
$"(intent path via the peer ingress, cadence {DecisionTickInterval} ticks).");
}
/// <summary>
/// The fixed-cadence decision loop. Registered after Combat and before
/// Victory, so decisions read the post-combat state of the executing
/// tick; a decided match ends every further order.
/// </summary>
public void ExecuteTick(Tick tick)
{
if (tick.Value % DecisionTickInterval != 0) return;
if (_victory.IsDecided) return;
Decide();
}
public void Shutdown()
{
}
// ------------------------------------------------------------------
// The decision loop (pure function of the committed state)
// ------------------------------------------------------------------
private void Decide()
{
FactionId faction = _economy.GetSlotFaction(_aiPlayerId);
ref readonly PlayerEconomyState eco = ref _economy.GetPlayerEconomy(_aiPlayerId);
long credits = eco.AetheriumCredits;
int powerMargin = eco.PowerProvided - eco.PowerRequired;
// One ascending-index scan of the entity store collecting every
// fact the decisions below read (deterministic iteration order).
uint hqRaw = 0, refineryRaw = 0, barracksRaw = 0;
int hqCellX = -1, hqCellY = -1, refineryCellX = -1, refineryCellY = -1;
bool powerCompleted = false;
int builders = 0, harvesters = 0, combatCount = 0;
var combatRaws = new List<uint>();
var combatUnits = new List<UnitState>();
var idleHarvesterRaws = new List<uint>();
var harvesterRaws = new List<uint>();
var harvesterUnits = new List<UnitState>();
var sites = new List<SiteInfo>();
UnitState[] units = _entityManager.RawUnits;
int capacity = _entityManager.Capacity;
for (int i = 0; i < capacity; i++)
{
ref readonly UnitState u = ref units[i];
if (!u.IsActive || u.PlayerId != _aiPlayerId) continue;
uint raw = UnitCommandStateView.ToRawEntityId(u.Id);
if (raw == 0) continue;
// 16.3 (#44): a site already carries its definition role.
// Classify through the site register BEFORE building roles so
// an unfinished Refinery/HQ/etc. never becomes a completed
// producer or prerequisite in the planner.
if (_construction.TryGetSite(raw, out _, out _, out uint assignedBuilder))
{
sites.Add(new SiteInfo
{
CellX = GridCellOf(u.Transform.PositionX),
CellY = GridCellOf(u.Transform.PositionY),
AssignedBuilderRaw = assignedBuilder,
});
continue;
}
if (SimDefinitions.IsBuildingRole(u.Role))
{
switch (u.Role)
{
case UnitRole.HQ when hqRaw == 0:
hqRaw = raw;
hqCellX = GridCellOf(u.Transform.PositionX);
hqCellY = GridCellOf(u.Transform.PositionY);
break;
case UnitRole.Refinery when refineryRaw == 0:
refineryRaw = raw;
refineryCellX = GridCellOf(u.Transform.PositionX);
refineryCellY = GridCellOf(u.Transform.PositionY);
break;
case UnitRole.Barracks when barracksRaw == 0:
barracksRaw = raw;
break;
case UnitRole.Power:
powerCompleted = true;
break;
}
continue;
}
switch (u.Role)
{
case UnitRole.Builder:
builders++;
break;
case UnitRole.Harvester:
harvesters++;
harvesterRaws.Add(raw);
harvesterUnits.Add(u);
if (u.HarvestFieldId == 0 && !u.IsReturningCargo)
{
idleHarvesterRaws.Add(raw);
}
break;
default:
if (IsCombatRole(u.Role))
{
combatCount++;
combatRaws.Add(raw);
combatUnits.Add(u);
}
break;
}
}
// A slot without an HQ cannot run the D-077 opening loop (and a
// slot that owns nothing is defeated anyway): stay idle.
if (hqRaw == 0) return;
// ---- (1) Build order: Refinery, required Power plant, then
// Barracks, one site at a time (a single Builder cannot progress
// two sites). Power also preempts whenever the committed margin
// would drop below the profile reserve — "when the margin would
// go negative" with the demo profile's reserve of 0. ----
if (sites.Count == 0)
{
UnitRole next = refineryRaw == 0
? UnitRole.Refinery
: (barracksRaw == 0 ? UnitRole.Barracks : UnitRole.Unit);
if (next != UnitRole.Unit
&& SimDefinitions.TryGetBuilding(faction, next, out SimBuildingDefinition nextDef))
{
UnitRoleMask missingPrerequisites = _construction.GetMissingPrerequisiteRoles(
_aiPlayerId,
nextDef.PrerequisiteRoles);
bool missingRequiredPower = (missingPrerequisites & UnitRoleMask.Power) != 0;
bool needsPowerMargin = nextDef.PowerRequired > 0
&& powerMargin < nextDef.PowerRequired + _profile.TargetPowerMargin;
if (!powerCompleted && (missingRequiredPower || needsPowerMargin))
{
next = UnitRole.Power;
}
TryPlaceBuilding(faction, next, credits, hqCellX, hqCellY);
}
}
// ---- (2) Construction support: the assigned Builder must stand
// in Chebyshev reach <= 1 of the site footprint or the site
// pauses (ConstructionSystem remarks) — walk it there. ----
for (int s = 0; s < sites.Count; s++)
{
SiteInfo site = sites[s];
if (site.AssignedBuilderRaw == 0) continue;
EntityId builderId = UnitCommandStateView.ToEntityId(site.AssignedBuilderRaw);
if (!_entityManager.TryGetUnit(builderId, out UnitState builder)) continue;
int originX = site.CellX - 1;
int originY = site.CellY - 1;
if (IsInReachOfFootprint(
GridCellOf(builder.Transform.PositionX), GridCellOf(builder.Transform.PositionY),
originX, originY))
{
continue;
}
// Deterministic adjacent cell: the first footprint-free
// cell in Chebyshev reach 1 of the site rectangle — a fixed
// side can lie inside a neighbour building, which is
// impassable since the Truppenführung sprint and would
// stall the site forever.
if (!TryFindFootprintAdjacentCell(originX, originY, out int targetX, out int targetY))
{
continue;
}
if (builder.IsMoving && builder.TargetGridPos.IsValid
&& builder.TargetGridPos.X == targetX && builder.TargetGridPos.Y == targetY)
{
continue; // already walking there
}
Submit(new MovePayload(
new[] { site.AssignedBuilderRaw }, SimFixed.FromInt(targetX), SimFixed.FromInt(targetY)));
}
// ---- (3) Replacement Builder at the HQ when none is alive. ----
if (builders == 0
&& SimDefinitions.TryGetUnit(faction, UnitRole.Builder, out SimUnitDefinition builderDef)
&& CountQueuedAt(hqRaw, builderDef.DefinitionId) == 0
&& credits >= builderDef.CostAE)
{
Submit(new QueueUnitPayload(hqRaw, builderDef.DefinitionId, 1));
}
// ---- (4) Economy: keep harvesters queued at the Refinery (the
// D-077 producer), send every idle own harvester to the own field
// and WALK harvesters into reach with explicit Move intents.
// This slice never submits SetRallyPoint; it does what a human
// player does and micros the harvesters into the economy's reach
// rule. That is a behavior choice, NOT a validator limit: the
// rally point would be accepted. ProductionSystem.IsProducerRole
// reads UnitRole.Refinery out of SimDefinitions.AllUnits (both
// factions' Harvester carries producerRole: Refinery since D-077)
// instead of a hardcoded list, precisely so the producer move
// could not strand it. Using the rally point here would change
// behavior and belongs in its own PR. ----
if (refineryRaw != 0
&& TryGetOwnFieldCell(hqCellX, hqCellY, out ushort ownFieldId, out int fieldX, out int fieldY))
{
if (SimDefinitions.TryGetUnit(faction, UnitRole.Harvester, out SimUnitDefinition harvesterDef))
{
int have = harvesters + CountQueuedAt(refineryRaw, harvesterDef.DefinitionId);
int batch = Math.Min(HarvesterQueueBatch, _profile.TargetHarvesterCount - have);
if (batch > 0 && credits >= (long)harvesterDef.CostAE * batch)
{
Submit(new QueueUnitPayload(refineryRaw, harvesterDef.DefinitionId, (ushort)batch));
}
}
if (idleHarvesterRaws.Count > 0)
{
idleHarvesterRaws.Sort();
SubmitEntityList(idleHarvesterRaws,
ids => CommandIntent.Create(new HarvestPayload(ids, ownFieldId)));
}
// Escort targets: the gather leg wants a cell in harvest reach
// of the field (Chebyshev 1 of the field cell) AND in deposit
// reach of the Refinery footprint, so the full auto-cycle
// (gather -> return -> gather, EconomySystem remarks) closes
// in one spot; the return leg wants any cell adjacent to the
// footprint. Deterministic ascending picks.
int refineryOriginX = refineryCellX - 1;
int refineryOriginY = refineryCellY - 1;
bool haveGatherSpot = TryFindDualReachCell(fieldX, fieldY, refineryOriginX, refineryOriginY,
out int gatherX, out int gatherY);
if (!haveGatherSpot)
{
// The field cell itself always satisfies harvest reach.
gatherX = fieldX;
gatherY = fieldY;
}
int returnX, returnY;
bool haveReturnSpot = TryFindFootprintAdjacentCell(refineryOriginX, refineryOriginY,
out returnX, out returnY);
var gatherEscort = new List<uint>();
var returnEscort = new List<uint>();
for (int i = 0; i < harvesterUnits.Count; i++)
{
UnitState harvester = harvesterUnits[i];
int cellX = GridCellOf(harvester.Transform.PositionX);
int cellY = GridCellOf(harvester.Transform.PositionY);
if (harvester.IsReturningCargo)
{
// The return leg resolves only in deposit reach of an
// own Refinery (the economy's documented footprint
// reach rule); walk there when held out of reach.
if (!haveReturnSpot || harvester.CargoAE <= 0) continue;
if (IsInDepositReach(cellX, cellY, refineryCellX, refineryCellY)) continue;
if (AlreadyHeadingTo(in harvester, returnX, returnY)) continue;
returnEscort.Add(harvesterRaws[i]);
}
else
{
// Out-of-reach harvest orders are HELD, never dropped
// (EconomySystem) — closing the distance is the AI's
// job, exactly like a human's move click.
if (IsInFieldReach(cellX, cellY, fieldX, fieldY)) continue;
if (AlreadyHeadingTo(in harvester, gatherX, gatherY)) continue;
gatherEscort.Add(harvesterRaws[i]);
}
}
if (gatherEscort.Count > 0)
{
gatherEscort.Sort();
SubmitEntityList(gatherEscort,
ids => CommandIntent.Create(new MovePayload(ids, SimFixed.FromInt(gatherX), SimFixed.FromInt(gatherY))));
}
if (returnEscort.Count > 0)
{
returnEscort.Sort();
SubmitEntityList(returnEscort,
ids => CommandIntent.Create(new MovePayload(ids, SimFixed.FromInt(returnX), SimFixed.FromInt(returnY))));
}
}
// ---- (5) Army: keep infantry queued up to the cap as funds allow. ----
if (barracksRaw != 0
&& SimDefinitions.TryGetUnit(faction, ProducedCombatRole, out SimUnitDefinition infantryDef))
{
int have = combatCount + CountQueuedAt(barracksRaw, infantryDef.DefinitionId);
int batch = Math.Min(InfantryQueueBatch, _profile.TargetArmySize - have);
if (batch > 0 && credits >= (long)infantryDef.CostAE * batch)
{
Submit(new QueueUnitPayload(barracksRaw, infantryDef.DefinitionId, (ushort)batch));
}
}
// ---- (6) Army: resolve one posture for the army, one assignment
// per unit, then submit the assignments grouped. See the three
// steps below; the rules are exactly the ones the previous
// whole-army block applied. ----
ArmyPosture posture = ResolveArmyPosture(
faction, barracksRaw, combatCount, combatUnits, hqCellX, hqCellY);
if (posture.Engages)
{
// Cells of the visible ARMED enemies, collected once per
// decision and only while the retreat rule is on. A local
// list, not a field: the system stays a pure function of the
// committed state, and nothing survives the decision.
List<long> threatCells = null;
List<uint> threatRaws = null;
if (_profile.Profile.RetreatHealthPercent > 0)
{
threatCells = new List<long>();
threatRaws = new List<uint>();
CollectVisibleThreats(threatCells, threatRaws);
}
var assignments = new List<UnitAssignment>(combatUnits.Count);
for (int i = 0; i < combatUnits.Count; i++)
{
UnitState unit = combatUnits[i];
assignments.Add(ResolveUnitAssignment(
combatRaws[i], in unit, in posture, hqCellX, hqCellY, threatCells, threatRaws));
}
SubmitAssignments(assignments, combatUnits);
}
}
// ------------------------------------------------------------------
// Army: posture -> per-unit assignment -> grouped submission
//
// THREE STEPS, because one whole-army order cannot express what the
// army has to do. The previous shape computed a single target and a
// single destination for every living combat unit, which is why
// "this one wounded unit turns back", "reinforcements wait at a
// staging cell" and "aim before the squad threshold is reached"
// could not be written down at all — and why a defence branch that
// switched the WHOLE army's destination every cadence produced 23 %
// more intents and a worse match (behaviour journal V002).
//
// The split is: what the army does (posture, derived from the
// committed state, never stored), what each unit does (assignment),
// and how that reaches the ingress (grouping, so N units sharing an
// order still cost ONE intent). The rules themselves are unchanged
// here: this shape reproduces the canonical match tick for tick.
// ------------------------------------------------------------------
/// <summary>
/// What the army as a whole is doing this decision. Derived fresh
/// every cadence from the committed state — the system stays
/// stateless, so there is nothing here to serialize.
/// </summary>
private struct ArmyPosture
{
/// <summary>
/// False when the army does not act at all: below the squad
/// threshold, or the own slot has no committed team view (only
/// slots below <see cref="FogOfWarSystem.TeamCount"/> do).
/// </summary>
public bool Engages;
/// <summary>The scored target the army shoots at; 0 when nothing enemy is visible.</summary>
public uint TargetRaw;
/// <summary>Where the army walks: the target's cell, else the enemy start area; -1 while the army does not act.</summary>
public int MoveCellX;
/// <summary>See <see cref="MoveCellX"/>.</summary>
public int MoveCellY;
/// <summary>
/// Where reinforcements gather before they march; -1 when waves are
/// off (<see cref="AiProfile.WaveSize"/> 1) or the army does not act.
/// <para>
/// Derived from the own HQ and the ENEMY START AREA, never from the
/// current target cell. That is deliberate: the target moves every
/// cadence, so a staging point derived from it would move too, and
/// every unit waiting there would be re-ordered on every decision.
/// That is precisely the churn that sank <c>DefendBase</c> (journal
/// V002, +23 % intents), and the intents-per-1000-ticks column is
/// the first number to look at here.
/// </para>
/// </summary>
public int StagingCellX;
/// <summary>See <see cref="StagingCellX"/>.</summary>
public int StagingCellY;
/// <summary>
/// True when what waits AT the staging cell is enough for the wave
/// to march — since r6 that is a sum of combat points, and only on
/// the off path (<see cref="AiProfile.WaveStrengthPoints"/> 0) a
/// count of units. Always true while waves are off entirely
/// (<see cref="AiProfile.WaveSize"/> 1), where every unit is its
/// own wave.
/// </summary>
public bool WaveReady;
}
/// <summary>
/// One unit's orders for this decision. The two slots are
/// INDEPENDENT on purpose — a unit can be told to shoot at one thing
/// and to stand somewhere else, and either half can be "no explicit
/// order, leave the standing one alone" (<see cref="AttackTargetRaw"/>
/// 0 hands the pick to the D-087 auto-acquisition,
/// <see cref="MoveCellX"/> < 0 leaves the unit where it walks).
/// </summary>
private struct UnitAssignment
{
public uint EntityRaw;
public uint AttackTargetRaw;
public int MoveCellX;
public int MoveCellY;
}
/// <summary>
/// The army's posture: at
/// <see cref="AiFactionProfile.AttackSquadThreshold"/> living combat
/// units the army marches on the enemy start area, and the best
/// visible enemy (integer score, committed view only) becomes the
/// shared target and the destination. No attack-move exists (GB-002),
/// but auto-acquisition does since D-087 — an explicit order simply
/// outranks it and is never retargeted.
/// </summary>
private ArmyPosture ResolveArmyPosture(
FactionId faction, uint barracksRaw, int combatCount, List<UnitState> combatUnits,
int hqCellX, int hqCellY)
{
var posture = new ArmyPosture
{
Engages = combatCount >= _profile.AttackSquadThreshold && _aiPlayerId < _fogOfWar.TeamCount,
MoveCellX = -1,
MoveCellY = -1,
StagingCellX = -1,
StagingCellY = -1,
WaveReady = true,
};
if (!posture.Engages) return posture;
posture.TargetRaw = FindBestVisibleEnemyByScore(combatUnits, out int targetCellX, out int targetCellY);
if (posture.TargetRaw != 0)
{
posture.MoveCellX = targetCellX;
posture.MoveCellY = targetCellY;
}
else
{
GetEnemyStartAreaCell(hqCellX, hqCellY, out posture.MoveCellX, out posture.MoveCellY);
}
// The staging cell is resolved whenever the army acts, because
// BOTH rules need it: it is where a wave gathers and where a
// wounded unit walks back to. Resolving it is pure arithmetic over
// static map knowledge — with every rule switched off it changes
// nothing, which is what keeps the off path byte-identical.
GetStagingCell(hqCellX, hqCellY, out posture.StagingCellX, out posture.StagingCellY);
// ---- waves, and the off setting that keeps this reproducible ----
//
// waveSize 1 leaves WaveReady at true, so every unit marches and
// the shipped-before behaviour is not "the same result through new
// code" but the same decision it always took. That is what makes
// the comparison run one-sided (finding M001): identical binary,
// one profile value apart.
int waveSize = EffectiveWaveSize();
if (waveSize <= 1) return posture;
int gathered = 0;
int committed = 0;
long gatheredStrength = 0;
for (int i = 0; i < combatUnits.Count; i++)
{
UnitState unit = combatUnits[i];
if (IsCommittedToTheWave(in unit, hqCellX, hqCellY))
{
committed++;
}
else
{
gathered++;
gatheredStrength += CombatStrength.Of(faction, unit.Role, unit.CurrentHealth);
}
}
// ---- the wave marches on STRENGTH, not on a head count ----
//
// A count does not know what a head is worth. Twelve Legion
// recruits weigh 528 points against twelve Alliance riflemen's
// 1.200, and the count calls both "a full wave" — so the Legion
// attacks at 44 % of the strength the same rule gives the Alliance,
// and pays for it in the loss column.
//
// waveStrengthPoints 0 skips this and leaves the count below
// untouched, bit for bit. That off setting is not politeness: a
// rule that lives only in C# reaches BOTH sides of a self-play
// match, and "later decided, more losses" then cannot be told from
// "two stronger armies" (finding M001).
//
// The second half of the condition is a guard, not a rule: a
// produced role worth 0 points would make the reachability cap
// meaningless (nothing production adds could ever close a gap), so
// the count path answers instead of a strength path that cannot.
// No shipped faction hits it — both Barracks build an armed unit.
int wavePoints = _profile.Profile.WaveStrengthPoints;
int producedStrength = wavePoints > 0
? CombatStrength.OfFullHealth(faction, ProducedCombatRole)
: 0;
if (wavePoints > 0 && producedStrength > 0)
{
posture.WaveReady = WaveStrengthGate.IsReady(
wavePoints, gatheredStrength, gathered, committed, producedStrength,
_profile.TargetArmySize, canProduce: barracksRaw != 0);
return posture;
}
// The wave waits for what production can still deliver, not for a
// fixed twelve.
//
// Every survivor of an earlier wave standing outside the ring is a
// unit the next wave will never get: the army cap counts it, so the
// barracks refills to TargetArmySize MINUS the survivors, and the
// count inside the ring can never reach a wave size equal to the
// cap again. One survivor that walks into an empty enemy start area
// and does not die is enough — measured consequence: eleven units
// stand at the staging cell until the time limit while a single
// unit holds the front alone.
//
// EffectiveWaveSize already refuses a wave production can never
// deliver; this is the same rule one step further, applied to what
// production can deliver RIGHT NOW instead of in principle. The
// floor of 1 keeps the wave launchable when more units are out than
// the cap allows for at home — the rest are already fighting.
int reachable = _profile.TargetArmySize - committed;
if (reachable < 1) reachable = 1;
int threshold = waveSize < reachable ? waveSize : reachable;
posture.WaveReady = gathered >= threshold;
return posture;
}
/// <summary>
/// The role the Barracks keeps queueing in step (5) — the one unit type
/// production can actually add to a gathering wave, and therefore the
/// one whose full-health strength says what "one more unit" is worth to
/// the wave threshold.
/// <para>
/// TWO PLACES HAVE TO AGREE ON IT, so they read the same constant
/// rather than the same literal twice. A test could only assert the
/// agreement after the fact; sharing the constant means they cannot
/// disagree in the first place, which is the difference between a
/// checked invariant and an enforced one.
/// </para>
/// </summary>
private const UnitRole ProducedCombatRole = UnitRole.BasicInfantry;
/// <summary>
/// The wave size actually used, clamped to the army cap.
/// <para>
/// Without the clamp a profile with <c>waveSize</c> above
/// <see cref="AiFactionProfile.TargetArmySize"/> would wait for a wave
/// production can never deliver, and the army would stand at the
/// staging cell until the time limit. The clamp is not a tuning
/// decision, it is the guard against a profile that cannot work.
/// </para>
/// </summary>
private int EffectiveWaveSize()
{
int waveSize = _profile.Profile.WaveSize;
return waveSize > _profile.TargetArmySize ? _profile.TargetArmySize : waveSize;
}
/// <summary>
/// The staging cell: <see cref="AiProfile.StagingDistanceCells"/> cells
/// from the own HQ along the straight line toward the enemy start area,
/// clamped into the grid. Static map knowledge on both ends, so this
/// cell is the SAME for the whole match — a unit ordered there is not
/// re-ordered on the next cadence.
/// <para>
/// Integer division truncates, which is deterministic and identical on
/// both machines; that is the only property that matters here.
/// </para>
/// </summary>
private void GetStagingCell(int hqCellX, int hqCellY, out int cellX, out int cellY)
{
GetEnemyStartAreaCell(hqCellX, hqCellY, out int enemyX, out int enemyY);
int distance = _profile.Profile.StagingDistanceCells;
int dx = enemyX - hqCellX;
int dy = enemyY - hqCellY;
int span = Math.Max(Math.Abs(dx), Math.Abs(dy));
if (span <= distance)
{
// The enemy start area is nearer than the staging distance:
// there is nothing between base and target to gather at.
cellX = enemyX;
cellY = enemyY;
return;
}
cellX = ClampToGrid(hqCellX + (dx * distance / span));
cellY = ClampToGrid(hqCellY + (dy * distance / span));
}
/// <summary>
/// True when this unit is pulling out: wounded below
/// <see cref="AiProfile.RetreatHealthPercent"/> AND either an armed
/// enemy is within <see cref="AiProfile.RetreatDangerCells"/> or it is
/// already walking home.
/// <para>
/// THE SECOND HALF IS THE DAMPING, and it replaces the health
/// hysteresis the plan sketch asked for. That sketch wanted a unit to
/// re-enter the fight above an exit percentage — which presumes
/// healing, and MS-1 units never heal (<c>Repair</c> validates its
/// target as a completed BUILDING). With an unreachable exit the
/// wounded would pile up at home, keep occupying the army cap, and the
/// wave would never fill again. So the rule is: run home, and once you
/// are home you are an ordinary waiting unit again and leave with the
/// next wave, wounded or not. "Already walking home" is read off the
/// standing order — the AI's only memory, and one that survives
/// save/restore because it is part of the world, not beside it.
/// </para>
/// <para>
/// A retreating unit is pointed at its nearest visible armed enemy —
/// see <see cref="NearestThreatRaw"/>. This paragraph used to claim the
/// opposite (no explicit target, so D-087 keeps shooting at whatever
/// chases it) and the claim was wrong: submitting no attack intent
/// leaves the march target standing, and a standing valid target is
/// exactly what makes the auto-acquisition skip the unit.
/// </para>
/// </summary>
private bool IsRetreating(in UnitState unit, in ArmyPosture posture, List<long> threatCells)
{
int threshold = _profile.Profile.RetreatHealthPercent;
if (threshold <= 0 || threatCells == null || posture.StagingCellX < 0) return false;
if (unit.MaxHealth <= 0) return false;
if ((long)unit.CurrentHealth * 100 / unit.MaxHealth >= threshold) return false;
if (AlreadyHeadingTo(in unit, posture.StagingCellX, posture.StagingCellY)) return true;
int cellX = GridCellOf(unit.Transform.PositionX);
int cellY = GridCellOf(unit.Transform.PositionY);
int danger = _profile.Profile.RetreatDangerCells;
for (int i = 0; i < threatCells.Count; i++)
{
int threatX = (int)(uint)threatCells[i];
int threatY = (int)(threatCells[i] >> 32);
if (Math.Abs(cellX - threatX) <= danger && Math.Abs(cellY - threatY) <= danger) return true;
}
return false;
}
/// <summary>
/// The cells of every ARMED enemy in the team's committed view, packed
/// as <c>(y << 32) | x</c>. Unarmed entities are left out: a
/// harvester at the fence is not a reason to run, and treating it as
/// one is exactly the over-reaction that sank <c>DefendBase</c>
/// (journal V002 — "react to a real threat, not to anything that
/// moves").
/// </summary>
private void CollectVisibleThreats(List<long> cells, List<uint> raws)
{
var visible = new List<EntityId>();
_fogOfWar.GetVisibleEntities(_aiPlayerId, visible);
for (int i = 0; i < visible.Count; i++)
{
if (!_entityManager.TryGetUnit(visible[i], out UnitState u)) continue;
if (u.PlayerId == _aiPlayerId) continue;
if (_construction.IsActiveSite(u.Id)) continue;
if (WeaponProfiles.Get(_economy.GetSlotFaction(u.PlayerId), u.Role).AttackDamage <= 0) continue;
long x = GridCellOf(u.Transform.PositionX);
long y = GridCellOf(u.Transform.PositionY);
cells.Add((y << 32) | x);
raws.Add(UnitCommandStateView.ToRawEntityId(u.Id));
}
}
/// <summary>
/// The nearest armed enemy this unit can see, as a raw entity id, or 0
/// when the retreat rule is off or nothing armed is visible.
/// <para>
/// WHY A RETREATING UNIT NEEDS AN EXPLICIT TARGET AT ALL. The retreat
/// branch used to hand out <c>AttackTargetRaw = 0</c> and the class
/// remarks called that "no explicit target, so the D-087
/// auto-acquisition keeps shooting at whatever chases it". It does not:
/// zero means "submit no attack intent", and submitting nothing leaves
/// the march order the unit already carries. Nothing else clears it —
/// <c>UnitState.Stop()</c> does not touch <c>AttackTarget</c>,
/// <c>ApplyMove</c> only calls <c>SetTarget</c>, and <c>CombatSystem</c>
/// releases a target only when it dies. The auto-acquisition then skips
/// the unit entirely (<c>CombatSystem</c>: <c>if (attacker.AttackTarget.IsValid) continue;</c>),
/// so the wounded unit walked home carrying a target it had left behind,
/// firing at nothing the whole way and defending nothing once home.
/// </para>
/// <para>
/// The command schema has no way to CLEAR a target — a raw 0 on the
/// wire is rejected as <c>InvalidEntityId</c>, by design. So the fix is
/// to overwrite the stale target with the one the unit should actually
/// be shooting at: its pursuer. That is what the remarks promised all
/// along, now issued rather than assumed.
/// </para>
/// <para>
/// Chebyshev distance, ties broken on the LOWER raw id — never on the
/// scan position, so two peers pick the same pursuer.
/// </para>
/// </summary>
private uint NearestThreatRaw(in UnitState unit, List<long> threatCells, List<uint> threatRaws)
{
if (threatCells == null || threatRaws == null) return 0u;
int cellX = GridCellOf(unit.Transform.PositionX);
int cellY = GridCellOf(unit.Transform.PositionY);
uint bestRaw = 0u;
int bestDistance = int.MaxValue;
for (int i = 0; i < threatCells.Count; i++)
{
int threatX = (int)(uint)threatCells[i];
int threatY = (int)(threatCells[i] >> 32);
int distance = Math.Max(Math.Abs(cellX - threatX), Math.Abs(cellY - threatY));
uint raw = threatRaws[i];
if (distance > bestDistance) continue;
if (distance == bestDistance && (bestRaw == 0u || raw >= bestRaw)) continue;
bestDistance = distance;
bestRaw = raw;
}
return bestRaw;
}
/// <summary>
/// True when this unit already stands at the staging cell — within
/// <see cref="AiProfile.StagingToleranceCells"/> of it, because the
/// formation distribution spreads an arriving group over several
/// cells. Used ONLY to keep quiet about a unit that is where it
/// belongs, never to decide whether the wave is full.
/// </summary>
private bool IsAtTheStagingCell(in UnitState unit, in ArmyPosture posture)
{
int dx = Math.Abs(GridCellOf(unit.Transform.PositionX) - posture.StagingCellX);
int dy = Math.Abs(GridCellOf(unit.Transform.PositionY) - posture.StagingCellY);
return Math.Max(dx, dy) <= _profile.Profile.StagingToleranceCells;
}
/// <summary>
/// True when this unit has left the staging ring around the own HQ —
/// it belongs to a wave that already marched and is not called back.
/// Everything INSIDE the ring is the wave that has not left yet, and
/// that count is what the wave size is compared against.
/// <para>
/// Measured against the OWN HQ, not against the target: the HQ does not
/// move, so a unit does not flip between "out" and "waiting" because
/// the enemy walked a few cells. Turning back a wave that is already
/// out is the V002 failure mode, and this predicate is the place it
/// would come back in.
/// </para>
/// <para>
/// MEASURED, NOT ASSUMED: the first version of this rule counted only
/// units standing within <see cref="AiProfile.StagingToleranceCells"/>
/// OF THE STAGING CELL. That never worked, and the recorded run showed
/// why in one screen — the formation distribution spreads a group of
/// twelve over more than four cells, so the count stayed under the wave
/// size forever and the army oscillated between the base and the
/// staging point for 11.000 ticks while a single enemy unit ground
/// down its HQ. The ring is the whole area inside
/// <c>StagingDistanceCells + StagingToleranceCells</c>, so where
/// exactly a unit stands while it waits does not matter.
/// </para>
/// </summary>
private bool IsCommittedToTheWave(in UnitState unit, int hqCellX, int hqCellY)
{
int cellX = GridCellOf(unit.Transform.PositionX);
int cellY = GridCellOf(unit.Transform.PositionY);
int dx = Math.Abs(cellX - hqCellX);
int dy = Math.Abs(cellY - hqCellY);
int ring = _profile.Profile.StagingDistanceCells + _profile.Profile.StagingToleranceCells;
return Math.Max(dx, dy) > ring;
}
/// <summary>
/// One unit's orders under the given posture. Today every combat unit
/// gets the same two — that IS the current behaviour, and this is the
/// one place a later rule (retreat below a health threshold, waiting
/// at a staging cell) has to change to break the uniformity.
/// <para>
/// Aiming BELOW the squad threshold was built here and measured back
/// out again — behaviour journal V003 carries the four variants and
/// the reason: an explicit order cannot be handed back to the D-087
/// auto-acquisition, because <c>AttackTarget</c> is released only by
/// the target's death (<c>UnitState.Stop()</c> leaves it untouched).
/// A standing unit that stops closing the distance therefore holds a
/// stale order, and holding beats aiming only while the unit walks
/// toward what it aims at.
/// </para>
/// </summary>
private UnitAssignment ResolveUnitAssignment(
uint entityRaw, in UnitState unit, in ArmyPosture posture, int hqCellX, int hqCellY,
List<long> threatCells, List<uint> threatRaws)
{
// A wounded unit walks home, whatever the wave is doing. This test
// comes FIRST on purpose: retreat has to outrank "you are out with
// the wave, keep going", or it can never pull anybody back.
bool retreats = IsRetreating(in unit, in posture, threatCells);
bool marches = !retreats
&& (posture.StagingCellX < 0 // no staging cell resolved
|| posture.WaveReady // the wave launches this decision
|| IsCommittedToTheWave(in unit, hqCellX, hqCellY)); // already out with an earlier wave
// The one order a retreating unit still needs: its pursuer.
// Zero does not clear the march target it is carrying — see
// NearestThreatRaw for why leaving it stale silenced the unit for
// the whole way home. A WAITING reinforcement keeps getting zero:
// it holds no stale order to overwrite (it never marched), and
// finding F001 is explicit that aiming while standing still is
// worse than letting D-087 acquire.
uint retreatTargetRaw = retreats
? NearestThreatRaw(in unit, threatCells, threatRaws)
: 0u;