-
Notifications
You must be signed in to change notification settings - Fork 90
/
KM_UnitGroups.pas
2010 lines (1657 loc) · 60.8 KB
/
KM_UnitGroups.pas
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
unit KM_UnitGroups;
{$I KaM_Remake.inc}
interface
uses
Classes, Math, SysUtils, Types,
KM_Defaults, KM_CommonClasses, KM_CommonTypes, KM_Points, KM_Houses, KM_Units,
KM_Units_Warrior;
type
TKMUnitGroup = class;
TKMUnitGroupEvent = procedure(aGroup: TKMUnitGroup) of object;
TKMTurnDirection = (tdNone, tdCW, tdCCW);
TKMInitialOrder = (ioNoOrder, ioSendGroup, ioAttackPosition);
TKMGroupOrder = (
goNone, //Last order was executed and now we have nothing to do
goWalkTo, //Ordered to walk somewhere or just change formation
goAttackHouse, //Attack house
goAttackUnit, //Attack specific unit
goStorm //Run forward
);
//MapEd allows to set order for a group that will be executed on mission start
TKMMapEdOrder = record
Order: TKMInitialOrder;
Pos: TKMPointDir;
end;
//Group of warriors
TKMUnitGroup = class
private
fUID: Integer;
fPointerCount: Cardinal;
fTicker: Cardinal;
fTargetFollowTicker: Cardinal;
fOwner: TKMHandIndex;
fMembers: TList;
fOffenders: TList;
fSelected: TKMUnitWarrior; //Unit selected by player in GUI. Should not be saved or affect game logic for MP consistency.
fUnitsPerRow: Word;
fTimeSinceHungryReminder: Integer;
fGroupType: TKMGroupType;
fDisableHungerMessage: Boolean;
fBlockOrders: Boolean;
fManualFormation: Boolean;
fOrder: TKMGroupOrder; //Remember last order incase we need to repeat it (e.g. to joined members)
fOrderLoc: TKMPointDir; //Dir is the direction to face after order
//Avoid accessing these directly
fOrderTargetUnit: TKMUnit; //Unit we are ordered to attack. This property should never be accessed, use public OrderTarget instead.
fOrderTargetGroup: TKMUnitGroup; //Unit we are ordered to attack. This property should never be accessed, use public OrderTarget instead.
fOrderTargetHouse: TKMHouse; //House we are ordered to attack. This property should never be accessed, use public OrderHouseTarget instead.
fMapEdCount: Word;
function GetCount: Integer;
function GetMember(aIndex: Integer): TKMUnitWarrior;
function GetFlagBearer: TKMUnitWarrior;
function GetNearestMember(aUnit: TKMUnitWarrior): Integer; overload;
function GetNearestMember(aLoc: TKMPoint): TKMUnitWarrior; overload;
function GetMemberLoc(aIndex: Integer): TKMPointExact;
procedure SetMapEdCount(aCount: Word);
procedure SetUnitsPerRow(aCount: Word);
procedure SetDirection(Value: TKMDirection);
procedure SetCondition(aValue: Integer);
procedure SetPosition(aValue: TKMPoint);
procedure ClearOrderTarget;
procedure ClearOffenders;
procedure HungarianReorderMembers;
function GetFlagPositionF: TKMPointF;
function GetFlagColor: Cardinal;
function GetOrderTargetUnit: TKMUnit;
function GetOrderTargetGroup: TKMUnitGroup;
function GetOrderTargetHouse: TKMHouse;
procedure SetOrderTargetUnit(aUnit: TKMUnit);
procedure SetOrderTargetHouse(aHouse: TKMHouse);
procedure UpdateOrderTargets;
procedure CheckForFight;
procedure CheckOrderDone;
procedure UpdateHungerMessage;
procedure Member_Died(aMember: TKMUnitWarrior);
procedure Member_PickedFight(aMember: TKMUnitWarrior; aEnemy: TKMUnit);
function GetCondition: Integer;
function GetDirection: TKMDirection;
function GetPosition: TKMPoint;
procedure SetSelected(aValue: TKMUnitWarrior);
public
//Each group can have initial order
//SendGroup - walk to some location
//AttackPosition - attack something at position (or walk there if its empty)
MapEdOrder: TKMMapEdOrder;
OnGroupDied: TKMUnitGroupEvent;
constructor Create(aID: Cardinal; aCreator: TKMUnitWarrior); overload;
constructor Create(aID: Cardinal; aOwner: TKMHandIndex; aUnitType: TKMUnitType; PosX, PosY: Word; aDir: TKMDirection; aUnitPerRow, aCount: Word); overload;
constructor Create(LoadStream: TKMemoryStream); overload;
procedure SyncLoad;
procedure Save(SaveStream: TKMemoryStream);
destructor Destroy; override;
function GetGroupPointer: TKMUnitGroup;
procedure ReleaseGroupPointer;
procedure AddMember(aWarrior: TKMUnitWarrior; aIndex: Integer = -1);
function MemberByUID(aUID: Integer): TKMUnitWarrior;
function HitTest(X,Y: Integer): Boolean;
procedure SelectFlagBearer;
function HasMember(aWarrior: TKMUnit): Boolean;
procedure ResetAnimStep;
function InFight(aCountCitizens: Boolean = False): Boolean; //Fighting and can't take any orders from player
function IsAttackingHouse: Boolean; //Attacking house
function IsAttackingUnit: Boolean;
function IsIdleToAI(aAllowWalking: Boolean = False): Boolean;
function IsPositioned(aLoc: TKMPoint; Dir: TKMDirection): Boolean;
function CanTakeOrders: Boolean;
function CanWalkTo(aTo: TKMPoint; aDistance: Single): Boolean;
function FightMaxRange: Single;
function IsRanged: Boolean;
function IsDead: Boolean;
function UnitType: TKMUnitType;
function GetOrderText: UnicodeString;
property GroupType: TKMGroupType read fGroupType;
property UID: Integer read fUID;
property Count: Integer read GetCount;
property MapEdCount: Word read fMapEdCount write SetMapEdCount;
property Members[aIndex: Integer]: TKMUnitWarrior read GetMember;
property FlagBearer: TKMUnitWarrior read GetFlagBearer;
property Owner: TKMHandIndex read fOwner;
property Position: TKMPoint read GetPosition write SetPosition;
property Direction: TKMDirection read GetDirection write SetDirection;
property UnitsPerRow: Word read fUnitsPerRow write SetUnitsPerRow;
property SelectedUnit: TKMUnitWarrior read fSelected write SetSelected;
property Condition: Integer read GetCondition write SetCondition;
property Order: TKMGroupOrder read fOrder;
property DisableHungerMessage: Boolean read fDisableHungerMessage write fDisableHungerMessage;
property BlockOrders: Boolean read fBlockOrders write fBlockOrders;
property ManualFormation: Boolean read fManualFormation write fManualFormation;
property FlagPositionF: TKMPointF read GetFlagPositionF;
property FlagColor: Cardinal read GetFlagColor;
function IsFlagRenderBeforeUnit: Boolean;
property OrderTargetUnit: TKMUnit read GetOrderTargetUnit write SetOrderTargetUnit;
property OrderTargetGroup: TKMUnitGroup read GetOrderTargetGroup;
property OrderTargetHouse: TKMHouse read GetOrderTargetHouse write SetOrderTargetHouse;
procedure SetOwner(aOwner: TKMHandIndex);
procedure OwnerUpdate(aOwner: TKMHandIndex; aMoveToNewOwner: Boolean = False);
procedure OrderAttackHouse(aHouse: TKMHouse; aClearOffenders: Boolean);
procedure OrderAttackUnit(aUnit: TKMUnit; aClearOffenders: Boolean);
procedure OrderFood(aClearOffenders: Boolean; aHungryOnly: Boolean = False);
procedure OrderFormation(aTurnAmount: TKMTurnDirection; aColumnsChange: ShortInt; aClearOffenders: Boolean);
procedure OrderHalt(aClearOffenders: Boolean);
procedure OrderLinkTo(aTargetGroup: TKMUnitGroup; aClearOffenders: Boolean);
procedure OrderNone;
procedure OrderRepeat;
procedure CopyOrderFrom(aGroup: TKMUnitGroup);
function OrderSplit(aClearOffenders: Boolean; aSplitSingle: Boolean = False): TKMUnitGroup;
function OrderSplitUnit(aUnit: TKMUnit; aClearOffenders: Boolean): TKMUnitGroup;
procedure OrderSplitLinkTo(aGroup: TKMUnitGroup; aCount: Word; aClearOffenders: Boolean);
procedure OrderStorm(aClearOffenders: Boolean);
procedure OrderWalk(aLoc: TKMPoint; aClearOffenders: Boolean; aDir: TKMDirection = dir_NA);
procedure UpdateState;
procedure PaintHighlighted(aHandColor: Cardinal; aFlagColor: Cardinal; aDoImmediateRender: Boolean = False; aDoHighlight: Boolean = False; aHighlightColor: Cardinal = 0);
procedure Paint;
end;
//Collection of Groups
TKMUnitGroups = class
private
fGroups: TKMList;
function GetCount: Integer;
function GetGroup(aIndex: Integer): TKMUnitGroup;
public
constructor Create;
destructor Destroy; override;
function AddGroup(aWarrior: TKMUnitWarrior): TKMUnitGroup; overload;
function AddGroup(aOwner: TKMHandIndex; aUnitType: TKMUnitType; PosX, PosY: Word; aDir: TKMDirection; aUnitPerRow, aCount: Word): TKMUnitGroup; overload;
procedure AddGroupToList(aGroup: TKMUnitGroup);
procedure DeleteGroupFromList(aGroup: TKMUnitGroup);
procedure RemGroup(aGroup: TKMUnitGroup);
property Count: Integer read GetCount;
property Groups[aIndex: Integer]: TKMUnitGroup read GetGroup; default;
function GetGroupByUID(aUID: Integer): TKMUnitGroup;
function GetGroupByMember(aUnit: TKMUnitWarrior): TKMUnitGroup;
function HitTest(X,Y: Integer): TKMUnitGroup;
function GetClosestGroup(aPoint: TKMPoint; aTypes: TKMGroupTypeSet = [Low(TKMGroupType)..High(TKMGroupType)]): TKMUnitGroup;
function WarriorTrained(aUnit: TKMUnitWarrior): TKMUnitGroup;
procedure Save(SaveStream: TKMemoryStream);
procedure Load(LoadStream: TKMemoryStream);
procedure SyncLoad;
procedure UpdateState;
procedure Paint(aRect: TKMRect);
end;
implementation
uses
KM_Game, KM_Hand, KM_HandsCollection, KM_Terrain, KM_Utils, KM_ResTexts, KM_RenderPool,
KM_Hungarian, KM_UnitActionWalkTo, KM_PerfLog, KM_AI, KM_ResUnits, KM_ScriptingEvents,
KM_UnitActionStormAttack;
const
HUNGER_CHECK_FREQ = 10; //Check warrior hunger every 1 second
{ TKMUnitGroup }
//Create a Group from a single warrior (short version)
constructor TKMUnitGroup.Create(aID: Cardinal; aCreator: TKMUnitWarrior);
begin
inherited Create;
fUID := aID;
fOwner := aCreator.Owner;
fGroupType := UnitGroups[aCreator.UnitType];
fMembers := TList.Create;
fOffenders := TList.Create;
//So when they click Halt for the first time it knows where to place them
fOrderLoc := KMPointDir(aCreator.GetPosition.X, aCreator.GetPosition.Y, aCreator.Direction);
AddMember(aCreator);
UnitsPerRow := 1;
end;
//Create a Group from script (creates all the warriors as well)
constructor TKMUnitGroup.Create(aID: Cardinal; aOwner: TKMHandIndex; aUnitType: TKMUnitType;
PosX, PosY: Word; aDir: TKMDirection; aUnitPerRow, aCount: Word);
var
Warrior: TKMUnitWarrior;
I: Integer;
DoesFit: Boolean;
UnitLoc: TKMPoint;
NewCondition: Word;
DesiredArea: Byte;
begin
inherited Create;
fUID := aID;
fOwner := aOwner;
fGroupType := UnitGroups[aUnitType];
fMembers := TList.Create;
fOffenders := TList.Create;
//So when they click Halt for the first time it knows where to place them
fOrderLoc := KMPointDir(PosX, PosY, aDir);
//Whole group should have the same condition
NewCondition := Round(UNIT_MAX_CONDITION * (UNIT_CONDITION_BASE + KaMRandomS(UNIT_CONDITION_RANDOM)));
if gGame.IsMapEditor then
begin
//In MapEd we create only flagholder, other members are virtual
Warrior := TKMUnitWarrior(gHands[aOwner].AddUnit(aUnitType, KMPoint(PosX, PosY), False));
if Warrior <> nil then
begin
Warrior.Direction := aDir;
Warrior.AnimStep := UnitStillFrames[aDir];
AddMember(Warrior);
Warrior.Condition := UNIT_MAX_CONDITION div 2; //Half-fed
fMapEdCount := aCount;
end;
end
else
begin
//We want all of the Group memmbers to be placed in one area
DesiredArea := gTerrain.GetWalkConnectID(KMPoint(PosX, PosY));
for I := 0 to aCount - 1 do
begin
UnitLoc := GetPositionInGroup2(PosX, PosY, aDir, I, aUnitPerRow, gTerrain.MapX, gTerrain.MapY, DoesFit);
if not DoesFit then Continue;
Warrior := TKMUnitWarrior(gHands[aOwner].AddUnit(aUnitType, UnitLoc, True, DesiredArea));
if Warrior = nil then Continue;
Warrior.Direction := aDir;
Warrior.AnimStep := UnitStillFrames[aDir];
AddMember(Warrior);
Warrior.Condition := NewCondition;
end;
end;
//We could not set it earlier cos it's limited by Count
UnitsPerRow := aUnitPerRow;
end;
//Load the Group from savegame
constructor TKMUnitGroup.Create(LoadStream: TKMemoryStream);
var
I, NewCount: Integer;
W: TKMUnitWarrior;
begin
inherited Create;
fMembers := TList.Create;
fOffenders := TList.Create;
LoadStream.Read(fGroupType, SizeOf(fGroupType));
LoadStream.Read(fUID);
LoadStream.Read(fOwner);
LoadStream.Read(NewCount);
for I := 0 to NewCount - 1 do
begin
LoadStream.Read(W, 4); //subst on syncload
fMembers.Add(W);
end;
LoadStream.Read(NewCount);
for I := 0 to NewCount - 1 do
begin
LoadStream.Read(W, 4); //subst on syncload
fOffenders.Add(W);
end;
LoadStream.Read(fOrder, SizeOf(fOrder));
LoadStream.Read(fOrderLoc);
LoadStream.Read(fOrderTargetGroup, 4); //subst on syncload
LoadStream.Read(fOrderTargetHouse, 4); //subst on syncload
LoadStream.Read(fOrderTargetUnit, 4); //subst on syncload
LoadStream.Read(fPointerCount);
LoadStream.Read(fTicker);
LoadStream.Read(fTargetFollowTicker);
LoadStream.Read(fTimeSinceHungryReminder);
LoadStream.Read(fUnitsPerRow);
LoadStream.Read(fDisableHungerMessage);
LoadStream.Read(fBlockOrders);
LoadStream.Read(fManualFormation);
end;
procedure TKMUnitGroup.SyncLoad;
var I: Integer;
begin
inherited;
//Assign event handlers after load
for I := 0 to Count - 1 do
begin
fMembers[I] := TKMUnitWarrior(gHands.GetUnitByUID(Cardinal(fMembers[I])));
Members[I].OnWarriorDied := Member_Died;
Members[I].OnPickedFight := Member_PickedFight;
end;
for I := 0 to fOffenders.Count - 1 do
fOffenders[I] := TKMUnitWarrior(gHands.GetUnitByUID(Cardinal(TKMUnitWarrior(fOffenders[I]))));
fOrderTargetGroup := gHands.GetGroupByUID(Cardinal(fOrderTargetGroup));
fOrderTargetHouse := gHands.GetHouseByUID(Cardinal(fOrderTargetHouse));
fOrderTargetUnit := gHands.GetUnitByUID(Cardinal(fOrderTargetUnit));
end;
destructor TKMUnitGroup.Destroy;
begin
//We don't release unit pointers from fMembers, because the group is only destroyed when fMembers.Count = 0
//or when the game is canceled (then it doesn't matter)
fMembers.Free;
//We need to release offenders pointers
ClearOffenders;
fOffenders.Free;
ClearOrderTarget; //Free pointers
inherited;
end;
function TKMUnitGroup.FightMaxRange: Single;
var
I: Integer;
begin
Result := 0;
for I := 0 to Count - 1 do
if Members[I].GetFightMaxRange > Result then
Result := Members[I].GetFightMaxRange;
end;
procedure TKMUnitGroup.Save(SaveStream: TKMemoryStream);
var I: Integer;
begin
inherited;
SaveStream.Write(fGroupType, SizeOf(fGroupType));
SaveStream.Write(fUID);
SaveStream.Write(fOwner);
SaveStream.Write(fMembers.Count);
for I := 0 to fMembers.Count - 1 do
SaveStream.Write(Members[I].UID);
SaveStream.Write(fOffenders.Count);
for I := 0 to fOffenders.Count - 1 do
SaveStream.Write(TKMUnitWarrior(fOffenders[I]).UID);
SaveStream.Write(fOrder, SizeOf(fOrder));
SaveStream.Write(fOrderLoc);
if fOrderTargetGroup <> nil then
SaveStream.Write(fOrderTargetGroup.UID)
else
SaveStream.Write(Integer(0));
if fOrderTargetHouse <> nil then
SaveStream.Write(fOrderTargetHouse.UID)
else
SaveStream.Write(Integer(0));
if fOrderTargetUnit <> nil then
SaveStream.Write(fOrderTargetUnit.UID)
else
SaveStream.Write(Integer(0));
SaveStream.Write(fPointerCount);
SaveStream.Write(fTicker);
SaveStream.Write(fTargetFollowTicker);
SaveStream.Write(fTimeSinceHungryReminder);
SaveStream.Write(fUnitsPerRow);
SaveStream.Write(fDisableHungerMessage);
SaveStream.Write(fBlockOrders);
SaveStream.Write(fManualFormation);
end;
//Group condition is the Min from all members (so that AI feeds the Group when needed)
function TKMUnitGroup.GetCondition: Integer;
var
I: Integer;
begin
Result := UNIT_MAX_CONDITION; //Assign const incase Count=0
for I := 0 to Count - 1 do
Result := Min(Result, Members[I].Condition);
end;
function TKMUnitGroup.GetCount: Integer;
begin
Result := fMembers.Count;
end;
function TKMUnitGroup.GetDirection: TKMDirection;
begin
Result := fOrderLoc.Dir;
end;
function TKMUnitGroup.GetMember(aIndex: Integer): TKMUnitWarrior;
begin
Result := fMembers.Items[aIndex];
end;
function TKMUnitGroup.GetFlagBearer: TKMUnitWarrior;
begin
Result := fMembers.Items[0];
end;
//Get member order location within formation
function TKMUnitGroup.GetMemberLoc(aIndex: Integer): TKMPointExact;
begin
//Allow off map positions so GetClosestTile works properly
Result.Loc := GetPositionInGroup2(fOrderLoc.Loc.X, fOrderLoc.Loc.Y,
fOrderLoc.Dir, aIndex, fUnitsPerRow,
gTerrain.MapX, gTerrain.MapY,
Result.Exact);
//Fits on map and is on passable terrain
Result.Exact := Result.Exact and gTerrain.CheckPassability(Result.Loc, tpWalk);
end;
function TKMUnitGroup.GetNearestMember(aUnit: TKMUnitWarrior): Integer;
var
I: Integer;
Dist, Best: Single;
begin
Result := -1;
Best := MaxSingle;
for I := 0 to Count - 1 do
if (Members[I] <> aUnit) and not Members[I].IsDeadOrDying then
begin
Dist := KMLengthSqr(aUnit.GetPosition, Members[I].GetPosition);
if Dist < Best then
begin
Best := Dist;
Result := I;
end;
end;
end;
function TKMUnitGroup.GetNearestMember(aLoc: TKMPoint): TKMUnitWarrior;
var
I: Integer;
Dist, Best: Single;
begin
Result := nil;
Best := MaxSingle;
for I := 0 to Count - 1 do
if not Members[I].IsDeadOrDying then
begin
Dist := KMLengthSqr(aLoc, Members[I].GetPosition);
if Dist < Best then
begin
Best := Dist;
Result := Members[I];
end;
end;
end;
//Returns self and adds on to the pointer counter
function TKMUnitGroup.GetGroupPointer: TKMUnitGroup;
begin
Inc(fPointerCount);
Result := Self;
end;
//Decreases the pointer counter
//Should be used only by gHands for clarity sake
procedure TKMUnitGroup.ReleaseGroupPointer;
begin
if fPointerCount < 1 then
raise ELocError.Create('Group remove pointer', Position);
Dec(fPointerCount);
end;
//Get current groups location (we use flagholder)
function TKMUnitGroup.GetPosition: TKMPoint;
begin
if not IsDead then
Result := Members[0].GetPosition
else
Result := KMPOINT_ZERO;
end;
procedure TKMUnitGroup.SetPosition(aValue: TKMPoint);
begin
Assert(gGame.IsMapEditor);
Members[0].SetPosition(aValue);
fOrderLoc.Loc := Members[0].GetPosition; //Don't assume we can move to aValue
end;
procedure TKMUnitGroup.SetSelected(aValue: TKMUnitWarrior);
begin
Assert(HasMember(aValue), 'Cant''t select unit that is not a groups member');
fSelected := aValue;
end;
procedure TKMUnitGroup.SetCondition(aValue: Integer);
var I: Integer;
begin
for I := 0 to Count - 1 do
Members[I].Condition := aValue;
end;
procedure TKMUnitGroup.SetDirection(Value: TKMDirection);
begin
Assert(gGame.IsMapEditor);
fOrderLoc.Dir := Value;
Members[0].Direction := Value;
end;
procedure TKMUnitGroup.SetMapEdCount(aCount: Word);
begin
fMapEdCount := aCount;
// Ensure that fUnitsPerRow is valid (less than or equal to fMapEdCount)
SetUnitsPerRow(fUnitsPerRow);
end;
procedure TKMUnitGroup.SetUnitsPerRow(aCount: Word);
begin
if gGame.IsMapEditor then
fUnitsPerRow := EnsureRange(aCount, 1, fMapEdCount)
else
fUnitsPerRow := EnsureRange(aCount, 1, Count);
end;
procedure TKMUnitGroup.AddMember(aWarrior: TKMUnitWarrior; aIndex: Integer = -1);
begin
Assert(fMembers.IndexOf(aWarrior) = -1, 'We already have this Warrior in group');
if aIndex <> -1 then
fMembers.Insert(aIndex, aWarrior.GetUnitPointer)
else
fMembers.Add(aWarrior.GetUnitPointer);
//Member reports to Group if something happens to him, so that Group can apply its logic
aWarrior.OnPickedFight := Member_PickedFight;
aWarrior.OnWarriorDied := Member_Died;
end;
function TKMUnitGroup.HasMember(aWarrior: TKMUnit): Boolean;
begin
Result := fMembers.IndexOf(aWarrior) <> -1;
end;
//Used by the MapEd after changing direction (so warriors are frozen on the right frame)
procedure TKMUnitGroup.ResetAnimStep;
begin
Assert(gGame.IsMapEditor);
Members[0].AnimStep := UnitStillFrames[Members[0].Direction];
end;
//If the player is allowed to issue orders to group
function TKMUnitGroup.CanTakeOrders: Boolean;
begin
Result := (IsRanged or not InFight) and (not fBlockOrders);
end;
function TKMUnitGroup.CanWalkTo(aTo: TKMPoint; aDistance: Single): Boolean;
begin
Result := (Count > 0) and Members[0].CanWalkTo(aTo, aDistance);
end;
//Group is dead, but still exists cos of pointers to it
function TKMUnitGroup.IsDead: Boolean;
begin
Result := (Count = 0);
end;
function TKMUnitGroup.IsRanged: Boolean;
begin
Result := (fGroupType = gt_Ranged);
end;
//Member reports that he has died (or been killed)
procedure TKMUnitGroup.Member_Died(aMember: TKMUnitWarrior);
var
I: Integer;
NewSel: Integer;
begin
I := fMembers.IndexOf(aMember);
Assert(I <> -1, 'No such member');
if (aMember = fSelected) then
begin
fSelected := nil;
//Transfer selection to nearest member
NewSel := GetNearestMember(aMember);
if NewSel <> -1 then
fSelected := Members[NewSel];
end;
fMembers.Delete(I);
//Move nearest member to placeholders place
if I = 0 then
begin
NewSel := GetNearestMember(aMember);
if NewSel <> -1 then
fMembers.Exchange(NewSel, 0);
end;
gHands.CleanUpUnitPointer(TKMUnit(aMember));
SetUnitsPerRow(fUnitsPerRow);
//If Group has died report to owner
if IsDead and Assigned(OnGroupDied) then
OnGroupDied(Self);
//Only repeat the order if we are not in a fight (since bowmen can still take orders when fighting)
if not IsDead and CanTakeOrders and not InFight then
OrderRepeat;
end;
//Member got in a fight
//Remember who we are fighting with, to guide idle units to
//This only works for melee offenders(?)
procedure TKMUnitGroup.Member_PickedFight(aMember: TKMUnitWarrior; aEnemy: TKMUnit);
begin
if (aEnemy is TKMUnitWarrior) then
fOffenders.Add(aEnemy.GetUnitPointer);
end;
//If we picked up a fight, while doing any other order - manage it here
procedure TKMUnitGroup.CheckForFight;
var
I,K: Integer;
U: TKMUnit;
FightWasOrdered: Boolean;
begin
//Verify we still have foes
for I := fOffenders.Count - 1 downto 0 do
if TKMUnitWarrior(fOffenders[I]).IsDeadOrDying then
begin
U := fOffenders[I]; //Need to pass var
gHands.CleanUpUnitPointer(U);
fOffenders.Delete(I);
if fOffenders.Count = 0 then
OrderRepeat;
end;
//Fight is over
if fOffenders.Count = 0 then Exit;
if IsRanged then
begin
FightWasOrdered := False;
for I := 0 to Count - 1 do
if not Members[I].InFight then
//If there are several enemies within range, shooting any of the offenders is first priority
//If there are no offenders in range then CheckForEnemy will pick a new target
//Archers stay still and attack enemies only within their range without walking to/from them
for K := 0 to fOffenders.Count - 1 do
if Members[I].WithinFightRange(TKMUnitWarrior(fOffenders[K]).GetPosition) then
begin
Members[I].OrderFight(TKMUnitWarrior(fOffenders[K]));
FightWasOrdered := True;
end;
//If nobody in the group is in a fight and all offenders are out of range then clear offenders
//(archers should forget about out of range offenders since they won't walk to them like melee)
if not FightWasOrdered and not InFight then
begin
fOffenders.Clear;
OrderRepeat;
end;
end
else
begin
//Idle members should help their comrades
for I := 0 to Count - 1 do
if not Members[I].InFight then
Members[I].OrderWalk(TKMUnitWarrior(fOffenders[KaMRandom(fOffenders.Count)]).NextPosition, False);
end;
end;
//Check if order has been executed and if necessary attempt to repeat it
procedure TKMUnitGroup.CheckOrderDone;
var
I: Integer;
OrderExecuted: Boolean;
P: TKMPointExact;
U: TKMUnitWarrior;
begin
OrderExecuted := False;
//1. Check the Order
//2. Attempt to finish the order
case fOrder of
goNone: OrderExecuted := False;
goWalkTo: begin
OrderExecuted := True;
for I := 0 to Count - 1 do
begin
OrderExecuted := OrderExecuted and Members[I].IsIdle and Members[I].OrderDone;
if Members[I].OrderDone then
begin
//If the unit is idle make them face the right direction
if Members[I].IsIdle
and (fOrderLoc.Dir <> dir_NA) and (Members[I].Direction <> fOrderLoc.Dir) then
begin
Members[I].Direction := fOrderLoc.Dir;
Members[I].SetActionStay(50, ua_Walk); //Make sure the animation still frame is updated
end;
end
else
//Guide Idle and pushed units back to their places
if Members[I].IsIdle
or ((Members[I].GetUnitAction is TUnitActionWalkTo) and TUnitActionWalkTo(Members[I].GetUnitAction).WasPushed) then
begin
P := GetMemberLoc(I);
Members[I].OrderWalk(P.Loc, P.Exact);
end;
end;
end;
goAttackHouse: begin
//It is TaskAttackHouse responsibility to execute it
OrderExecuted := (OrderTargetHouse = nil);
end;
goAttackUnit: begin
if IsRanged then
begin
//Ranged units must kill target unit only
//Then they will attack anything within their reach by themselves
OrderExecuted := (OrderTargetUnit = nil);
if not OrderExecuted then
//If our leader is out of range (enemy has walked away) we need to walk closer
if (KMLength(fOrderLoc.Loc, OrderTargetUnit.GetPosition) > Members[0].GetFightMaxRange) then
OrderAttackUnit(OrderTargetUnit, False)
else
//Our leader is in range so each member should get into position
for I := 0 to Count - 1 do
if Members[I].IsIdle then
begin
P := GetMemberLoc(I);
if KMSamePoint(Members[I].GetPosition, P.Loc)
or (KMLength(Members[I].GetPosition, OrderTargetUnit.GetPosition) <= Members[I].GetFightMaxRange) then
begin
//We are at the right spot, so face towards enemy
Members[I].Direction := KMGetDirection(Members[I].GetPosition, OrderTargetUnit.GetPosition);
Members[I].FaceDir := Members[I].Direction;
if not Members[I].CheckForEnemy then
//If we are too close to shoot, make sure the animation still frame is still updated
Members[I].SetActionStay(10, ua_Walk);
end
else
begin
//Too far away. Walk to the enemy in our formation
Members[I].OrderWalk(P.Loc, P.Exact);
Members[I].FaceDir := fOrderLoc.Dir;
end;
end;
end
else
begin
//Melee units must kill target unit and its Group
OrderExecuted := (OrderTargetUnit = nil) and (OrderTargetGroup = nil);
if OrderTargetUnit <> nil then
begin
//See if target is escaping
if not KMSamePoint(OrderTargetUnit.NextPosition, fOrderLoc.Loc) then
begin
Inc(fTargetFollowTicker);
//It's wasteful to run pathfinding to correct route every step of the way, so if the target unit
//is within 4 tiles, update every step. Within 8, every 2 steps, 12, every 3 steps, etc.
if fTargetFollowTicker mod Max((Round(KMLengthDiag(GetPosition, OrderTargetUnit.GetPosition)) div 4), 1) = 0 then
OrderAttackUnit(OrderTargetUnit, False);
end;
for I := 0 to Count - 1 do
if Members[I].IsIdle then
begin
P := GetMemberLoc(I);
Members[I].OrderWalk(P.Loc, P.Exact);
end;
end;
//If Enemy was killed, but target Group still exists
if (OrderTargetUnit = nil) and (OrderTargetGroup <> nil) then
begin
//Old enemy has died, change target to his comrades
U := OrderTargetGroup.GetNearestMember(Members[0].GetPosition);
Assert(U <> nil, 'We checked that Group is not dead, hence we should have a valid Unit');
OrderAttackUnit(U, False);
end;
end;
end;
goStorm: OrderExecuted := False;
end;
if OrderExecuted then
begin
for I := 0 to Count - 1 do
if (fOrderLoc.Dir <> dir_NA) and Members[I].IsIdle then //Don't change direction whilst f.e. walking
Members[I].Direction := fOrderLoc.Dir;
OrderNone;
end;
end;
//Fighting with citizens does not count by default
function TKMUnitGroup.InFight(aCountCitizens: Boolean = False): Boolean;
var I: Integer;
begin
Result := False;
for I := 0 to Count - 1 do
if Members[I].InFight(aCountCitizens) then
begin
Result := True;
Exit;
end;
end;
function TKMUnitGroup.IsAttackingHouse: Boolean;
var I: Integer;
begin
Result := False;
for I := 0 to Count - 1 do
if (Members[I].UnitTask <> nil)
and (Members[I].UnitTask.TaskName = utn_AttackHouse) then
begin
Result := True;
Exit;
end;
end;
function TKMUnitGroup.IsAttackingUnit: Boolean;
begin
Result := (fOrder = goAttackUnit) and (OrderTargetUnit <> nil);
end;
function TKMUnitGroup.IsIdleToAI(aAllowWalking: Boolean = False): Boolean;
begin
//First check that the previous order has completed
if fOrder = goWalkTo then
Result := aAllowWalking or (KMLengthDiag(Position, fOrderLoc.Loc) < 2)
else
Result := (fOrder = goNone);
//Even fighting citizens should also stop the AI repositioning the group
Result := Result and not InFight(True);
//Also wait until we have dealt with all offenders
Result := Result and (fOffenders.Count = 0);
end;
function TKMUnitGroup.IsPositioned(aLoc:TKMPoint; Dir: TKMDirection): Boolean;
var I: Integer; P: TKMPointExact; U: TKMUnitWarrior;
begin
Result := True;
for I := 0 to Count - 1 do
begin
P.Loc := GetPositionInGroup2(aLoc.X, aLoc.Y, Dir, I, fUnitsPerRow,
gTerrain.MapX, gTerrain.MapY,
P.Exact);
U := Members[I];
Result := U.IsIdle and KMSamePoint(U.GetPosition, P.Loc) and (U.Direction = Dir);
if not Result then Exit;
end;
end;
function TKMUnitGroup.MemberByUID(aUID: Integer): TKMUnitWarrior;
var
I: Integer;
begin
Result := nil;
for I := 0 to Count - 1 do
if (Members[I].UID = aUID) and not Members[I].IsDead then
begin
Result := Members[I];
Break;
end;
end;
function TKMUnitGroup.HitTest(X,Y: Integer): Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 to Count - 1 do
if Members[I].HitTest(X, Y) and not Members[I].IsDead then
begin
Result := True;
Break;
end;
end;
procedure TKMUnitGroup.SelectFlagBearer;
begin
fSelected := fMembers[0];
end;
procedure TKMUnitGroup.SetOwner(aOwner: TKMHandIndex);
var I: Integer;
begin
fOwner := aOwner;
for I := 0 to fMembers.Count - 1 do
TKMUnitWarrior(fMembers[I]).SetOwner(aOwner);
end;
procedure TKMUnitGroup.OwnerUpdate(aOwner: TKMHandIndex; aMoveToNewOwner: Boolean = False);
var I: Integer;
begin
if aMoveToNewOwner and (fOwner <> aOwner) then