-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathBaseConflict.EntityComponents.Shared.pas
2625 lines (2329 loc) · 85.7 KB
/
BaseConflict.EntityComponents.Shared.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 BaseConflict.EntityComponents.Shared;
interface
uses
Generics.Collections,
Math,
RTTI,
SysUtils,
Engine.Helferlein,
Engine.Helferlein.Windows,
Engine.Math,
Engine.Math.Collision2D,
Engine.Collision,
Engine.Serializer,
Engine.Network,
Engine.Script,
Engine.Log,
BaseConflict.Constants,
BaseConflict.Constants.Cards,
BaseConflict.Entity,
BaseConflict.Map,
BaseConflict.Types.Shared,
BaseConflict.Types.Target,
BaseConflict.Classes.Shared,
BaseConflict.Classes.Pathfinding;
type
ProcFilterFunction = reference to function(Entity : TEntity) : single;
{$RTTI EXPLICIT METHODS([vcPublic, vcPublished]) PROPERTIES([vcPublic, vcPublished]) FIELDS([vcPrivate, vcProtected, vcPublic])}
{$RTTI INHERIT}
/// <summary> Adds a unit property to an entity as long this component is attached to this entity. </summary>
TUnitPropertyComponent = class(TEntityComponent)
protected
FGiveOwner, FRemove : boolean;
FUnitProperties : SetUnitProperty;
published
function GetCommanderUnitProperties(Previous : RParam) : RParam;
[XEvent(eiAfterCreate, epLast, etTrigger)]
function OnAfterCreate() : boolean;
[XEvent(eiUnitProperties, epMiddle, etRead)]
/// <summary> Adds the unit properties. </summary>
function OnUnitProperties(Previous : RParam) : RParam;
public
constructor CreateGrouped(Owner : TEntity; ComponentGroup : TArray<byte>; AttachedProperties : TArray<byte>); reintroduce;
/// <summary> Remove the unit properties instead of adding them. </summary>
function Remove : TUnitPropertyComponent;
/// <summary> Gives the property the owning commander instead of this unit. </summary>
function GivePropertyOwner() : TUnitPropertyComponent;
destructor Destroy; override;
end;
{$RTTI INHERIT}
/// <summary> A global manager component, which throws events at certain game ticks and manages eiGameEventTimeTo events. </summary>
TGameDirectorComponent = class(TEntityComponent)
protected
type
RGameDirectorAction = record
GameTick : integer;
Eventname : string;
end;
var
FActions : TList<RGameDirectorAction>;
published
[XEvent(eiGameEventTimeTo, epFirst, etRead, esGlobal)]
/// <summary> Returns the time to this event. </summary>
function OnGameEventTimeTo(Eventname, Previous : RParam) : RParam;
{$IFDEF SERVER}
[XEvent(eiGameTick, epHigh, etTrigger, esGlobal)]
/// <summary> Check on each game tick, whether a event should be fired. </summary>
function OnGameTick() : boolean;
{$ENDIF}
public
constructor Create(Owner : TEntity); override;
function AddEvent(GameTick : integer; Eventname : string) : TGameDirectorComponent;
function AddEventIf(Condition : boolean; GameTick : integer; Eventname : string) : TGameDirectorComponent;
function ClearEvents : TGameDirectorComponent;
destructor Destroy; override;
end;
{$RTTI INHERIT}
/// <summary> Adjust the eiWeladamage of its group so its linear depleting over time (1.0 at eiCooldown).</summary>
TNexusEarlyVulnerabilityComponent = class(TEntityComponent)
published
[XEvent(eiWelaDamage, epHigh, etRead)]
/// <summary> Adjust damage according the depleted time. </summary>
function OnWelaDamage(Previous : RParam) : RParam;
end;
{$RTTI INHERIT}
/// <summary> Handles synchronous positioning of entities. </summary>
TPositionComponent = class(TSerializableEntityComponent)
published
[XEvent(eiSyncPosition, epLast, etTrigger)]
/// <summary> Move entity to synchronized position. </summary>
function OnSyncPosition(Pos : RParam) : boolean;
end;
{$RTTI INHERIT}
/// <summary> Handles movement of units. </summary>
TMovementComponent = class(TPositionComponent)
private
{$IFDEF SERVER}
FSyncTimer : TTimer;
{$ENDIF}
{$IFDEF CLIENT}
FOverwriteMovementSpeed : boolean;
FOverwrittenSpeed : single;
{$ENDIF}
FTargetPathfindingPosition : RVector2;
protected
[XNetworkSerialize(eiMoveTo)]
FTarget : RTarget;
FPath : TArray<RSmallIntVector2>;
FMoving, FUsePathfinding : boolean;
FRange : single;
function TargetReached : boolean;
procedure ComputeNewPath;
procedure IdlePathfinding;
procedure IdleDirect;
{$IFDEF CLIENT}
function OptimizePath(const Path : TArray<TPathfindingTile>) : TArray<TPathfindingTile>;
{$ENDIF}
published
[XEvent(eiAfterCreate, epLast, etTrigger)]
/// <summary> Init. </summary>
function OnAfterCreate() : boolean;
[XEvent(eiExiled, epLast, etWrite)]
/// <summary> Unit stops movement on exile. </summary>
function OnExiled(Exiled : RParam) : boolean;
[XEvent(eiIsMoving, epFirst, etRead)]
function OnIsMoving() : RParam;
[XEvent(eiMoveTo, epLast, etTrigger)]
/// <summary> Sets the new movementtarget and start moving. </summary>
function OnMoveTo(Target : RParam; Range : RParam) : boolean;
[XEvent(eiMoveTargetReached, epFirst, etRead)]
/// <summary> Return whether the target has been reached. Instead of polling should be
/// register on trigger. </summary>
function OnMoveTargetReached() : RParam;
[XEvent(eiStand, epFirst, etTrigger)]
/// <summary> Stand still, now. </summary>
function OnStand() : boolean;
[XEvent(eiMove, epLast, etTrigger)]
/// <summary> Sets the entity to the target. </summary>
function OnMove(Target : RParam) : boolean;
[XEvent(eiSyncPath, epLast, etTrigger)]
/// <summary> Sets the walking path of the unit. </summary>
function OnSyncPath(Start, Target, Path : RParam) : boolean;
[XEvent(eiIdle, epHigher, etTrigger, esGlobal)]
/// <summary> Compute movement. </summary>
function OnIdle() : boolean;
[XEvent(eiDie, epLast, etTrigger)]
/// <summary> If unit dies, it shouldn't move any longer. </summary>
function OnDie(KillerID, KillerCommanderID : RParam) : boolean;
[XEvent(eiLose, epMiddle, etTrigger, esGlobal)]
/// <summary> Stop movement on lose. </summary>
function OnLose(TeamID : RParam) : boolean;
public
constructor Create(Owner : TEntity); reintroduce;
destructor Destroy; override;
end;
{$RTTI INHERIT}
/// <summary> Manages the health of a unit. </summary>
THealthComponent = class(TSerializableEntityComponent)
protected const
OVERHEAL_LIMIT_FACTOR = 2.0;
protected
FIsAlive, FInstaDeath : boolean;
FKillerCommanderID, FKillerID : integer;
function IsAlive : boolean;
function IsInvincible : boolean;
function CanBeHealed : boolean;
function CurrentHealth : single;
function MaxHealth : single;
function CurrentOverheal : single;
function MaxOverheal : single;
procedure UpdateAlive;
procedure ResolveKiller(ID : integer);
published
{$IFDEF SERVER}
[XEvent(eiTakeDamage, epLower, etRead)]
/// <summary> Take some damage. </summary>
function OnDamage(Amount : RParam; DamageType : RParam; InflictorID, Previous : RParam) : RParam;
[XEvent(eiHeal, epLast, etRead)]
/// <summary> Receive some heal. </summary>
function OnHeal(var Amount : RParam; HealModifier, InflictorID : RParam) : RParam;
[XEvent(eiIdle, epMiddle, etTrigger, esGlobal)]
/// <summary> Send killevents until unit is dead, when Health is 0. </summary>
function OnIdle() : boolean;
[XEvent(eiKill, epLast, etTrigger)]
/// <summary> Kills the unit instantly. </summary>
function OnKill(KillerID, KillerCommanderID : RParam) : boolean;
[XEvent(eiResourceCap, epLast, etWrite)]
/// <summary> Adjusts dynamic caps like overheal. </summary>
function OnWriteResourceCap(ResourceID, Amount : RParam) : boolean;
{$ENDIF}
[XEvent(eiIsAlive, epFirst, etRead)]
/// <summary> Return alivestate. Do we need this? </summary>
function OnIsAlive() : RParam;
[XEvent(eiIsAlive, epLast, etWrite)]
/// <summary> Set alivestate. Do we need this? </summary>
function OnSetIsAlive(IsAlive : RParam) : boolean;
[XEvent(eiDamageable, epFirst, etRead)]
/// <summary> Returns true if alive. </summary>
function OnDamageable() : RParam;
[XEvent(eiDie, epLast, etTrigger)]
/// <summary> Sets the unit to dead. </summary>
function OnDie(KillerID, KillerCommanderID : RParam) : boolean;
[XEvent(eiUnitProperties, epMiddle, etRead)]
/// <summary> Tags the unit with certain properties. </summary>
function OnUnitProperies(Previous : RParam) : RParam;
public
constructor Create(Owner : TEntity); override;
end;
RCommanderCard = record
CardUID : string;
League, Level : integer;
constructor Create(const CardUID : string; League, Level : integer);
constructor CreateMaxed(const CardUID : string);
end;
{$RTTI INHERIT}
/// <summary> Transfers all commander abilities to the clients as they are generated on server side.
/// This component will created on server side only and then transferred to the client. </summary>
TCommanderAbilityComponent = class(TSerializableEntityComponent)
protected
FSlot : integer;
// deserialization of records with string explodes, so don't use RCommanderCard here
FCardUID : string;
FCardLeague, FCardLevel : integer;
procedure Init;
published
[XEvent(eiAfterCreate, epLast, etTrigger), ScriptExcludeMember]
/// <summary> Apply the scripts on the client. </summary>
function OnAfterCreate() : boolean;
public
constructor CreateGrouped(Owner : TEntity; Group : TArray<byte>; Card : RCommanderCard); reintroduce;
constructor CreateGroupedSlot(Owner : TEntity; Group : TArray<byte>; Card : RCommanderCard; Slot : integer);
end;
{$RTTI INHERIT}
ANetworkParameters = array of TValue;
/// <summary> Handles all networktasks. </summary>
TNetworkComponent = class(TEntityComponent)
protected
FNetworkDelay : integer;
procedure NewData(Data : TDatapacket); virtual;
published
[XEvent(eiNetworkSend, epLast, etTrigger, esGlobal)]
/// <summary> Send an event via the network. </summary>
function OnNetworkSend(EntityID : RParam; Event : RParam; Group : RParam; ComponentID : RParam; Parameters : RParam; Write : RParam) : boolean;
public
constructor Create(Owner : TEntity); override;
procedure Send(Data : TCommandSequence); virtual; abstract;
destructor Destroy; override;
end;
ProcEntityFilterFunction = reference to function(Entity : TEntity) : boolean;
{$RTTI INHERIT}
/// <summary> Manages all deployed entities. Provides several global methods. </summary>
TEntityManagerComponent = class(TEntityComponent)
private
function GetDeployedEntityCount() : integer;
protected
FEntities : TDictionary<integer, TEntity>;
FComponentGroupsToKill : TList<RTuple<integer, SetComponentGroup>>;
FComponentsToKill : TList<RTuple<integer, integer>>;
FIDCounter : integer;
FNexusList : TList<TEntity>;
FEntitiesToFree : TList<TEntity>;
procedure NewEntity(Entity : TEntity); virtual;
procedure KillDeferred;
procedure BeforeComponentFree; override;
published
[XEvent(eiNewEntity, epMiddle, etTrigger, esGlobal)]
/// <summary> Register the entity. </summary>
function OnNewEntity(Entity : RParam) : boolean;
[XEvent(eiRemoveComponent, epLast, etTrigger, esGlobal)]
/// <summary> Frees the component of the entity. </summary>
function OnRemoveComponent(EntityID, ComponentID : RParam) : boolean;
[XEvent(eiRemoveComponentGroup, epLast, etTrigger, esGlobal)]
/// <summary> Frees the componentgroup of the entity. </summary>
function OnRemoveComponentGroup(EntityID : RParam; ComponentGroup : RParam) : boolean;
[XEvent(eiKillEntity, epLast, etTrigger, esGlobal)]
/// <summary> Frees the entity. </summary>
function OnKillEntity(EntityID : RParam) : boolean;
[XEvent(eiSetGridFieldBlocking, epLast, etWrite, esGlobal)]
/// <summary> Set whether a field of a build grid is blocked and cannot be build over. </summary>
function OnSetGridFieldBlocking(GridID, GridCoord, BlockingEntityID : RParam) : boolean;
[XEvent(eiReplaceEntity, epLower, etTrigger, esGlobal)]
/// <summary> Updates the grid. </summary>
function OnReplaceEntity(oldEntityID, newEntityID, isSameEntity : RParam) : boolean;
public
{$IFDEF DEBUG}
[ScriptExcludeMember]
property Entities : TDictionary<integer, TEntity> read FEntities;
{$ENDIF}
property DeployedEntityCount : integer read GetDeployedEntityCount;
constructor Create(Owner : TEntity); override;
/// <summary> Returns a list of all deployed entities. List have to be freed. </summary>
[ScriptExcludeMember]
function GetDeployedEntityList : TList<TEntity>;
/// <summary> Generate unique EntityID. IDs starting at 2 (IDs < 0 are invalid, 0 is global eventbus, 1 is game entity) and increasing one by one. </summary>
function GenerateUniqueID : integer;
function HasEntityByID(ID : integer) : boolean;
/// <summary> Return the Entity to the ID if found, otherwise nil. </summary>
function GetEntityByID(ID : integer) : TEntity;
/// <summary> Return the Entity to the UID if found, otherwise nil. </summary>
function GetEntityByUID(UID : string) : TEntity;
/// <summary> Remote invokes an event on target entities eventbus. </summary>
procedure InvokeEventOnEntity(EntityID : integer; Eventname : EnumEventIdentifier; const Group : SetComponentGroup; ComponentID : integer; RawParameters : TArray<byte>; Write : boolean);
/// <summary> Frees the given componentgroup of the entity at the beginning of the next frame. </summary>
procedure FreeComponentGroup(EntityID : integer; Group : SetComponentGroup);
procedure FreeComponent(EntityID, ComponentID : integer); overload;
procedure FreeComponent(Component : TEntityComponent); overload;
/// <summary> A safe way to free entities without being in a event stack. </summary>
procedure FreeEntity(Entity : TEntity);
function FilterEntities(MustHave, MustNotHave : SetUnitProperty) : TList<TEntity>;
/// <summary> List is managed </summary>
function NexusList : TList<TEntity>;
function NexusByTeamID(TeamID : integer) : TEntity;
function TryGetNexusByTeamID(TeamID : integer; out Nexus : TEntity) : boolean;
/// <summary> Retrieves the next hostile nexus. </summary>
function NexusNextEnemy(Position : RVector2; MyTeamID : integer) : TEntity;
function NexusNext(Position : RVector2) : TEntity;
function TryGetNexusNextEnemy(Position : RVector2; MyTeamID : integer; out Nexus : TEntity) : boolean; overload;
function TryGetNexusNextEnemy(reference : TEntity; out Nexus : TEntity) : boolean; overload;
function TryGetEntityByID(ID : integer; out Entity : TEntity) : boolean;
function TryGetEntityByUID(UID : string; out Entity : TEntity) : boolean;
/// <summary> Return the owning commander of the entity if found, otherwise nil. </summary>
function GetOwningCommander(Entity : TEntity) : TEntity;
function TryGetOwningCommander(Entity : TEntity; out Commander : TEntity) : boolean;
/// <summary> Returns the number of existing entities with the given unitproperties and matching the team constraint. </summary>
function EntityCountByUnitProperty(const UnitProperties : SetUnitProperty; CountTeamConstraint : EnumTargetTeamConstraint = tcAll; TeamID : integer = -1) : integer;
procedure Idle; virtual;
destructor Destroy; override;
end;
{$RTTI INHERIT}
TGameTickComponent = class(TEntityComponent)
protected
FTickTimer : TTimer;
FTickCounter : integer;
published
[XEvent(eiGameCommencing, epMiddle, etTrigger, esGlobal)]
/// <summary> Starts first spawntimer. </summary>
function OnGameCommencing() : boolean;
{$IFDEF SERVER}
[XEvent(eiIdle, epMiddle, etTrigger, esGlobal)]
/// <summary> Check for spawning. </summary>
function OnIdle() : boolean;
{$ENDIF}
[XEvent(eiGameTick, epHigher, etTrigger, esGlobal)]
/// <summary> Resets tick timer. </summary>
function OnGameTick() : boolean;
[XEvent(eiGameTickTimeToFirstTick, epFirst, etRead, esGlobal)]
/// <summary> Get ms to next tick. </summary>
function OnGetTimeToFirstTick() : RParam;
[XEvent(eiGameTickCounter, epFirst, etRead, esGlobal)]
/// <summary> Get current game tick counter. </summary>
function OnGetGameTickCounter() : RParam;
public
constructor Create(Owner : TEntity); override;
destructor Destroy; override;
end;
{$RTTI INHERIT}
/// <summary> Component for handling resource within an entity. </summary>
TResourceManagerComponent = class(TEntityComponent)
protected
FInitialValues : TDictionary<integer, RParam>;
published
[XEvent(eiAfterCreate, epLast, etTrigger)]
/// <summary> Save initial values. </summary>
function OnAfterCreate() : boolean;
[XEvent(eiResourceReset, epLast, etTrigger)]
/// <summary> Returns the balance of the resource. </summary>
function OnResetResource(ResourceID : RParam) : boolean;
[XEvent(eiResourceBalance, epFirst, etRead)]
/// <summary> Returns the balance of the resource. </summary>
function OnGetResource(ResourceID, Previous : RParam) : RParam;
[XEvent(eiResourceBalance, epLast, etWrite)]
/// <summary> Sets the balance of the resource. </summary>
function OnSetResource(ResourceID, Amount : RParam) : boolean;
[XEvent(eiResourceTransaction, epFirst, etRead)]
/// <summary> Return whether transaction can be made inbound. </summary>
function OnCanTransact(ResourceID, Amount, Previous : RParam) : RParam;
[XEvent(eiResourceTransaction, epLast, etTrigger)]
/// <summary> Executes the transaction. </summary>
function OnTransact(ResourceID, Amount : RParam) : boolean;
[XEvent(eiResourceSubtraction, epFirst, etRead)]
/// <summary> Return whether negative transaction can be made inbound. </summary>
function OnCanTransactNegative(ResourceID, Amount, Previous : RParam) : RParam;
[XEvent(eiResourceSubtraction, epLast, etTrigger)]
/// <summary> Executes the negative transaction. </summary>
function OnTransactNegative(ResourceID, Amount : RParam) : boolean;
[XEvent(eiResourceCap, epFirst, etRead)]
/// <summary> Returns the upper bound of the resource. </summary>
function OnGetResourceCap(ResourceID, Previous : RParam) : RParam;
[XEvent(eiResourceCap, epLast, etWrite)]
/// <summary> Sets the upper bound of the resource. </summary>
function OnSetResourceCap(ResourceID, Amount : RParam) : boolean;
[XEvent(eiResourceCost, epFirst, etRead)]
/// <summary> Returns the amount of the resources. </summary>
function OnGetResourceCost(Previous : RParam) : RParam;
[XEvent(eiResourceCost, epLast, etWrite)]
/// <summary> Saves the new cost. </summary>
function OnSetResourceCost(ResourceID, Amount : RParam) : boolean;
[XEvent(eiResourceCapTransaction, epLast, etTrigger)]
/// <summary> Adjusts the upper bound of the resource. </summary>
function OnResourceCapTransaction(ResourceID, Amount, Empty : RParam) : boolean;
public
destructor Destroy; override;
end;
{$RTTI INHERIT}
/// <summary> Component for spatial management and collision tests of units </summary>
TCollisionManagerComponent = class(TEntityComponent)
protected
FQuadTree : TEntityLooseQuardtree;
published
[XEvent(eiClosestEntityInRange, epFirst, etRead, esGlobal)]
/// <summary> Return the closest matching entity. </summary>
function OnClosestEntityInRange(Pos, Range : RParam; SourceTeamID, TargetTeamConstraint : RParam; Filter : RParam) : RParam;
[XEvent(eiEntitiesInRange, epFirst, etRead, esGlobal)]
/// <summary> Return all matching entities. </summary>
function OnEntitiesInRangeOf(Pos : RParam; Range : RParam; SourceTeamID, TargetTeamConstraint : RParam; Filter : RParam) : RParam;
public
constructor Create(Owner : TEntity); override;
procedure RegisterCollidable(Collidable : TLooseQuadTreeNodeData<TEntity>);
procedure RemoveCollidable(Collidable : TLooseQuadTreeNodeData<TEntity>);
destructor Destroy(); override;
end;
{$RTTI INHERIT}
/// <summary> Adds infinite resources to all commanders. </summary>
TSandboxComponent = class(TEntityComponent)
published
[XEvent(eiGameCommencing, epLast, etTrigger, esGlobal)]
function OnGameCommencing() : boolean;
end;
{$RTTI INHERIT}
/// <summary> Component that keeps the entity up-to-date in the spatial partitioning
/// data structure within the TCollisionComponentManager. All units are handled as spheres.</summary>
TCollisionComponent = class(TEntityComponent)
protected
FRegistered : boolean;
FElement : TEntityLooseQuadtreeData;
FRadius : single;
published
[XEvent(eiPosition, epLast, etWrite)]
/// <summary> Updates the collidable. </summary>
function OnWritePosition(Position : RParam) : boolean;
[XEvent(eiTeamID, epLast, etWrite)]
/// <summary> Updates the LooseQuadtreeData. </summary>
function OnWriteTeamID(TeamID : RParam) : boolean;
[XEvent(eiDie, epLast, etTrigger)]
/// <summary> Dead units don't have any repulsioneffect on other units. </summary>
function OnDie(KillerID, KillerCommanderID : RParam) : boolean;
[XEvent(eiExiled, epLast, etWrite)]
/// <summary> Exiled units are not on the battlefield anymore. </summary>
function OnExiled(IsExiled : RParam) : boolean;
public
constructor Create(Owner : TEntity); reintroduce;
destructor Destroy(); override;
end;
TPathfindingComponent = class(TEntityComponent)
private
FCurrentTile : TPathfindingTile;
published
[XEvent(eiPosition, epLast, etWrite)]
/// <summary> Updates the position on map. </summary>
function OnWritePosition(Position : RParam) : boolean;
[XEvent(eiStand, epLast, etTrigger)]
/// <summary> If stand, the entity should no longer reserve any timeslots.</summary>
function OnStand() : boolean;
[XEvent(eiAfterCreate, epLast, etTrigger)]
/// <summary> If a entity is created it will block a tile</summary>
function OnAfterCreate() : boolean;
[XEvent(eiPathfindingTile, epFirst, etRead)]
/// <summary> Return the current used pathfinding tile </summary>
function OnPathfindingTile() : RParam;
public
constructor Create(Owner : TEntity); override;
destructor Destroy(); override;
end;
{$RTTI INHERIT}
/// <summary> Takes different armor into account while damaging (type and value). </summary>
TArmorComponent = class(TEntityComponent)
published
[XEvent(eiTakeDamage, epMiddle, etRead)]
/// <summary> Adjust damage according to the ArmorMatrix and the armor value of the unit. </summary>
function OnDamage(var Amount : RParam; DamageType, InflictorID, Previous : RParam) : RParam;
end;
{$RTTI INHERIT}
/// <summary> Manages the default income of a commander. WARNING: Component only for commander! </summary>
TCommanderIncomeComponent = class(TEntityComponent)
protected
function AdjustIncome(const Income : RIncome) : RIncome; virtual;
published
[XEvent(eiIncome, epMiddle, etRead, esGlobal)]
/// <summary> Set up default income. </summary>
function OnReadIncome(CommanderID, Previous : RParam) : RParam;
end;
{$RTTI INHERIT}
/// <summary> Manages the default income of a commander. WARNING: Component only for commander! </summary>
TCommanderIncomeDefaultComponent = class(TCommanderIncomeComponent)
protected
function AdjustIncome(const Income : RIncome) : RIncome; override;
public
constructor CreateGrouped(Owner : TEntity; Group : TArray<byte>); override;
end;
{$RTTI INHERIT}
/// <summary> Makes adjustments to the current income. </summary>
TCommanderIncomeLoanComponent = class(TCommanderIncomeComponent)
protected
FFactor : single;
FTimer : TTimer;
function AdjustIncome(const Income : RIncome) : RIncome; override;
public
/// <summary> Rate of income increase. </summary>
function Factor(Factor : single) : TCommanderIncomeLoanComponent;
/// <summary> Time of income increase. Will reduce transform gold income for the duration * factor / 2 afterwards. </summary>
function Duration(Duration : integer) : TCommanderIncomeLoanComponent;
destructor Destroy; override;
end;
{$RTTI INHERIT}
/// <summary> Manages the overflow of income of a commander. WARNING: Component only for commander! </summary>
TCommanderIncomeOverflowComponent = class(TCommanderIncomeComponent)
protected
function AdjustIncome(const Income : RIncome) : RIncome; override;
public
constructor CreateGrouped(Owner : TEntity; Group : TArray<byte>); override;
end;
{$RTTI INHERIT}
EnumDynamicZoneResult = (drNone, drTrue, drFalse);
/// <summary> Emits a dynamic zone around this unit. </summary>
TDynamicZoneEmitterComponent = class abstract(TEntityComponent)
protected
FDynamicZone : SetDynamicZone;
FNegate : boolean;
function IsInDynamicZone(Position : RVector2; TeamID : integer) : EnumDynamicZoneResult; virtual; abstract;
published
[XEvent(eiInDynamicZone, epMiddle, etRead, esGlobal), ScriptExcludeMember]
/// <summary> Checks whether the position is covered by this emitter. </summary>
function OnInDynamicZone(Position, TeamID, Zone, Previous : RParam) : RParam;
public
function SetZone(Zone : TArray<byte>) : TDynamicZoneEmitterComponent;
function Exclude : TDynamicZoneEmitterComponent;
end;
{$RTTI INHERIT}
/// <summary> Emits a radial dynamic zone around this unit. </summary>
TDynamicZoneRadialEmitterComponent = class(TDynamicZoneEmitterComponent)
protected
function IsInDynamicZone(Position : RVector2; TeamID : integer) : EnumDynamicZoneResult; override;
end;
{$RTTI INHERIT}
/// <summary> Emits a dynamic zone depending on the dot-product with a normal. >= 0 True </summary>
TDynamicZoneAxisEmitterComponent = class(TDynamicZoneEmitterComponent)
protected
FNormal, FPosition : RVector2;
function IsInDynamicZone(Position : RVector2; TeamID : integer) : EnumDynamicZoneResult; override;
public
constructor CreateGrouped(Owner : TEntity; Group : TArray<byte>); override;
function SetPosition(X, Y : single) : TDynamicZoneAxisEmitterComponent;
function SetNormal(X, Y : single) : TDynamicZoneAxisEmitterComponent;
end;
{$RTTI INHERIT}
[XNetworkBaseType]
/// <summary> Only nexus get this component. Lose-Condition for teams. </summary>
TPrimaryTargetComponent = class(TSerializableEntityComponent)
published
[XEvent(eiEnumerateNexus, epFirst, etRead, esGlobal)]
/// <summary> Return this as RTarget if team matches. </summary>
function OnGetNexusPosition(Previous : RParam) : RParam;
end;
{$RTTI INHERIT}
/// <summary> This effect set game events globally on fire. </summary>
TGameEventEnumeratorComponent = class(TEntityComponent)
protected
FGameEvents : TArray<string>;
published
[XEvent(eiGameEvent, epMiddle, etRead, esGlobal)]
function OnGameEvent(Event, Previous : RParam) : RParam;
public
/// <summary> Adds an event, which will be set on fire.</summary>
function Event(const EventID : string) : TGameEventEnumeratorComponent;
end;
implementation
uses
{$IFDEF SERVER}
BaseConflict.Globals.Server,
{$ENDIF}
BaseConflict.Globals;
{ TPositionComponent }
function TPositionComponent.OnSyncPosition(Pos : RParam) : boolean;
begin
Result := True;
Owner.Position := Pos.AsVector2;
end;
{ TMovementComponent }
procedure TMovementComponent.ComputeNewPath;
var
Path : TArray<TPathfindingTile>;
CoordPath : TArray<RSmallIntVector2>;
i : integer;
AEntity : TEntity;
IgnoreOtherEntities, UseWaypoints : boolean;
begin
Map.Pathfinding.CancelLastComputedPath(Owner);
// negate because IgnoreOtherEntities is the opposite of USE_PATHFINDING
// USE_PATHFINDING is confusing caption, because if value false pathfinding will used but without
// takeing other entites into account (entity will block timeslots but ignore other an so will walk through units)
IgnoreOtherEntities := not Owner.UnitData(udUsePathfinding).AsTypeDefault(True);
// Use direct (beeline heuristic) pathfinding if non-nexus entity is targeted
if FTarget.IsEntity and FTarget.TryGetTargetEntity(AEntity) then
begin
// is nexus?
if upNexus in AEntity.Eventbus.Read(eiUnitProperties, []).AsSetType<SetUnitProperty> then
UseWaypoints := True
else
UseWaypoints := False;
end
else
UseWaypoints := False;
Path := Map.Pathfinding.ComputePath(Owner, FTarget.GetTargetPosition, PATHFINDING_MAX_COMPUTED_PATH_LENGTH, UseWaypoints, IgnoreOtherEntities);
SetLength(CoordPath, Length(Path));
for i := 0 to Length(CoordPath) - 1 do
CoordPath[i] := Path[i].GridPosition;
Eventbus.Trigger(eiSyncPath, [Owner.Position, FTarget.GetTargetPosition, RParam.FromArray<RSmallIntVector2>(CoordPath)]);
end;
constructor TMovementComponent.Create(Owner : TEntity);
begin
inherited Create(Owner);
{$IFDEF SERVER}
FSyncTimer := TTimer.CreateAndStart(UNITSYNCINTERVAL);
{$ENDIF}
end;
destructor TMovementComponent.Destroy;
begin
{$IFDEF SERVER}
FSyncTimer.Free;
{$ENDIF}
inherited;
end;
procedure TMovementComponent.IdleDirect;
var
Position, targetPos, between : RVector2;
distance, walkingdistance : single;
begin
if FMoving then
begin
walkingdistance := GameTimeManager.ZDiff * Eventbus.Read(eiSpeed, []).AsSingle;
Position := Owner.Position;
targetPos := FTarget.GetTargetPosition;
between := targetPos - Position;
distance := between.Length;
if TargetReached then
begin
between := between.SetLength(FRange);
Eventbus.Trigger(eiMove, [targetPos - between]);
Eventbus.Trigger(eiStand, []);
exit;
end;
if distance - FRange <= walkingdistance then
begin
between := between.SetLength(FRange);
Eventbus.Trigger(eiMove, [targetPos - between]);
Eventbus.Trigger(eiStand, []);
end
else
begin
between := targetPos - Position;
Eventbus.Trigger(eiMove, [Position + (walkingdistance * between.Normalize)]);
end;
end;
{$IFDEF SERVER}
if FSyncTimer.Expired then
begin
Position := Owner.Position;
Eventbus.Trigger(eiSyncPosition, [Position]);
FSyncTimer.Start;
end;
{$ENDIF}
end;
procedure TMovementComponent.IdlePathfinding;
var
Position, targetPos, between : RVector2;
distance, walkingdistance : single;
NextNode, TargetTile : TPathfindingTile;
{$IFDEF SERVER}
CurrentTile : TPathfindingTile;
{$ENDIF}
begin
if FMoving then
begin
{$IFDEF CLIENT}
if FOverwriteMovementSpeed then
walkingdistance := GameTimeManager.ZDiff * FOverwrittenSpeed
else
{$ENDIF}
walkingdistance := GameTimeManager.ZDiff * Eventbus.Read(eiSpeed, []).AsSingle;
// safety for lags
if (walkingdistance > 50) or (walkingdistance < 0) then walkingdistance := 0;
if FUsePathfinding then
begin
Position := Owner.Position;
{$IFDEF SERVER}
if Length(FPath) <= 0 then
begin
ComputeNewPath;
exit;
end;
{$ENDIF}
while Length(FPath) > 0 do
begin
NextNode := Map.Pathfinding.GridBy2D[FPath[high(FPath)]];
{$IFDEF SERVER}
CurrentTile := Owner.Eventbus.Read(eiPathfindingTile, []).AsType<TPathfindingTile>;
// if a tile (where unit next want to walk) and where the unit currently not stand, is
// blocked, we need a new path, old path is no longer valid
if (CurrentTile <> NextNode) and NextNode.IsBlocked then
begin
// we need a new path
ComputeNewPath;
exit;
end;
{$ENDIF}
TargetTile := Map.Pathfinding.GetTileByPosition(FTargetPathfindingPosition);
if NextNode = TargetTile then
targetPos := FTargetPathfindingPosition
else
targetPos := NextNode.WorldSpaceBoundaries.Center;
distance := Position.distance(targetPos);
if distance <= walkingdistance then
begin
Position := targetPos;
Eventbus.Trigger(eiMove, [Position]);
walkingdistance := walkingdistance - distance;
SetLength(FPath, Length(FPath) - 1);
continue;
end
else
begin
between := (targetPos - Position).Normalize;
Position := Position + (between * walkingdistance);
break;
end;
end;
Eventbus.Trigger(eiMove, [Position]);
if TargetReached then
Eventbus.Trigger(eiStand, []);
end
end;
end;
function TMovementComponent.OnDie(KillerID, KillerCommanderID : RParam) : boolean;
begin
Result := True;
Eventbus.Trigger(eiStand, []);
end;
function TMovementComponent.OnExiled(Exiled : RParam) : boolean;
begin
Result := True;
if Exiled.AsBoolean then
Eventbus.Trigger(eiStand, []);
end;
function TMovementComponent.OnIdle : boolean;
begin
Result := True;
if FUsePathfinding then IdlePathfinding
else IdleDirect;
end;
function TMovementComponent.OnIsMoving : RParam;
begin
Result := FMoving;
end;
function TMovementComponent.OnLose(TeamID : RParam) : boolean;
begin
Result := True;
{$IFDEF SERVER}
FMoving := False;
{$ELSE}
Eventbus.Trigger(eiStand, []);
{$ENDIF}
end;
function TMovementComponent.OnMove(Target : RParam) : boolean;
var
Front : RVector2;
begin
Result := True;
Front := Owner.Position.DirectionTo(Target.AsVector2);
if not Front.IsZeroVector then
Owner.Front := Front;
Owner.Position := Target.AsVector2;
end;
function TMovementComponent.OnMoveTargetReached : RParam;
begin
Result := TargetReached;
end;
function TMovementComponent.OnMoveTo(Target : RParam; Range : RParam) : boolean;
var
NewTarget : RTarget;
Position : RVector2;
begin
FRange := Range.AsSingle;
NewTarget := Target.AsType<RTarget>;
// cannot move to empty target
if NewTarget.IsEmpty then exit(True);
// only start moving if new target is different from current or we're not moving at the moment
Result := (FTarget <> NewTarget) or not FMoving;
if Result then
begin
Position := Owner.Position;
FTarget := NewTarget;
FMoving := True;
{$IFDEF SERVER}
if FUsePathfinding then
ComputeNewPath;
Eventbus.Trigger(eiSyncPosition, [Position]);
{$ENDIF}
end;
end;
function TMovementComponent.OnStand() : boolean;
begin
Result := FMoving;
FMoving := False;
if Result then
begin
FPath := nil;
{$IFDEF SERVER}
Eventbus.Trigger(eiSyncPosition, [Owner.Position]);
{$ENDIF}
Eventbus.Trigger(eiMoveTargetReached, []);
end;
end;
function TMovementComponent.OnSyncPath(Start, Target, Path : RParam) : boolean;
{$IFDEF CLIENT}
var
optimizedPath, nodePath : TArray<TPathfindingTile>;
oldLength : single;
{$ENDIF}
begin
Result := True;
FTargetPathfindingPosition := Target.AsVector2;
{$IFDEF CLIENT}
nodePath := HArray.Map<RSmallIntVector2, TPathfindingTile>(Path.AsArray<RSmallIntVector2>,
function(const Coord : RSmallIntVector2) : TPathfindingTile
begin
Result := Map.Pathfinding.GridBy2D[Coord];
end);
optimizedPath := OptimizePath(nodePath);
if Length(optimizedPath) <> Length(nodePath) then
begin
oldLength := Map.Pathfinding.ComputePathLength(nodePath);
FOverwrittenSpeed := Map.Pathfinding.ComputePathLength(optimizedPath) * Eventbus.Read(eiSpeed, []).AsSingle / oldLength;
FOverwriteMovementSpeed := True;
end
else FOverwriteMovementSpeed := False;
FPath := HArray.Map<TPathfindingTile, RSmallIntVector2>(optimizedPath,
function(const Tile : TPathfindingTile) : RSmallIntVector2
begin
Result := Tile.GridPosition;
end);
FPath := HArray.Reverse<RSmallIntVector2>(FPath);
{$ELSE}
FPath := HArray.Reverse<RSmallIntVector2>(Path.AsArray<RSmallIntVector2>);
{$ENDIF}
end;
{$IFDEF CLIENT}
function TMovementComponent.OptimizePath(const Path : TArray<TPathfindingTile>) : TArray<TPathfindingTile>;
var
NodeCount : integer;
node, NextNode, Target : TPathfindingTile;
i : integer;
procedure AddNode(node : TPathfindingTile);
begin
Result[NodeCount] := node;
inc(NodeCount);
end;
begin
// if path is shorter or equal two nodes, there is nothing to optimize
if Length(Path) > 2 then
begin
NodeCount := 0;
SetLength(Result, Length(Path));
Target := Path[Length(Path) - 1];
// the first node belongs to every path
AddNode(Path[0]);
for i := 1 to Length(Path) - 2 do
begin
NextNode := Path[i + 1];
node := Path[i];
// if next node is best choice, we don't need it in path because the node
// is only the discreet
if node.GetOptimalNeighbour(Target) = NextNode then
continue
else
AddNode(node);
end;
// the last node belongs to every path
AddNode(Target);
SetLength(Result, NodeCount);
end
else
Result := Path;
end;
{$ENDIF}
function TMovementComponent.TargetReached : boolean;
var
Position : RVector2;
begin
Position := Owner.Position;
if FUsePathfinding then
Result := Map.Pathfinding.GetTileByPosition(Position) = Map.Pathfinding.GetTileByPosition(FTarget.GetTargetPosition)
else
Result := Position.distance(FTarget.GetTargetPosition) - FRange <= SPATIALEPSILON;
end;
function TMovementComponent.OnAfterCreate() : boolean;
begin
Result := True;
FUsePathfinding := Owner.UnitData(udUsePathfinding).AsBoolean;